@pithy-sh/payments 0.3.9 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/client/api.d.ts +19 -0
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +26 -1
- package/dist/client/hooks.d.ts +43 -0
- package/dist/client/hooks.d.ts.map +1 -1
- package/dist/client/hooks.js +58 -2
- package/dist/client/paddleLink.d.ts +31 -0
- package/dist/client/paddleLink.d.ts.map +1 -0
- package/dist/client/paddleLink.js +37 -0
- package/dist/data/paddleIds.d.ts +28 -0
- package/dist/data/paddleIds.d.ts.map +1 -0
- package/dist/data/paddleIds.js +73 -0
- package/dist/entitlement/unimplementedSubject.d.ts.map +1 -1
- package/dist/entitlement/unimplementedSubject.js +3 -2
- package/dist/http/responses.d.ts +23 -5
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +24 -7
- package/dist/http/routes.d.ts +6 -2
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +210 -38
- package/dist/http/schemas.d.ts +21 -1
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +20 -2
- package/dist/http/webhookGuard.d.ts.map +1 -1
- package/dist/http/webhookGuard.js +1 -1
- package/dist/rails/paddle/events.d.ts.map +1 -1
- package/dist/rails/paddle/events.js +2 -1
- package/dist/rails/paddle/refresh.d.ts +10 -5
- package/dist/rails/paddle/refresh.d.ts.map +1 -1
- package/dist/rails/paddle/refresh.js +8 -5
- package/dist/rails/paddle/refund.d.ts.map +1 -1
- package/dist/rails/paddle/refund.js +10 -2
- package/dist/rails/paddle/subscription.d.ts.map +1 -1
- package/dist/rails/paddle/subscription.js +8 -3
- package/dist/rails/paddle/verify.d.ts.map +1 -1
- package/dist/rails/paddle/verify.js +2 -3
- package/dist/secret/registry.d.ts.map +1 -1
- package/dist/secret/registry.js +3 -2
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/dist/workflows/workerConfig.d.ts.map +1 -1
- package/dist/workflows/workerConfig.js +8 -2
- package/docs/paddle.md +17 -2
- package/package.json +6 -6
- package/src/client/api.ts +35 -0
- package/src/client/hooks.ts +78 -0
- package/src/client/paddleLink.ts +41 -0
- package/src/data/paddleIds.ts +74 -0
- package/src/entitlement/unimplementedSubject.ts +3 -4
- package/src/http/responses.ts +33 -6
- package/src/http/routes.ts +729 -454
- package/src/http/schemas.ts +32 -1
- package/src/http/webhookGuard.ts +3 -2
- package/src/rails/paddle/events.ts +2 -1
- package/src/rails/paddle/refresh.ts +17 -10
- package/src/rails/paddle/refund.ts +10 -2
- package/src/rails/paddle/subscription.ts +8 -3
- package/src/rails/paddle/verify.ts +6 -4
- package/src/secret/registry.ts +3 -2
- package/src/version.generated.ts +1 -1
- package/src/workflows/workerConfig.ts +9 -3
package/src/http/routes.ts
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
-
import { zValidator } from "@hono/zod-validator";
|
|
6
5
|
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
7
6
|
import { safeEmit } from "@pithy-sh/core/src/controlPlane/audit/actions";
|
|
8
7
|
import type { ControlPlaneContext } from "@pithy-sh/core/src/controlPlane/context";
|
|
9
8
|
import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
|
|
10
9
|
import { InternalError, NotFoundError, PithyError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
11
10
|
import { memoryJwksCache } from "@pithy-sh/core/src/http/oidcWebhook";
|
|
12
|
-
import {
|
|
11
|
+
import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
|
|
12
|
+
import { validate } from "@pithy-sh/core/src/http/validation";
|
|
13
13
|
import { resolveWorkflowBinding } from "@pithy-sh/core/src/workflow/dispatch";
|
|
14
14
|
import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
|
|
15
15
|
import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
|
|
@@ -76,7 +76,7 @@ import { type RailTrustOptions, resolveRailProvider } from "../rails/providers";
|
|
|
76
76
|
import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/registry";
|
|
77
77
|
import { PAYMENTS_CAPABILITY, paymentsWorkflows } from "../workflows/specs";
|
|
78
78
|
import { requireAuth } from "./guards";
|
|
79
|
-
import
|
|
79
|
+
import {
|
|
80
80
|
PaymentsAdminCatalogResponse,
|
|
81
81
|
PaymentsAdminDiscountsResponse,
|
|
82
82
|
PaymentsAdminEntitlementsResponse,
|
|
@@ -91,17 +91,18 @@ import type {
|
|
|
91
91
|
PaymentsEntitlementsResponse,
|
|
92
92
|
PaymentsPortalHandoffResponse,
|
|
93
93
|
PaymentsPricingEnvelope,
|
|
94
|
-
PaymentsPricingResponse,
|
|
94
|
+
type PaymentsPricingResponse,
|
|
95
95
|
PaymentsPurchaseResponse,
|
|
96
|
-
PaymentsQuotedFrom,
|
|
97
|
-
PaymentsRefundRequest,
|
|
96
|
+
type PaymentsQuotedFrom,
|
|
97
|
+
type PaymentsRefundRequest,
|
|
98
98
|
PaymentsRefundResponse,
|
|
99
99
|
PaymentsRestoreResponse,
|
|
100
|
-
PaymentsSubscriptionQuote,
|
|
100
|
+
type PaymentsSubscriptionQuote,
|
|
101
101
|
PaymentsSubscriptionQuoteResponse,
|
|
102
102
|
PaymentsSubscriptionResponse,
|
|
103
103
|
PaymentsSubscriptionStandingResponse,
|
|
104
|
-
PaymentsSubscriptionView,
|
|
104
|
+
type PaymentsSubscriptionView,
|
|
105
|
+
PaymentsWebhookAck,
|
|
105
106
|
} from "./responses";
|
|
106
107
|
import {
|
|
107
108
|
AdminDiscountsQuery,
|
|
@@ -117,6 +118,7 @@ import {
|
|
|
117
118
|
EntitlementRevokeRequest,
|
|
118
119
|
GoogleWebhookNotification,
|
|
119
120
|
LemonSqueezyWebhookNotification,
|
|
121
|
+
PaddleResumeQuery,
|
|
120
122
|
PaddleWebhookNotification,
|
|
121
123
|
PurchaseSubmission,
|
|
122
124
|
RestoreRequest,
|
|
@@ -165,6 +167,8 @@ import { completeWebhook, requireSignedWebhook, verifiedWebhook } from "./webhoo
|
|
|
165
167
|
* (bearer | session) —
|
|
166
168
|
* POST /payments/checkout → a hosted checkout, on whichever rail sells the product
|
|
167
169
|
* (bearer | session) json: CheckoutRequest
|
|
170
|
+
* GET /payments/checkout/resume → open the transaction a `_ptxn` link arrived for
|
|
171
|
+
* (none) query: PaddleResumeQuery
|
|
168
172
|
* POST /payments/portal → a billing-portal session (bearer | session) —
|
|
169
173
|
* GET /payments/subscription → where the caller's subscription stands, read live
|
|
170
174
|
* (bearer | session) —
|
|
@@ -231,8 +235,10 @@ import { completeWebhook, requireSignedWebhook, verifiedWebhook } from "./webhoo
|
|
|
231
235
|
* selects a verifier through `resolveRailProvider`, and everything past that point is the normalized event. A
|
|
232
236
|
* rail arriving is one entry in `rails/providers.ts`, not a case in a handler.
|
|
233
237
|
*
|
|
234
|
-
* **
|
|
235
|
-
*
|
|
238
|
+
* **One `public` route, and only one.** `GET /checkout/resume` opens the transaction a Paddle payment link
|
|
239
|
+
* arrived for, and the person following that link may not be signed in. Every other caller is either an
|
|
240
|
+
* authenticated user acting on their own purchases or a machine proving authenticity. Turnstile has nothing
|
|
241
|
+
* to gate here.
|
|
236
242
|
*
|
|
237
243
|
* **`signed-webhook` is one strategy over three unrelated mechanisms** — Apple signs a JWS against its
|
|
238
244
|
* certificate chain, Google's Pub/Sub push carries an OIDC token verified with an audience check, Stripe sends
|
|
@@ -1328,13 +1334,23 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1328
1334
|
* No query at all, and none to add: the catalog is small, fixed at deploy, and has no page. What
|
|
1329
1335
|
* crosses is decided by `adminCatalogView` and asserted as an invariant rather than as a field list.
|
|
1330
1336
|
*/
|
|
1331
|
-
app.get(
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1337
|
+
app.get(
|
|
1338
|
+
`${base}/admin/catalog`,
|
|
1339
|
+
describeRoute({
|
|
1340
|
+
summary: "Read what this project sells, and the keys it comps by hand.",
|
|
1341
|
+
verification: "control-plane",
|
|
1342
|
+
scopes: [PAYMENTS_CATALOG_READ_SCOPE],
|
|
1343
|
+
responses: { 200: PaymentsAdminCatalogResponse },
|
|
1344
|
+
}),
|
|
1345
|
+
requireControlPlane(PAYMENTS_CATALOG_READ_SCOPE),
|
|
1346
|
+
async (c) => {
|
|
1347
|
+
const view = adminCatalogView(config);
|
|
1348
|
+
await recordRead(c, PaymentsAuditActions.catalogRead, null, {
|
|
1349
|
+
products: view.enabled ? view.products.length : 0,
|
|
1350
|
+
});
|
|
1351
|
+
return c.json(view satisfies PaymentsAdminCatalogResponse, 200);
|
|
1352
|
+
},
|
|
1353
|
+
);
|
|
1338
1354
|
|
|
1339
1355
|
/**
|
|
1340
1356
|
* CONTROL PLANE. The purchase log, paged, newest first.
|
|
@@ -1346,8 +1362,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1346
1362
|
*/
|
|
1347
1363
|
app.get(
|
|
1348
1364
|
`${base}/admin/purchases`,
|
|
1365
|
+
describeRoute({
|
|
1366
|
+
summary: "Read the purchase log, newest first.",
|
|
1367
|
+
verification: "control-plane",
|
|
1368
|
+
scopes: [PAYMENTS_PURCHASES_READ_SCOPE],
|
|
1369
|
+
responses: { 200: PaymentsAdminPurchasesResponse },
|
|
1370
|
+
}),
|
|
1349
1371
|
requireControlPlane(PAYMENTS_PURCHASES_READ_SCOPE),
|
|
1350
|
-
|
|
1372
|
+
validate("query", AdminPurchasesQuery),
|
|
1351
1373
|
async (c) => {
|
|
1352
1374
|
const query = c.req.valid("query");
|
|
1353
1375
|
const subject = subjectFilter(query);
|
|
@@ -1392,8 +1414,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1392
1414
|
*/
|
|
1393
1415
|
app.get(
|
|
1394
1416
|
`${base}/admin/subscriptions`,
|
|
1417
|
+
describeRoute({
|
|
1418
|
+
summary: "Read the purchases that renew, newest first.",
|
|
1419
|
+
verification: "control-plane",
|
|
1420
|
+
scopes: [PAYMENTS_SUBSCRIPTIONS_READ_SCOPE],
|
|
1421
|
+
responses: { 200: PaymentsAdminSubscriptionsResponse },
|
|
1422
|
+
}),
|
|
1395
1423
|
requireControlPlane(PAYMENTS_SUBSCRIPTIONS_READ_SCOPE),
|
|
1396
|
-
|
|
1424
|
+
validate("query", AdminSubscriptionsQuery),
|
|
1397
1425
|
async (c) => {
|
|
1398
1426
|
const query = c.req.valid("query");
|
|
1399
1427
|
const subject = subjectFilter(query);
|
|
@@ -1431,8 +1459,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1431
1459
|
*/
|
|
1432
1460
|
app.get(
|
|
1433
1461
|
`${base}/admin/entitlements`,
|
|
1462
|
+
describeRoute({
|
|
1463
|
+
summary: "Read the entitlement model, page by page.",
|
|
1464
|
+
verification: "control-plane",
|
|
1465
|
+
scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
|
|
1466
|
+
responses: { 200: PaymentsAdminEntitlementsResponse },
|
|
1467
|
+
}),
|
|
1434
1468
|
requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE),
|
|
1435
|
-
|
|
1469
|
+
validate("query", AdminEntitlementsQuery),
|
|
1436
1470
|
async (c) => {
|
|
1437
1471
|
const query = c.req.valid("query");
|
|
1438
1472
|
const now = clock();
|
|
@@ -1479,8 +1513,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1479
1513
|
*/
|
|
1480
1514
|
app.get(
|
|
1481
1515
|
`${base}/admin/entitlements/:subjectType/:subjectId`,
|
|
1516
|
+
describeRoute({
|
|
1517
|
+
summary: "Read one subject's entitlements, resolved now.",
|
|
1518
|
+
verification: "control-plane",
|
|
1519
|
+
scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
|
|
1520
|
+
responses: { 200: PaymentsAdminSubjectEntitlementsResponse },
|
|
1521
|
+
}),
|
|
1482
1522
|
requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE),
|
|
1483
|
-
|
|
1523
|
+
validate("param", AdminSubjectParam),
|
|
1484
1524
|
async (c) => {
|
|
1485
1525
|
const subject = c.req.valid("param");
|
|
1486
1526
|
const now = clock();
|
|
@@ -1512,8 +1552,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1512
1552
|
*/
|
|
1513
1553
|
app.get(
|
|
1514
1554
|
`${base}/admin/reconcile-runs`,
|
|
1555
|
+
describeRoute({
|
|
1556
|
+
summary: "Read the reconciliation passes this deployment has run.",
|
|
1557
|
+
verification: "control-plane",
|
|
1558
|
+
scopes: [PAYMENTS_RECONCILE_READ_SCOPE],
|
|
1559
|
+
responses: { 200: PaymentsAdminReconcileRunsResponse },
|
|
1560
|
+
}),
|
|
1515
1561
|
requireControlPlane(PAYMENTS_RECONCILE_READ_SCOPE),
|
|
1516
|
-
|
|
1562
|
+
validate("query", AdminReconcileRunsQuery),
|
|
1517
1563
|
async (c) => {
|
|
1518
1564
|
const query = c.req.valid("query");
|
|
1519
1565
|
const page = await listReconcileRuns(database(c), query);
|
|
@@ -1550,50 +1596,60 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1550
1596
|
* pass happen, and answering 202 while nothing started is the failure this codebase spends its comments
|
|
1551
1597
|
* avoiding — so the binding is resolved directly and its absence is a refusal naming what to deploy.
|
|
1552
1598
|
*
|
|
1553
|
-
*
|
|
1554
|
-
*
|
|
1599
|
+
* Every press that is not refused starts a pass and answers `started: true`. A second press while one is
|
|
1600
|
+
* in flight starts a second: the pass is idempotent, so two converge on the same repairs.
|
|
1555
1601
|
*/
|
|
1556
|
-
app.post(
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1602
|
+
app.post(
|
|
1603
|
+
`${base}/admin/reconcile-runs`,
|
|
1604
|
+
describeRoute({
|
|
1605
|
+
summary: "Start a reconciliation pass now.",
|
|
1606
|
+
verification: "control-plane",
|
|
1607
|
+
scopes: [PAYMENTS_RECONCILE_RUN_SCOPE],
|
|
1608
|
+
responses: { 202: PaymentsAdminReconcileRunStarted },
|
|
1609
|
+
}),
|
|
1610
|
+
requireControlPlane(PAYMENTS_RECONCILE_RUN_SCOPE),
|
|
1611
|
+
async (c) => {
|
|
1612
|
+
const spec = paymentsWorkflows.reconcile;
|
|
1613
|
+
const binding = resolveWorkflowBinding(c.env as Record<string, unknown>, {
|
|
1614
|
+
binding: spec.binding,
|
|
1615
|
+
capability: PAYMENTS_CAPABILITY,
|
|
1616
|
+
log: c.var.log,
|
|
1568
1617
|
});
|
|
1569
|
-
|
|
1618
|
+
if (!binding) {
|
|
1619
|
+
// Named as a provisioning fact rather than a fault of the request: the caller's scope was right, the
|
|
1620
|
+
// route exists, and the job's host is not deployed here. `action` is what a person does about it.
|
|
1621
|
+
throw new PaymentsReconcileNotProvisionedError({
|
|
1622
|
+
detail: `Dispatching a reconciliation pass needs a Workflow binding named ${spec.binding} on this Worker.`,
|
|
1623
|
+
});
|
|
1624
|
+
}
|
|
1570
1625
|
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
const who = controlPlaneCaller(c);
|
|
1582
|
-
await c.var.emit({
|
|
1583
|
-
action: PaymentsAuditActions.reconcileRunStarted,
|
|
1584
|
-
outcome: "success",
|
|
1585
|
-
// The token's `sub`, so the trail names the person at the console rather than the console. One
|
|
1586
|
-
// connection is normally shared by everybody using it, and this row is the join to every repair the
|
|
1587
|
-
// pass then made.
|
|
1588
|
-
actorType: "control-plane",
|
|
1589
|
-
actorId: who.subject,
|
|
1590
|
-
resourceType: "reconcile_run",
|
|
1591
|
-
resourceId: runId,
|
|
1592
|
-
metadata: { deployment: deploymentName(c) },
|
|
1593
|
-
});
|
|
1626
|
+
// `create` answers `unknown` — the binding is structural, matched by having the method at all, and a
|
|
1627
|
+
// loopback stand-in under `pithy dev` answers a different shape from the Workflows runtime. Narrowed
|
|
1628
|
+
// here rather than cast: an instance with no readable id is a pass that started and cannot be named,
|
|
1629
|
+
// which is `runId: null` and a true sentence, not a reason to fail the press.
|
|
1630
|
+
const instance: unknown = await binding.create({ params: {} });
|
|
1631
|
+
const runId =
|
|
1632
|
+
typeof instance === "object" && instance !== null && "id" in instance && typeof instance.id === "string"
|
|
1633
|
+
? instance.id
|
|
1634
|
+
: null;
|
|
1594
1635
|
|
|
1595
|
-
|
|
1596
|
-
|
|
1636
|
+
const who = controlPlaneCaller(c);
|
|
1637
|
+
await c.var.emit({
|
|
1638
|
+
action: PaymentsAuditActions.reconcileRunStarted,
|
|
1639
|
+
outcome: "success",
|
|
1640
|
+
// The token's `sub`, so the trail names the person at the console rather than the console. One
|
|
1641
|
+
// connection is normally shared by everybody using it, and this row is the join to every repair the
|
|
1642
|
+
// pass then made.
|
|
1643
|
+
actorType: "control-plane",
|
|
1644
|
+
actorId: who.subject,
|
|
1645
|
+
resourceType: "reconcile_run",
|
|
1646
|
+
resourceId: runId,
|
|
1647
|
+
metadata: { deployment: deploymentName(c) },
|
|
1648
|
+
});
|
|
1649
|
+
|
|
1650
|
+
return c.json({ started: true, runId } satisfies PaymentsAdminReconcileRunStarted, 202);
|
|
1651
|
+
},
|
|
1652
|
+
);
|
|
1597
1653
|
|
|
1598
1654
|
/**
|
|
1599
1655
|
* AUTHED WRITE. The purchaser's own app submitting what the store SDK gave it, so the buyer sees their
|
|
@@ -1601,63 +1657,73 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1601
1657
|
* existing purchase — the write path is idempotent, so a repeat is not an error. A receipt belonging to
|
|
1602
1658
|
* somebody else is a 409, audited as denied.
|
|
1603
1659
|
*/
|
|
1604
|
-
app.post(
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1660
|
+
app.post(
|
|
1661
|
+
`${base}/purchases`,
|
|
1662
|
+
describeRoute({
|
|
1663
|
+
summary: "Verify a receipt and project the purchase.",
|
|
1664
|
+
verification: ["bearer", "session"],
|
|
1665
|
+
responses: { 200: PaymentsPurchaseResponse },
|
|
1666
|
+
}),
|
|
1667
|
+
requireAuth(),
|
|
1668
|
+
validate("json", PurchaseSubmission),
|
|
1669
|
+
async (c) => {
|
|
1670
|
+
const input = c.req.valid("json");
|
|
1671
|
+
// Resolved before the store is called: a caller acting for nobody has no row to write, so refusing here
|
|
1672
|
+
// costs no round trip and cannot leave a charged customer with an unattributed purchase.
|
|
1673
|
+
const subject = await requirePaymentsSubject(c, seam);
|
|
1674
|
+
try {
|
|
1675
|
+
const projection = await submit(c, subject, input.rail, input.receipt);
|
|
1676
|
+
await c.var.emit({
|
|
1677
|
+
action: PaymentsAuditActions.purchaseVerified,
|
|
1678
|
+
outcome: "success",
|
|
1679
|
+
// The person who submitted, always — the subject they act for rides in the metadata below. Under
|
|
1680
|
+
// organization billing the two differ, and collapsing them would answer "who did this" with a
|
|
1681
|
+
// company rather than with somebody who can be asked.
|
|
1682
|
+
actorType: "user",
|
|
1683
|
+
actorId: c.var.auth?.userId,
|
|
1684
|
+
sessionId: c.var.auth?.sessionId,
|
|
1685
|
+
resourceType: "purchase",
|
|
1686
|
+
resourceId: projection.purchase.id,
|
|
1687
|
+
// Identifiers and outcomes only. Never the receipt: the trail is long-lived and queryable, and a
|
|
1688
|
+
// receipt is a bearer artifact. The holder is two keys, never one joined string.
|
|
1689
|
+
metadata: {
|
|
1690
|
+
rail: input.rail,
|
|
1691
|
+
subjectType: subject.subjectType,
|
|
1692
|
+
subjectId: subject.subjectId,
|
|
1693
|
+
productId: projection.product.id,
|
|
1694
|
+
status: projection.purchase.status,
|
|
1695
|
+
outcome: projection.outcome,
|
|
1696
|
+
},
|
|
1697
|
+
});
|
|
1698
|
+
return c.json(
|
|
1699
|
+
{
|
|
1700
|
+
purchase: purchaseView(projection),
|
|
1701
|
+
entitlements: projection.entitlements.map((row) =>
|
|
1702
|
+
entitlementView({ key: row.entitlement, active: row.active, expiresAt: row.expiresAt }),
|
|
1703
|
+
),
|
|
1704
|
+
} satisfies PaymentsPurchaseResponse,
|
|
1705
|
+
200,
|
|
1706
|
+
);
|
|
1707
|
+
} catch (cause) {
|
|
1708
|
+
// A refused submission is the security-relevant event, so it is recorded before the error propagates.
|
|
1709
|
+
await c.var.emit({
|
|
1710
|
+
action: PaymentsAuditActions.purchaseVerified,
|
|
1711
|
+
outcome: "denied",
|
|
1712
|
+
severity: "warning",
|
|
1713
|
+
actorType: "user",
|
|
1714
|
+
actorId: c.var.auth?.userId,
|
|
1715
|
+
sessionId: c.var.auth?.sessionId,
|
|
1716
|
+
metadata: {
|
|
1717
|
+
rail: input.rail,
|
|
1718
|
+
subjectType: subject.subjectType,
|
|
1719
|
+
subjectId: subject.subjectId,
|
|
1720
|
+
reason: cause instanceof PithyError ? cause.payload.code : "unknown",
|
|
1721
|
+
},
|
|
1722
|
+
});
|
|
1723
|
+
throw cause;
|
|
1724
|
+
}
|
|
1725
|
+
},
|
|
1726
|
+
);
|
|
1661
1727
|
|
|
1662
1728
|
/**
|
|
1663
1729
|
* AUTHED READ. Always the caller's own holder — the subject comes from the seam, never the request, so
|
|
@@ -1669,14 +1735,23 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1669
1735
|
* already answers for somebody who has bought nothing — and a 403 here would make a paywall render an
|
|
1670
1736
|
* error where it should render the paywall.
|
|
1671
1737
|
*/
|
|
1672
|
-
app.get(
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1738
|
+
app.get(
|
|
1739
|
+
`${base}/entitlements`,
|
|
1740
|
+
describeRoute({
|
|
1741
|
+
summary: "Read the caller's own entitlements.",
|
|
1742
|
+
verification: ["bearer", "session"],
|
|
1743
|
+
responses: { 200: PaymentsEntitlementsResponse },
|
|
1744
|
+
}),
|
|
1745
|
+
requireAuth(),
|
|
1746
|
+
async (c) => {
|
|
1747
|
+
const subject = await resolvePaymentsSubject(c, seam);
|
|
1748
|
+
if (subject === undefined) {
|
|
1749
|
+
return c.json({ entitlements: [] } satisfies PaymentsEntitlementsResponse, 200);
|
|
1750
|
+
}
|
|
1751
|
+
const entitlements = await resolveEntitlements(paymentsDatabase(database(c)), subject, clock());
|
|
1752
|
+
return c.json({ entitlements: entitlements.map(entitlementView) } satisfies PaymentsEntitlementsResponse, 200);
|
|
1753
|
+
},
|
|
1754
|
+
);
|
|
1680
1755
|
|
|
1681
1756
|
/**
|
|
1682
1757
|
* AUTHED WRITE. Restore Purchases, client-driven because only the device can enumerate what its store
|
|
@@ -1687,42 +1762,58 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1687
1762
|
* success would hide it. Every receipt that did project stays projected — the writer is idempotent, so the
|
|
1688
1763
|
* client simply retries.
|
|
1689
1764
|
*/
|
|
1690
|
-
app.post(
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1765
|
+
app.post(
|
|
1766
|
+
`${base}/restore`,
|
|
1767
|
+
describeRoute({
|
|
1768
|
+
summary: "Restore purchases onto the caller's own holder.",
|
|
1769
|
+
verification: ["bearer", "session"],
|
|
1770
|
+
responses: { 200: PaymentsRestoreResponse },
|
|
1771
|
+
}),
|
|
1772
|
+
requireAuth(),
|
|
1773
|
+
validate("json", RestoreRequest),
|
|
1774
|
+
async (c) => {
|
|
1775
|
+
const input = c.req.valid("json");
|
|
1776
|
+
// One resolution for the whole batch. A client submits *its own* history, so every receipt in it is
|
|
1777
|
+
// filed against one holder or the request is refused — asking the seam per receipt would let the answer
|
|
1778
|
+
// change mid-batch and split one store account across two.
|
|
1779
|
+
const subject = await requirePaymentsSubject(c, seam);
|
|
1780
|
+
const purchases: ReturnType<typeof purchaseView>[] = [];
|
|
1781
|
+
for (const receipt of input.receipts)
|
|
1782
|
+
purchases.push(purchaseView(await submit(c, subject, input.rail, receipt)));
|
|
1783
|
+
|
|
1784
|
+
const entitlements = await resolveEntitlements(paymentsDatabase(database(c)), subject, clock());
|
|
1785
|
+
await c.var.emit({
|
|
1786
|
+
action: PaymentsAuditActions.purchaseRestored,
|
|
1787
|
+
outcome: "success",
|
|
1788
|
+
actorType: "user",
|
|
1789
|
+
actorId: c.var.auth?.userId,
|
|
1790
|
+
sessionId: c.var.auth?.sessionId,
|
|
1791
|
+
metadata: {
|
|
1792
|
+
rail: input.rail,
|
|
1793
|
+
subjectType: subject.subjectType,
|
|
1794
|
+
subjectId: subject.subjectId,
|
|
1795
|
+
restored: purchases.length,
|
|
1796
|
+
},
|
|
1797
|
+
});
|
|
1798
|
+
return c.json(
|
|
1799
|
+
{ purchases, entitlements: entitlements.map(entitlementView) } satisfies PaymentsRestoreResponse,
|
|
1800
|
+
200,
|
|
1801
|
+
);
|
|
1802
|
+
},
|
|
1803
|
+
);
|
|
1718
1804
|
|
|
1719
1805
|
/**
|
|
1720
1806
|
* SIGNED WEBHOOK — Apple. App Store Server Notifications V2, signed as a JWS against Apple's pinned chain.
|
|
1721
1807
|
*/
|
|
1722
1808
|
app.post(
|
|
1723
1809
|
`${base}/webhooks/apple`,
|
|
1810
|
+
describeRoute({
|
|
1811
|
+
summary: "Receive an App Store Server Notification.",
|
|
1812
|
+
verification: "signed-webhook",
|
|
1813
|
+
responses: { 200: PaymentsWebhookAck },
|
|
1814
|
+
}),
|
|
1724
1815
|
requireSignedWebhook("apple", { config, now: clock, trust }),
|
|
1725
|
-
|
|
1816
|
+
validate("json", AppleWebhookNotification),
|
|
1726
1817
|
webhookHandler("apple"),
|
|
1727
1818
|
);
|
|
1728
1819
|
|
|
@@ -1735,8 +1826,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1735
1826
|
*/
|
|
1736
1827
|
app.post(
|
|
1737
1828
|
`${base}/webhooks/google`,
|
|
1829
|
+
describeRoute({
|
|
1830
|
+
summary: "Receive a Play notification, pushed through Pub/Sub.",
|
|
1831
|
+
verification: "signed-webhook",
|
|
1832
|
+
responses: { 200: PaymentsWebhookAck },
|
|
1833
|
+
}),
|
|
1738
1834
|
requireSignedWebhook("google", { config, now: clock, trust }),
|
|
1739
|
-
|
|
1835
|
+
validate("json", GoogleWebhookNotification),
|
|
1740
1836
|
webhookHandler("google"),
|
|
1741
1837
|
);
|
|
1742
1838
|
|
|
@@ -1750,8 +1846,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1750
1846
|
*/
|
|
1751
1847
|
app.post(
|
|
1752
1848
|
`${base}/webhooks/stripe`,
|
|
1849
|
+
describeRoute({
|
|
1850
|
+
summary: "Receive a Stripe event.",
|
|
1851
|
+
verification: "signed-webhook",
|
|
1852
|
+
responses: { 200: PaymentsWebhookAck },
|
|
1853
|
+
}),
|
|
1753
1854
|
requireSignedWebhook("stripe", { config, now: clock, trust }),
|
|
1754
|
-
|
|
1855
|
+
validate("json", StripeWebhookNotification),
|
|
1755
1856
|
webhookHandler("stripe"),
|
|
1756
1857
|
);
|
|
1757
1858
|
|
|
@@ -1770,8 +1871,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1770
1871
|
*/
|
|
1771
1872
|
app.post(
|
|
1772
1873
|
`${base}/webhooks/lemon-squeezy`,
|
|
1874
|
+
describeRoute({
|
|
1875
|
+
summary: "Receive a Lemon Squeezy event.",
|
|
1876
|
+
verification: "signed-webhook",
|
|
1877
|
+
responses: { 200: PaymentsWebhookAck },
|
|
1878
|
+
}),
|
|
1773
1879
|
requireSignedWebhook("lemonSqueezy", { config, now: clock, trust }),
|
|
1774
|
-
|
|
1880
|
+
validate("json", LemonSqueezyWebhookNotification),
|
|
1775
1881
|
webhookHandler("lemonSqueezy"),
|
|
1776
1882
|
);
|
|
1777
1883
|
|
|
@@ -1792,8 +1898,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1792
1898
|
*/
|
|
1793
1899
|
app.post(
|
|
1794
1900
|
`${base}/webhooks/paddle`,
|
|
1901
|
+
describeRoute({
|
|
1902
|
+
summary: "Receive a Paddle event.",
|
|
1903
|
+
verification: "signed-webhook",
|
|
1904
|
+
responses: { 200: PaymentsWebhookAck },
|
|
1905
|
+
}),
|
|
1795
1906
|
requireSignedWebhook("paddle", { config, now: clock, trust }),
|
|
1796
|
-
|
|
1907
|
+
validate("json", PaddleWebhookNotification),
|
|
1797
1908
|
webhookHandler("paddle"),
|
|
1798
1909
|
);
|
|
1799
1910
|
|
|
@@ -1810,63 +1921,138 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1810
1921
|
* be charged as, and refusing before the 404 keeps this from answering what a project sells to somebody it
|
|
1811
1922
|
* cannot bill.
|
|
1812
1923
|
*/
|
|
1813
|
-
app.post(
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1924
|
+
app.post(
|
|
1925
|
+
`${base}/checkout`,
|
|
1926
|
+
describeRoute({
|
|
1927
|
+
summary: "Start a hosted checkout for one catalog product.",
|
|
1928
|
+
verification: ["bearer", "session"],
|
|
1929
|
+
responses: { 200: PaymentsCheckoutHandoffResponse },
|
|
1930
|
+
}),
|
|
1931
|
+
requireAuth(),
|
|
1932
|
+
validate("json", CheckoutRequest),
|
|
1933
|
+
async (c) => {
|
|
1934
|
+
const input = c.req.valid("json");
|
|
1935
|
+
const subject = await requirePaymentsSubject(c, seam);
|
|
1936
|
+
const entry = product(config, input.productId);
|
|
1937
|
+
const rail = checkoutRailFor(entry, input.rail);
|
|
1938
|
+
const settings = returnUrls(rail);
|
|
1939
|
+
const sku = providerProductId(entry.product, rail);
|
|
1940
|
+
if (sku === undefined) {
|
|
1941
|
+
// In the catalog, but not sold here. A 404 on the product rather than on the rail: the rail is
|
|
1942
|
+
// available, this product simply is not one of the things it sells.
|
|
1943
|
+
throw new PaymentsProductNotFoundError({
|
|
1944
|
+
detail: `Product "${entry.id}" declares no ${rail} SKU, so it cannot be bought through hosted checkout.`,
|
|
1945
|
+
});
|
|
1946
|
+
}
|
|
1827
1947
|
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1948
|
+
const provider = await checkoutRail(c, rail);
|
|
1949
|
+
const handoff = await provider.createCheckoutSession(
|
|
1950
|
+
{
|
|
1951
|
+
providerProductId: sku,
|
|
1952
|
+
subscription: entry.product.type === "subscription",
|
|
1953
|
+
// The pair, so the rail stamps `encodeSubjectReference(subject)` into the checkout it creates and
|
|
1954
|
+
// the webhook that follows already names a holder this server chose.
|
|
1955
|
+
subject,
|
|
1956
|
+
// Reuse the buyer's existing store customer, so one buyer keeps one account and their billing portal
|
|
1957
|
+
// shows every purchase rather than only the last one's.
|
|
1958
|
+
providerAccountId: await accountFor(c, rail, subject),
|
|
1959
|
+
successUrl: settings.successUrl,
|
|
1960
|
+
cancelUrl: settings.cancelUrl,
|
|
1961
|
+
// Passed to the store unchanged. Pithy never computes a discounted amount and never checks a code
|
|
1962
|
+
// against anything of its own — the provider is the authority on what is owed.
|
|
1963
|
+
discountCode: input.discountCode,
|
|
1964
|
+
},
|
|
1965
|
+
{ now: clock(), deployment: deploymentName(c) },
|
|
1966
|
+
);
|
|
1847
1967
|
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1968
|
+
await c.var.emit({
|
|
1969
|
+
action: PaymentsAuditActions.checkoutStarted,
|
|
1970
|
+
outcome: "success",
|
|
1971
|
+
actorType: "user",
|
|
1972
|
+
actorId: c.var.auth?.userId,
|
|
1973
|
+
sessionId: c.var.auth?.sessionId,
|
|
1974
|
+
resourceType: "product",
|
|
1975
|
+
resourceId: entry.id,
|
|
1976
|
+
metadata: {
|
|
1977
|
+
rail,
|
|
1978
|
+
subjectType: subject.subjectType,
|
|
1979
|
+
subjectId: subject.subjectId,
|
|
1980
|
+
productId: entry.id,
|
|
1981
|
+
subscription: entry.product.type === "subscription",
|
|
1982
|
+
// Whether one was used, never which. The trail is long-lived and a code is a commercial fact.
|
|
1983
|
+
discounted: input.discountCode !== undefined,
|
|
1984
|
+
},
|
|
1985
|
+
});
|
|
1986
|
+
// The handoff, verbatim. A `redirect` carries a URL; a `paddle` handoff carries the transaction the
|
|
1987
|
+
// browser opens in place, because that rail's overlay and inline modes never leave this page.
|
|
1988
|
+
return c.json(handoff satisfies PaymentsCheckoutHandoffResponse, 200);
|
|
1989
|
+
},
|
|
1990
|
+
);
|
|
1991
|
+
|
|
1992
|
+
/**
|
|
1993
|
+
* PUBLIC READ — Paddle only. What a page needs to resume a transaction Paddle itself created.
|
|
1994
|
+
*
|
|
1995
|
+
* **`#680`.** Paddle appends `?_ptxn=<transaction_id>` to a seller's *Default payment link* and expects
|
|
1996
|
+
* the page it lands on to open a checkout for that transaction. Those links are the ones Paddle sends
|
|
1997
|
+
* rather than the ones this kit opens — a past-due dunning mail, a manually-collected invoice, the
|
|
1998
|
+
* payment-method-update link minted for a subscription — and until this route existed the kit could not
|
|
1999
|
+
* use one: `POST {base}/checkout` mints a transaction, and here the transaction already exists.
|
|
2000
|
+
*
|
|
2001
|
+
* **Unauthenticated, and that is the point rather than an oversight.** The buyer following a dunning
|
|
2002
|
+
* link is frequently signed out — that is the population this serves, so `requireAuth()` would break it
|
|
2003
|
+
* for exactly them. It is safe because it discloses nothing: `clientToken` is publishable by design,
|
|
2004
|
+
* `environment`, `displayMode` and `successUrl` are config constants identical for every transaction,
|
|
2005
|
+
* and the id is the caller's own, echoed. The sum of what a stranger learns is this project's Paddle
|
|
2006
|
+
* account, which every pricing page already ships.
|
|
2007
|
+
*
|
|
2008
|
+
* **It must never read the transaction from Paddle**, and that is the one line to defend in review. A
|
|
2009
|
+
* lookup would turn an unauthenticated route into an oracle for whether a transaction id exists, and
|
|
2010
|
+
* then for what it costs. Shape is checked; existence is Paddle's to tell the buyer, inside the
|
|
2011
|
+
* checkout, where it is already their own transaction.
|
|
2012
|
+
*
|
|
2013
|
+
* **Nothing about a session is read, structurally.** No `requireAuth`, no `requirePaymentsSubject`, and
|
|
2014
|
+
* `PaddleResumeQuery` has no holder field for one — so a resume cannot stamp the current user onto a
|
|
2015
|
+
* transaction that arrived in a URL, which is the way this route could have been used to claim somebody
|
|
2016
|
+
* else's payment.
|
|
2017
|
+
*
|
|
2018
|
+
* **`hosted` refuses.** In that mode this kit never opens a checkout in the page: it redirects to
|
|
2019
|
+
* Paddle's own, at a URL only a transaction read would yield — the read this route may not do. A buyer
|
|
2020
|
+
* on a hosted-mode project is already on Paddle's page, so there is nothing here to resume.
|
|
2021
|
+
*/
|
|
2022
|
+
app.get(
|
|
2023
|
+
`${base}/checkout/resume`,
|
|
2024
|
+
describeRoute({
|
|
2025
|
+
summary: "Resume a Paddle transaction a payment link arrived for.",
|
|
2026
|
+
verification: "public",
|
|
2027
|
+
responses: { 200: PaymentsCheckoutHandoffResponse },
|
|
2028
|
+
}),
|
|
2029
|
+
validate("query", PaddleResumeQuery),
|
|
2030
|
+
(c) => {
|
|
2031
|
+
const { transaction } = c.req.valid("query");
|
|
2032
|
+
if (config.paddle === undefined) {
|
|
2033
|
+
throw new PaymentsRailNotConfiguredError({
|
|
2034
|
+
detail: "The paddle rail is off in this project's config, so there is no payment link to resume.",
|
|
2035
|
+
});
|
|
2036
|
+
}
|
|
2037
|
+
if (config.paddle.checkout === "hosted") {
|
|
2038
|
+
throw new PaymentsRailNotConfiguredError({
|
|
2039
|
+
detail:
|
|
2040
|
+
'This project runs `paddle.checkout: "hosted"`, which redirects to Paddle\'s own checkout rather than opening one in the page, so a `_ptxn` arrival has nothing to resume here.',
|
|
2041
|
+
});
|
|
2042
|
+
}
|
|
2043
|
+
const handoff = {
|
|
2044
|
+
kind: "paddle",
|
|
2045
|
+
transactionId: transaction,
|
|
2046
|
+
clientToken: config.paddle.clientToken,
|
|
2047
|
+
environment: config.paddle.environment,
|
|
2048
|
+
displayMode: config.paddle.checkout,
|
|
2049
|
+
// From config, exactly as the minted path takes it, and for the reason stated on the field there:
|
|
2050
|
+
// a client that could name one could send a paying customer to a page it controls.
|
|
2051
|
+
successUrl: config.paddle.successUrl,
|
|
2052
|
+
} as const;
|
|
2053
|
+
return c.json(handoff satisfies PaymentsCheckoutHandoffResponse, 200);
|
|
2054
|
+
},
|
|
2055
|
+
);
|
|
1870
2056
|
|
|
1871
2057
|
/**
|
|
1872
2058
|
* AUTHED WRITE — Stripe only. Open the Billing Portal for the caller's own store account.
|
|
@@ -1875,77 +2061,86 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1875
2061
|
* and it comes from the provider-account map. A `customer` field here would be the whole vulnerability —
|
|
1876
2062
|
* any signed-in caller could open a session against somebody else's billing history and cancel it.
|
|
1877
2063
|
*/
|
|
1878
|
-
app.post(
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
if (enabled.length === 0) {
|
|
1889
|
-
throw new PaymentsRailNotConfiguredError({
|
|
1890
|
-
detail:
|
|
1891
|
-
"No hosted-checkout rail is on in this project's config, so there is no billing portal to open. Enable `rails.stripe`, `rails.lemonSqueezy`, or `rails.paddle`.",
|
|
1892
|
-
});
|
|
1893
|
-
}
|
|
2064
|
+
app.post(
|
|
2065
|
+
`${base}/portal`,
|
|
2066
|
+
describeRoute({
|
|
2067
|
+
summary: "Open the billing portal for the caller's own store account.",
|
|
2068
|
+
verification: ["bearer", "session"],
|
|
2069
|
+
responses: { 200: PaymentsPortalHandoffResponse },
|
|
2070
|
+
}),
|
|
2071
|
+
requireAuth(),
|
|
2072
|
+
async (c) => {
|
|
2073
|
+
const subject = await requirePaymentsSubject(c, seam);
|
|
1894
2074
|
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
2075
|
+
// Which rail this caller actually bought on, found by asking the account map rather than by taking it
|
|
2076
|
+
// from the request. Still no body: the caller names neither the customer nor the rail, so there is
|
|
2077
|
+
// nothing here anyone could point at somebody else's billing.
|
|
2078
|
+
const enabled = PAYMENTS_HOSTED_RAILS.filter((rail) => railEnabled(config, rail));
|
|
2079
|
+
// No hosted rail at all is a fact about the deployment, not about this caller — a mobile-only project
|
|
2080
|
+
// has no billing portal to open. Same refusal `/checkout` gives, rather than a 404 that reads as "you
|
|
2081
|
+
// have no account" to somebody who could never have had one.
|
|
2082
|
+
if (enabled.length === 0) {
|
|
2083
|
+
throw new PaymentsRailNotConfiguredError({
|
|
2084
|
+
detail:
|
|
2085
|
+
"No hosted-checkout rail is on in this project's config, so there is no billing portal to open. Enable `rails.stripe`, `rails.lemonSqueezy`, or `rails.paddle`.",
|
|
2086
|
+
});
|
|
1901
2087
|
}
|
|
1902
|
-
}
|
|
1903
2088
|
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
});
|
|
1913
|
-
}
|
|
2089
|
+
let found: { rail: PaymentsRail; providerAccountId: string } | undefined;
|
|
2090
|
+
for (const rail of enabled) {
|
|
2091
|
+
const providerAccountId = await accountFor(c, rail, subject);
|
|
2092
|
+
if (providerAccountId !== null) {
|
|
2093
|
+
found = { rail, providerAccountId };
|
|
2094
|
+
break;
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
1914
2097
|
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
// There is still no request field: the route reads what this caller owns.
|
|
1926
|
-
subscriptionIds: await ownSubscriptionIds(c, found.rail, subject),
|
|
1927
|
-
},
|
|
1928
|
-
{ now: clock(), deployment: deploymentName(c) },
|
|
1929
|
-
);
|
|
2098
|
+
if (found === undefined) {
|
|
2099
|
+
// Nothing has ever been bought through a hosted rail by this caller, so there is no billing to
|
|
2100
|
+
// manage. Not a payments-domain refusal: the rail is configured and working, the resource simply
|
|
2101
|
+
// does not exist.
|
|
2102
|
+
throw new NotFoundError({
|
|
2103
|
+
message: "No billing account yet.",
|
|
2104
|
+
action: "Buy a subscription first, then manage it here.",
|
|
2105
|
+
detail: `No hosted-rail provider account is linked to ${encodeSubjectReference(subject)}.`,
|
|
2106
|
+
});
|
|
2107
|
+
}
|
|
1930
2108
|
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
2109
|
+
const provider = await checkoutRail(c, found.rail);
|
|
2110
|
+
const session = await provider.createPortalSession(
|
|
2111
|
+
{
|
|
2112
|
+
providerAccountId: found.providerAccountId,
|
|
2113
|
+
// Undefined for a rail whose portal takes no return parameter — Lemon Squeezy's is a signed,
|
|
2114
|
+
// expiring link with nowhere to go back to, and Paddle's takes none at all. The contract admits
|
|
2115
|
+
// that rather than have the rail silently drop a URL an adopter configured.
|
|
2116
|
+
returnUrl: found.rail === "stripe" ? stripeSettings().portalReturnUrl : undefined,
|
|
2117
|
+
// **From the caller's own rows, never from a body.** A store that mints per-subscription deep
|
|
2118
|
+
// links mints authenticated ones, so naming a subscription is naming somebody's cancel button.
|
|
2119
|
+
// There is still no request field: the route reads what this caller owns.
|
|
2120
|
+
subscriptionIds: await ownSubscriptionIds(c, found.rail, subject),
|
|
2121
|
+
},
|
|
2122
|
+
{ now: clock(), deployment: deploymentName(c) },
|
|
2123
|
+
);
|
|
2124
|
+
|
|
2125
|
+
await c.var.emit({
|
|
2126
|
+
action: PaymentsAuditActions.portalOpened,
|
|
2127
|
+
outcome: "success",
|
|
2128
|
+
actorType: "user",
|
|
2129
|
+
actorId: c.var.auth?.userId,
|
|
2130
|
+
sessionId: c.var.auth?.sessionId,
|
|
2131
|
+
resourceType: "provider_account",
|
|
2132
|
+
resourceId: found.providerAccountId,
|
|
2133
|
+
metadata: { rail: found.rail, subjectType: subject.subjectType, subjectId: subject.subjectId },
|
|
2134
|
+
});
|
|
2135
|
+
return c.json(
|
|
2136
|
+
{
|
|
2137
|
+
url: session.url,
|
|
2138
|
+
...(session.subscriptions === undefined ? {} : { subscriptions: [...session.subscriptions] }),
|
|
2139
|
+
} satisfies PaymentsPortalHandoffResponse,
|
|
2140
|
+
200,
|
|
2141
|
+
);
|
|
2142
|
+
},
|
|
2143
|
+
);
|
|
1949
2144
|
|
|
1950
2145
|
/**
|
|
1951
2146
|
* CONTROL PLANE. Grant an entitlement by hand — a comped account, or the repair of a purchase that
|
|
@@ -1985,58 +2180,67 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
1985
2180
|
* bought anything has no pricing and may still have no customer, and somebody mid-subscription has
|
|
1986
2181
|
* both. Nesting one in the other would make the common case unreachable.
|
|
1987
2182
|
*/
|
|
1988
|
-
app.get(
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
.
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
.
|
|
2015
|
-
.
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2183
|
+
app.get(
|
|
2184
|
+
`${base}/pricing`,
|
|
2185
|
+
describeRoute({
|
|
2186
|
+
summary: "Read what the caller's own subscription pays, and when that changes.",
|
|
2187
|
+
verification: ["bearer", "session"],
|
|
2188
|
+
responses: { 200: PaymentsPricingEnvelope },
|
|
2189
|
+
}),
|
|
2190
|
+
requireAuth(),
|
|
2191
|
+
async (c) => {
|
|
2192
|
+
const subject = await resolvePaymentsSubject(c, seam);
|
|
2193
|
+
// A read, so nobody resolved is the empty answer rather than a refusal — the same direction
|
|
2194
|
+
// `GET {base}/entitlements` takes, and for the same reason: a screen with no billing account selected
|
|
2195
|
+
// is quoting from nothing, which is a fact rather than a failure.
|
|
2196
|
+
if (subject === undefined)
|
|
2197
|
+
return c.json({ pricing: null, quotedFrom: null } satisfies PaymentsPricingEnvelope, 200);
|
|
2198
|
+
const db = paymentsDatabase(database(c));
|
|
2199
|
+
|
|
2200
|
+
// The one read, shared with `/checkout`. `accountFor` is what that route calls to decide who is
|
|
2201
|
+
// charged, so a screen quoting from this answer is quoting from the row that will be billed.
|
|
2202
|
+
const paddleCustomer = await accountFor(c, "paddle", subject);
|
|
2203
|
+
const quotedFrom: PaymentsQuotedFrom | null =
|
|
2204
|
+
paddleCustomer === null ? null : { rail: "paddle", providerAccountId: paddleCustomer };
|
|
2205
|
+
/** The envelope, so every exit below carries both facts rather than three of them carrying one. */
|
|
2206
|
+
const answer = (pricing: PaymentsPricingResponse | null) =>
|
|
2207
|
+
c.json({ pricing, quotedFrom } satisfies PaymentsPricingEnvelope, 200);
|
|
2208
|
+
|
|
2209
|
+
// The newest subscription row this caller holds on a rail that can price one. `role` matters: a money
|
|
2210
|
+
// row records a closed period and has no "next".
|
|
2211
|
+
const rows = await db
|
|
2212
|
+
.selectFrom(PAYMENTS_PURCHASES_TABLE)
|
|
2213
|
+
.selectAll()
|
|
2214
|
+
.where("subjectType", "=", subject.subjectType)
|
|
2215
|
+
.where("subjectId", "=", subject.subjectId)
|
|
2216
|
+
.where("type", "=", "subscription")
|
|
2217
|
+
.orderBy("providerEventAt", "desc")
|
|
2218
|
+
.execute();
|
|
2219
|
+
// The row that carries the subscription's *standing*, preferred over any receipt.
|
|
2220
|
+
//
|
|
2221
|
+
// On Lemon Squeezy a subscriber's newest rows are `charge` receipts — one per invoice — and a receipt
|
|
2222
|
+
// names a closed period no rail can price. Taking the newest of any role therefore returned null for
|
|
2223
|
+
// every LS subscriber while looking like it had worked. Every other rail writes `charge` for
|
|
2224
|
+
// everything and has no `state` row, so the fallback is what serves them.
|
|
2225
|
+
const row = rows.find((candidate) => candidate.role === "state") ?? rows[0];
|
|
2226
|
+
if (row === undefined) return answer(null);
|
|
2227
|
+
|
|
2228
|
+
const purchase = PaymentsPurchase.parse(row);
|
|
2229
|
+
const provider = resolveRailProvider(purchase.rail, config, await credentials(c), trust);
|
|
2230
|
+
if (!isPricingRail(provider)) return answer(null);
|
|
2231
|
+
|
|
2232
|
+
const pricing = await provider.readPricing(purchase, { now: clock(), deployment: deploymentName(c) });
|
|
2233
|
+
if (pricing === undefined) return answer(null);
|
|
2234
|
+
|
|
2235
|
+
return answer({
|
|
2236
|
+
currency: pricing.currency,
|
|
2237
|
+
currentAmountMinor: pricing.currentAmountMinor,
|
|
2238
|
+
listAmountMinor: pricing.listAmountMinor,
|
|
2239
|
+
discountCode: pricing.discountCode,
|
|
2240
|
+
discountEndsAt: pricing.discountEndsAt === null ? null : pricing.discountEndsAt.toISOString(),
|
|
2241
|
+
});
|
|
2242
|
+
},
|
|
2243
|
+
);
|
|
2040
2244
|
|
|
2041
2245
|
/**
|
|
2042
2246
|
* AUTHED READ — where the caller's own subscription stands, read live from the store.
|
|
@@ -2061,30 +2265,39 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2061
2265
|
* shape of this request that reads somebody else's. Nobody resolved is the empty answer rather than a
|
|
2062
2266
|
* refusal, which is the read half of the seam's rule and what `GET {base}/entitlements` already does.
|
|
2063
2267
|
*/
|
|
2064
|
-
app.get(
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2268
|
+
app.get(
|
|
2269
|
+
`${base}/subscription`,
|
|
2270
|
+
describeRoute({
|
|
2271
|
+
summary: "Read where the caller's own subscription stands, live from the store.",
|
|
2272
|
+
verification: ["bearer", "session"],
|
|
2273
|
+
responses: { 200: PaymentsSubscriptionResponse },
|
|
2274
|
+
}),
|
|
2275
|
+
requireAuth(),
|
|
2276
|
+
async (c) => {
|
|
2277
|
+
const subject = await resolvePaymentsSubject(c, seam);
|
|
2278
|
+
if (subject === undefined) return c.json({ subscription: null } satisfies PaymentsSubscriptionResponse, 200);
|
|
2279
|
+
|
|
2280
|
+
const target = await changeableSubscription(database(c), subject, clock());
|
|
2281
|
+
// Two subscriptions have no encoding in an envelope that holds one, and picking is the defect the
|
|
2282
|
+
// whole resolver exists to prevent. The refusal is the same one every verb gives.
|
|
2283
|
+
if (target.found === "many") throw tooManySubscriptions(target.purchases);
|
|
2284
|
+
if (target.found === "none") return c.json({ subscription: null } satisfies PaymentsSubscriptionResponse, 200);
|
|
2285
|
+
|
|
2286
|
+
const provider = await subscriptionRail(c, target.purchase.rail);
|
|
2287
|
+
const standing = await provider.readStanding(target.purchase, { now: clock(), deployment: deploymentName(c) });
|
|
2288
|
+
// A rail that cannot address this purchase, or a store that no longer knows it. A fact about the
|
|
2289
|
+
// purchase rather than a failure — a store that could not be *reached* raises
|
|
2290
|
+
// `payments/provider_unavailable` instead, so a screen distinguishes the two.
|
|
2291
|
+
if (standing === undefined) return c.json({ subscription: null } satisfies PaymentsSubscriptionResponse, 200);
|
|
2292
|
+
|
|
2293
|
+
return c.json(
|
|
2294
|
+
{
|
|
2295
|
+
subscription: subscriptionView(target.purchase.productId, standing),
|
|
2296
|
+
} satisfies PaymentsSubscriptionResponse,
|
|
2297
|
+
200,
|
|
2298
|
+
);
|
|
2299
|
+
},
|
|
2300
|
+
);
|
|
2088
2301
|
|
|
2089
2302
|
/**
|
|
2090
2303
|
* AUTHED READ — what moving to one catalog product would cost, as the store previews it.
|
|
@@ -2110,8 +2323,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2110
2323
|
*/
|
|
2111
2324
|
app.post(
|
|
2112
2325
|
`${base}/subscription/preview`,
|
|
2326
|
+
describeRoute({
|
|
2327
|
+
summary: "Preview what moving to one catalog product would cost.",
|
|
2328
|
+
verification: ["bearer", "session"],
|
|
2329
|
+
responses: { 200: PaymentsSubscriptionQuoteResponse },
|
|
2330
|
+
}),
|
|
2113
2331
|
requireAuth(),
|
|
2114
|
-
|
|
2332
|
+
validate("json", SubscriptionPreviewRequest),
|
|
2115
2333
|
async (c) => {
|
|
2116
2334
|
const input = c.req.valid("json");
|
|
2117
2335
|
const subject = await requirePaymentsSubject(c, seam);
|
|
@@ -2161,8 +2379,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2161
2379
|
*/
|
|
2162
2380
|
app.post(
|
|
2163
2381
|
`${base}/subscription/change`,
|
|
2382
|
+
describeRoute({
|
|
2383
|
+
summary: "Move the caller's own subscription onto one catalog product.",
|
|
2384
|
+
verification: ["bearer", "session"],
|
|
2385
|
+
responses: { 200: PaymentsSubscriptionStandingResponse },
|
|
2386
|
+
}),
|
|
2164
2387
|
requireAuth(),
|
|
2165
|
-
|
|
2388
|
+
validate("json", SubscriptionChangeRequest),
|
|
2166
2389
|
async (c) => {
|
|
2167
2390
|
const input = c.req.valid("json");
|
|
2168
2391
|
const subject = await requirePaymentsSubject(c, seam);
|
|
@@ -2235,8 +2458,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2235
2458
|
*/
|
|
2236
2459
|
app.post(
|
|
2237
2460
|
`${base}/subscription/cancel`,
|
|
2461
|
+
describeRoute({
|
|
2462
|
+
summary: "Stop the caller's own subscription renewing.",
|
|
2463
|
+
verification: ["bearer", "session"],
|
|
2464
|
+
responses: { 200: PaymentsSubscriptionStandingResponse },
|
|
2465
|
+
}),
|
|
2238
2466
|
requireAuth(),
|
|
2239
|
-
|
|
2467
|
+
validate("json", SubscriptionCancelRequest),
|
|
2240
2468
|
async (c) => {
|
|
2241
2469
|
const input = c.req.valid("json");
|
|
2242
2470
|
const subject = await requirePaymentsSubject(c, seam);
|
|
@@ -2303,38 +2531,49 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2303
2531
|
* A subscription with nothing scheduled is the no-op rather than a refusal — it already renews, which
|
|
2304
2532
|
* is what the caller asked for — and it writes no audit row, for {@link standingMoved}'s reason.
|
|
2305
2533
|
*/
|
|
2306
|
-
app.post(
|
|
2307
|
-
|
|
2308
|
-
|
|
2534
|
+
app.post(
|
|
2535
|
+
`${base}/subscription/keep`,
|
|
2536
|
+
describeRoute({
|
|
2537
|
+
summary: "Withdraw a scheduled cancellation.",
|
|
2538
|
+
verification: ["bearer", "session"],
|
|
2539
|
+
responses: { 200: PaymentsSubscriptionStandingResponse },
|
|
2540
|
+
}),
|
|
2541
|
+
requireAuth(),
|
|
2542
|
+
async (c) => {
|
|
2543
|
+
const subject = await requirePaymentsSubject(c, seam);
|
|
2544
|
+
const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
|
|
2309
2545
|
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2546
|
+
const provider = await subscriptionRail(c, purchase.rail);
|
|
2547
|
+
const context = { now: clock(), deployment: deploymentName(c) };
|
|
2548
|
+
const before = await provider.readStanding(purchase, context);
|
|
2549
|
+
const standing = await provider.keepSubscription(purchase, context);
|
|
2314
2550
|
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2551
|
+
if (standingMoved(before, standing)) {
|
|
2552
|
+
await c.var.emit({
|
|
2553
|
+
action: PaymentsAuditActions.subscriptionCancelWithdrawn,
|
|
2554
|
+
outcome: "success",
|
|
2555
|
+
actorType: "user",
|
|
2556
|
+
actorId: c.var.auth?.userId,
|
|
2557
|
+
sessionId: c.var.auth?.sessionId,
|
|
2558
|
+
resourceType: "purchase",
|
|
2559
|
+
resourceId: purchase.id,
|
|
2560
|
+
metadata: {
|
|
2561
|
+
rail: purchase.rail,
|
|
2562
|
+
subjectType: subject.subjectType,
|
|
2563
|
+
subjectId: subject.subjectId,
|
|
2564
|
+
productId: purchase.productId,
|
|
2565
|
+
},
|
|
2566
|
+
});
|
|
2567
|
+
}
|
|
2332
2568
|
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2569
|
+
return c.json(
|
|
2570
|
+
{
|
|
2571
|
+
subscription: subscriptionView(purchase.productId, standing),
|
|
2572
|
+
} satisfies PaymentsSubscriptionStandingResponse,
|
|
2573
|
+
200,
|
|
2574
|
+
);
|
|
2575
|
+
},
|
|
2576
|
+
);
|
|
2338
2577
|
|
|
2339
2578
|
/**
|
|
2340
2579
|
* AUTHED WRITE — ask the store to give this subscription's payments back.
|
|
@@ -2368,67 +2607,76 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2368
2607
|
* already standing is the state the caller wanted, and a trail claiming two of them is worse than one
|
|
2369
2608
|
* claiming none.
|
|
2370
2609
|
*/
|
|
2371
|
-
app.post(
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
//
|
|
2383
|
-
//
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
},
|
|
2399
|
-
{ now: clock(), deployment: deploymentName(c) },
|
|
2400
|
-
);
|
|
2610
|
+
app.post(
|
|
2611
|
+
`${base}/subscription/refund`,
|
|
2612
|
+
describeRoute({
|
|
2613
|
+
summary: "Ask the store to refund the payments on the caller's own subscription.",
|
|
2614
|
+
verification: ["bearer", "session"],
|
|
2615
|
+
responses: { 200: PaymentsRefundResponse },
|
|
2616
|
+
}),
|
|
2617
|
+
requireAuth(),
|
|
2618
|
+
async (c) => {
|
|
2619
|
+
const subject = await requirePaymentsSubject(c, seam);
|
|
2620
|
+
const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
|
|
2621
|
+
// The rail is narrowed **before** the payments are resolved, and the order is the answer a caller
|
|
2622
|
+
// gets. "This store does not refund from the server" is true of every payment on the subscription and
|
|
2623
|
+
// is what an Apple or Google subscriber needs to hear; "there is no payment to refund" would be the
|
|
2624
|
+
// same 409 they would get if they had never paid, and it would send them looking for the wrong thing.
|
|
2625
|
+
const provider = await refundRail(c, purchase.rail);
|
|
2626
|
+
const payments = await refundablePayments(database(c), subject, purchase);
|
|
2627
|
+
if (payments.length === 0) {
|
|
2628
|
+
// A 409 rather than an empty report, and rather than a 404. The subscription is there and the
|
|
2629
|
+
// request is well-formed; what is absent is a payment to refund, which is a fact about the account's
|
|
2630
|
+
// present state. An empty report would read as "refunded, nothing to do".
|
|
2631
|
+
throw new PaymentsSubscriptionChangeRefusedError({
|
|
2632
|
+
message: "There is no payment on this subscription to refund.",
|
|
2633
|
+
action: "Check the subscription's payment history. A refund attaches to a payment, not to a plan.",
|
|
2634
|
+
detail: `No charge rows resolved on ${purchase.rail} for the family this subscription heads.`,
|
|
2635
|
+
});
|
|
2636
|
+
}
|
|
2401
2637
|
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
actorId: c.var.auth?.userId,
|
|
2410
|
-
sessionId: c.var.auth?.sessionId,
|
|
2411
|
-
resourceType: "purchase",
|
|
2412
|
-
resourceId: purchase.id,
|
|
2413
|
-
// Counts and the store's own handles on the money in flight. **No amount**: how much anybody is
|
|
2414
|
-
// getting back is the store's later decision, and a figure here would assert something nobody has
|
|
2415
|
-
// agreed to, in the one table nothing corrects.
|
|
2416
|
-
metadata: {
|
|
2417
|
-
rail: purchase.rail,
|
|
2418
|
-
subjectType: subject.subjectType,
|
|
2419
|
-
subjectId: subject.subjectId,
|
|
2420
|
-
productId: purchase.productId,
|
|
2421
|
-
payments: refund.outcomes.length,
|
|
2422
|
-
requested: raised.length,
|
|
2423
|
-
alreadyRequested: refund.outcomes.filter((outcome) => outcome.outcome === "already_requested").length,
|
|
2424
|
-
failed: refund.outcomes.filter((outcome) => outcome.outcome === "failed").length,
|
|
2425
|
-
adjustmentIds: raised.map((outcome) => outcome.adjustmentId),
|
|
2638
|
+
const refund = await provider.requestRefunds(
|
|
2639
|
+
{
|
|
2640
|
+
purchases: payments,
|
|
2641
|
+
// Composed here and never read from a body: it is written into the adopter's own store console,
|
|
2642
|
+
// where a person reads it as a statement about their business. The catalog product and nothing
|
|
2643
|
+
// else — no customer text, no identifier a store does not already hold.
|
|
2644
|
+
reason: `Refund requested by the subscriber for "${purchase.productId}".`,
|
|
2426
2645
|
},
|
|
2427
|
-
|
|
2428
|
-
|
|
2646
|
+
{ now: clock(), deployment: deploymentName(c) },
|
|
2647
|
+
);
|
|
2429
2648
|
|
|
2430
|
-
|
|
2431
|
-
|
|
2649
|
+
const raised = refund.outcomes.filter((outcome) => outcome.outcome === "requested");
|
|
2650
|
+
if (raised.length > 0) {
|
|
2651
|
+
await c.var.emit({
|
|
2652
|
+
action: PaymentsAuditActions.subscriptionRefundRequested,
|
|
2653
|
+
outcome: "success",
|
|
2654
|
+
// The person who asked, always — the holder they act for rides in the metadata.
|
|
2655
|
+
actorType: "user",
|
|
2656
|
+
actorId: c.var.auth?.userId,
|
|
2657
|
+
sessionId: c.var.auth?.sessionId,
|
|
2658
|
+
resourceType: "purchase",
|
|
2659
|
+
resourceId: purchase.id,
|
|
2660
|
+
// Counts and the store's own handles on the money in flight. **No amount**: how much anybody is
|
|
2661
|
+
// getting back is the store's later decision, and a figure here would assert something nobody has
|
|
2662
|
+
// agreed to, in the one table nothing corrects.
|
|
2663
|
+
metadata: {
|
|
2664
|
+
rail: purchase.rail,
|
|
2665
|
+
subjectType: subject.subjectType,
|
|
2666
|
+
subjectId: subject.subjectId,
|
|
2667
|
+
productId: purchase.productId,
|
|
2668
|
+
payments: refund.outcomes.length,
|
|
2669
|
+
requested: raised.length,
|
|
2670
|
+
alreadyRequested: refund.outcomes.filter((outcome) => outcome.outcome === "already_requested").length,
|
|
2671
|
+
failed: refund.outcomes.filter((outcome) => outcome.outcome === "failed").length,
|
|
2672
|
+
adjustmentIds: raised.map((outcome) => outcome.adjustmentId),
|
|
2673
|
+
},
|
|
2674
|
+
});
|
|
2675
|
+
}
|
|
2676
|
+
|
|
2677
|
+
return c.json({ refund: refundView(refund) } satisfies PaymentsRefundResponse, 200);
|
|
2678
|
+
},
|
|
2679
|
+
);
|
|
2432
2680
|
|
|
2433
2681
|
/**
|
|
2434
2682
|
* CONTROL PLANE. The discount codes this project has issued.
|
|
@@ -2442,8 +2690,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2442
2690
|
*/
|
|
2443
2691
|
app.get(
|
|
2444
2692
|
`${base}/admin/discounts`,
|
|
2693
|
+
describeRoute({
|
|
2694
|
+
summary: "Read the discount codes this project has issued at one store.",
|
|
2695
|
+
verification: "control-plane",
|
|
2696
|
+
scopes: [PAYMENTS_DISCOUNT_READ_SCOPE],
|
|
2697
|
+
responses: { 200: PaymentsAdminDiscountsResponse },
|
|
2698
|
+
}),
|
|
2445
2699
|
requireControlPlane(PAYMENTS_DISCOUNT_READ_SCOPE),
|
|
2446
|
-
|
|
2700
|
+
validate("query", AdminDiscountsQuery),
|
|
2447
2701
|
async (c) => {
|
|
2448
2702
|
const { rail } = c.req.valid("query");
|
|
2449
2703
|
const provider = resolveRailProvider(rail, config, await credentials(c), trust);
|
|
@@ -2478,8 +2732,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2478
2732
|
*/
|
|
2479
2733
|
app.post(
|
|
2480
2734
|
`${base}/admin/discounts`,
|
|
2735
|
+
describeRoute({
|
|
2736
|
+
summary: "Mint a discount code at one store.",
|
|
2737
|
+
verification: "control-plane",
|
|
2738
|
+
scopes: [PAYMENTS_DISCOUNT_CREATE_SCOPE],
|
|
2739
|
+
responses: { 200: PaymentsDiscountResponse },
|
|
2740
|
+
}),
|
|
2481
2741
|
requireControlPlane(PAYMENTS_DISCOUNT_CREATE_SCOPE),
|
|
2482
|
-
|
|
2742
|
+
validate("json", DiscountCreateRequest),
|
|
2483
2743
|
async (c) => {
|
|
2484
2744
|
const input = c.req.valid("json");
|
|
2485
2745
|
const provider = resolveRailProvider(input.rail, config, await credentials(c), trust);
|
|
@@ -2531,8 +2791,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2531
2791
|
|
|
2532
2792
|
app.post(
|
|
2533
2793
|
`${base}/entitlements/grant`,
|
|
2794
|
+
describeRoute({
|
|
2795
|
+
summary: "Grant an entitlement by hand.",
|
|
2796
|
+
verification: "control-plane",
|
|
2797
|
+
scopes: [PAYMENTS_ENTITLEMENT_GRANT_SCOPE],
|
|
2798
|
+
responses: { 200: PaymentsEntitlementResponse },
|
|
2799
|
+
}),
|
|
2534
2800
|
requireControlPlane(PAYMENTS_ENTITLEMENT_GRANT_SCOPE),
|
|
2535
|
-
|
|
2801
|
+
validate("json", EntitlementGrantRequest),
|
|
2536
2802
|
async (c) => {
|
|
2537
2803
|
const input = c.req.valid("json");
|
|
2538
2804
|
const caller = controlPlaneCaller(c);
|
|
@@ -2656,8 +2922,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2656
2922
|
*/
|
|
2657
2923
|
app.post(
|
|
2658
2924
|
`${base}/entitlements/revoke`,
|
|
2925
|
+
describeRoute({
|
|
2926
|
+
summary: "Revoke an entitlement by hand.",
|
|
2927
|
+
verification: "control-plane",
|
|
2928
|
+
scopes: [PAYMENTS_ENTITLEMENT_REVOKE_SCOPE],
|
|
2929
|
+
responses: { 200: PaymentsEntitlementResponse },
|
|
2930
|
+
}),
|
|
2659
2931
|
requireControlPlane(PAYMENTS_ENTITLEMENT_REVOKE_SCOPE),
|
|
2660
|
-
|
|
2932
|
+
validate("json", EntitlementRevokeRequest),
|
|
2661
2933
|
async (c) => {
|
|
2662
2934
|
const input = c.req.valid("json");
|
|
2663
2935
|
const caller = controlPlaneCaller(c);
|
|
@@ -2760,7 +3032,7 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2760
3032
|
...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
|
|
2761
3033
|
},
|
|
2762
3034
|
});
|
|
2763
|
-
return c.json({ received: true, projected: false }, 200);
|
|
3035
|
+
return c.json({ received: true, projected: false } satisfies PaymentsWebhookAck, 200);
|
|
2764
3036
|
};
|
|
2765
3037
|
|
|
2766
3038
|
// Bind the store account to a user, when the notification carried both halves — before anything else,
|
|
@@ -2838,7 +3110,10 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2838
3110
|
projected: true,
|
|
2839
3111
|
},
|
|
2840
3112
|
});
|
|
2841
|
-
return c.json(
|
|
3113
|
+
return c.json(
|
|
3114
|
+
{ received: true, projected: true, outcome: projection.outcome } satisfies PaymentsWebhookAck,
|
|
3115
|
+
200,
|
|
3116
|
+
);
|
|
2842
3117
|
}
|
|
2843
3118
|
return await acknowledge({
|
|
2844
3119
|
error: `${noteText(notification.note) ?? "voided purchase"} — no purchase is stored under that order id.`,
|
|
@@ -2945,7 +3220,7 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
2945
3220
|
projected: true,
|
|
2946
3221
|
},
|
|
2947
3222
|
});
|
|
2948
|
-
return c.json({ received: true, projected: true, outcome: projection.outcome }, 200);
|
|
3223
|
+
return c.json({ received: true, projected: true, outcome: projection.outcome } satisfies PaymentsWebhookAck, 200);
|
|
2949
3224
|
};
|
|
2950
3225
|
}
|
|
2951
3226
|
}
|