diff --git a/README.md b/README.md index 95e1d29..c90a139 100644 --- a/README.md +++ b/README.md @@ -20,9 +20,10 @@ The server loads `.env` automatically. Real environment variables override `.env | HISTORY_MIGRATION_WORKERS | 4 | Concurrent background workers used to backfill missing project histories (clamped to 1-8) | | APP_URL | https://api.mistwarp.org | Public URL of this API | | ROTUR_APP_KEY | mistwarp | The old validator key, for editors that predate validators keyed to the Rotur App | -| COMMERCE_SERVICE_KEY | | Key registered for `mistwarp` in Rotur's `COMMERCE_SERVICE_KEYS` | +| COMMERCE_SERVICE_KEY | | Key registered for `mistwarp` in Rotur's `COMMERCE_SERVICE_KEYS`. Only bounty awards and the groups integration still use it | | ROTUR_CLIENT_ID | | The MistWarp Rotur App's client ID (`app_1938b6a87799f862`). With the secret, mistwarp-api calls the apps API as MistWarp | | ROTUR_CLIENT_SECRET | | One of the MistWarp Rotur App's secrets, made with **New secret** on rotur.dev/me/developer | +| MISTWARP_ROTUR_USER | | Rotur account that gets MistWarp's share of sales. Without it, the MistWarp Rotur App's owner gets it | | ROTUR_WEBHOOK_SECRET | | Signing secret (`whsec_…`) of the MistWarp Rotur App's webhook. Without it `POST /v1/rotur/webhook` answers 503 | | R2_ENDPOINT | | https://accountid.r2.cloudflarestorage.com | | R2_BUCKET | mistwarp | R2 bucket name | @@ -52,12 +53,23 @@ The MistWarp Rotur App declares that people can talk and can spend credits. Befo Rotur only answers about people who have used MistWarp through Sign in with Rotur, or made their account on MistWarp. For anyone else, or if Rotur can't be reached, MistWarp carries on as it did before. Rotur counts credits towards a parent's monthly limit when it moves them, so the purchase signal only asks. +## Payments + +Buying a project or a game product, donating with a comment and refunding a game product are Rotur payment requests (`POST /v2/apps//payment-requests`). mistwarp-api never holds a permission to spend anyone's credits. + +1. The editor asks for an intent. mistwarp-api asks Rotur for the payment, with a purchase key (`mwbuy_`, `mwgame_`, `mwdonate_` or `mwrefund_`) as its `reference`, and answers with the key and Rotur's `approveUrl`. +2. The person approves it on rotur.dev with their password. Rotur moves the credits, shared between everyone the sale pays: the creator, collaborators, the remixed project's creator and MistWarp's fee. +3. Rotur's `payment.completed` webhook marks the key paid and delivers projects and game products. The editor's confirm call does the same if it gets there first, asking Rotur whether the request was paid. Whichever comes second finds it done. + +Donations are delivered when their comment is posted, and refunds when the product is revoked. Paid keys waiting for that are kept for 30 days, and unpaid ones for an hour (Rotur's requests expire after 15 minutes). + ## Rotur webhooks Set the MistWarp Rotur App's webhook to `https://api.mistwarp.org/v1/rotur/webhook` on rotur.dev/me/developer, with privacy requests on, and put its signing secret in `ROTUR_WEBHOOK_SECRET`. - `user.deleted`, `user.left` and `user.banned` erase everything MistWarp holds about that person, the same as deleting their data from Settings. - A `privacy.request` for `erasure` does the same. One for `access` sends them a MistWarp notification pointing to the download in Settings. +- `payment.completed` finishes the purchase it names (see Payments). Deliveries are checked against `Rotur-Signature` and refused if their timestamp is more than five minutes out. Each is saved to `data/rotur-webhooks.json`, answered, then handled in the background, and a retried delivery is only handled once. Anything not yet handled when the server stops is handled when it starts. diff --git a/admin.osl b/admin.osl index a19b3b5..ec9a814 100644 --- a/admin.osl +++ b/admin.osl @@ -674,12 +674,6 @@ def handleAdminStats(*serve.Context c) ( object bans = banData.bans number bannedUsers = bans.getKeys().len array news = loadNews() - object payoutStore = loadPendingPayouts() - array pendingPayouts = payoutStore.payouts.assert(array) - number pendingPayoutAmount = 0 - for i pendingPayouts.len ( - pendingPayoutAmount += pendingPayouts[i].amount.toNum() - ) c.json(200, { ok: true, totalProjects: totalProjects, @@ -694,8 +688,6 @@ def handleAdminStats(*serve.Context c) ( openErrors: openErrors, bannedUsers: bannedUsers, newsPosts: news.len, - pendingPayouts: pendingPayouts.len, - pendingPayoutAmount: pendingPayoutAmount, days: days, averageProjectBytes: if totalProjects > 0 then totalBytes / totalProjects else 0, averageViews: if totalProjects > 0 then totalViews / totalProjects else 0, diff --git a/comments.osl b/comments.osl index a499bca..5edb83f 100644 --- a/comments.osl +++ b/comments.osl @@ -396,8 +396,7 @@ def handleGetProjectComments(*serve.Context c) ( ) def handleProjectCommentDonationIntent(*serve.Context c) ( - if commerceServiceKey == "" ( - c.json(503, {ok: false, error: "donations are not available right now"}) + if refuseOldPaymentClient(c) ( return ) auto result = loadProject(c.param("id")) @@ -443,22 +442,14 @@ def handleProjectCommentDonationIntent(*serve.Context c) ( return ) - string key = "mwdonate_" ++ randomString(16) - object store = prunePurchaseKeys(loadPurchaseKeys()) - object keys = store.keys - keys[key] = {kind: "comment_donation", projectId: project.id.toStr(), buyer: donor, amount: amount, at: timestamp} - store.keys = keys - savePurchaseKeys(store) - c.json(200, { - ok: true, - key: key, - amount: amount, - projectId: project.id, - title: project.title, - recipient: project.owner, - splits: [{username: project.owner, basis_points: 10000}] - }) -) + object started = startPurchase("mwdonate_", {kind: "comment_donation", projectId: project.id.toStr(), buyer: donor, amount: amount}, donor, project.owner.toStr(), [], amount, "Donation to " ++ project.title.toStr(), (body.returnUrl ?? "").toStr()) + if !started.ok ( + c.json(503, started) + return + ) + started.amount = amount + started.recipient = project.owner + c.json(200, started)) def handleCreateProjectComment(*serve.Context c) ( auto result = loadProject(c.param("id")) @@ -513,13 +504,10 @@ def handleCreateProjectComment(*serve.Context c) ( return ) object donation = body.donation.assertElse(object, {}) - if donation.contains("key") and donation.key != null ( - donationKey = donation.key.toStr().strip() - ) - if donation.contains("paymentId") and donation.paymentId != null ( - donationPaymentId = donation.paymentId.toStr().strip() - ) - if donationKey == "" or donationPaymentId == "" ( + donationKey = (donation.key ?? "").toStr().strip() + object pendingDonation = paidPurchase(donationKey) + donationPaymentId = (pendingDonation.requestId ?? "").toStr() + if !donationKey.startsWith("mwdonate_") ( c.badRequest("missing donation confirmation") return ) @@ -533,22 +521,15 @@ def handleCreateProjectComment(*serve.Context c) ( ) ) - object donationStore = loadPurchaseKeys() - object donationKeys = donationStore.keys - if !donationKeys.contains(donationKey) ( - c.badRequest("this donation expired, start again") + if donationPaymentId == "" ( + c.json(402, {ok: false, pending: true, error: "donation not received yet, try again in a moment"}) return ) - object pendingDonation = donationKeys[donationKey].assert(object) - if !pendingDonation.contains("kind") or pendingDonation.kind.toStr() != "comment_donation" or pendingDonation.projectId.toStr() != project.id.toStr() or normalizeUsername(pendingDonation.buyer.toStr()) != normalizeUsername(c.getString("username")) ( + if pendingDonation.projectId.toStr() != project.id.toStr() or normalizeUsername(pendingDonation.buyer.toStr()) != normalizeUsername(c.getString("username")) ( c.badRequest("this donation key does not match") return ) donationAmount = pendingDonation.amount.toNum() - if !verifyCommerceCommentDonation(donationPaymentId, c.getString("username"), project, donationAmount) ( - c.json(402, {ok: false, pending: true, error: "donation not received yet, try again in a moment"}) - return - ) ) object created = createComment("project-" ++ project.id.toStr(), c.getString("username"), c.getString("userId"), body.content.toStr(), parentId, kind, donationAmount, donationPaymentId) @@ -557,11 +538,7 @@ def handleCreateProjectComment(*serve.Context c) ( return ) if donationKey != "" ( - object donationStore = loadPurchaseKeys() - object donationKeys = donationStore.keys - donationKeys.delete(donationKey) - donationStore.keys = donationKeys - savePurchaseKeys(donationStore) + forgetPurchase(donationKey) ) if created.contains("duplicate") and created.duplicate == true ( created.comment = commentResponse(created.comment.assert(object), c.getString("username")) diff --git a/game-marketplace.osl b/game-marketplace.osl index 3aeb579..6338068 100644 --- a/game-marketplace.osl +++ b/game-marketplace.osl @@ -124,6 +124,9 @@ def handleOwnsGameProduct(*serve.Context c) ( ) def handleGameProductIntent(*serve.Context c) ( + if refuseOldPaymentClient(c) ( + return + ) auto loaded = loadProject(c.param("id")) if !loaded.ok or !projectIsViewable(loaded.project.assert(object)) ( c.notFound("project not found") @@ -148,10 +151,6 @@ def handleGameProductIntent(*serve.Context c) ( c.json(200, {ok: true, already: true, product: gameProductResponse(project, product, c)}) return ) - if commerceServiceKey == "" ( - c.json(503, {ok: false, error: "purchases are not available right now"}) - return - ) if ownsGameProduct(project.id.toStr(), c.getString("userId"), product.id.toStr()) ( object entitlements = loadGameEntitlements(project.id.toStr(), c.getString("userId")) object products = entitlements.products.assertElse(object, {}) @@ -169,159 +168,128 @@ def handleGameProductIntent(*serve.Context c) ( return ) - string key = "mwgame_" ++ randomString(16) - object store = prunePurchaseKeys(loadPurchaseKeys()) - object keys = store.keys - keys[key] = { - type: "game_product", - projectId: project.id.toStr(), - productId: product.id.toStr(), - buyer: normalizeUsername(c.getString("username")), - price: product.price, - at: timestamp - } - store.keys = keys - savePurchaseKeys(store) - c.json(200, { - ok: true, - key: key, - amount: product.price, - title: product.name, - resourceId: project.id.toStr() ++ ":" ++ product.id.toStr(), - splits: projectCommerceSplits(project) - }) -) - -def verifyGameProductPayment(string paymentId, string buyer, object project, object product, array expectedSplits) boolean ( - string endpoint = roturBase ++ "/v2/commerce/payments/" ++ url.escape(paymentId) ++ "/verify?source=mistwarp" - object resp = requests.get(endpoint, {headers: {"X-Commerce-Key": commerceServiceKey}}) - if !resp.success or resp.status.toInt() != 200 ( - return false - ) - auto parsed = json.parse(resp.body, {type: "object"}) - if parsed.isErr() ( - return false - ) - object payload = parsed.unwrap().assert(object) - object payment = payload.payment.assertElse(object, {}) - if payment.status.toStr() != "completed" or payment.source.toStr() != "mistwarp" or payment.kind.toStr() != "game_product" ( - return false + array splits = projectCommerceSplits(project) + if splits.len == 0 ( + c.json(503, {ok: false, error: "MistWarp can't take payments right now. Try again in a few minutes."}) + return ) - string resourceId = project.id.toStr() ++ ":" ++ product.id.toStr() - if payment.resource_type.toStr() != "game_product" or payment.resource_id.toStr() != resourceId ( - return false + object entry = {type: "game_product", projectId: project.id.toStr(), productId: product.id.toStr(), buyer: normalizeUsername(c.getString("username")), userId: c.getString("userId"), price: product.price} + object started = startPurchase("mwgame_", entry, c.getString("username"), project.owner.toStr(), splits, product.price.toNum(), (product.name ?? product.id).toStr() ++ " in " ++ project.title.toStr(), (c.bodyJSON().returnUrl ?? "").toStr()) + if !started.ok ( + c.json(503, started) + return ) - if normalizeUsername(payment.payer.toStr()) != normalizeUsername(buyer) or payment.amount.toNum() + 0.001 < product.price.toNum() ( - return false + started.amount = product.price + started.title = product.name + c.json(200, started)) + +// Delivers a paid game product, once, whether the editor or Rotur's webhook +// gets here first. +def completeGameProductPurchase(string key) object ( + sync.lock("purchase:" ++ key) + object entry = paidPurchase(key) + auto loaded = loadProject((entry.projectId ?? "").toStr()) + if !entry.contains("paid") or !loaded.ok ( + sync.unlock("purchase:" ++ key) + return {ok: false} ) - array actual = payment.recipients.assertElse(array, []) - if actual.len != expectedSplits.len ( - return false + object project = loaded.project.assert(object) + object found = findGameProduct(project, entry.productId.toStr()) + if !found.ok ( + sync.unlock("purchase:" ++ key) + return {ok: false} ) - for i expectedSplits.len ( - object expected = expectedSplits[i].assert(object) - boolean matched = false - for j actual.len ( - object recipient = actual[j].assert(object) - if normalizeUsername(recipient.username.toStr()) == normalizeUsername(expected.username.toStr()) and recipient.basis_points.toNum().toInt() == expected.basis_points.toNum().toInt() ( - matched = true - ) - ) - if !matched ( - return false + object product = found.product.assert(object) + string userId = entry.userId.toStr() + string buyer = entry.buyer.toStr() + string paymentId = entry.requestId.toStr() + if !ownsGameProduct(project.id.toStr(), userId, product.id.toStr()) ( + if !saveGameProductEntitlement(project.id.toStr(), userId, product.id.toStr(), paymentId) or !grantGameProductItem(project, product, userId, paymentId) ( + sync.unlock("purchase:" ++ key) + return {ok: false, error: "failed to grant game product"} ) - ) - return true + // What the buyer paid, which a refund pays back. + number paid = (entry.price ?? product.price).toNum() + addPurchaseRecord(buyer, {projectId: project.id.toStr(), productId: product.id, title: product.name, seller: project.owner, amount: paid, at: timestamp, type: "game_product"}) + addNotification(project.owner.toStr(), buyer, "purchase", {projectId: project.id, projectTitle: project.title, productId: product.id, productName: product.name, amount: paid}) + ) + forgetPurchase(key) + sync.unlock("purchase:" ++ key) + return {ok: true, project: project, product: product} ) def handleGameProductConfirm(*serve.Context c) ( - auto loaded = loadProject(c.param("id")) - if !loaded.ok ( - c.notFound("project not found") - return + string key = (c.bodyJSON().key ?? "").toStr().strip() + object pending = loadPurchaseKeys().keys[key] ?? {} + boolean mine = key.startsWith("mwgame_") and (pending.userId ?? "").toStr() == c.getString("userId") and (pending.productId ?? "").toStr() == c.param("product") + object completed = {ok: false} + if mine ( + completed = completeGameProductPurchase(key) + ) + if !completed.ok and ownsGameProduct(c.param("id"), c.getString("userId"), c.param("product")) ( + // Rotur's webhook got here first. + auto loaded = loadProject(c.param("id")) + object found = findGameProduct(loaded.project.assertElse(object, {}), c.param("product")) + if loaded.ok and found.ok ( + c.json(200, {ok: true, already: true, product: gameProductResponse(loaded.project.assert(object), found.product.assert(object), c)}) + return + ) ) - object project = loaded.project.assert(object) - object found = findGameProduct(project, c.param("product")) - if !found.ok ( - c.notFound("game product not found") + if !mine ( + c.badRequest("this purchase expired, start again") return ) - object product = found.product.assert(object) - if ownsGameProduct(project.id.toStr(), c.getString("userId"), product.id.toStr()) ( - c.json(200, {ok: true, already: true, product: gameProductResponse(project, product, c)}) + if !completed.ok ( + c.json(402, {ok: false, pending: true, error: (completed.error ?? "payment not received yet, try again in a moment").toStr()}) return ) - object body = c.bodyJSON() - string key = body.key.toStr().strip() - string paymentId = body.paymentId.toStr().strip() - object store = loadPurchaseKeys() - object keys = store.keys - if key == "" or paymentId == "" or !keys.contains(key) ( - c.badRequest("this purchase expired, start again") - return + c.json(200, {ok: true, product: gameProductResponse(completed.project.assert(object), completed.product.assert(object), c)}) +) + +// What the buyer last paid for this product, from their purchase records, or 0 +// if they never paid for it (a creator grant or a free claim). +def gameProductAmountPaid(string buyer, string projectId, string productId) number ( + object profile = loadProfile(normalizeUsername(buyer)) + array purchases = (profile.purchases ?? []).assertElse(array, []) + for i purchases.len ( + object record = purchases[i].assertElse(object, {}) + if (record.type ?? "").toStr() == "game_product" and (record.projectId ?? "").toStr() == projectId and (record.productId ?? "").toStr() == productId ( + return (record.amount ?? 0).toNum() + ) ) - object pending = keys[key].assert(object) - string buyer = c.getString("username") - if pending.type.toStr() != "game_product" or pending.projectId.toStr() != project.id.toStr() or pending.productId.toStr() != product.id.toStr() or normalizeUsername(pending.buyer.toStr()) != normalizeUsername(buyer) ( - c.badRequest("this purchase key does not match") + return 0 +) + +// The creator pays the buyer back through Rotur before revoking a paid +// product: this asks Rotur for that payment. +def handleGameProductRefundIntent(*serve.Context c) ( + auto loaded = loadProject(c.param("id")) + if !loaded.ok or !canEditProject(loaded.project.assert(object), c) ( + c.forbidden("only the project creator can refund products") return ) - array splits = projectCommerceSplits(project) - if !verifyGameProductPayment(paymentId, buyer, project, product, splits) ( - c.json(402, {ok: false, pending: true, error: "payment not received yet, try again in a moment"}) + object project = loaded.project.assert(object) + object found = findGameProduct(project, c.param("product")) + object body = c.bodyJSON() + string buyer = body.username.toStr() + string buyerId = userIdForUsername(buyer) + if !found.ok or buyerId == "" or !ownsGameProduct(project.id.toStr(), buyerId, c.param("product")) ( + c.badRequest("they don't own this product") return ) - if !saveGameProductEntitlement(project.id.toStr(), c.getString("userId"), product.id.toStr(), paymentId) ( - c.internalError("failed to grant game product") + object product = found.product.assert(object) + number paid = gameProductAmountPaid(buyer, project.id.toStr(), product.id.toStr()) + if paid <= 0 ( + c.badRequest("there's no payment from them to refund, revoke without a refund") return ) - if !grantGameProductItem(project, product, c.getString("userId"), paymentId) ( - c.internalError("failed to grant the product's portable item") + object entry = {type: "game_refund", projectId: project.id.toStr(), productId: product.id.toStr(), buyer: normalizeUsername(c.getString("username")), refundTo: buyerId, amount: paid} + object started = startPurchase("mwrefund_", entry, c.getString("username"), buyer, [], paid, "Refund for " ++ (product.name ?? product.id).toStr(), (body.returnUrl ?? "").toStr()) + if !started.ok ( + c.json(503, started) return ) - keys.delete(key) - store.keys = keys - savePurchaseKeys(store) - addPurchaseRecord(normalizeUsername(buyer), {projectId: project.id.toStr(), productId: product.id, title: product.name, seller: project.owner, amount: product.price, at: timestamp, type: "game_product"}) - addNotification(project.owner.toStr(), buyer, "purchase", {projectId: project.id, projectTitle: project.title, productId: product.id, productName: product.name, amount: product.price}) - c.json(200, {ok: true, product: gameProductResponse(project, product, c)}) -) - -def verifyGameProductRefund(string paymentId, string creator, string buyer, string projectId, string productId, number price) boolean ( - if commerceServiceKey == "" or paymentId == "" ( - return false - ) - string endpoint = roturBase ++ "/v2/commerce/payments/" ++ url.escape(paymentId) ++ "/verify?source=mistwarp" - object resp = requests.get(endpoint, {headers: {"X-Commerce-Key": commerceServiceKey}}) - if !resp.success or resp.status.toInt() != 200 ( - return false - ) - auto parsed = json.parse(resp.body, {type: "object"}) - if parsed.isErr() ( - return false - ) - object payload = parsed.unwrap().assert(object) - object payment = payload.payment.assertElse(object, {}) - if payment.status.toStr() != "completed" or payment.source.toStr() != "mistwarp" ( - return false - ) - if normalizeUsername(payment.payer.toStr()) != normalizeUsername(creator) or payment.amount.toNum() + 0.001 < price ( - return false - ) - if payment.resource_type.toStr() != "game_product" or payment.resource_id.toStr() != projectId ++ ":" ++ productId ( - return false - ) - array actual = payment.recipients.assertElse(array, []) - if actual.len == 0 ( - return true - ) - for i actual.len ( - object recipient = actual[i].assert(object) - if normalizeUsername(recipient.username.toStr()) == normalizeUsername(buyer) ( - return true - ) - ) - return false + c.json(200, started) ) def handleGrantGameProduct(*serve.Context c) ( @@ -390,19 +358,23 @@ def handleRevokeGameProduct(*serve.Context c) ( c.json(200, {ok: true, removed: false}) return ) - number price = product.price.toNum() boolean refunded = false - if price > 0 and body.noRefund != true ( - string paymentId = body.paymentId.toStr().strip() - if !verifyGameProductRefund(paymentId, c.getString("username"), targetUsername, project.id.toStr(), product.id.toStr(), price) ( + if product.price.toNum() > 0 and body.noRefund != true ( + string refundKey = (body.refundKey ?? "").toStr() + object refund = paidPurchase(refundKey) + if !refundKey.startsWith("mwrefund_") or (refund.refundTo ?? "").toStr() != targetId or (refund.projectId ?? "").toStr() != project.id.toStr() or (refund.productId ?? "").toStr() != product.id.toStr() ( c.json(402, {ok: false, error: "refund payment not received yet, send the refund first or revoke without refund"}) return ) refunded = true ) if !removeGameProductEntitlement(project.id.toStr(), targetId, product.id.toStr()) ( + // The refund key stays, so revoking can be tried again with it. c.internalError("failed to revoke game product") return ) + if refunded ( + forgetPurchase((body.refundKey ?? "").toStr()) + ) c.json(200, {ok: true, removed: true, refunded: refunded}) ) diff --git a/main.osl b/main.osl index 28df4ab..431ef0f 100644 --- a/main.osl +++ b/main.osl @@ -131,7 +131,6 @@ if historyMigrationWorkers > 8 ( historyMigrationWorkers = 8 ) string purchaseKeysFile = "data/purchase-keys.json" -string pendingPayoutsFile = "data/pending-payouts.json" boolean r2Local = r2Endpoint == "" or r2AccessKeyId == "" string localBlobsDir = "data/blobs/" @@ -162,6 +161,7 @@ import "./cache-policy.osl" import "./git-inspection.osl" import "./gitea.osl" import "./rotur-app.osl" +import "./rotur-payments.osl" import "./rotur-signals.osl" import "./rotur-badges.osl" import "./auth.osl" @@ -216,6 +216,7 @@ import "./history-migration.osl" auto remoteMilestoneChecks = cache.create(10000, 10) auto viewDedup = cache.create(100000, 21600) +auto roturAppOwnerCache = cache.create(4, 3600) auto viewIndexFlush = cache.create(100000, 600) auto userIdsCache = cache.create(10000, 300) auto identityRefreshCache = cache.create(10000, 300) @@ -441,6 +442,7 @@ def setupApiRoutes(*serve.Router api) ( api.POST("/projects/:id/products/:product/purchase/confirm", requireAuth, handleGameProductConfirm) api.POST("/projects/:id/products/:product/grant", requireAuth, handleGrantGameProduct) api.POST("/projects/:id/products/:product/revoke", requireAuth, handleRevokeGameProduct) + api.POST("/projects/:id/products/:product/refund/intent", requireAuth, handleGameProductRefundIntent) api.GET("/projects/:id/game-inventory-config", requireAuth, handleGetGameInventoryConfig) api.GET("/projects/:id/me/inventory", requireAuth, handleGetProjectInventory) api.POST("/projects/:id/me/inventory/grant", requireAuth, handleGrantProjectItem) @@ -567,8 +569,6 @@ def setupApiRoutes(*serve.Router api) ( api.GET("/admin/stats", requireAdmin, handleAdminStats) api.GET("/admin/storage", requireAdmin, handleAdminStorageStats) api.POST("/admin/storage/sync", requireAdmin, handleAdminSyncR2StorageStats) - api.GET("/admin/payouts", requireAdmin, handleListPendingPayouts) - api.POST("/admin/payouts/retry", requireAdmin, handleRetryPendingPayouts) api.GET("/admin/users", requireAdmin, handleListUsers) api.GET("/admin/agreement", requireAdmin, handleAdminGetAgreement) api.POST("/admin/agreement", requireAdmin, handleAdminUpdateAgreement) diff --git a/monetize.osl b/monetize.osl index 6996b75..67fae9e 100644 --- a/monetize.osl +++ b/monetize.osl @@ -138,63 +138,6 @@ def canRemixProject(object project,*serve.Context c) boolean ( return canSeeInsideProject(project, c) ) -def roturGet(string path) object ( - return requests.get(roturBase ++ path, {headers: {"Authorization": "Bearer " ++ mistwarpRoturToken}}) -) - -def roturPost(string path, object body) object ( - return requests.post(roturBase ++ path, {headers: {"Authorization": "Bearer " ++ mistwarpRoturToken, "Content-Type": "application/json"}, body: json.stringify(body)}) -) - -def payoutTo(string recipient, number amount, string note) boolean ( - object payResp = roturPost("/me/transfer", {to: recipient, amount: amount, note: note}) - return payResp.success and payResp.status.toInt() == 200 -) - -def mistwarpAccountUser() string ( - if mistwarpRoturUser != "" ( - return mistwarpRoturUser - ) - object resp = roturGet("/me") - if !resp.success or resp.status.toInt() != 200 ( - return "" - ) - auto parsed = json.parse(resp.body, {type: "object"}) - if parsed.isErr() ( - return "" - ) - object me = parsed.unwrap().assert(object) - if me.contains("username") and me.username != null ( - return me.username.toStr() - ) - return "" -) - -def verifyIncomingTransfer(string fromLower, string note, number minAmount) boolean ( - object resp = roturGet("/me") - if !resp.success or resp.status.toInt() != 200 ( - return false - ) - auto parsed = json.parse(resp.body, {type: "object"}) - if parsed.isErr() ( - return false - ) - object me = parsed.unwrap().assert(object) - if !me.contains("sys.transactions") or me["sys.transactions"] == null ( - return false - ) - array txns = me["sys.transactions"].assert(array) - for i txns.len ( - object tx = txns[i] - if tx.type.toStr() == "in" ( - if tx.note.toStr() == note and normalizeUsername(tx.user.toStr()) == fromLower and tx.amount.toNum() + 0.001 >= minAmount ( - return true - ) - ) - ) - return false -) - def addCommerceSplit(object totals, string username, number basisPoints) ( string normalized = normalizeUsername(username) if normalized == "" or basisPoints <= 0 ( @@ -216,9 +159,17 @@ def projectCommerceSplits(object project) array ( if platformPoints > 5000 ( platformPoints = 5000 ) - string platformUser = mistwarpAccountUser() + string platformUser = "" + if platformPoints > 0 ( + platformUser = mistwarpFeeAccount() + if platformUser == "" ( + // Without the fee account its share would go to the creator. No splits + // means the sale can't start. + return [] + ) + ) number allocated = 0 - if platformUser != "" and platformPoints > 0 ( + if platformPoints > 0 ( addCommerceSplit(totals, platformUser, platformPoints) allocated = platformPoints ) @@ -270,92 +221,6 @@ def ownerAmountFromSplits(object project, number amount, array splits) number ( return 0 ) -def verifyCommerceProjectPayment(string paymentId, string buyer, object project, number amount, array expectedSplits) boolean ( - if commerceServiceKey == "" or paymentId == "" ( - return false - ) - string endpoint = roturBase ++ "/v2/commerce/payments/" ++ url.escape(paymentId) ++ "/verify?source=mistwarp" - object resp = requests.get(endpoint, {headers: {"X-Commerce-Key": commerceServiceKey}}) - if !resp.success or resp.status.toInt() != 200 ( - return false - ) - auto parsed = json.parse(resp.body, {type: "object"}) - if parsed.isErr() ( - return false - ) - object payload = parsed.unwrap().assert(object) - if !payload.contains("payment") or payload.payment == null ( - return false - ) - object payment = payload.payment.assert(object) - if payment.status.toStr() != "completed" or payment.source.toStr() != "mistwarp" or payment.kind.toStr() != "project_sale" ( - return false - ) - if payment.resource_type.toStr() != "project" or payment.resource_id.toStr() != project.id.toStr() ( - return false - ) - if normalizeUsername(payment.payer.toStr()) != normalizeUsername(buyer) or payment.amount.toNum() + 0.001 < amount ( - return false - ) - array actual = payment.recipients.assert(array) - if actual.len != expectedSplits.len ( - return false - ) - for i expectedSplits.len ( - object expected = expectedSplits[i].assert(object) - boolean found = false - for j actual.len ( - object recipient = actual[j].assert(object) - if normalizeUsername(recipient.username.toStr()) == normalizeUsername(expected.username.toStr()) and recipient.basis_points.toNum().toInt() == expected.basis_points.toNum().toInt() ( - found = true - ) - ) - if !found ( - return false - ) - ) - return true -) - -def verifyCommerceCommentDonation(string paymentId, string donor, object project, number amount) boolean ( - if commerceServiceKey == "" or paymentId == "" ( - return false - ) - string endpoint = roturBase ++ "/v2/commerce/payments/" ++ url.escape(paymentId) ++ "/verify?source=mistwarp" - object resp = requests.get(endpoint, {headers: {"X-Commerce-Key": commerceServiceKey}}) - if !resp.success or resp.status.toInt() != 200 ( - return false - ) - auto parsed = json.parse(resp.body, {type: "object"}) - if parsed.isErr() ( - return false - ) - object payload = parsed.unwrap().assert(object) - if !payload.contains("payment") or payload.payment == null ( - return false - ) - object payment = payload.payment.assert(object) - if payment.status.toStr() != "completed" or payment.source.toStr() != "mistwarp" or payment.kind.toStr() != "comment_donation" ( - return false - ) - if payment.resource_type.toStr() != "project" or payment.resource_id.toStr() != project.id.toStr() ( - return false - ) - if normalizeUsername(payment.payer.toStr()) != normalizeUsername(donor) ( - return false - ) - number paidAmount = payment.amount.toNum() - if paidAmount + 0.001 < amount or paidAmount - 0.001 > amount ( - return false - ) - array recipients = payment.recipients.assert(array) - if recipients.len != 1 ( - return false - ) - object recipient = recipients[1].assert(object) - return normalizeUsername(recipient.username.toStr()) == normalizeUsername(project.owner.toStr()) and recipient.basis_points.toNum().toInt() == 10000 -) - def awardContributionBounty(string bountyId, string projectId, string recipient) boolean ( if bountyId == "" or commerceServiceKey == "" ( return false @@ -387,14 +252,6 @@ def savePurchaseKeys(object store) boolean ( return writeFile(purchaseKeysFile, store) ) -def loadPendingPayouts() object ( - auto result = readFile(pendingPayoutsFile) - if !result.ok ( - return {payouts: []} - ) - return result.data.assert(object) -) - def renameUserMonetization(string oldKey, string newName) boolean ( string newKey = normalizeUsername(newName) object purchaseStore = loadPurchaseKeys() @@ -409,65 +266,11 @@ def renameUserMonetization(string oldKey, string newName) boolean ( ) ) purchaseStore.keys = keys - savePurchaseKeys(purchaseStore) - - object payoutStore = loadPendingPayouts() - array payouts = payoutStore.payouts.assertElse(array, []) - for i payouts.len ( - object payout = payouts[i].assert(object) - if normalizeUsername(payout.seller.toStr()) == oldKey ( - payout.seller = newName - ) - if normalizeUsername(payout.buyer.toStr()) == oldKey ( - payout.buyer = newName - ) - payouts[i] = payout - ) - payoutStore.payouts = payouts - return writeFile(pendingPayoutsFile, payoutStore) -) - -def recordPendingPayout(string projectId, string seller, string buyer, number amount) ( - object store = loadPendingPayouts() - array payouts = store.payouts.assert(array) - payouts.append({projectId: projectId, seller: seller, buyer: buyer, amount: amount, at: timestamp}) - store.payouts = payouts - writeFile(pendingPayoutsFile, store) -) - -def retryPendingPayouts() object ( - object store = loadPendingPayouts() - array payouts = store.payouts.assert(array) - array remaining = [] - number paid = 0 - for i payouts.len ( - object p = payouts[i] - boolean ok = payoutTo(p.seller.toStr(), p.amount.toNum(), "MistWarp sale (retry)") - if ok ( - paid += 1 - ) else ( - remaining.append(p) - ) - ) - store.payouts = remaining - writeFile(pendingPayoutsFile, store) - return {paid: paid, remaining: remaining.len} -) - -def handleListPendingPayouts(*serve.Context c) ( - object store = loadPendingPayouts() - c.json(200, {ok: true, payouts: store.payouts.assert(array)}) -) - -def handleRetryPendingPayouts(*serve.Context c) ( - if mistwarpRoturToken == "" ( - c.json(503, {ok: false, error: "payouts are not available right now"}) - return - ) - object result = retryPendingPayouts() - c.json(200, {ok: true, paid: result.paid, remaining: result.remaining}) + return savePurchaseKeys(purchaseStore) ) +// Unpaid keys go after an hour (Rotur's requests expire after 15 minutes). +// Paid ones still waiting for their comment or revoke are kept for 30 days. def prunePurchaseKeys(object store) object ( object keys = store.keys array names = keys.getKeys() @@ -475,7 +278,8 @@ def prunePurchaseKeys(object store) object ( for i names.len ( string k = names[i].toStr() object entry = keys[k] - if timestamp - entry.at.toNum() < 3600000 ( + number age = timestamp - entry.at.toNum() + if age < 3600000 or (entry.paid == true and age < 2592000000) ( kept[k] = entry ) ) @@ -653,9 +457,19 @@ def recordSale(object project, string buyer, number price, number sellerAmount) project.saleHistory = sales ) +// An editor or packaged game from before payment requests sends no returnUrl. +// It would pay MistWarp the old way, which nothing delivers any more, so it's +// told to reload before anything is asked of Rotur. +def refuseOldPaymentClient(*serve.Context c) boolean ( + if c.bodyJSON().contains("returnUrl") ( + return false + ) + c.json(409, {ok: false, code: "client_outdated", error: "MistWarp was updated, reload this page"}) + return true +) + def handlePurchaseIntent(*serve.Context c) ( - if commerceServiceKey == "" ( - c.json(503, {ok: false, error: "purchases are not available right now"}) + if refuseOldPaymentClient(c) ( return ) auto result = loadProject(c.param("id")) @@ -689,97 +503,76 @@ def handlePurchaseIntent(*serve.Context c) ( return ) - string key = "mwbuy_" ++ randomString(16) - object store = prunePurchaseKeys(loadPurchaseKeys()) - object keys = store.keys - keys[key] = {projectId: project.id.toStr(), buyer: buyerLower, price: price, at: timestamp} - store.keys = keys - savePurchaseKeys(store) - - c.json(200, {ok: true, key: key, amount: price, title: project.title, splits: projectCommerceSplits(project)}) -) - -def handlePurchaseConfirm(*serve.Context c) ( - if commerceServiceKey == "" ( - c.json(503, {ok: false, error: "purchases are not available right now"}) - return - ) - auto result = loadProject(c.param("id")) - if !result.ok ( - c.notFound("project not found") - return - ) - object project = result.project.assert(object) - number price = projectPrice(project) - if price <= 0 ( - c.badRequest("this project is not for sale") + array splits = projectCommerceSplits(project) + if splits.len == 0 ( + c.json(503, {ok: false, error: "MistWarp can't take payments right now. Try again in a few minutes."}) return ) - string buyer = c.getString("username") - string buyerLower = normalizeUsername(buyer) - if hasBought(project, buyerLower) ( - c.json(200, {ok: true, already: true, project: projectResponse(project, c)}) + object started = startPurchase("mwbuy_", {projectId: project.id.toStr(), buyer: buyerLower, price: price}, buyerLower, project.owner.toStr(), splits, price, project.title.toStr(), (c.bodyJSON().returnUrl ?? "").toStr()) + if !started.ok ( + c.json(503, started) return ) + started.amount = price + started.title = project.title + c.json(200, started) +) - object body = c.bodyJSON() - string key = "" - if body.contains("key") and body.key != null ( - key = body.key.toStr().strip() - ) - if key == "" ( - c.badRequest("missing purchase key") - return - ) - string paymentId = "" - if body.contains("paymentId") and body.paymentId != null ( - paymentId = body.paymentId.toStr().strip() +// Delivers a paid project purchase, once, whether the editor or Rotur's +// webhook gets here first. +def completeProjectPurchase(string key) object ( + sync.lock("purchase:" ++ key) + object entry = paidPurchase(key) + auto result = loadProject((entry.projectId ?? "").toStr()) + if !entry.contains("paid") or !result.ok ( + sync.unlock("purchase:" ++ key) + return {ok: false} ) - if paymentId == "" ( - c.badRequest("missing payment id") - return + object project = result.project.assert(object) + string buyer = entry.buyer.toStr() + if !hasBought(project, buyer) ( + number owed = entry.price.toNum() + string seller = project.owner.toStr() + // The splits Rotur paid, as they were when the purchase started. + array splits = (entry.splits ?? projectCommerceSplits(project)).assertElse(array, []) + recordSale(project, buyer, owed, ownerAmountFromSplits(project, owed, splits)) + if addToLibrary(buyer, project.id.toStr()) ( + project.saves = projectSaves(project) + 1 + ) + saveProject(project) + upsertIndexEntry(project) + siteBroadcastStats(project.id.toStr(), buyer, {saved: true}) + addPurchaseRecord(buyer, {projectId: project.id.toStr(), title: project.title, seller: seller, amount: owed, at: timestamp}) + addNotification(seller, buyer, "purchase", {projectId: project.id, projectTitle: project.title, amount: owed}) ) + forgetPurchase(key) + sync.unlock("purchase:" ++ key) + return {ok: true, project: project} +) - object store = loadPurchaseKeys() - object keys = store.keys - if !keys.contains(key) ( - c.badRequest("this purchase expired, start again") - return +def handlePurchaseConfirm(*serve.Context c) ( + string key = (c.bodyJSON().key ?? "").toStr().strip() + object pending = loadPurchaseKeys().keys[key] ?? {} + boolean mine = key.startsWith("mwbuy_") and (pending.buyer ?? "").toStr() == normalizeUsername(c.getString("username")) and (pending.projectId ?? "").toStr() == c.param("id") + object completed = {ok: false} + if mine ( + completed = completeProjectPurchase(key) + ) + if !completed.ok ( + // Rotur's webhook may have got here first. + auto loaded = loadProject(c.param("id")) + if loaded.ok and hasBought(loaded.project.assert(object), normalizeUsername(c.getString("username"))) ( + c.json(200, {ok: true, already: true, project: projectResponse(loaded.project.assert(object), c)}) + return + ) ) - object pending = keys[key] - if pending.projectId.toStr() != project.id.toStr() or normalizeUsername(pending.buyer.toStr()) != buyerLower ( - c.badRequest("this purchase key does not match") + if !mine ( + c.badRequest("this purchase expired, start again") return ) - number owed = pending.price.toNum() - number priceLimit = mistwarpBenefitsForProject(project).maxProjectPrice.toNum() - if owed > priceLimit ( - owed = priceLimit - ) - - array splits = projectCommerceSplits(project) - if !verifyCommerceProjectPayment(paymentId, buyerLower, project, owed, splits) ( + if !completed.ok ( c.json(402, {ok: false, pending: true, error: "payment not received yet, try again in a moment"}) return ) - - string seller = project.owner.toStr() - number sellerAmount = ownerAmountFromSplits(project, owed, splits) - - keys.delete(key) - store.keys = keys - savePurchaseKeys(store) - - recordSale(project, buyer, owed, sellerAmount) - if addToLibrary(buyerLower, project.id.toStr()) ( - number savesNow = projectSaves(project) - project.saves = savesNow + 1 - ) - saveProject(project) - upsertIndexEntry(project) - siteBroadcastStats(project.id.toStr(), buyer, {saved: true}) - addPurchaseRecord(buyerLower, {projectId: project.id.toStr(), title: project.title, seller: seller, amount: owed, at: timestamp}) - addNotification(seller, buyer, "purchase", {projectId: project.id, projectTitle: project.title, amount: owed}) - - c.json(200, {ok: true, paidOut: true, project: projectResponse(project, c)}) + c.json(200, {ok: true, paidOut: true, project: projectResponse(completed.project.assert(object), c)}) ) diff --git a/rotur-payments.osl b/rotur-payments.osl new file mode 100644 index 0000000..af70766 --- /dev/null +++ b/rotur-payments.osl @@ -0,0 +1,218 @@ +// Payments through Rotur payment requests: +// https://docs.rotur.dev/build-an-app/payments +// +// mistwarp-api asks Rotur, with the app's credentials, for someone to pay. They +// approve it on rotur.dev with their password, Rotur moves the credits (shared +// between everyone a sale pays), and Rotur tells MistWarp with the +// payment.completed webhook. MistWarp never holds a permission to spend +// anyone's credits. +// +// Each purchase key (data/purchase-keys.json) remembers its payment request. +// The key is the request's reference, so the webhook knows which purchase was +// paid, and the editor's confirm call asks Rotur directly if the webhook hasn't +// come yet. + +// MistWarp's share of a sale goes to its own Rotur account: MISTWARP_ROTUR_USER, +// or the MistWarp Rotur App's owner. +def mistwarpFeeAccount() string ( + if mistwarpRoturUser != "" ( + return mistwarpRoturUser + ) + if roturAppOwnerCache.has("owner") ( + return roturAppOwnerCache.get("owner").toStr() + ) + object result = roturApp("GET", "", {}) + string owner = "" + if result.ok ( + owner = (result.data.owner.username ?? "").toStr() + ) + if owner != "" ( + roturAppOwnerCache.set("owner", owner) + ) + return owner +) + +// Asks Rotur for a payment of amount from payer to payee, shared by splits +// ([{username, basis_points}]) when there is more than one. Returns {ok, id, +// approveUrl} or {ok: false, error}. +def requestRoturPayment(string payer, string payee, array splits, number amount, string note, string reference, string returnUrl) object ( + object body = {payer: roturUserRef(payer), "to": roturUserRef(payee), amount: amount, note: note.trim(1, 160), reference: reference} + if splits.len > 1 ( + array shares = [] + for i splits.len ( + object split = splits[i].assert(object) + shares.append({"to": roturUserRef(split.username.toStr()), basis_points: split.basis_points}) + ) + body.splits = shares + ) + if returnUrl != "" ( + body.return_url = returnUrl + ) + object result = roturApp("POST", "/payment-requests", body) + if !result.ok and (result.data.code ?? "").toStr() == "invalid_return_url" ( + // The editor's page isn't on one of the app's origins: no way back, but + // the editor still sees the window close. + body.delete("return_url") + result = roturApp("POST", "/payment-requests", body) + ) + if !result.ok ( + return {ok: false, error: (result.data.error ?? "payments are not available right now").toStr()} + ) + number expiresAt = (result.data.expires_at ?? 0).toNum() + if expiresAt <= 0 ( + // Rotur's requests last 15 minutes. + expiresAt = timestamp + 900000 + ) + return {ok: true, id: result.data.id.toStr(), approveUrl: result.data.approve_url.toStr(), expiresAt: expiresAt} +) + +// Rotur refuses splits that pay the payer, as when someone buys a remix of +// their own project, or the fee account buys something. Their share goes to +// the next person in the splits instead. +def splitsWithoutPayer(array splits, string payer) array ( + array kept = [] + number carried = 0 + for i splits.len ( + object split = splits[i].assertElse(object, {}) + number points = (split.basis_points ?? 0).toNum().toInt() + carried + if split.username.toStr().toLower() == payer.toLower() ( + carried = points + ) else ( + kept.append({username: split.username.toStr(), basis_points: points}) + carried = 0 + ) + ) + if carried > 0 and kept.len > 0 ( + object last = kept[kept.len].assertElse(object, {}) + last.basis_points = last.basis_points.toNum().toInt() + carried + kept[kept.len] = last + ) + return kept +) + +// The same purchase, started again before it was paid: everything the caller +// said about it matches, and Rotur's request has a minute or more left. +def samePurchase(object stored, object entry, string prefix, string key) boolean ( + if !key.startsWith(prefix) or stored.paid == true or (stored.expiresAt ?? 0).toNum() < timestamp + 60000 or (stored.approveUrl ?? "").toStr() == "" ( + return false + ) + array fields = entry.getKeys() + for i fields.len ( + string field = fields[i].toStr() + if json.stringify(stored[field]) != json.stringify(entry[field]) ( + return false + ) + ) + return true +) + +// Rotur's status for a payment request: "pending", "paid", "declined", +// "cancelled" or "expired", or "" if it couldn't be read. +def roturPaymentStatus(string requestId) string ( + object result = roturApp("GET", "/payment-requests/" ++ url.escape(requestId), {}) + if !result.ok ( + return "" + ) + return (result.data.status ?? "").toStr() +) + +def roturPaymentPaid(string requestId, string reference) boolean ( + if requestId == "" ( + return false + ) + object result = roturApp("GET", "/payment-requests/" ++ url.escape(requestId), {}) + return result.ok and result.data.status == "paid" and (result.data.reference ?? "").toStr() == reference +) + +// Starts a purchase: saves its key and asks Rotur for the payment. Returns what +// the editor needs to open Rotur's window, with the splits Rotur was given, or +// {ok: false, error}. The same purchase started again while its request is +// still open gets that request back, so one purchase is only ever one payment. +def startPurchase(string prefix, object entry, string payer, string payee, array splits, number amount, string note, string returnUrl) object ( + array shares = splitsWithoutPayer(splits, payer) + entry.splits = shares + // One start at a time for the same purchase, so two clicks can't both miss + // the open request and make two. + string lock = "purchase-start:" ++ prefix ++ json.stringify(entry) + sync.lock(lock) + object open = loadPurchaseKeys().keys.assertElse(object, {}) + array openKeys = open.getKeys() + for i openKeys.len ( + string openKey = openKeys[i].toStr() + object stored = open[openKey].assertElse(object, {}) + // Only a request still waiting for an answer is reused. A declined one + // would leave the person unable to try again until it expired. + if samePurchase(stored, entry, prefix, openKey) and roturPaymentStatus(stored.requestId.toStr()) == "pending" ( + sync.unlock(lock) + return {ok: true, key: openKey, requestId: stored.requestId.toStr(), approveUrl: stored.approveUrl.toStr(), splits: shares} + ) + ) + string key = prefix ++ randomString(16) + object request = requestRoturPayment(payer, payee, shares, amount, note, key, returnUrl) + if !request.ok ( + sync.unlock(lock) + return request + ) + entry.requestId = request.id + entry.approveUrl = request.approveUrl + entry.expiresAt = request.expiresAt + entry.at = timestamp + sync.lock("purchase-keys") + object store = prunePurchaseKeys(loadPurchaseKeys()) + object keys = store.keys + keys[key] = entry + store.keys = keys + savePurchaseKeys(store) + sync.unlock("purchase-keys") + sync.unlock(lock) + return {ok: true, key: key, requestId: request.id, approveUrl: request.approveUrl, splits: shares} +) + +// The purchase key's entry, once it has been paid, else {}. Rotur is asked if +// the webhook hasn't said so yet. +def paidPurchase(string key) object ( + object keys = loadPurchaseKeys().keys + if key == "" or !keys.contains(key) ( + return {} + ) + object entry = keys[key].assert(object) + if entry.paid != true and !roturPaymentPaid((entry.requestId ?? "").toStr(), key) ( + return {} + ) + entry.paid = true + return entry +) + +def forgetPurchase(string key) ( + sync.lock("purchase-keys") + object store = loadPurchaseKeys() + object keys = store.keys + keys.delete(key) + store.keys = keys + savePurchaseKeys(store) + sync.unlock("purchase-keys") +) + +// payment.completed: mark the purchase paid, and deliver what needs no more +// from the buyer. Donations and refunds wait for the comment or the revoke +// that started them. +def completeRoturPayment(string reference, string requestId) ( + sync.lock("purchase-keys") + object store = loadPurchaseKeys() + object keys = store.keys + if !keys.contains(reference) or (keys[reference].requestId ?? "").toStr() != requestId ( + sync.unlock("purchase-keys") + return + ) + object entry = keys[reference].assert(object) + entry.paid = true + keys[reference] = entry + store.keys = keys + savePurchaseKeys(store) + sync.unlock("purchase-keys") + if reference.startsWith("mwbuy_") ( + completeProjectPurchase(reference) + ) else if reference.startsWith("mwgame_") ( + completeGameProductPurchase(reference) + ) +) diff --git a/rotur-payments.test.osl b/rotur-payments.test.osl new file mode 100644 index 0000000..e15fc74 --- /dev/null +++ b/rotur-payments.test.osl @@ -0,0 +1,182 @@ +import "std:testing" +import "std:fs" +import "std:json" +import "std:sync" +import "std:cache" +import "std:url" + +string dir = "/tmp/mistwarp-rotur-payments-" ++ timestamp.toStr() ++ "/" +fs.mkdirAll(dir) +string purchaseKeysFile = dir ++ "purchase-keys.json" +string mistwarpRoturUser = "" +auto roturAppOwnerCache = cache.create(4, 3600) + +def readFile(string path) object ( + if !fs.exists(path) ( + return {ok: false} + ) + return {ok: true, data: json.parse(fs.readFile(path), {type: "object"}).unwrap()} +) + +def writeFile(string path, object data) boolean ( + fs.writeFile(path, json.stringify(data)) + return true +) + +def loadPurchaseKeys() object ( + auto result = readFile(purchaseKeysFile) + if !result.ok ( + return {keys: {}} + ) + return result.data.assert(object) +) + +def savePurchaseKeys(object store) boolean ( + return writeFile(purchaseKeysFile, store) +) + +def prunePurchaseKeys(object store) object ( + return store +) + +number keyCount = 0 +def randomString(number length) string ( + keyCount += 1 + return "k" ++ keyCount.toStr() +) + +def roturUserRef(string username) string ( + if username == "sam" ( + return "u-sam" + ) + return username +) + +// A pretend Rotur: payment requests by ID, and every call made. +array calls = [] +object requests = {} +def roturApp(string method, string path, object body) object ( + calls.append({method: method, path: path, body: body}) + if method == "GET" and path == "" ( + return {ok: true, status: 200, data: {owner: {username: "mist"}}} + ) + if method == "POST" and path == "/payment-requests" ( + if body.contains("return_url") and body.return_url.toStr().startsWith("https://evil") ( + return {ok: false, status: 400, data: {code: "invalid_return_url", error: "not one of the app's origins"}} + ) + if body.amount.toNum() <= 0 ( + return {ok: false, status: 400, data: {code: "invalid_amount", error: "amount must be positive"}} + ) + string id = "payreq_" ++ (requests.getKeys().len + 1).toStr() + requests[id] = {id: id, status: "pending", reference: body.reference} + return {ok: true, status: 201, data: {id: id, approve_url: "https://rotur.dev/pay/approve/" ++ id}} + ) + if method == "GET" and path.startsWith("/payment-requests/") ( + string id = path.split("/")[3] + if requests.contains(id) ( + return {ok: true, status: 200, data: requests[id]} + ) + return {ok: false, status: 404, data: {}} + ) + return {ok: false, status: 404, data: {}} +) + +array delivered = [] +def completeProjectPurchase(string key) object ( + delivered.append(key) + return {ok: true} +) +def completeGameProductPurchase(string key) object ( + delivered.append(key) + return {ok: true} +) + +import "./rotur-payments.osl" + +// MistWarp's share goes to the app owner unless MISTWARP_ROTUR_USER says otherwise. +testing.assert(mistwarpFeeAccount() == "mist", "the app owner gets MistWarp's share") +mistwarpFeeAccount() +number ownerLookups = 0 +for i calls.len ( + if calls[i].method == "GET" and calls[i].path == "" ( + ownerLookups += 1 + ) +) +testing.assert(ownerLookups == 1, "the owner is looked up once") + +// A sale shared between people asks Rotur for one request with splits. +object sale = startPurchase("mwbuy_", {projectId: "p1", buyer: "sam", price: 10}, "sam", "kit", [{username: "kit", basis_points: 9000}, {username: "mist", basis_points: 1000}], 10, "A game", "https://mistwarp.org/projects/p1") +testing.assert(sale.ok and sale.key == "mwbuy_k1" and sale.approveUrl == "https://rotur.dev/pay/approve/" ++ sale.requestId, "starts a purchase: " ++ json.stringify(sale)) +object asked = calls[calls.len].body +testing.assert(asked.payer == "u-sam" and asked["to"] == "kit" and asked.amount == 10 and asked.reference == sale.key, "asks the buyer to pay the creator, with the key as reference") +testing.assert(asked.splits.len == 2 and asked.splits[1].basis_points == 9000 and asked.splits[2]["to"] == "mist", "shares the sale") +testing.assert(asked.return_url == "https://mistwarp.org/projects/p1", "comes back to the page") + +// One person paid needs no splits. +object tip = startPurchase("mwdonate_", {kind: "comment_donation", projectId: "p1", buyer: "sam", amount: 2}, "sam", "kit", [], 2, "Donation", "") +testing.assert(tip.ok and !calls[calls.len].body.assert(object).contains("splits") and !calls[calls.len].body.assert(object).contains("return_url"), "a donation goes to one person") + +// Starting the same purchase again while its request is open gets that +// request back, not a second one to pay. +number postsBefore = calls.len +object again = startPurchase("mwbuy_", {projectId: "p1", buyer: "sam", price: 10}, "sam", "kit", [{username: "kit", basis_points: 9000}, {username: "mist", basis_points: 1000}], 10, "A game", "") +testing.assert(again.ok and again.key == sale.key and again.requestId == sale.requestId and again.approveUrl == sale.approveUrl, "reuses the open request: " ++ json.stringify(again)) +testing.assert(calls.len == postsBefore + 1 and calls[calls.len].method == "GET", "only checks the open request is still pending") +// A declined request isn't reused, so the person can try again straight away. +requests[sale.requestId].status = "declined" +object afterDecline = startPurchase("mwbuy_", {projectId: "p1", buyer: "sam", price: 10}, "sam", "kit", [{username: "kit", basis_points: 9000}, {username: "mist", basis_points: 1000}], 10, "A game", "") +testing.assert(afterDecline.ok and afterDecline.key != sale.key and afterDecline.requestId != sale.requestId, "a declined request gets a new one") +requests[sale.requestId].status = "pending" +object otherPrice = startPurchase("mwbuy_", {projectId: "p1", buyer: "sam", price: 12}, "sam", "kit", [], 12, "A game", "") +testing.assert(otherPrice.ok and otherPrice.key != sale.key, "a different price is a different purchase") +object store = loadPurchaseKeys() +store.keys[otherPrice.key].expiresAt = timestamp + 30000 +savePurchaseKeys(store) +object afterExpiry = startPurchase("mwbuy_", {projectId: "p1", buyer: "sam", price: 12}, "sam", "kit", [], 12, "A game", "") +testing.assert(afterExpiry.ok and afterExpiry.key != otherPrice.key, "a request about to expire isn't reused") + +// The payer is never in the splits: their share goes to the next person. +array shares = splitsWithoutPayer([{username: "mist", basis_points: 1000}, {username: "Sam", basis_points: 1000}, {username: "kit", basis_points: 8000}], "sam") +testing.assert(json.stringify(shares) == json.stringify([{username: "mist", basis_points: 1000}, {username: "kit", basis_points: 9000}]), "a remix parent buying gives their share on: " ++ json.stringify(shares)) +shares = splitsWithoutPayer([{username: "kit", basis_points: 9000}, {username: "mist", basis_points: 1000}], "mist") +testing.assert(json.stringify(shares) == json.stringify([{username: "kit", basis_points: 10000}]), "the fee account buying gives its share to the one before it: " ++ json.stringify(shares)) +object ownSale = startPurchase("mwbuy_", {projectId: "p2", buyer: "mist", price: 10}, "mist", "kit", [{username: "kit", basis_points: 9000}, {username: "mist", basis_points: 1000}], 10, "A game", "") +testing.assert(ownSale.ok and !calls[calls.len].body.assert(object).contains("splits") and loadPurchaseKeys().keys[ownSale.key].splits.len == 1, "with only the creator left, no splits are sent, and the key keeps what was used") + +// A page Rotur won't send people back to still gets a request. +object elsewhere = startPurchase("mwbuy_", {projectId: "p1", buyer: "sam", price: 1}, "sam", "kit", [], 1, "A game", "https://evil.example/") +testing.assert(elsewhere.ok and !calls[calls.len].body.assert(object).contains("return_url"), "retries without the return URL") + +object refused = startPurchase("mwbuy_", {projectId: "p1", buyer: "sam", price: 0}, "sam", "kit", [], 0, "A game", "") +testing.assert(!refused.ok and refused.error == "amount must be positive", "passes Rotur's refusal on") +testing.assert(!loadPurchaseKeys().keys.assert(object).contains("mwbuy_k" ++ keyCount.toStr()), "a refused request saves no key") + +// Nothing counts as paid until Rotur says so. +testing.assert(paidPurchase(sale.key).len == 0, "an unpaid purchase is not paid") +testing.assert(paidPurchase("mwbuy_nope").len == 0, "an unknown key is not paid") +testing.assert(paidPurchase("").len == 0, "no key is not paid") + +// The editor's confirm can ask Rotur before the webhook comes. +requests[sale.requestId].status = "paid" +testing.assert(paidPurchase(sale.key).paid == true, "a paid request is paid") +requests[tip.requestId].status = "paid" +requests[tip.requestId].reference = "mwdonate_other" +testing.assert(paidPurchase(tip.key).len == 0, "a paid request for another reference doesn't count") + +// The webhook marks the purchase paid and delivers sales. +completeRoturPayment(sale.key, "payreq_wrong") +testing.assert(delivered.len == 0 and loadPurchaseKeys().keys[sale.key].paid != true, "ignores a request that isn't the key's") +completeRoturPayment(sale.key, sale.requestId) +testing.assert(delivered.len == 1 and delivered[1] == sale.key, "delivers a paid sale") +testing.assert(loadPurchaseKeys().keys[sale.key].paid == true, "remembers it was paid") +completeRoturPayment(tip.key, tip.requestId) +testing.assert(delivered.len == 1, "a donation waits for its comment") +requests[tip.requestId].status = "pending" +testing.assert(paidPurchase(tip.key).paid == true, "once the webhook says so, Rotur isn't asked again") +completeRoturPayment("mwbuy_unknown", "payreq_1") +testing.assert(delivered.len == 1, "ignores unknown references") + +forgetPurchase(sale.key) +testing.assert(!loadPurchaseKeys().keys.assert(object).contains(sale.key), "forgets a delivered purchase") + +fs.remove(dir) diff --git a/rotur-webhooks.osl b/rotur-webhooks.osl index 26a84d9..00bbf3d 100644 --- a/rotur-webhooks.osl +++ b/rotur-webhooks.osl @@ -4,7 +4,9 @@ // leaves MistWarp from rotur.dev/me/apps (user.left) or is banned from Rotur // (user.banned). MistWarp must then delete what it holds about them within 30 // days, so it does it straight away. With privacy requests turned on, people -// can also ask for a copy of their data or for it to be deleted. +// can also ask for a copy of their data or for it to be deleted. When someone +// approves a payment request, payment.completed says which purchase was paid +// (rotur-payments.osl). // // Rotur waits 10 seconds for an answer, and erasing someone can take longer, // so each delivery is saved to disk, answered, then handled by a worker. Saved @@ -69,6 +71,8 @@ def queueRoturWebhook(object event) boolean ( type: event.type.toStr(), userId: (data.user_id ?? "").toStr(), kind: (data.kind ?? "").toStr(), + reference: (data.reference ?? "").toStr(), + paymentRequest: (data.payment_request ?? "").toStr(), received: timestamp, done: false } @@ -94,6 +98,10 @@ def markRoturWebhookDone(string id) ( def handleRoturEvent(object event) ( string type = event.type.toStr() + if type == "payment.completed" ( + completeRoturPayment((event.reference ?? "").toStr(), (event.paymentRequest ?? "").toStr()) + return + ) string userId = event.userId.toStr() if userId == "" or isStudentUserId(userId) ( return diff --git a/rotur-webhooks.test.osl b/rotur-webhooks.test.osl index 8250c48..1fd0d2a 100644 --- a/rotur-webhooks.test.osl +++ b/rotur-webhooks.test.osl @@ -50,6 +50,11 @@ def addNotification(string target, string actor, string notifType, object payloa sent.append({target: target, type: notifType, message: payload.message}) ) +array completed = [] +def completeRoturPayment(string reference, string requestId) ( + completed.append(reference ++ "|" ++ requestId) +) + import "./rotur-webhooks.osl" roturWebhooksFile = dir ++ "rotur-webhooks.json" @@ -76,11 +81,13 @@ queueRoturWebhook({id: "evt_3", type: "user.banned", data: {user_id: "mwc_studen queueRoturWebhook({id: "evt_4", type: "privacy.request", data: {user_id: "u-sam", kind: "access"}}) queueRoturWebhook({id: "evt_5", type: "privacy.request", data: {user_id: "u-sam", kind: "erasure"}}) queueRoturWebhook({id: "evt_6", type: "app.test", data: {message: "This is a test from Rotur."}}) +queueRoturWebhook({id: "evt_7", type: "payment.completed", data: {payment_request: "payreq_1", reference: "mwbuy_abc", user_id: "u-sam", amount: 5}}) processRoturWebhooks() testing.assert(erased.len == 3, "erases on leaving, deleting the account and an erasure request: " ++ json.stringify(erased)) testing.assert(erased.contains("u-sam|sam"), "erases someone MistWarp knows") testing.assert(erased.contains("u-unknown|"), "still erases what is keyed by ID for someone it doesn't") testing.assert(!erased.contains("mwc_student|"), "never acts on classroom students") +testing.assert(completed.len == 1 and completed[1] == "mwbuy_abc|payreq_1", "hands a completed payment to its purchase: " ++ json.stringify(completed)) testing.assert(sent.len == 1 and sent[1].target == "sam" and sent[1].type == "moderation", "answers an access request in MistWarp") processRoturWebhooks()