@pithy-sh/payments 0.3.10 → 0.5.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.
Files changed (215) hide show
  1. package/README.md +11 -3
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +26 -2
  4. package/dist/admin/read.d.ts +48 -1
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +89 -2
  7. package/dist/audit/actions.d.ts +13 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +14 -1
  10. package/dist/capability.d.ts +33 -2
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +52 -9
  13. package/dist/client/api.d.ts +38 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +59 -1
  16. package/dist/client/hooks.d.ts +63 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +96 -2
  19. package/dist/client/paddleLink.d.ts +31 -0
  20. package/dist/client/paddleLink.d.ts.map +1 -0
  21. package/dist/client/paddleLink.js +37 -0
  22. package/dist/client/projection.d.ts +29 -0
  23. package/dist/client/projection.d.ts.map +1 -1
  24. package/dist/config/allowances.d.ts +71 -0
  25. package/dist/config/allowances.d.ts.map +1 -0
  26. package/dist/config/allowances.js +115 -0
  27. package/dist/config/config.d.ts +155 -9
  28. package/dist/config/config.d.ts.map +1 -1
  29. package/dist/config/config.js +164 -14
  30. package/dist/data/meterCounter.d.ts +34 -0
  31. package/dist/data/meterCounter.d.ts.map +1 -0
  32. package/dist/data/meterCounter.js +33 -0
  33. package/dist/data/override.d.ts +56 -0
  34. package/dist/data/override.d.ts.map +1 -0
  35. package/dist/data/override.js +58 -0
  36. package/dist/data/paddleIds.d.ts +28 -0
  37. package/dist/data/paddleIds.d.ts.map +1 -0
  38. package/dist/data/paddleIds.js +73 -0
  39. package/dist/data/period.d.ts +10 -0
  40. package/dist/data/period.d.ts.map +1 -0
  41. package/dist/data/period.js +37 -0
  42. package/dist/data/purchase.d.ts +1 -0
  43. package/dist/data/purchase.d.ts.map +1 -1
  44. package/dist/data/purchase.js +1 -0
  45. package/dist/data/tables.d.ts +17 -1
  46. package/dist/data/tables.d.ts.map +1 -1
  47. package/dist/data/tables.js +24 -4
  48. package/dist/data/usageReport.d.ts +68 -0
  49. package/dist/data/usageReport.d.ts.map +1 -0
  50. package/dist/data/usageReport.js +55 -0
  51. package/dist/data/usageRun.d.ts +93 -0
  52. package/dist/data/usageRun.d.ts.map +1 -0
  53. package/dist/data/usageRun.js +50 -0
  54. package/dist/entitlement/allowance.d.ts +100 -0
  55. package/dist/entitlement/allowance.d.ts.map +1 -0
  56. package/dist/entitlement/allowance.js +171 -0
  57. package/dist/entitlement/manual.d.ts +5 -5
  58. package/dist/entitlement/manual.js +3 -3
  59. package/dist/entitlement/meter.d.ts +98 -0
  60. package/dist/entitlement/meter.d.ts.map +1 -0
  61. package/dist/entitlement/meter.js +177 -0
  62. package/dist/entitlement/override.d.ts +119 -0
  63. package/dist/entitlement/override.d.ts.map +1 -0
  64. package/dist/entitlement/override.js +256 -0
  65. package/dist/entitlement/resolver.d.ts +2 -1
  66. package/dist/entitlement/resolver.d.ts.map +1 -1
  67. package/dist/entitlement/resolver.js +32 -1
  68. package/dist/entitlement/unimplementedSubject.d.ts.map +1 -1
  69. package/dist/entitlement/unimplementedSubject.js +3 -2
  70. package/dist/error/errors.d.ts +19 -0
  71. package/dist/error/errors.d.ts.map +1 -1
  72. package/dist/error/errors.js +35 -2
  73. package/dist/http/responses.d.ts +390 -5
  74. package/dist/http/responses.d.ts.map +1 -1
  75. package/dist/http/responses.js +169 -13
  76. package/dist/http/routes.d.ts +6 -2
  77. package/dist/http/routes.d.ts.map +1 -1
  78. package/dist/http/routes.js +478 -52
  79. package/dist/http/schemas.d.ts +75 -1
  80. package/dist/http/schemas.d.ts.map +1 -1
  81. package/dist/http/schemas.js +80 -3
  82. package/dist/http/scopes.d.ts +25 -0
  83. package/dist/http/scopes.d.ts.map +1 -1
  84. package/dist/http/scopes.js +60 -1
  85. package/dist/http/view.d.ts +22 -4
  86. package/dist/http/view.d.ts.map +1 -1
  87. package/dist/http/view.js +88 -7
  88. package/dist/http/webhookGuard.d.ts.map +1 -1
  89. package/dist/http/webhookGuard.js +1 -1
  90. package/dist/index.d.ts +2 -1
  91. package/dist/index.d.ts.map +1 -1
  92. package/dist/index.js +3 -2
  93. package/dist/migrations/0002_allowances.d.ts +26 -0
  94. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  95. package/dist/migrations/0002_allowances.js +62 -0
  96. package/dist/peer.d.ts +1 -0
  97. package/dist/peer.d.ts.map +1 -1
  98. package/dist/projection/event.d.ts +1 -0
  99. package/dist/projection/event.d.ts.map +1 -1
  100. package/dist/projection/event.js +1 -0
  101. package/dist/projection/writer.d.ts.map +1 -1
  102. package/dist/projection/writer.js +3 -1
  103. package/dist/rails/contract.d.ts +6 -0
  104. package/dist/rails/contract.d.ts.map +1 -1
  105. package/dist/rails/google/playApi.d.ts.map +1 -1
  106. package/dist/rails/google/playApi.js +2 -0
  107. package/dist/rails/paddle/events.d.ts.map +1 -1
  108. package/dist/rails/paddle/events.js +2 -1
  109. package/dist/rails/paddle/objects.d.ts +2 -0
  110. package/dist/rails/paddle/objects.d.ts.map +1 -1
  111. package/dist/rails/paddle/objects.js +7 -2
  112. package/dist/rails/paddle/refresh.d.ts +10 -5
  113. package/dist/rails/paddle/refresh.d.ts.map +1 -1
  114. package/dist/rails/paddle/refresh.js +8 -5
  115. package/dist/rails/paddle/refund.d.ts.map +1 -1
  116. package/dist/rails/paddle/refund.js +10 -2
  117. package/dist/rails/paddle/subscription.d.ts.map +1 -1
  118. package/dist/rails/paddle/subscription.js +8 -3
  119. package/dist/rails/paddle/usage.d.ts +11 -0
  120. package/dist/rails/paddle/usage.d.ts.map +1 -0
  121. package/dist/rails/paddle/usage.js +49 -0
  122. package/dist/rails/paddle/verify.d.ts.map +1 -1
  123. package/dist/rails/paddle/verify.js +2 -3
  124. package/dist/rails/quantity.d.ts +12 -0
  125. package/dist/rails/quantity.d.ts.map +1 -0
  126. package/dist/rails/quantity.js +16 -0
  127. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  128. package/dist/rails/stripe/checkout.js +1 -1
  129. package/dist/rails/stripe/objects.d.ts.map +1 -1
  130. package/dist/rails/stripe/objects.js +3 -0
  131. package/dist/rails/stripe/usage.d.ts +10 -0
  132. package/dist/rails/stripe/usage.d.ts.map +1 -0
  133. package/dist/rails/stripe/usage.js +49 -0
  134. package/dist/secret/registry.d.ts.map +1 -1
  135. package/dist/secret/registry.js +3 -2
  136. package/dist/usage/pass.d.ts +120 -0
  137. package/dist/usage/pass.d.ts.map +1 -0
  138. package/dist/usage/pass.js +363 -0
  139. package/dist/usage/reporter.d.ts +36 -0
  140. package/dist/usage/reporter.d.ts.map +1 -0
  141. package/dist/usage/reporter.js +2 -0
  142. package/dist/version.generated.d.ts +1 -1
  143. package/dist/version.generated.d.ts.map +1 -1
  144. package/dist/version.generated.js +1 -1
  145. package/dist/workflows/specs.d.ts +28 -0
  146. package/dist/workflows/specs.d.ts.map +1 -1
  147. package/dist/workflows/specs.js +26 -1
  148. package/dist/workflows/usage.d.ts +38 -0
  149. package/dist/workflows/usage.d.ts.map +1 -0
  150. package/dist/workflows/usage.js +77 -0
  151. package/dist/workflows/worker.js +2 -2
  152. package/dist/workflows/workerConfig.d.ts.map +1 -1
  153. package/dist/workflows/workerConfig.js +8 -2
  154. package/docs/entitlements.md +249 -0
  155. package/docs/lemon-squeezy.md +1 -0
  156. package/docs/paddle.md +18 -2
  157. package/package.json +7 -7
  158. package/pithy.manifest.json +3 -8
  159. package/src/admin/coverage.ts +28 -0
  160. package/src/admin/read.ts +173 -1
  161. package/src/audit/actions.ts +13 -0
  162. package/src/capability.ts +87 -9
  163. package/src/client/api.ts +79 -0
  164. package/src/client/hooks.ts +122 -0
  165. package/src/client/paddleLink.ts +41 -0
  166. package/src/client/projection.ts +31 -0
  167. package/src/config/allowances.ts +211 -0
  168. package/src/config/config.ts +283 -15
  169. package/src/data/meterCounter.ts +38 -0
  170. package/src/data/override.ts +74 -0
  171. package/src/data/paddleIds.ts +74 -0
  172. package/src/data/period.ts +53 -0
  173. package/src/data/purchase.ts +9 -0
  174. package/src/data/tables.ts +25 -1
  175. package/src/data/usageReport.ts +64 -0
  176. package/src/data/usageRun.ts +66 -0
  177. package/src/entitlement/allowance.ts +213 -0
  178. package/src/entitlement/manual.ts +6 -6
  179. package/src/entitlement/meter.ts +252 -0
  180. package/src/entitlement/override.ts +381 -0
  181. package/src/entitlement/resolver.ts +43 -2
  182. package/src/entitlement/unimplementedSubject.ts +3 -4
  183. package/src/error/errors.ts +44 -1
  184. package/src/http/responses.ts +338 -10
  185. package/src/http/routes.ts +1089 -460
  186. package/src/http/schemas.ts +171 -2
  187. package/src/http/scopes.ts +68 -0
  188. package/src/http/view.ts +112 -7
  189. package/src/http/webhookGuard.ts +3 -2
  190. package/src/index.ts +18 -0
  191. package/src/migrations/0002_allowances.ts +149 -0
  192. package/src/projection/event.ts +9 -0
  193. package/src/projection/writer.ts +4 -0
  194. package/src/rails/contract.ts +6 -0
  195. package/src/rails/google/playApi.ts +2 -0
  196. package/src/rails/paddle/events.ts +2 -1
  197. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  198. package/src/rails/paddle/objects.ts +6 -0
  199. package/src/rails/paddle/refresh.ts +17 -10
  200. package/src/rails/paddle/refund.ts +10 -2
  201. package/src/rails/paddle/subscription.ts +8 -3
  202. package/src/rails/paddle/usage.ts +66 -0
  203. package/src/rails/paddle/verify.ts +6 -4
  204. package/src/rails/quantity.ts +14 -0
  205. package/src/rails/stripe/checkout.ts +3 -1
  206. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  207. package/src/rails/stripe/objects.ts +4 -0
  208. package/src/rails/stripe/usage.ts +61 -0
  209. package/src/secret/registry.ts +3 -2
  210. package/src/usage/pass.ts +539 -0
  211. package/src/usage/reporter.ts +38 -0
  212. package/src/version.generated.ts +1 -1
  213. package/src/workflows/specs.ts +34 -0
  214. package/src/workflows/usage.ts +97 -0
  215. package/src/workflows/workerConfig.ts +9 -3
@@ -2,19 +2,30 @@
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";
9
+ import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
10
10
  import { InternalError, NotFoundError, PithyError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
11
11
  import { memoryJwksCache } from "@pithy-sh/core/src/http/oidcWebhook";
12
- import { validationHook } from "@pithy-sh/core/src/http/validation";
12
+ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
13
+ import { validate } from "@pithy-sh/core/src/http/validation";
13
14
  import { resolveWorkflowBinding } from "@pithy-sh/core/src/workflow/dispatch";
14
15
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
15
16
  import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
16
17
  import type { Context, Hono } from "hono";
17
- import { listEntitlements, listPurchases, listReconcileRuns, listSubscriptions, readEntitlements } from "../admin/read";
18
+ import {
19
+ lastReports,
20
+ listEntitlements,
21
+ listOverrides,
22
+ listPurchases,
23
+ listReconcileRuns,
24
+ listSubscriptions,
25
+ listUsageRuns,
26
+ readEntitlements,
27
+ unrestrictedSubjects,
28
+ } from "../admin/read";
18
29
  import { type PaymentsAuditAction, PaymentsAuditActions } from "../audit/actions";
19
30
  import {
20
31
  type PaymentsCatalogEntry,
@@ -44,7 +55,19 @@ import {
44
55
  } from "../data/subscription";
45
56
  import { PAYMENTS_PURCHASES_TABLE, paymentsDatabase } from "../data/tables";
46
57
  import { WEBHOOK_EVENT_ORPHANED } from "../data/webhookEvent";
58
+ import { resolveAllowances } from "../entitlement/allowance";
47
59
  import { grantEntitlement, revokeEntitlement } from "../entitlement/manual";
60
+ import { allowanceInputFor } from "../entitlement/meter";
61
+ import {
62
+ allowanceOverride,
63
+ clearOverride,
64
+ type OverrideChange,
65
+ overrideCeiling,
66
+ overrideVersion,
67
+ readOverride,
68
+ setOverride,
69
+ setUnrestricted,
70
+ } from "../entitlement/override";
48
71
  import { type PaymentsSubjectSeam, requirePaymentsSubject, resolvePaymentsSubject } from "../entitlement/subjectSeam";
49
72
  import {
50
73
  PaymentsEntitlementNotInCatalogError,
@@ -76,40 +99,46 @@ import { type RailTrustOptions, resolveRailProvider } from "../rails/providers";
76
99
  import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/registry";
77
100
  import { PAYMENTS_CAPABILITY, paymentsWorkflows } from "../workflows/specs";
78
101
  import { requireAuth } from "./guards";
79
- import type {
102
+ import {
80
103
  PaymentsAdminCatalogResponse,
81
104
  PaymentsAdminDiscountsResponse,
82
105
  PaymentsAdminEntitlementsResponse,
106
+ PaymentsAdminOverridesResponse,
83
107
  PaymentsAdminPurchasesResponse,
84
108
  PaymentsAdminReconcileRunStarted,
85
109
  PaymentsAdminReconcileRunsResponse,
86
110
  PaymentsAdminSubjectEntitlementsResponse,
87
111
  PaymentsAdminSubscriptionsResponse,
112
+ PaymentsAdminUsageRunsResponse,
88
113
  PaymentsCheckoutHandoffResponse,
89
114
  PaymentsDiscountResponse,
90
115
  PaymentsEntitlementResponse,
91
116
  PaymentsEntitlementsResponse,
117
+ PaymentsOverrideResponse,
92
118
  PaymentsPortalHandoffResponse,
93
119
  PaymentsPricingEnvelope,
94
- PaymentsPricingResponse,
120
+ type PaymentsPricingResponse,
95
121
  PaymentsPurchaseResponse,
96
- PaymentsQuotedFrom,
97
- PaymentsRefundRequest,
122
+ type PaymentsQuotedFrom,
123
+ type PaymentsRefundRequest,
98
124
  PaymentsRefundResponse,
99
125
  PaymentsRestoreResponse,
100
- PaymentsSubscriptionQuote,
126
+ type PaymentsSubscriptionQuote,
101
127
  PaymentsSubscriptionQuoteResponse,
102
128
  PaymentsSubscriptionResponse,
103
129
  PaymentsSubscriptionStandingResponse,
104
- PaymentsSubscriptionView,
130
+ type PaymentsSubscriptionView,
131
+ PaymentsWebhookAck,
105
132
  } from "./responses";
106
133
  import {
107
134
  AdminDiscountsQuery,
108
135
  AdminEntitlementsQuery,
136
+ AdminOverridesQuery,
109
137
  AdminPurchasesQuery,
110
138
  AdminReconcileRunsQuery,
111
139
  AdminSubjectParam,
112
140
  AdminSubscriptionsQuery,
141
+ AdminUsageRunsQuery,
113
142
  AppleWebhookNotification,
114
143
  CheckoutRequest,
115
144
  DiscountCreateRequest,
@@ -117,6 +146,10 @@ import {
117
146
  EntitlementRevokeRequest,
118
147
  GoogleWebhookNotification,
119
148
  LemonSqueezyWebhookNotification,
149
+ OverrideClearRequest,
150
+ OverrideSetRequest,
151
+ OverrideUnrestrictedRequest,
152
+ PaddleResumeQuery,
120
153
  PaddleWebhookNotification,
121
154
  PurchaseSubmission,
122
155
  RestoreRequest,
@@ -132,17 +165,25 @@ import {
132
165
  PAYMENTS_ENTITLEMENT_GRANT_SCOPE,
133
166
  PAYMENTS_ENTITLEMENT_REVOKE_SCOPE,
134
167
  PAYMENTS_ENTITLEMENTS_READ_SCOPE,
168
+ PAYMENTS_OVERRIDE_CLEAR_SCOPE,
169
+ PAYMENTS_OVERRIDE_SET_SCOPE,
170
+ PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE,
135
171
  PAYMENTS_PURCHASES_READ_SCOPE,
136
172
  PAYMENTS_RECONCILE_READ_SCOPE,
137
173
  PAYMENTS_RECONCILE_RUN_SCOPE,
138
174
  PAYMENTS_SUBSCRIPTIONS_READ_SCOPE,
175
+ PAYMENTS_USAGE_READ_SCOPE,
139
176
  } from "./scopes";
140
177
  import {
178
+ adminAllowancesView,
141
179
  adminCatalogView,
142
180
  adminEntitlementView,
181
+ adminOverrideView,
143
182
  adminPurchaseView,
144
183
  adminReconcileRunView,
184
+ adminUsageRunView,
145
185
  entitlementView,
186
+ overrideView,
146
187
  purchaseView,
147
188
  } from "./view";
148
189
  import { completeWebhook, requireSignedWebhook, verifiedWebhook } from "./webhookGuard";
@@ -165,6 +206,8 @@ import { completeWebhook, requireSignedWebhook, verifiedWebhook } from "./webhoo
165
206
  * (bearer | session) —
166
207
  * POST /payments/checkout → a hosted checkout, on whichever rail sells the product
167
208
  * (bearer | session) json: CheckoutRequest
209
+ * GET /payments/checkout/resume → open the transaction a `_ptxn` link arrived for
210
+ * (none) query: PaddleResumeQuery
168
211
  * POST /payments/portal → a billing-portal session (bearer | session) —
169
212
  * GET /payments/subscription → where the caller's subscription stands, read live
170
213
  * (bearer | session) —
@@ -231,8 +274,10 @@ import { completeWebhook, requireSignedWebhook, verifiedWebhook } from "./webhoo
231
274
  * selects a verifier through `resolveRailProvider`, and everything past that point is the normalized event. A
232
275
  * rail arriving is one entry in `rails/providers.ts`, not a case in a handler.
233
276
  *
234
- * **No `public` routes, ever.** Every caller is either an authenticated user acting on their own purchases or a
235
- * machine proving authenticity. Turnstile has nothing to gate here.
277
+ * **One `public` route, and only one.** `GET /checkout/resume` opens the transaction a Paddle payment link
278
+ * arrived for, and the person following that link may not be signed in. Every other caller is either an
279
+ * authenticated user acting on their own purchases or a machine proving authenticity. Turnstile has nothing
280
+ * to gate here.
236
281
  *
237
282
  * **`signed-webhook` is one strategy over three unrelated mechanisms** — Apple signs a JWS against its
238
283
  * certificate chain, Google's Pub/Sub push carries an OIDC token verified with an audience check, Stripe sends
@@ -1328,13 +1373,23 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1328
1373
  * No query at all, and none to add: the catalog is small, fixed at deploy, and has no page. What
1329
1374
  * crosses is decided by `adminCatalogView` and asserted as an invariant rather than as a field list.
1330
1375
  */
1331
- app.get(`${base}/admin/catalog`, requireControlPlane(PAYMENTS_CATALOG_READ_SCOPE), async (c) => {
1332
- const view = adminCatalogView(config);
1333
- await recordRead(c, PaymentsAuditActions.catalogRead, null, {
1334
- products: view.enabled ? view.products.length : 0,
1335
- });
1336
- return c.json(view satisfies PaymentsAdminCatalogResponse, 200);
1337
- });
1376
+ app.get(
1377
+ `${base}/admin/catalog`,
1378
+ describeRoute({
1379
+ summary: "Read what this project sells, and the keys it comps by hand.",
1380
+ verification: "control-plane",
1381
+ scopes: [PAYMENTS_CATALOG_READ_SCOPE],
1382
+ responses: { 200: PaymentsAdminCatalogResponse },
1383
+ }),
1384
+ requireControlPlane(PAYMENTS_CATALOG_READ_SCOPE),
1385
+ async (c) => {
1386
+ const view = adminCatalogView(config);
1387
+ await recordRead(c, PaymentsAuditActions.catalogRead, null, {
1388
+ products: view.enabled ? view.products.length : 0,
1389
+ });
1390
+ return c.json(view satisfies PaymentsAdminCatalogResponse, 200);
1391
+ },
1392
+ );
1338
1393
 
1339
1394
  /**
1340
1395
  * CONTROL PLANE. The purchase log, paged, newest first.
@@ -1346,8 +1401,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1346
1401
  */
1347
1402
  app.get(
1348
1403
  `${base}/admin/purchases`,
1404
+ describeRoute({
1405
+ summary: "Read the purchase log, newest first.",
1406
+ verification: "control-plane",
1407
+ scopes: [PAYMENTS_PURCHASES_READ_SCOPE],
1408
+ responses: { 200: PaymentsAdminPurchasesResponse },
1409
+ }),
1349
1410
  requireControlPlane(PAYMENTS_PURCHASES_READ_SCOPE),
1350
- zValidator("query", AdminPurchasesQuery, validationHook),
1411
+ validate("query", AdminPurchasesQuery),
1351
1412
  async (c) => {
1352
1413
  const query = c.req.valid("query");
1353
1414
  const subject = subjectFilter(query);
@@ -1373,7 +1434,7 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1373
1434
  );
1374
1435
  return c.json(
1375
1436
  {
1376
- purchases: page.items.map(adminPurchaseView),
1437
+ purchases: page.items.map((row) => adminPurchaseView(row)),
1377
1438
  nextCursor: page.nextCursor,
1378
1439
  } satisfies PaymentsAdminPurchasesResponse,
1379
1440
  200,
@@ -1392,12 +1453,26 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1392
1453
  */
1393
1454
  app.get(
1394
1455
  `${base}/admin/subscriptions`,
1456
+ describeRoute({
1457
+ summary: "Read the purchases that renew, newest first.",
1458
+ verification: "control-plane",
1459
+ scopes: [PAYMENTS_SUBSCRIPTIONS_READ_SCOPE],
1460
+ responses: { 200: PaymentsAdminSubscriptionsResponse },
1461
+ }),
1395
1462
  requireControlPlane(PAYMENTS_SUBSCRIPTIONS_READ_SCOPE),
1396
- zValidator("query", AdminSubscriptionsQuery, validationHook),
1463
+ validate("query", AdminSubscriptionsQuery),
1397
1464
  async (c) => {
1398
1465
  const query = c.req.valid("query");
1399
1466
  const subject = subjectFilter(query);
1400
1467
  const page = await listSubscriptions(database(c), { ...query, subject });
1468
+ const reported = await lastReports(
1469
+ database(c),
1470
+ page.items.flatMap((row) =>
1471
+ row.originalTransactionId === null
1472
+ ? []
1473
+ : [{ rail: row.rail, providerSubscriptionId: row.originalTransactionId }],
1474
+ ),
1475
+ );
1401
1476
  await recordRead(
1402
1477
  c,
1403
1478
  PaymentsAuditActions.subscriptionsRead,
@@ -1414,7 +1489,9 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1414
1489
  );
1415
1490
  return c.json(
1416
1491
  {
1417
- subscriptions: page.items.map(adminPurchaseView),
1492
+ subscriptions: page.items.map((row) =>
1493
+ adminPurchaseView(row, reported.get(`${row.rail}:${row.originalTransactionId}`) ?? null),
1494
+ ),
1418
1495
  nextCursor: page.nextCursor,
1419
1496
  } satisfies PaymentsAdminSubscriptionsResponse,
1420
1497
  200,
@@ -1431,13 +1508,22 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1431
1508
  */
1432
1509
  app.get(
1433
1510
  `${base}/admin/entitlements`,
1511
+ describeRoute({
1512
+ summary: "Read the entitlement model, page by page.",
1513
+ verification: "control-plane",
1514
+ scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
1515
+ responses: { 200: PaymentsAdminEntitlementsResponse },
1516
+ }),
1434
1517
  requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE),
1435
- zValidator("query", AdminEntitlementsQuery, validationHook),
1518
+ validate("query", AdminEntitlementsQuery),
1436
1519
  async (c) => {
1437
1520
  const query = c.req.valid("query");
1438
1521
  const now = clock();
1439
1522
  const subject = subjectFilter(query);
1440
1523
  const page = await listEntitlements(database(c), { ...query, subject });
1524
+ // Which of the page's subjects are unrestricted, in one read — marked on every row, because the
1525
+ // largest grant the kit has must be visible wherever its holder is.
1526
+ const unrestricted = await unrestrictedSubjects(database(c), page.items);
1441
1527
  await recordRead(
1442
1528
  c,
1443
1529
  PaymentsAuditActions.entitlementsRead,
@@ -1454,7 +1540,9 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1454
1540
  );
1455
1541
  return c.json(
1456
1542
  {
1457
- entitlements: page.items.map((row) => adminEntitlementView(row, now)),
1543
+ entitlements: page.items.map((row) =>
1544
+ adminEntitlementView(row, now, unrestricted.has(encodeSubjectReference(row))),
1545
+ ),
1458
1546
  nextCursor: page.nextCursor,
1459
1547
  } satisfies PaymentsAdminEntitlementsResponse,
1460
1548
  200,
@@ -1462,6 +1550,62 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1462
1550
  },
1463
1551
  );
1464
1552
 
1553
+ /**
1554
+ * CONTROL PLANE. Every subject's override, most recently changed first.
1555
+ *
1556
+ * The read the override writes are paired with, on the entitlement read's scope: what a subject may have
1557
+ * is one question with its entitlements, and an operator who can see one can see the other. Filterable to
1558
+ * `unrestricted=true`, because "who holds the whole product" must be a question anyone holding this scope
1559
+ * can answer in one request.
1560
+ */
1561
+ app.get(
1562
+ `${base}/admin/overrides`,
1563
+ describeRoute({
1564
+ summary: "Read every subject's override, page by page.",
1565
+ verification: "control-plane",
1566
+ scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
1567
+ responses: { 200: PaymentsAdminOverridesResponse },
1568
+ }),
1569
+ requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE),
1570
+ validate("query", AdminOverridesQuery),
1571
+ async (c) => {
1572
+ const query = c.req.valid("query");
1573
+ const subject = subjectFilter(query);
1574
+ const unrestricted = query.unrestricted === undefined ? undefined : query.unrestricted === "true";
1575
+ const page = await listOverrides(database(c), {
1576
+ ...(subject ? { subject } : {}),
1577
+ ...(unrestricted === undefined ? {} : { unrestricted }),
1578
+ ...(query.cursor ? { cursor: query.cursor } : {}),
1579
+ ...(query.limit ? { limit: query.limit } : {}),
1580
+ });
1581
+ await recordRead(
1582
+ c,
1583
+ PaymentsAuditActions.entitlementsRead,
1584
+ subject === undefined ? null : encodeSubjectReference(subject),
1585
+ {
1586
+ returned: page.items.length,
1587
+ resumed: query.cursor !== undefined,
1588
+ filters: {
1589
+ subjectType: subject?.subjectType ?? null,
1590
+ subjectId: subject?.subjectId ?? null,
1591
+ unrestricted: unrestricted ?? null,
1592
+ },
1593
+ },
1594
+ );
1595
+ return c.json(
1596
+ {
1597
+ overrides: page.items.map((row) => ({
1598
+ subjectType: row.subjectType,
1599
+ subjectId: row.subjectId,
1600
+ override: overrideView(row),
1601
+ })),
1602
+ nextCursor: page.nextCursor,
1603
+ } satisfies PaymentsAdminOverridesResponse,
1604
+ 200,
1605
+ );
1606
+ },
1607
+ );
1608
+
1465
1609
  /**
1466
1610
  * CONTROL PLANE. Everything one subject is entitled to, resolved now.
1467
1611
  *
@@ -1479,21 +1623,41 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1479
1623
  */
1480
1624
  app.get(
1481
1625
  `${base}/admin/entitlements/:subjectType/:subjectId`,
1626
+ describeRoute({
1627
+ summary: "Read one subject's entitlements, resolved now.",
1628
+ verification: "control-plane",
1629
+ scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
1630
+ responses: { 200: PaymentsAdminSubjectEntitlementsResponse },
1631
+ }),
1482
1632
  requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE),
1483
- zValidator("param", AdminSubjectParam, validationHook),
1633
+ validate("param", AdminSubjectParam),
1484
1634
  async (c) => {
1485
1635
  const subject = c.req.valid("param");
1486
1636
  const now = clock();
1487
- const rows = await readEntitlements(database(c), subject);
1637
+ const d1 = database(c);
1638
+ const rows = await readEntitlements(d1, subject);
1639
+ const override = await readOverride(paymentsDatabase(d1), subject);
1640
+ // The held keys from the rows already read, resolved against `now` exactly as the gate resolves them.
1641
+ const held = grantedEntitlementKeys(
1642
+ rows.map((row) => ({ key: row.entitlement, active: row.active, expiresAt: row.expiresAt, source: null })),
1643
+ now,
1644
+ );
1645
+ const resolved = resolveAllowances({ declarations: config, held, override: allowanceOverride(override) });
1646
+ const unrestricted = override?.unrestricted === true;
1488
1647
  await recordRead(c, PaymentsAuditActions.entitlementsRead, encodeSubjectReference(subject), {
1489
1648
  subjectType: subject.subjectType,
1490
1649
  subjectId: subject.subjectId,
1491
1650
  returned: rows.length,
1651
+ unrestricted,
1492
1652
  });
1493
1653
  return c.json(
1494
1654
  {
1495
1655
  ...subject,
1496
- entitlements: rows.map((row) => adminEntitlementView(row, now)),
1656
+ entitlements: rows.map((row) => adminEntitlementView(row, now, unrestricted)),
1657
+ unrestricted,
1658
+ overrideVersion: overrideVersion(override),
1659
+ override: adminOverrideView(override),
1660
+ allowances: adminAllowancesView(resolved, (name) => overrideCeiling(config, held, name)),
1497
1661
  } satisfies PaymentsAdminSubjectEntitlementsResponse,
1498
1662
  200,
1499
1663
  );
@@ -1512,8 +1676,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1512
1676
  */
1513
1677
  app.get(
1514
1678
  `${base}/admin/reconcile-runs`,
1679
+ describeRoute({
1680
+ summary: "Read the reconciliation passes this deployment has run.",
1681
+ verification: "control-plane",
1682
+ scopes: [PAYMENTS_RECONCILE_READ_SCOPE],
1683
+ responses: { 200: PaymentsAdminReconcileRunsResponse },
1684
+ }),
1515
1685
  requireControlPlane(PAYMENTS_RECONCILE_READ_SCOPE),
1516
- zValidator("query", AdminReconcileRunsQuery, validationHook),
1686
+ validate("query", AdminReconcileRunsQuery),
1517
1687
  async (c) => {
1518
1688
  const query = c.req.valid("query");
1519
1689
  const page = await listReconcileRuns(database(c), query);
@@ -1532,6 +1702,40 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1532
1702
  },
1533
1703
  );
1534
1704
 
1705
+ /**
1706
+ * CONTROL PLANE. What usage reporting has done — the passes this Worker has run, newest first.
1707
+ *
1708
+ * Its own scope, separate from the reconciliation log's: a run's findings name the subjects it did not
1709
+ * report and why, which is what an operator answering "why was this customer not billed" needs and what a
1710
+ * health monitor does not.
1711
+ */
1712
+ app.get(
1713
+ `${base}/admin/usage-runs`,
1714
+ describeRoute({
1715
+ summary: "Read the usage-reporting passes this deployment has run.",
1716
+ verification: "control-plane",
1717
+ scopes: [PAYMENTS_USAGE_READ_SCOPE],
1718
+ responses: { 200: PaymentsAdminUsageRunsResponse },
1719
+ }),
1720
+ requireControlPlane(PAYMENTS_USAGE_READ_SCOPE),
1721
+ validate("query", AdminUsageRunsQuery),
1722
+ async (c) => {
1723
+ const query = c.req.valid("query");
1724
+ const page = await listUsageRuns(database(c), query);
1725
+ await recordRead(c, PaymentsAuditActions.usageRunsRead, null, {
1726
+ returned: page.items.length,
1727
+ resumed: query.cursor !== undefined,
1728
+ });
1729
+ return c.json(
1730
+ {
1731
+ runs: page.items.map(adminUsageRunView),
1732
+ nextCursor: page.nextCursor,
1733
+ } satisfies PaymentsAdminUsageRunsResponse,
1734
+ 200,
1735
+ );
1736
+ },
1737
+ );
1738
+
1535
1739
  /**
1536
1740
  * CONTROL PLANE WRITE. Start a reconciliation pass now.
1537
1741
  *
@@ -1550,50 +1754,60 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1550
1754
  * pass happen, and answering 202 while nothing started is the failure this codebase spends its comments
1551
1755
  * avoiding — so the binding is resolved directly and its absence is a refusal naming what to deploy.
1552
1756
  *
1553
- * Idempotent, like the pass itself. A second press while one is in flight starts nothing and says
1554
- * `started: false`, which is a true sentence rather than a 409 that reads as a fault.
1757
+ * Every press that is not refused starts a pass and answers `started: true`. A second press while one is
1758
+ * in flight starts a second: the pass is idempotent, so two converge on the same repairs.
1555
1759
  */
1556
- app.post(`${base}/admin/reconcile-runs`, requireControlPlane(PAYMENTS_RECONCILE_RUN_SCOPE), async (c) => {
1557
- const spec = paymentsWorkflows.reconcile;
1558
- const binding = resolveWorkflowBinding(c.env as Record<string, unknown>, {
1559
- binding: spec.binding,
1560
- capability: PAYMENTS_CAPABILITY,
1561
- log: c.var.log,
1562
- });
1563
- if (!binding) {
1564
- // Named as a provisioning fact rather than a fault of the request: the caller's scope was right, the
1565
- // route exists, and the job's host is not deployed here. `action` is what a person does about it.
1566
- throw new PaymentsReconcileNotProvisionedError({
1567
- detail: `Dispatching a reconciliation pass needs a Workflow binding named ${spec.binding} on this Worker.`,
1760
+ app.post(
1761
+ `${base}/admin/reconcile-runs`,
1762
+ describeRoute({
1763
+ summary: "Start a reconciliation pass now.",
1764
+ verification: "control-plane",
1765
+ scopes: [PAYMENTS_RECONCILE_RUN_SCOPE],
1766
+ responses: { 202: PaymentsAdminReconcileRunStarted },
1767
+ }),
1768
+ requireControlPlane(PAYMENTS_RECONCILE_RUN_SCOPE),
1769
+ async (c) => {
1770
+ const spec = paymentsWorkflows.reconcile;
1771
+ const binding = resolveWorkflowBinding(c.env as Record<string, unknown>, {
1772
+ binding: spec.binding,
1773
+ capability: PAYMENTS_CAPABILITY,
1774
+ log: c.var.log,
1568
1775
  });
1569
- }
1776
+ if (!binding) {
1777
+ // Named as a provisioning fact rather than a fault of the request: the caller's scope was right, the
1778
+ // route exists, and the job's host is not deployed here. `action` is what a person does about it.
1779
+ throw new PaymentsReconcileNotProvisionedError({
1780
+ detail: `Dispatching a reconciliation pass needs a Workflow binding named ${spec.binding} on this Worker.`,
1781
+ });
1782
+ }
1570
1783
 
1571
- // `create` answers `unknown` — the binding is structural, matched by having the method at all, and a
1572
- // loopback stand-in under `pithy dev` answers a different shape from the Workflows runtime. Narrowed
1573
- // here rather than cast: an instance with no readable id is a pass that started and cannot be named,
1574
- // which is `runId: null` and a true sentence, not a reason to fail the press.
1575
- const instance: unknown = await binding.create({ params: {} });
1576
- const runId =
1577
- typeof instance === "object" && instance !== null && "id" in instance && typeof instance.id === "string"
1578
- ? instance.id
1579
- : null;
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
- });
1784
+ // `create` answers `unknown` — the binding is structural, matched by having the method at all, and a
1785
+ // loopback stand-in under `pithy dev` answers a different shape from the Workflows runtime. Narrowed
1786
+ // here rather than cast: an instance with no readable id is a pass that started and cannot be named,
1787
+ // which is `runId: null` and a true sentence, not a reason to fail the press.
1788
+ const instance: unknown = await binding.create({ params: {} });
1789
+ const runId =
1790
+ typeof instance === "object" && instance !== null && "id" in instance && typeof instance.id === "string"
1791
+ ? instance.id
1792
+ : null;
1594
1793
 
1595
- return c.json({ started: true, runId } satisfies PaymentsAdminReconcileRunStarted, 202);
1596
- });
1794
+ const who = controlPlaneCaller(c);
1795
+ await c.var.emit({
1796
+ action: PaymentsAuditActions.reconcileRunStarted,
1797
+ outcome: "success",
1798
+ // The token's `sub`, so the trail names the person at the console rather than the console. One
1799
+ // connection is normally shared by everybody using it, and this row is the join to every repair the
1800
+ // pass then made.
1801
+ actorType: "control-plane",
1802
+ actorId: who.subject,
1803
+ resourceType: "reconcile_run",
1804
+ resourceId: runId,
1805
+ metadata: { deployment: deploymentName(c) },
1806
+ });
1807
+
1808
+ return c.json({ started: true, runId } satisfies PaymentsAdminReconcileRunStarted, 202);
1809
+ },
1810
+ );
1597
1811
 
1598
1812
  /**
1599
1813
  * AUTHED WRITE. The purchaser's own app submitting what the store SDK gave it, so the buyer sees their
@@ -1601,63 +1815,73 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1601
1815
  * existing purchase — the write path is idempotent, so a repeat is not an error. A receipt belonging to
1602
1816
  * somebody else is a 409, audited as denied.
1603
1817
  */
1604
- app.post(`${base}/purchases`, requireAuth(), zValidator("json", PurchaseSubmission, validationHook), async (c) => {
1605
- const input = c.req.valid("json");
1606
- // Resolved before the store is called: a caller acting for nobody has no row to write, so refusing here
1607
- // costs no round trip and cannot leave a charged customer with an unattributed purchase.
1608
- const subject = await requirePaymentsSubject(c, seam);
1609
- try {
1610
- const projection = await submit(c, subject, input.rail, input.receipt);
1611
- await c.var.emit({
1612
- action: PaymentsAuditActions.purchaseVerified,
1613
- outcome: "success",
1614
- // The person who submitted, always — the subject they act for rides in the metadata below. Under
1615
- // organization billing the two differ, and collapsing them would answer "who did this" with a
1616
- // company rather than with somebody who can be asked.
1617
- actorType: "user",
1618
- actorId: c.var.auth?.userId,
1619
- sessionId: c.var.auth?.sessionId,
1620
- resourceType: "purchase",
1621
- resourceId: projection.purchase.id,
1622
- // Identifiers and outcomes only. Never the receipt: the trail is long-lived and queryable, and a
1623
- // receipt is a bearer artifact. The holder is two keys, never one joined string.
1624
- metadata: {
1625
- rail: input.rail,
1626
- subjectType: subject.subjectType,
1627
- subjectId: subject.subjectId,
1628
- productId: projection.product.id,
1629
- status: projection.purchase.status,
1630
- outcome: projection.outcome,
1631
- },
1632
- });
1633
- return c.json(
1634
- {
1635
- purchase: purchaseView(projection),
1636
- entitlements: projection.entitlements.map((row) =>
1637
- entitlementView({ key: row.entitlement, active: row.active, expiresAt: row.expiresAt }),
1638
- ),
1639
- } satisfies PaymentsPurchaseResponse,
1640
- 200,
1641
- );
1642
- } catch (cause) {
1643
- // A refused submission is the security-relevant event, so it is recorded before the error propagates.
1644
- await c.var.emit({
1645
- action: PaymentsAuditActions.purchaseVerified,
1646
- outcome: "denied",
1647
- severity: "warning",
1648
- actorType: "user",
1649
- actorId: c.var.auth?.userId,
1650
- sessionId: c.var.auth?.sessionId,
1651
- metadata: {
1652
- rail: input.rail,
1653
- subjectType: subject.subjectType,
1654
- subjectId: subject.subjectId,
1655
- reason: cause instanceof PithyError ? cause.payload.code : "unknown",
1656
- },
1657
- });
1658
- throw cause;
1659
- }
1660
- });
1818
+ app.post(
1819
+ `${base}/purchases`,
1820
+ describeRoute({
1821
+ summary: "Verify a receipt and project the purchase.",
1822
+ verification: ["bearer", "session"],
1823
+ responses: { 200: PaymentsPurchaseResponse },
1824
+ }),
1825
+ requireAuth(),
1826
+ validate("json", PurchaseSubmission),
1827
+ async (c) => {
1828
+ const input = c.req.valid("json");
1829
+ // Resolved before the store is called: a caller acting for nobody has no row to write, so refusing here
1830
+ // costs no round trip and cannot leave a charged customer with an unattributed purchase.
1831
+ const subject = await requirePaymentsSubject(c, seam);
1832
+ try {
1833
+ const projection = await submit(c, subject, input.rail, input.receipt);
1834
+ await c.var.emit({
1835
+ action: PaymentsAuditActions.purchaseVerified,
1836
+ outcome: "success",
1837
+ // The person who submitted, always — the subject they act for rides in the metadata below. Under
1838
+ // organization billing the two differ, and collapsing them would answer "who did this" with a
1839
+ // company rather than with somebody who can be asked.
1840
+ actorType: "user",
1841
+ actorId: c.var.auth?.userId,
1842
+ sessionId: c.var.auth?.sessionId,
1843
+ resourceType: "purchase",
1844
+ resourceId: projection.purchase.id,
1845
+ // Identifiers and outcomes only. Never the receipt: the trail is long-lived and queryable, and a
1846
+ // receipt is a bearer artifact. The holder is two keys, never one joined string.
1847
+ metadata: {
1848
+ rail: input.rail,
1849
+ subjectType: subject.subjectType,
1850
+ subjectId: subject.subjectId,
1851
+ productId: projection.product.id,
1852
+ status: projection.purchase.status,
1853
+ outcome: projection.outcome,
1854
+ },
1855
+ });
1856
+ return c.json(
1857
+ {
1858
+ purchase: purchaseView(projection),
1859
+ entitlements: projection.entitlements.map((row) =>
1860
+ entitlementView({ key: row.entitlement, active: row.active, expiresAt: row.expiresAt }),
1861
+ ),
1862
+ } satisfies PaymentsPurchaseResponse,
1863
+ 200,
1864
+ );
1865
+ } catch (cause) {
1866
+ // A refused submission is the security-relevant event, so it is recorded before the error propagates.
1867
+ await c.var.emit({
1868
+ action: PaymentsAuditActions.purchaseVerified,
1869
+ outcome: "denied",
1870
+ severity: "warning",
1871
+ actorType: "user",
1872
+ actorId: c.var.auth?.userId,
1873
+ sessionId: c.var.auth?.sessionId,
1874
+ metadata: {
1875
+ rail: input.rail,
1876
+ subjectType: subject.subjectType,
1877
+ subjectId: subject.subjectId,
1878
+ reason: cause instanceof PithyError ? cause.payload.code : "unknown",
1879
+ },
1880
+ });
1881
+ throw cause;
1882
+ }
1883
+ },
1884
+ );
1661
1885
 
1662
1886
  /**
1663
1887
  * AUTHED READ. Always the caller's own holder — the subject comes from the seam, never the request, so
@@ -1669,14 +1893,36 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1669
1893
  * already answers for somebody who has bought nothing — and a 403 here would make a paywall render an
1670
1894
  * error where it should render the paywall.
1671
1895
  */
1672
- app.get(`${base}/entitlements`, requireAuth(), async (c) => {
1673
- const subject = await resolvePaymentsSubject(c, seam);
1674
- if (subject === undefined) {
1675
- return c.json({ entitlements: [] } satisfies PaymentsEntitlementsResponse, 200);
1676
- }
1677
- const entitlements = await resolveEntitlements(paymentsDatabase(database(c)), subject, clock());
1678
- return c.json({ entitlements: entitlements.map(entitlementView) } satisfies PaymentsEntitlementsResponse, 200);
1679
- });
1896
+ app.get(
1897
+ `${base}/entitlements`,
1898
+ describeRoute({
1899
+ summary: "Read the caller's own entitlements.",
1900
+ verification: ["bearer", "session"],
1901
+ responses: { 200: PaymentsEntitlementsResponse },
1902
+ }),
1903
+ requireAuth(),
1904
+ async (c) => {
1905
+ const subject = await resolvePaymentsSubject(c, seam);
1906
+ const now = clock();
1907
+ // The allowances ride beside the keys, resolved exactly as `quota(c, name)` resolves them — the floor
1908
+ // for a caller acting for nobody, never an error and never unlimited.
1909
+ const db = subject === undefined ? undefined : paymentsDatabase(database(c));
1910
+ const input = await allowanceInputFor(db, config, subject, now);
1911
+ const resolved = resolveAllowances(input);
1912
+ const allowances = {
1913
+ quotas: Object.fromEntries(resolved.quotas.map((entry) => [entry.name, entry.effective.value])),
1914
+ features: Object.fromEntries(resolved.features.map((entry) => [entry.name, entry.effective.value])),
1915
+ };
1916
+ if (subject === undefined || db === undefined) {
1917
+ return c.json({ entitlements: [], ...allowances } satisfies PaymentsEntitlementsResponse, 200);
1918
+ }
1919
+ const entitlements = await resolveEntitlements(db, subject, now);
1920
+ return c.json(
1921
+ { entitlements: entitlements.map(entitlementView), ...allowances } satisfies PaymentsEntitlementsResponse,
1922
+ 200,
1923
+ );
1924
+ },
1925
+ );
1680
1926
 
1681
1927
  /**
1682
1928
  * AUTHED WRITE. Restore Purchases, client-driven because only the device can enumerate what its store
@@ -1687,42 +1933,58 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1687
1933
  * success would hide it. Every receipt that did project stays projected — the writer is idempotent, so the
1688
1934
  * client simply retries.
1689
1935
  */
1690
- app.post(`${base}/restore`, requireAuth(), zValidator("json", RestoreRequest, validationHook), async (c) => {
1691
- const input = c.req.valid("json");
1692
- // One resolution for the whole batch. A client submits *its own* history, so every receipt in it is
1693
- // filed against one holder or the request is refused — asking the seam per receipt would let the answer
1694
- // change mid-batch and split one store account across two.
1695
- const subject = await requirePaymentsSubject(c, seam);
1696
- const purchases: ReturnType<typeof purchaseView>[] = [];
1697
- for (const receipt of input.receipts) purchases.push(purchaseView(await submit(c, subject, input.rail, receipt)));
1698
-
1699
- const entitlements = await resolveEntitlements(paymentsDatabase(database(c)), subject, clock());
1700
- await c.var.emit({
1701
- action: PaymentsAuditActions.purchaseRestored,
1702
- outcome: "success",
1703
- actorType: "user",
1704
- actorId: c.var.auth?.userId,
1705
- sessionId: c.var.auth?.sessionId,
1706
- metadata: {
1707
- rail: input.rail,
1708
- subjectType: subject.subjectType,
1709
- subjectId: subject.subjectId,
1710
- restored: purchases.length,
1711
- },
1712
- });
1713
- return c.json(
1714
- { purchases, entitlements: entitlements.map(entitlementView) } satisfies PaymentsRestoreResponse,
1715
- 200,
1716
- );
1717
- });
1936
+ app.post(
1937
+ `${base}/restore`,
1938
+ describeRoute({
1939
+ summary: "Restore purchases onto the caller's own holder.",
1940
+ verification: ["bearer", "session"],
1941
+ responses: { 200: PaymentsRestoreResponse },
1942
+ }),
1943
+ requireAuth(),
1944
+ validate("json", RestoreRequest),
1945
+ async (c) => {
1946
+ const input = c.req.valid("json");
1947
+ // One resolution for the whole batch. A client submits *its own* history, so every receipt in it is
1948
+ // filed against one holder or the request is refused — asking the seam per receipt would let the answer
1949
+ // change mid-batch and split one store account across two.
1950
+ const subject = await requirePaymentsSubject(c, seam);
1951
+ const purchases: ReturnType<typeof purchaseView>[] = [];
1952
+ for (const receipt of input.receipts)
1953
+ purchases.push(purchaseView(await submit(c, subject, input.rail, receipt)));
1954
+
1955
+ const entitlements = await resolveEntitlements(paymentsDatabase(database(c)), subject, clock());
1956
+ await c.var.emit({
1957
+ action: PaymentsAuditActions.purchaseRestored,
1958
+ outcome: "success",
1959
+ actorType: "user",
1960
+ actorId: c.var.auth?.userId,
1961
+ sessionId: c.var.auth?.sessionId,
1962
+ metadata: {
1963
+ rail: input.rail,
1964
+ subjectType: subject.subjectType,
1965
+ subjectId: subject.subjectId,
1966
+ restored: purchases.length,
1967
+ },
1968
+ });
1969
+ return c.json(
1970
+ { purchases, entitlements: entitlements.map(entitlementView) } satisfies PaymentsRestoreResponse,
1971
+ 200,
1972
+ );
1973
+ },
1974
+ );
1718
1975
 
1719
1976
  /**
1720
1977
  * SIGNED WEBHOOK — Apple. App Store Server Notifications V2, signed as a JWS against Apple's pinned chain.
1721
1978
  */
1722
1979
  app.post(
1723
1980
  `${base}/webhooks/apple`,
1981
+ describeRoute({
1982
+ summary: "Receive an App Store Server Notification.",
1983
+ verification: "signed-webhook",
1984
+ responses: { 200: PaymentsWebhookAck },
1985
+ }),
1724
1986
  requireSignedWebhook("apple", { config, now: clock, trust }),
1725
- zValidator("json", AppleWebhookNotification, validationHook),
1987
+ validate("json", AppleWebhookNotification),
1726
1988
  webhookHandler("apple"),
1727
1989
  );
1728
1990
 
@@ -1735,8 +1997,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1735
1997
  */
1736
1998
  app.post(
1737
1999
  `${base}/webhooks/google`,
2000
+ describeRoute({
2001
+ summary: "Receive a Play notification, pushed through Pub/Sub.",
2002
+ verification: "signed-webhook",
2003
+ responses: { 200: PaymentsWebhookAck },
2004
+ }),
1738
2005
  requireSignedWebhook("google", { config, now: clock, trust }),
1739
- zValidator("json", GoogleWebhookNotification, validationHook),
2006
+ validate("json", GoogleWebhookNotification),
1740
2007
  webhookHandler("google"),
1741
2008
  );
1742
2009
 
@@ -1750,8 +2017,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1750
2017
  */
1751
2018
  app.post(
1752
2019
  `${base}/webhooks/stripe`,
2020
+ describeRoute({
2021
+ summary: "Receive a Stripe event.",
2022
+ verification: "signed-webhook",
2023
+ responses: { 200: PaymentsWebhookAck },
2024
+ }),
1753
2025
  requireSignedWebhook("stripe", { config, now: clock, trust }),
1754
- zValidator("json", StripeWebhookNotification, validationHook),
2026
+ validate("json", StripeWebhookNotification),
1755
2027
  webhookHandler("stripe"),
1756
2028
  );
1757
2029
 
@@ -1770,8 +2042,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1770
2042
  */
1771
2043
  app.post(
1772
2044
  `${base}/webhooks/lemon-squeezy`,
2045
+ describeRoute({
2046
+ summary: "Receive a Lemon Squeezy event.",
2047
+ verification: "signed-webhook",
2048
+ responses: { 200: PaymentsWebhookAck },
2049
+ }),
1773
2050
  requireSignedWebhook("lemonSqueezy", { config, now: clock, trust }),
1774
- zValidator("json", LemonSqueezyWebhookNotification, validationHook),
2051
+ validate("json", LemonSqueezyWebhookNotification),
1775
2052
  webhookHandler("lemonSqueezy"),
1776
2053
  );
1777
2054
 
@@ -1792,8 +2069,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1792
2069
  */
1793
2070
  app.post(
1794
2071
  `${base}/webhooks/paddle`,
2072
+ describeRoute({
2073
+ summary: "Receive a Paddle event.",
2074
+ verification: "signed-webhook",
2075
+ responses: { 200: PaymentsWebhookAck },
2076
+ }),
1795
2077
  requireSignedWebhook("paddle", { config, now: clock, trust }),
1796
- zValidator("json", PaddleWebhookNotification, validationHook),
2078
+ validate("json", PaddleWebhookNotification),
1797
2079
  webhookHandler("paddle"),
1798
2080
  );
1799
2081
 
@@ -1810,63 +2092,139 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1810
2092
  * be charged as, and refusing before the 404 keeps this from answering what a project sells to somebody it
1811
2093
  * cannot bill.
1812
2094
  */
1813
- app.post(`${base}/checkout`, requireAuth(), zValidator("json", CheckoutRequest, validationHook), async (c) => {
1814
- const input = c.req.valid("json");
1815
- const subject = await requirePaymentsSubject(c, seam);
1816
- const entry = product(config, input.productId);
1817
- const rail = checkoutRailFor(entry, input.rail);
1818
- const settings = returnUrls(rail);
1819
- const sku = providerProductId(entry.product, rail);
1820
- if (sku === undefined) {
1821
- // In the catalog, but not sold here. A 404 on the product rather than on the rail: the rail is
1822
- // available, this product simply is not one of the things it sells.
1823
- throw new PaymentsProductNotFoundError({
1824
- detail: `Product "${entry.id}" declares no ${rail} SKU, so it cannot be bought through hosted checkout.`,
1825
- });
1826
- }
2095
+ app.post(
2096
+ `${base}/checkout`,
2097
+ describeRoute({
2098
+ summary: "Start a hosted checkout for one catalog product.",
2099
+ verification: ["bearer", "session"],
2100
+ responses: { 200: PaymentsCheckoutHandoffResponse },
2101
+ }),
2102
+ requireAuth(),
2103
+ validate("json", CheckoutRequest),
2104
+ async (c) => {
2105
+ const input = c.req.valid("json");
2106
+ const subject = await requirePaymentsSubject(c, seam);
2107
+ const entry = product(config, input.productId);
2108
+ const rail = checkoutRailFor(entry, input.rail);
2109
+ const settings = returnUrls(rail);
2110
+ const sku = providerProductId(entry.product, rail);
2111
+ if (sku === undefined) {
2112
+ // In the catalog, but not sold here. A 404 on the product rather than on the rail: the rail is
2113
+ // available, this product simply is not one of the things it sells.
2114
+ throw new PaymentsProductNotFoundError({
2115
+ detail: `Product "${entry.id}" declares no ${rail} SKU, so it cannot be bought through hosted checkout.`,
2116
+ });
2117
+ }
1827
2118
 
1828
- const provider = await checkoutRail(c, rail);
1829
- const handoff = await provider.createCheckoutSession(
1830
- {
1831
- providerProductId: sku,
1832
- subscription: entry.product.type === "subscription",
1833
- // The pair, so the rail stamps `encodeSubjectReference(subject)` into the checkout it creates and
1834
- // the webhook that follows already names a holder this server chose.
1835
- subject,
1836
- // Reuse the buyer's existing store customer, so one buyer keeps one account and their billing portal
1837
- // shows every purchase rather than only the last one's.
1838
- providerAccountId: await accountFor(c, rail, subject),
1839
- successUrl: settings.successUrl,
1840
- cancelUrl: settings.cancelUrl,
1841
- // Passed to the store unchanged. Pithy never computes a discounted amount and never checks a code
1842
- // against anything of its own — the provider is the authority on what is owed.
1843
- discountCode: input.discountCode,
1844
- },
1845
- { now: clock(), deployment: deploymentName(c) },
1846
- );
2119
+ const provider = await checkoutRail(c, rail);
2120
+ const handoff = await provider.createCheckoutSession(
2121
+ {
2122
+ providerProductId: sku,
2123
+ subscription: entry.product.type === "subscription",
2124
+ reported: entry.product.billing?.kind === "reported",
2125
+ // The pair, so the rail stamps `encodeSubjectReference(subject)` into the checkout it creates and
2126
+ // the webhook that follows already names a holder this server chose.
2127
+ subject,
2128
+ // Reuse the buyer's existing store customer, so one buyer keeps one account and their billing portal
2129
+ // shows every purchase rather than only the last one's.
2130
+ providerAccountId: await accountFor(c, rail, subject),
2131
+ successUrl: settings.successUrl,
2132
+ cancelUrl: settings.cancelUrl,
2133
+ // Passed to the store unchanged. Pithy never computes a discounted amount and never checks a code
2134
+ // against anything of its own — the provider is the authority on what is owed.
2135
+ discountCode: input.discountCode,
2136
+ },
2137
+ { now: clock(), deployment: deploymentName(c) },
2138
+ );
1847
2139
 
1848
- await c.var.emit({
1849
- action: PaymentsAuditActions.checkoutStarted,
1850
- outcome: "success",
1851
- actorType: "user",
1852
- actorId: c.var.auth?.userId,
1853
- sessionId: c.var.auth?.sessionId,
1854
- resourceType: "product",
1855
- resourceId: entry.id,
1856
- metadata: {
1857
- rail,
1858
- subjectType: subject.subjectType,
1859
- subjectId: subject.subjectId,
1860
- productId: entry.id,
1861
- subscription: entry.product.type === "subscription",
1862
- // Whether one was used, never which. The trail is long-lived and a code is a commercial fact.
1863
- discounted: input.discountCode !== undefined,
1864
- },
1865
- });
1866
- // The handoff, verbatim. A `redirect` carries a URL; a `paddle` handoff carries the transaction the
1867
- // browser opens in place, because that rail's overlay and inline modes never leave this page.
1868
- return c.json(handoff satisfies PaymentsCheckoutHandoffResponse, 200);
1869
- });
2140
+ await c.var.emit({
2141
+ action: PaymentsAuditActions.checkoutStarted,
2142
+ outcome: "success",
2143
+ actorType: "user",
2144
+ actorId: c.var.auth?.userId,
2145
+ sessionId: c.var.auth?.sessionId,
2146
+ resourceType: "product",
2147
+ resourceId: entry.id,
2148
+ metadata: {
2149
+ rail,
2150
+ subjectType: subject.subjectType,
2151
+ subjectId: subject.subjectId,
2152
+ productId: entry.id,
2153
+ subscription: entry.product.type === "subscription",
2154
+ // Whether one was used, never which. The trail is long-lived and a code is a commercial fact.
2155
+ discounted: input.discountCode !== undefined,
2156
+ },
2157
+ });
2158
+ // The handoff, verbatim. A `redirect` carries a URL; a `paddle` handoff carries the transaction the
2159
+ // browser opens in place, because that rail's overlay and inline modes never leave this page.
2160
+ return c.json(handoff satisfies PaymentsCheckoutHandoffResponse, 200);
2161
+ },
2162
+ );
2163
+
2164
+ /**
2165
+ * PUBLIC READ — Paddle only. What a page needs to resume a transaction Paddle itself created.
2166
+ *
2167
+ * **`#680`.** Paddle appends `?_ptxn=<transaction_id>` to a seller's *Default payment link* and expects
2168
+ * the page it lands on to open a checkout for that transaction. Those links are the ones Paddle sends
2169
+ * rather than the ones this kit opens — a past-due dunning mail, a manually-collected invoice, the
2170
+ * payment-method-update link minted for a subscription — and until this route existed the kit could not
2171
+ * use one: `POST {base}/checkout` mints a transaction, and here the transaction already exists.
2172
+ *
2173
+ * **Unauthenticated, and that is the point rather than an oversight.** The buyer following a dunning
2174
+ * link is frequently signed out — that is the population this serves, so `requireAuth()` would break it
2175
+ * for exactly them. It is safe because it discloses nothing: `clientToken` is publishable by design,
2176
+ * `environment`, `displayMode` and `successUrl` are config constants identical for every transaction,
2177
+ * and the id is the caller's own, echoed. The sum of what a stranger learns is this project's Paddle
2178
+ * account, which every pricing page already ships.
2179
+ *
2180
+ * **It must never read the transaction from Paddle**, and that is the one line to defend in review. A
2181
+ * lookup would turn an unauthenticated route into an oracle for whether a transaction id exists, and
2182
+ * then for what it costs. Shape is checked; existence is Paddle's to tell the buyer, inside the
2183
+ * checkout, where it is already their own transaction.
2184
+ *
2185
+ * **Nothing about a session is read, structurally.** No `requireAuth`, no `requirePaymentsSubject`, and
2186
+ * `PaddleResumeQuery` has no holder field for one — so a resume cannot stamp the current user onto a
2187
+ * transaction that arrived in a URL, which is the way this route could have been used to claim somebody
2188
+ * else's payment.
2189
+ *
2190
+ * **`hosted` refuses.** In that mode this kit never opens a checkout in the page: it redirects to
2191
+ * Paddle's own, at a URL only a transaction read would yield — the read this route may not do. A buyer
2192
+ * on a hosted-mode project is already on Paddle's page, so there is nothing here to resume.
2193
+ */
2194
+ app.get(
2195
+ `${base}/checkout/resume`,
2196
+ describeRoute({
2197
+ summary: "Resume a Paddle transaction a payment link arrived for.",
2198
+ verification: "public",
2199
+ responses: { 200: PaymentsCheckoutHandoffResponse },
2200
+ }),
2201
+ validate("query", PaddleResumeQuery),
2202
+ (c) => {
2203
+ const { transaction } = c.req.valid("query");
2204
+ if (config.paddle === undefined) {
2205
+ throw new PaymentsRailNotConfiguredError({
2206
+ detail: "The paddle rail is off in this project's config, so there is no payment link to resume.",
2207
+ });
2208
+ }
2209
+ if (config.paddle.checkout === "hosted") {
2210
+ throw new PaymentsRailNotConfiguredError({
2211
+ detail:
2212
+ '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.',
2213
+ });
2214
+ }
2215
+ const handoff = {
2216
+ kind: "paddle",
2217
+ transactionId: transaction,
2218
+ clientToken: config.paddle.clientToken,
2219
+ environment: config.paddle.environment,
2220
+ displayMode: config.paddle.checkout,
2221
+ // From config, exactly as the minted path takes it, and for the reason stated on the field there:
2222
+ // a client that could name one could send a paying customer to a page it controls.
2223
+ successUrl: config.paddle.successUrl,
2224
+ } as const;
2225
+ return c.json(handoff satisfies PaymentsCheckoutHandoffResponse, 200);
2226
+ },
2227
+ );
1870
2228
 
1871
2229
  /**
1872
2230
  * AUTHED WRITE — Stripe only. Open the Billing Portal for the caller's own store account.
@@ -1875,77 +2233,86 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1875
2233
  * and it comes from the provider-account map. A `customer` field here would be the whole vulnerability —
1876
2234
  * any signed-in caller could open a session against somebody else's billing history and cancel it.
1877
2235
  */
1878
- app.post(`${base}/portal`, requireAuth(), async (c) => {
1879
- const subject = await requirePaymentsSubject(c, seam);
1880
-
1881
- // Which rail this caller actually bought on, found by asking the account map rather than by taking it
1882
- // from the request. Still no body: the caller names neither the customer nor the rail, so there is
1883
- // nothing here anyone could point at somebody else's billing.
1884
- const enabled = PAYMENTS_HOSTED_RAILS.filter((rail) => railEnabled(config, rail));
1885
- // No hosted rail at all is a fact about the deployment, not about this caller — a mobile-only project
1886
- // has no billing portal to open. Same refusal `/checkout` gives, rather than a 404 that reads as "you
1887
- // have no account" to somebody who could never have had one.
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
- }
2236
+ app.post(
2237
+ `${base}/portal`,
2238
+ describeRoute({
2239
+ summary: "Open the billing portal for the caller's own store account.",
2240
+ verification: ["bearer", "session"],
2241
+ responses: { 200: PaymentsPortalHandoffResponse },
2242
+ }),
2243
+ requireAuth(),
2244
+ async (c) => {
2245
+ const subject = await requirePaymentsSubject(c, seam);
1894
2246
 
1895
- let found: { rail: PaymentsRail; providerAccountId: string } | undefined;
1896
- for (const rail of enabled) {
1897
- const providerAccountId = await accountFor(c, rail, subject);
1898
- if (providerAccountId !== null) {
1899
- found = { rail, providerAccountId };
1900
- break;
2247
+ // Which rail this caller actually bought on, found by asking the account map rather than by taking it
2248
+ // from the request. Still no body: the caller names neither the customer nor the rail, so there is
2249
+ // nothing here anyone could point at somebody else's billing.
2250
+ const enabled = PAYMENTS_HOSTED_RAILS.filter((rail) => railEnabled(config, rail));
2251
+ // No hosted rail at all is a fact about the deployment, not about this caller — a mobile-only project
2252
+ // has no billing portal to open. Same refusal `/checkout` gives, rather than a 404 that reads as "you
2253
+ // have no account" to somebody who could never have had one.
2254
+ if (enabled.length === 0) {
2255
+ throw new PaymentsRailNotConfiguredError({
2256
+ detail:
2257
+ "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`.",
2258
+ });
1901
2259
  }
1902
- }
1903
2260
 
1904
- if (found === undefined) {
1905
- // Nothing has ever been bought through a hosted rail by this caller, so there is no billing to
1906
- // manage. Not a payments-domain refusal: the rail is configured and working, the resource simply
1907
- // does not exist.
1908
- throw new NotFoundError({
1909
- message: "No billing account yet.",
1910
- action: "Buy a subscription first, then manage it here.",
1911
- detail: `No hosted-rail provider account is linked to ${encodeSubjectReference(subject)}.`,
1912
- });
1913
- }
2261
+ let found: { rail: PaymentsRail; providerAccountId: string } | undefined;
2262
+ for (const rail of enabled) {
2263
+ const providerAccountId = await accountFor(c, rail, subject);
2264
+ if (providerAccountId !== null) {
2265
+ found = { rail, providerAccountId };
2266
+ break;
2267
+ }
2268
+ }
1914
2269
 
1915
- const provider = await checkoutRail(c, found.rail);
1916
- const session = await provider.createPortalSession(
1917
- {
1918
- providerAccountId: found.providerAccountId,
1919
- // Undefined for a rail whose portal takes no return parameter — Lemon Squeezy's is a signed,
1920
- // expiring link with nowhere to go back to, and Paddle's takes none at all. The contract admits
1921
- // that rather than have the rail silently drop a URL an adopter configured.
1922
- returnUrl: found.rail === "stripe" ? stripeSettings().portalReturnUrl : undefined,
1923
- // **From the caller's own rows, never from a body.** A store that mints per-subscription deep
1924
- // links mints authenticated ones, so naming a subscription is naming somebody's cancel button.
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
- );
2270
+ if (found === undefined) {
2271
+ // Nothing has ever been bought through a hosted rail by this caller, so there is no billing to
2272
+ // manage. Not a payments-domain refusal: the rail is configured and working, the resource simply
2273
+ // does not exist.
2274
+ throw new NotFoundError({
2275
+ message: "No billing account yet.",
2276
+ action: "Buy a subscription first, then manage it here.",
2277
+ detail: `No hosted-rail provider account is linked to ${encodeSubjectReference(subject)}.`,
2278
+ });
2279
+ }
1930
2280
 
1931
- await c.var.emit({
1932
- action: PaymentsAuditActions.portalOpened,
1933
- outcome: "success",
1934
- actorType: "user",
1935
- actorId: c.var.auth?.userId,
1936
- sessionId: c.var.auth?.sessionId,
1937
- resourceType: "provider_account",
1938
- resourceId: found.providerAccountId,
1939
- metadata: { rail: found.rail, subjectType: subject.subjectType, subjectId: subject.subjectId },
1940
- });
1941
- return c.json(
1942
- {
1943
- url: session.url,
1944
- ...(session.subscriptions === undefined ? {} : { subscriptions: [...session.subscriptions] }),
1945
- } satisfies PaymentsPortalHandoffResponse,
1946
- 200,
1947
- );
1948
- });
2281
+ const provider = await checkoutRail(c, found.rail);
2282
+ const session = await provider.createPortalSession(
2283
+ {
2284
+ providerAccountId: found.providerAccountId,
2285
+ // Undefined for a rail whose portal takes no return parameter — Lemon Squeezy's is a signed,
2286
+ // expiring link with nowhere to go back to, and Paddle's takes none at all. The contract admits
2287
+ // that rather than have the rail silently drop a URL an adopter configured.
2288
+ returnUrl: found.rail === "stripe" ? stripeSettings().portalReturnUrl : undefined,
2289
+ // **From the caller's own rows, never from a body.** A store that mints per-subscription deep
2290
+ // links mints authenticated ones, so naming a subscription is naming somebody's cancel button.
2291
+ // There is still no request field: the route reads what this caller owns.
2292
+ subscriptionIds: await ownSubscriptionIds(c, found.rail, subject),
2293
+ },
2294
+ { now: clock(), deployment: deploymentName(c) },
2295
+ );
2296
+
2297
+ await c.var.emit({
2298
+ action: PaymentsAuditActions.portalOpened,
2299
+ outcome: "success",
2300
+ actorType: "user",
2301
+ actorId: c.var.auth?.userId,
2302
+ sessionId: c.var.auth?.sessionId,
2303
+ resourceType: "provider_account",
2304
+ resourceId: found.providerAccountId,
2305
+ metadata: { rail: found.rail, subjectType: subject.subjectType, subjectId: subject.subjectId },
2306
+ });
2307
+ return c.json(
2308
+ {
2309
+ url: session.url,
2310
+ ...(session.subscriptions === undefined ? {} : { subscriptions: [...session.subscriptions] }),
2311
+ } satisfies PaymentsPortalHandoffResponse,
2312
+ 200,
2313
+ );
2314
+ },
2315
+ );
1949
2316
 
1950
2317
  /**
1951
2318
  * CONTROL PLANE. Grant an entitlement by hand — a comped account, or the repair of a purchase that
@@ -1985,58 +2352,67 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1985
2352
  * bought anything has no pricing and may still have no customer, and somebody mid-subscription has
1986
2353
  * both. Nesting one in the other would make the common case unreachable.
1987
2354
  */
1988
- app.get(`${base}/pricing`, requireAuth(), async (c) => {
1989
- const subject = await resolvePaymentsSubject(c, seam);
1990
- // A read, so nobody resolved is the empty answer rather than a refusal — the same direction
1991
- // `GET {base}/entitlements` takes, and for the same reason: a screen with no billing account selected
1992
- // is quoting from nothing, which is a fact rather than a failure.
1993
- if (subject === undefined)
1994
- return c.json({ pricing: null, quotedFrom: null } satisfies PaymentsPricingEnvelope, 200);
1995
- const db = paymentsDatabase(database(c));
1996
-
1997
- // The one read, shared with `/checkout`. `accountFor` is what that route calls to decide who is
1998
- // charged, so a screen quoting from this answer is quoting from the row that will be billed.
1999
- const paddleCustomer = await accountFor(c, "paddle", subject);
2000
- const quotedFrom: PaymentsQuotedFrom | null =
2001
- paddleCustomer === null ? null : { rail: "paddle", providerAccountId: paddleCustomer };
2002
- /** The envelope, so every exit below carries both facts rather than three of them carrying one. */
2003
- const answer = (pricing: PaymentsPricingResponse | null) =>
2004
- c.json({ pricing, quotedFrom } satisfies PaymentsPricingEnvelope, 200);
2005
-
2006
- // The newest subscription row this caller holds on a rail that can price one. `role` matters: a money
2007
- // row records a closed period and has no "next".
2008
- const rows = await db
2009
- .selectFrom(PAYMENTS_PURCHASES_TABLE)
2010
- .selectAll()
2011
- .where("subjectType", "=", subject.subjectType)
2012
- .where("subjectId", "=", subject.subjectId)
2013
- .where("type", "=", "subscription")
2014
- .orderBy("providerEventAt", "desc")
2015
- .execute();
2016
- // The row that carries the subscription's *standing*, preferred over any receipt.
2017
- //
2018
- // On Lemon Squeezy a subscriber's newest rows are `charge` receipts — one per invoice — and a receipt
2019
- // names a closed period no rail can price. Taking the newest of any role therefore returned null for
2020
- // every LS subscriber while looking like it had worked. Every other rail writes `charge` for
2021
- // everything and has no `state` row, so the fallback is what serves them.
2022
- const row = rows.find((candidate) => candidate.role === "state") ?? rows[0];
2023
- if (row === undefined) return answer(null);
2024
-
2025
- const purchase = PaymentsPurchase.parse(row);
2026
- const provider = resolveRailProvider(purchase.rail, config, await credentials(c), trust);
2027
- if (!isPricingRail(provider)) return answer(null);
2028
-
2029
- const pricing = await provider.readPricing(purchase, { now: clock(), deployment: deploymentName(c) });
2030
- if (pricing === undefined) return answer(null);
2031
-
2032
- return answer({
2033
- currency: pricing.currency,
2034
- currentAmountMinor: pricing.currentAmountMinor,
2035
- listAmountMinor: pricing.listAmountMinor,
2036
- discountCode: pricing.discountCode,
2037
- discountEndsAt: pricing.discountEndsAt === null ? null : pricing.discountEndsAt.toISOString(),
2038
- });
2039
- });
2355
+ app.get(
2356
+ `${base}/pricing`,
2357
+ describeRoute({
2358
+ summary: "Read what the caller's own subscription pays, and when that changes.",
2359
+ verification: ["bearer", "session"],
2360
+ responses: { 200: PaymentsPricingEnvelope },
2361
+ }),
2362
+ requireAuth(),
2363
+ async (c) => {
2364
+ const subject = await resolvePaymentsSubject(c, seam);
2365
+ // A read, so nobody resolved is the empty answer rather than a refusal — the same direction
2366
+ // `GET {base}/entitlements` takes, and for the same reason: a screen with no billing account selected
2367
+ // is quoting from nothing, which is a fact rather than a failure.
2368
+ if (subject === undefined)
2369
+ return c.json({ pricing: null, quotedFrom: null } satisfies PaymentsPricingEnvelope, 200);
2370
+ const db = paymentsDatabase(database(c));
2371
+
2372
+ // The one read, shared with `/checkout`. `accountFor` is what that route calls to decide who is
2373
+ // charged, so a screen quoting from this answer is quoting from the row that will be billed.
2374
+ const paddleCustomer = await accountFor(c, "paddle", subject);
2375
+ const quotedFrom: PaymentsQuotedFrom | null =
2376
+ paddleCustomer === null ? null : { rail: "paddle", providerAccountId: paddleCustomer };
2377
+ /** The envelope, so every exit below carries both facts rather than three of them carrying one. */
2378
+ const answer = (pricing: PaymentsPricingResponse | null) =>
2379
+ c.json({ pricing, quotedFrom } satisfies PaymentsPricingEnvelope, 200);
2380
+
2381
+ // The newest subscription row this caller holds on a rail that can price one. `role` matters: a money
2382
+ // row records a closed period and has no "next".
2383
+ const rows = await db
2384
+ .selectFrom(PAYMENTS_PURCHASES_TABLE)
2385
+ .selectAll()
2386
+ .where("subjectType", "=", subject.subjectType)
2387
+ .where("subjectId", "=", subject.subjectId)
2388
+ .where("type", "=", "subscription")
2389
+ .orderBy("providerEventAt", "desc")
2390
+ .execute();
2391
+ // The row that carries the subscription's *standing*, preferred over any receipt.
2392
+ //
2393
+ // On Lemon Squeezy a subscriber's newest rows are `charge` receipts — one per invoice — and a receipt
2394
+ // names a closed period no rail can price. Taking the newest of any role therefore returned null for
2395
+ // every LS subscriber while looking like it had worked. Every other rail writes `charge` for
2396
+ // everything and has no `state` row, so the fallback is what serves them.
2397
+ const row = rows.find((candidate) => candidate.role === "state") ?? rows[0];
2398
+ if (row === undefined) return answer(null);
2399
+
2400
+ const purchase = PaymentsPurchase.parse(row);
2401
+ const provider = resolveRailProvider(purchase.rail, config, await credentials(c), trust);
2402
+ if (!isPricingRail(provider)) return answer(null);
2403
+
2404
+ const pricing = await provider.readPricing(purchase, { now: clock(), deployment: deploymentName(c) });
2405
+ if (pricing === undefined) return answer(null);
2406
+
2407
+ return answer({
2408
+ currency: pricing.currency,
2409
+ currentAmountMinor: pricing.currentAmountMinor,
2410
+ listAmountMinor: pricing.listAmountMinor,
2411
+ discountCode: pricing.discountCode,
2412
+ discountEndsAt: pricing.discountEndsAt === null ? null : pricing.discountEndsAt.toISOString(),
2413
+ });
2414
+ },
2415
+ );
2040
2416
 
2041
2417
  /**
2042
2418
  * AUTHED READ — where the caller's own subscription stands, read live from the store.
@@ -2061,30 +2437,52 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2061
2437
  * shape of this request that reads somebody else's. Nobody resolved is the empty answer rather than a
2062
2438
  * refusal, which is the read half of the seam's rule and what `GET {base}/entitlements` already does.
2063
2439
  */
2064
- app.get(`${base}/subscription`, requireAuth(), async (c) => {
2065
- const subject = await resolvePaymentsSubject(c, seam);
2066
- if (subject === undefined) return c.json({ subscription: null } satisfies PaymentsSubscriptionResponse, 200);
2067
-
2068
- const target = await changeableSubscription(database(c), subject, clock());
2069
- // Two subscriptions have no encoding in an envelope that holds one, and picking is the defect the
2070
- // whole resolver exists to prevent. The refusal is the same one every verb gives.
2071
- if (target.found === "many") throw tooManySubscriptions(target.purchases);
2072
- if (target.found === "none") return c.json({ subscription: null } satisfies PaymentsSubscriptionResponse, 200);
2073
-
2074
- const provider = await subscriptionRail(c, target.purchase.rail);
2075
- const standing = await provider.readStanding(target.purchase, { now: clock(), deployment: deploymentName(c) });
2076
- // A rail that cannot address this purchase, or a store that no longer knows it. A fact about the
2077
- // purchase rather than a failure — a store that could not be *reached* raises
2078
- // `payments/provider_unavailable` instead, so a screen distinguishes the two.
2079
- if (standing === undefined) return c.json({ subscription: null } satisfies PaymentsSubscriptionResponse, 200);
2080
-
2081
- return c.json(
2082
- {
2083
- subscription: subscriptionView(target.purchase.productId, standing),
2084
- } satisfies PaymentsSubscriptionResponse,
2085
- 200,
2086
- );
2087
- });
2440
+ app.get(
2441
+ `${base}/subscription`,
2442
+ describeRoute({
2443
+ summary: "Read where the caller's own subscription stands, live from the store.",
2444
+ verification: ["bearer", "session"],
2445
+ responses: { 200: PaymentsSubscriptionResponse },
2446
+ }),
2447
+ requireAuth(),
2448
+ async (c) => {
2449
+ const subject = await resolvePaymentsSubject(c, seam);
2450
+ if (subject === undefined) return c.json({ subscription: null } satisfies PaymentsSubscriptionResponse, 200);
2451
+
2452
+ const target = await changeableSubscription(database(c), subject, clock());
2453
+ // Two subscriptions have no encoding in an envelope that holds one, and picking is the defect the
2454
+ // whole resolver exists to prevent. The refusal is the same one every verb gives.
2455
+ if (target.found === "many") throw tooManySubscriptions(target.purchases);
2456
+ if (target.found === "none") return c.json({ subscription: null } satisfies PaymentsSubscriptionResponse, 200);
2457
+
2458
+ const provider = await subscriptionRail(c, target.purchase.rail);
2459
+ const standing = await provider.readStanding(target.purchase, { now: clock(), deployment: deploymentName(c) });
2460
+ // A rail that cannot address this purchase, or a store that no longer knows it. A fact about the
2461
+ // purchase rather than a failure — a store that could not be *reached* raises
2462
+ // `payments/provider_unavailable` instead, so a screen distinguishes the two.
2463
+ if (standing === undefined) return c.json({ subscription: null } satisfies PaymentsSubscriptionResponse, 200);
2464
+
2465
+ // The last count reported for a quantity-billed product, from the subscription's own report rows. A
2466
+ // flat-priced product has none, which reads as null rather than absent: this Worker can say.
2467
+ const subscriptionId = target.purchase.originalTransactionId;
2468
+ const last =
2469
+ subscriptionId === null
2470
+ ? undefined
2471
+ : (
2472
+ await lastReports(database(c), [{ rail: target.purchase.rail, providerSubscriptionId: subscriptionId }])
2473
+ ).get(`${target.purchase.rail}:${subscriptionId}`);
2474
+ return c.json(
2475
+ {
2476
+ subscription: {
2477
+ ...subscriptionView(target.purchase.productId, standing),
2478
+ reportedQuantity: last?.quantity ?? null,
2479
+ reportedAt: last?.reportedAt.toISOString() ?? null,
2480
+ },
2481
+ } satisfies PaymentsSubscriptionResponse,
2482
+ 200,
2483
+ );
2484
+ },
2485
+ );
2088
2486
 
2089
2487
  /**
2090
2488
  * AUTHED READ — what moving to one catalog product would cost, as the store previews it.
@@ -2110,8 +2508,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2110
2508
  */
2111
2509
  app.post(
2112
2510
  `${base}/subscription/preview`,
2511
+ describeRoute({
2512
+ summary: "Preview what moving to one catalog product would cost.",
2513
+ verification: ["bearer", "session"],
2514
+ responses: { 200: PaymentsSubscriptionQuoteResponse },
2515
+ }),
2113
2516
  requireAuth(),
2114
- zValidator("json", SubscriptionPreviewRequest, validationHook),
2517
+ validate("json", SubscriptionPreviewRequest),
2115
2518
  async (c) => {
2116
2519
  const input = c.req.valid("json");
2117
2520
  const subject = await requirePaymentsSubject(c, seam);
@@ -2161,8 +2564,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2161
2564
  */
2162
2565
  app.post(
2163
2566
  `${base}/subscription/change`,
2567
+ describeRoute({
2568
+ summary: "Move the caller's own subscription onto one catalog product.",
2569
+ verification: ["bearer", "session"],
2570
+ responses: { 200: PaymentsSubscriptionStandingResponse },
2571
+ }),
2164
2572
  requireAuth(),
2165
- zValidator("json", SubscriptionChangeRequest, validationHook),
2573
+ validate("json", SubscriptionChangeRequest),
2166
2574
  async (c) => {
2167
2575
  const input = c.req.valid("json");
2168
2576
  const subject = await requirePaymentsSubject(c, seam);
@@ -2235,8 +2643,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2235
2643
  */
2236
2644
  app.post(
2237
2645
  `${base}/subscription/cancel`,
2646
+ describeRoute({
2647
+ summary: "Stop the caller's own subscription renewing.",
2648
+ verification: ["bearer", "session"],
2649
+ responses: { 200: PaymentsSubscriptionStandingResponse },
2650
+ }),
2238
2651
  requireAuth(),
2239
- zValidator("json", SubscriptionCancelRequest, validationHook),
2652
+ validate("json", SubscriptionCancelRequest),
2240
2653
  async (c) => {
2241
2654
  const input = c.req.valid("json");
2242
2655
  const subject = await requirePaymentsSubject(c, seam);
@@ -2303,38 +2716,49 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2303
2716
  * A subscription with nothing scheduled is the no-op rather than a refusal — it already renews, which
2304
2717
  * is what the caller asked for — and it writes no audit row, for {@link standingMoved}'s reason.
2305
2718
  */
2306
- app.post(`${base}/subscription/keep`, requireAuth(), async (c) => {
2307
- const subject = await requirePaymentsSubject(c, seam);
2308
- const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
2719
+ app.post(
2720
+ `${base}/subscription/keep`,
2721
+ describeRoute({
2722
+ summary: "Withdraw a scheduled cancellation.",
2723
+ verification: ["bearer", "session"],
2724
+ responses: { 200: PaymentsSubscriptionStandingResponse },
2725
+ }),
2726
+ requireAuth(),
2727
+ async (c) => {
2728
+ const subject = await requirePaymentsSubject(c, seam);
2729
+ const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
2309
2730
 
2310
- const provider = await subscriptionRail(c, purchase.rail);
2311
- const context = { now: clock(), deployment: deploymentName(c) };
2312
- const before = await provider.readStanding(purchase, context);
2313
- const standing = await provider.keepSubscription(purchase, context);
2731
+ const provider = await subscriptionRail(c, purchase.rail);
2732
+ const context = { now: clock(), deployment: deploymentName(c) };
2733
+ const before = await provider.readStanding(purchase, context);
2734
+ const standing = await provider.keepSubscription(purchase, context);
2314
2735
 
2315
- if (standingMoved(before, standing)) {
2316
- await c.var.emit({
2317
- action: PaymentsAuditActions.subscriptionCancelWithdrawn,
2318
- outcome: "success",
2319
- actorType: "user",
2320
- actorId: c.var.auth?.userId,
2321
- sessionId: c.var.auth?.sessionId,
2322
- resourceType: "purchase",
2323
- resourceId: purchase.id,
2324
- metadata: {
2325
- rail: purchase.rail,
2326
- subjectType: subject.subjectType,
2327
- subjectId: subject.subjectId,
2328
- productId: purchase.productId,
2329
- },
2330
- });
2331
- }
2736
+ if (standingMoved(before, standing)) {
2737
+ await c.var.emit({
2738
+ action: PaymentsAuditActions.subscriptionCancelWithdrawn,
2739
+ outcome: "success",
2740
+ actorType: "user",
2741
+ actorId: c.var.auth?.userId,
2742
+ sessionId: c.var.auth?.sessionId,
2743
+ resourceType: "purchase",
2744
+ resourceId: purchase.id,
2745
+ metadata: {
2746
+ rail: purchase.rail,
2747
+ subjectType: subject.subjectType,
2748
+ subjectId: subject.subjectId,
2749
+ productId: purchase.productId,
2750
+ },
2751
+ });
2752
+ }
2332
2753
 
2333
- return c.json(
2334
- { subscription: subscriptionView(purchase.productId, standing) } satisfies PaymentsSubscriptionStandingResponse,
2335
- 200,
2336
- );
2337
- });
2754
+ return c.json(
2755
+ {
2756
+ subscription: subscriptionView(purchase.productId, standing),
2757
+ } satisfies PaymentsSubscriptionStandingResponse,
2758
+ 200,
2759
+ );
2760
+ },
2761
+ );
2338
2762
 
2339
2763
  /**
2340
2764
  * AUTHED WRITE — ask the store to give this subscription's payments back.
@@ -2368,67 +2792,76 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2368
2792
  * already standing is the state the caller wanted, and a trail claiming two of them is worse than one
2369
2793
  * claiming none.
2370
2794
  */
2371
- app.post(`${base}/subscription/refund`, requireAuth(), async (c) => {
2372
- const subject = await requirePaymentsSubject(c, seam);
2373
- const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
2374
- // The rail is narrowed **before** the payments are resolved, and the order is the answer a caller
2375
- // gets. "This store does not refund from the server" is true of every payment on the subscription and
2376
- // is what an Apple or Google subscriber needs to hear; "there is no payment to refund" would be the
2377
- // same 409 they would get if they had never paid, and it would send them looking for the wrong thing.
2378
- const provider = await refundRail(c, purchase.rail);
2379
- const payments = await refundablePayments(database(c), subject, purchase);
2380
- if (payments.length === 0) {
2381
- // A 409 rather than an empty report, and rather than a 404. The subscription is there and the
2382
- // request is well-formed; what is absent is a payment to refund, which is a fact about the account's
2383
- // present state. An empty report would read as "refunded, nothing to do".
2384
- throw new PaymentsSubscriptionChangeRefusedError({
2385
- message: "There is no payment on this subscription to refund.",
2386
- action: "Check the subscription's payment history. A refund attaches to a payment, not to a plan.",
2387
- detail: `No charge rows resolved on ${purchase.rail} for the family this subscription heads.`,
2388
- });
2389
- }
2390
-
2391
- const refund = await provider.requestRefunds(
2392
- {
2393
- purchases: payments,
2394
- // Composed here and never read from a body: it is written into the adopter's own store console,
2395
- // where a person reads it as a statement about their business. The catalog product and nothing
2396
- // else — no customer text, no identifier a store does not already hold.
2397
- reason: `Refund requested by the subscriber for "${purchase.productId}".`,
2398
- },
2399
- { now: clock(), deployment: deploymentName(c) },
2400
- );
2795
+ app.post(
2796
+ `${base}/subscription/refund`,
2797
+ describeRoute({
2798
+ summary: "Ask the store to refund the payments on the caller's own subscription.",
2799
+ verification: ["bearer", "session"],
2800
+ responses: { 200: PaymentsRefundResponse },
2801
+ }),
2802
+ requireAuth(),
2803
+ async (c) => {
2804
+ const subject = await requirePaymentsSubject(c, seam);
2805
+ const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
2806
+ // The rail is narrowed **before** the payments are resolved, and the order is the answer a caller
2807
+ // gets. "This store does not refund from the server" is true of every payment on the subscription and
2808
+ // is what an Apple or Google subscriber needs to hear; "there is no payment to refund" would be the
2809
+ // same 409 they would get if they had never paid, and it would send them looking for the wrong thing.
2810
+ const provider = await refundRail(c, purchase.rail);
2811
+ const payments = await refundablePayments(database(c), subject, purchase);
2812
+ if (payments.length === 0) {
2813
+ // A 409 rather than an empty report, and rather than a 404. The subscription is there and the
2814
+ // request is well-formed; what is absent is a payment to refund, which is a fact about the account's
2815
+ // present state. An empty report would read as "refunded, nothing to do".
2816
+ throw new PaymentsSubscriptionChangeRefusedError({
2817
+ message: "There is no payment on this subscription to refund.",
2818
+ action: "Check the subscription's payment history. A refund attaches to a payment, not to a plan.",
2819
+ detail: `No charge rows resolved on ${purchase.rail} for the family this subscription heads.`,
2820
+ });
2821
+ }
2401
2822
 
2402
- const raised = refund.outcomes.filter((outcome) => outcome.outcome === "requested");
2403
- if (raised.length > 0) {
2404
- await c.var.emit({
2405
- action: PaymentsAuditActions.subscriptionRefundRequested,
2406
- outcome: "success",
2407
- // The person who asked, always — the holder they act for rides in the metadata.
2408
- actorType: "user",
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),
2823
+ const refund = await provider.requestRefunds(
2824
+ {
2825
+ purchases: payments,
2826
+ // Composed here and never read from a body: it is written into the adopter's own store console,
2827
+ // where a person reads it as a statement about their business. The catalog product and nothing
2828
+ // else — no customer text, no identifier a store does not already hold.
2829
+ reason: `Refund requested by the subscriber for "${purchase.productId}".`,
2426
2830
  },
2427
- });
2428
- }
2831
+ { now: clock(), deployment: deploymentName(c) },
2832
+ );
2429
2833
 
2430
- return c.json({ refund: refundView(refund) } satisfies PaymentsRefundResponse, 200);
2431
- });
2834
+ const raised = refund.outcomes.filter((outcome) => outcome.outcome === "requested");
2835
+ if (raised.length > 0) {
2836
+ await c.var.emit({
2837
+ action: PaymentsAuditActions.subscriptionRefundRequested,
2838
+ outcome: "success",
2839
+ // The person who asked, always — the holder they act for rides in the metadata.
2840
+ actorType: "user",
2841
+ actorId: c.var.auth?.userId,
2842
+ sessionId: c.var.auth?.sessionId,
2843
+ resourceType: "purchase",
2844
+ resourceId: purchase.id,
2845
+ // Counts and the store's own handles on the money in flight. **No amount**: how much anybody is
2846
+ // getting back is the store's later decision, and a figure here would assert something nobody has
2847
+ // agreed to, in the one table nothing corrects.
2848
+ metadata: {
2849
+ rail: purchase.rail,
2850
+ subjectType: subject.subjectType,
2851
+ subjectId: subject.subjectId,
2852
+ productId: purchase.productId,
2853
+ payments: refund.outcomes.length,
2854
+ requested: raised.length,
2855
+ alreadyRequested: refund.outcomes.filter((outcome) => outcome.outcome === "already_requested").length,
2856
+ failed: refund.outcomes.filter((outcome) => outcome.outcome === "failed").length,
2857
+ adjustmentIds: raised.map((outcome) => outcome.adjustmentId),
2858
+ },
2859
+ });
2860
+ }
2861
+
2862
+ return c.json({ refund: refundView(refund) } satisfies PaymentsRefundResponse, 200);
2863
+ },
2864
+ );
2432
2865
 
2433
2866
  /**
2434
2867
  * CONTROL PLANE. The discount codes this project has issued.
@@ -2442,8 +2875,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2442
2875
  */
2443
2876
  app.get(
2444
2877
  `${base}/admin/discounts`,
2878
+ describeRoute({
2879
+ summary: "Read the discount codes this project has issued at one store.",
2880
+ verification: "control-plane",
2881
+ scopes: [PAYMENTS_DISCOUNT_READ_SCOPE],
2882
+ responses: { 200: PaymentsAdminDiscountsResponse },
2883
+ }),
2445
2884
  requireControlPlane(PAYMENTS_DISCOUNT_READ_SCOPE),
2446
- zValidator("query", AdminDiscountsQuery, validationHook),
2885
+ validate("query", AdminDiscountsQuery),
2447
2886
  async (c) => {
2448
2887
  const { rail } = c.req.valid("query");
2449
2888
  const provider = resolveRailProvider(rail, config, await credentials(c), trust);
@@ -2478,8 +2917,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2478
2917
  */
2479
2918
  app.post(
2480
2919
  `${base}/admin/discounts`,
2920
+ describeRoute({
2921
+ summary: "Mint a discount code at one store.",
2922
+ verification: "control-plane",
2923
+ scopes: [PAYMENTS_DISCOUNT_CREATE_SCOPE],
2924
+ responses: { 200: PaymentsDiscountResponse },
2925
+ }),
2481
2926
  requireControlPlane(PAYMENTS_DISCOUNT_CREATE_SCOPE),
2482
- zValidator("json", DiscountCreateRequest, validationHook),
2927
+ validate("json", DiscountCreateRequest),
2483
2928
  async (c) => {
2484
2929
  const input = c.req.valid("json");
2485
2930
  const provider = resolveRailProvider(input.rail, config, await credentials(c), trust);
@@ -2531,8 +2976,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2531
2976
 
2532
2977
  app.post(
2533
2978
  `${base}/entitlements/grant`,
2979
+ describeRoute({
2980
+ summary: "Grant an entitlement by hand.",
2981
+ verification: "control-plane",
2982
+ scopes: [PAYMENTS_ENTITLEMENT_GRANT_SCOPE],
2983
+ responses: { 200: PaymentsEntitlementResponse },
2984
+ }),
2534
2985
  requireControlPlane(PAYMENTS_ENTITLEMENT_GRANT_SCOPE),
2535
- zValidator("json", EntitlementGrantRequest, validationHook),
2986
+ validate("json", EntitlementGrantRequest),
2536
2987
  async (c) => {
2537
2988
  const input = c.req.valid("json");
2538
2989
  const caller = controlPlaneCaller(c);
@@ -2656,8 +3107,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2656
3107
  */
2657
3108
  app.post(
2658
3109
  `${base}/entitlements/revoke`,
3110
+ describeRoute({
3111
+ summary: "Revoke an entitlement by hand.",
3112
+ verification: "control-plane",
3113
+ scopes: [PAYMENTS_ENTITLEMENT_REVOKE_SCOPE],
3114
+ responses: { 200: PaymentsEntitlementResponse },
3115
+ }),
2659
3116
  requireControlPlane(PAYMENTS_ENTITLEMENT_REVOKE_SCOPE),
2660
- zValidator("json", EntitlementRevokeRequest, validationHook),
3117
+ validate("json", EntitlementRevokeRequest),
2661
3118
  async (c) => {
2662
3119
  const input = c.req.valid("json");
2663
3120
  const caller = controlPlaneCaller(c);
@@ -2700,6 +3157,175 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2700
3157
  );
2701
3158
  },
2702
3159
  );
3160
+
3161
+ /**
3162
+ * The billing-kind check every override write shares, refused exactly as a grant refuses it. An override
3163
+ * keyed on a kind no read path resolves would shade nobody's numbers and answer 200.
3164
+ */
3165
+ function requireBilledKind(subjectType: PaymentsSubjectType): void {
3166
+ if (subjectType === config.billingSubject) return;
3167
+ throw new ValidationError({
3168
+ message: `This project bills ${config.billingSubject}s, not ${subjectType}s.`,
3169
+ action: "Send `subjectType` as the kind this project bills, or change `billingSubject` in pithy.config.ts.",
3170
+ detail: `An override for a ${subjectType} here writes a row keyed on a kind no read path resolves, so it would shade nobody's allowances and the table would say otherwise.`,
3171
+ });
3172
+ }
3173
+
3174
+ /** What every override write answers. */
3175
+ function overrideResponse(subject: PaymentsSubject, change: OverrideChange): PaymentsOverrideResponse {
3176
+ return {
3177
+ ...subject,
3178
+ override: adminOverrideView(change.after),
3179
+ version: overrideVersion(change.after),
3180
+ };
3181
+ }
3182
+
3183
+ /**
3184
+ * The audit event every override write emits — the subject, the mode, the before and the after, and the
3185
+ * reason verbatim. Severity `warning`, as a comp is: nothing else here changes what a customer may have
3186
+ * with no money moving.
3187
+ */
3188
+ async function emitOverride(
3189
+ c: Context<PithyHonoEnv>,
3190
+ action: PaymentsAuditAction,
3191
+ subject: PaymentsSubject,
3192
+ mode: "patch" | "unrestricted" | "clear",
3193
+ reason: string | null,
3194
+ change: OverrideChange,
3195
+ ): Promise<void> {
3196
+ const caller = controlPlaneCaller(c);
3197
+ await c.var.emit({
3198
+ action,
3199
+ outcome: "success",
3200
+ severity: "warning",
3201
+ actorType: "control-plane",
3202
+ actorId: caller.subject,
3203
+ resourceType: "entitlement_override",
3204
+ resourceId: encodeSubjectReference(subject),
3205
+ metadata: {
3206
+ connectionId: caller.connectionId,
3207
+ subjectType: subject.subjectType,
3208
+ subjectId: subject.subjectId,
3209
+ mode,
3210
+ reason,
3211
+ before: adminOverrideView(change.before),
3212
+ after: adminOverrideView(change.after),
3213
+ },
3214
+ });
3215
+ }
3216
+
3217
+ /**
3218
+ * CONTROL PLANE. Pin a negotiated number or switch for one subject.
3219
+ *
3220
+ * **A merge by name, never a replace.** Only the names sent change; every other pin stands and every name
3221
+ * never pinned keeps tracking the plan, so an upgrade still reaches a customer whose email allowance was
3222
+ * negotiated. **Version-checked**: the body names the version it read, and a set behind the row is
3223
+ * `payments/override_stale` with nothing written. **Bounded**: a number past a declared `overrideMax` is a
3224
+ * 400 naming the limit. **Explained**: `reason` is required and the audit event carries it.
3225
+ *
3226
+ * It does not set `unrestricted`, and a body that tries is a 400 rather than a field quietly dropped:
3227
+ * that is the other route, behind its own scope.
3228
+ */
3229
+ app.post(
3230
+ `${base}/entitlements/overrides`,
3231
+ describeRoute({
3232
+ summary: "Pin quotas and features for one subject.",
3233
+ verification: "control-plane",
3234
+ scopes: [PAYMENTS_OVERRIDE_SET_SCOPE],
3235
+ responses: { 200: PaymentsOverrideResponse },
3236
+ }),
3237
+ requireControlPlane(PAYMENTS_OVERRIDE_SET_SCOPE),
3238
+ validate("json", OverrideSetRequest),
3239
+ async (c) => {
3240
+ const input = c.req.valid("json");
3241
+ requireBilledKind(input.subjectType);
3242
+ const subject: PaymentsSubject = { subjectType: input.subjectType, subjectId: input.subjectId };
3243
+ const change = await setOverride(
3244
+ database(c),
3245
+ config,
3246
+ {
3247
+ subject,
3248
+ version: input.version,
3249
+ reason: input.reason,
3250
+ ...(input.quotas ? { quotas: input.quotas } : {}),
3251
+ ...(input.features ? { features: input.features } : {}),
3252
+ },
3253
+ { now: clock() },
3254
+ );
3255
+ await emitOverride(c, PaymentsAuditActions.overrideSet, subject, "patch", input.reason, change);
3256
+ return c.json(overrideResponse(subject, change) satisfies PaymentsOverrideResponse, 200);
3257
+ },
3258
+ );
3259
+
3260
+ /**
3261
+ * CONTROL PLANE. Grant one subject the whole product, or take it back.
3262
+ *
3263
+ * **Its own route and its own scope**, because it is the largest grant the kit has and the only one whose
3264
+ * reach grows by itself as names are declared: a credential that may raise one email cap must not be able
3265
+ * to do this. Never bounded by `overrideMax` — being unbounded is the point. It grants no entitlement key:
3266
+ * a subject holding nothing is still refused at every gate.
3267
+ */
3268
+ app.post(
3269
+ `${base}/entitlements/overrides/unrestricted`,
3270
+ describeRoute({
3271
+ summary: "Turn unrestricted on or off for one subject.",
3272
+ verification: "control-plane",
3273
+ scopes: [PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE],
3274
+ responses: { 200: PaymentsOverrideResponse },
3275
+ }),
3276
+ requireControlPlane(PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE),
3277
+ validate("json", OverrideUnrestrictedRequest),
3278
+ async (c) => {
3279
+ const input = c.req.valid("json");
3280
+ requireBilledKind(input.subjectType);
3281
+ const subject: PaymentsSubject = { subjectType: input.subjectType, subjectId: input.subjectId };
3282
+ const change = await setUnrestricted(
3283
+ database(c),
3284
+ { subject, version: input.version, reason: input.reason, unrestricted: input.unrestricted },
3285
+ { now: clock() },
3286
+ );
3287
+ await emitOverride(c, PaymentsAuditActions.overrideSet, subject, "unrestricted", input.reason, change);
3288
+ return c.json(overrideResponse(subject, change) satisfies PaymentsOverrideResponse, 200);
3289
+ },
3290
+ );
3291
+
3292
+ /**
3293
+ * CONTROL PLANE. Unpin names for one subject, or clear its override.
3294
+ *
3295
+ * **Idempotent**: a subject with no override answers 200 with nothing changed — the state the caller asked
3296
+ * for — and writes no audit row, because nothing moved. A name unpinned resolves from the plan again.
3297
+ */
3298
+ app.post(
3299
+ `${base}/entitlements/overrides/clear`,
3300
+ describeRoute({
3301
+ summary: "Unpin allowances for one subject, or clear its override.",
3302
+ verification: "control-plane",
3303
+ scopes: [PAYMENTS_OVERRIDE_CLEAR_SCOPE],
3304
+ responses: { 200: PaymentsOverrideResponse },
3305
+ }),
3306
+ requireControlPlane(PAYMENTS_OVERRIDE_CLEAR_SCOPE),
3307
+ validate("json", OverrideClearRequest),
3308
+ async (c) => {
3309
+ const input = c.req.valid("json");
3310
+ requireBilledKind(input.subjectType);
3311
+ const subject: PaymentsSubject = { subjectType: input.subjectType, subjectId: input.subjectId };
3312
+ const change = await clearOverride(
3313
+ database(c),
3314
+ {
3315
+ subject,
3316
+ ...(input.version !== undefined ? { version: input.version } : {}),
3317
+ ...(input.quotas ? { quotas: input.quotas } : {}),
3318
+ ...(input.features ? { features: input.features } : {}),
3319
+ ...(input.reason ? { reason: input.reason } : {}),
3320
+ },
3321
+ { now: clock() },
3322
+ );
3323
+ if (change.before !== undefined) {
3324
+ await emitOverride(c, PaymentsAuditActions.overrideCleared, subject, "clear", input.reason ?? null, change);
3325
+ }
3326
+ return c.json(overrideResponse(subject, change) satisfies PaymentsOverrideResponse, 200);
3327
+ },
3328
+ );
2703
3329
  };
2704
3330
 
2705
3331
  /**
@@ -2760,7 +3386,7 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2760
3386
  ...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
2761
3387
  },
2762
3388
  });
2763
- return c.json({ received: true, projected: false }, 200);
3389
+ return c.json({ received: true, projected: false } satisfies PaymentsWebhookAck, 200);
2764
3390
  };
2765
3391
 
2766
3392
  // Bind the store account to a user, when the notification carried both halves — before anything else,
@@ -2838,7 +3464,10 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2838
3464
  projected: true,
2839
3465
  },
2840
3466
  });
2841
- return c.json({ received: true, projected: true, outcome: projection.outcome }, 200);
3467
+ return c.json(
3468
+ { received: true, projected: true, outcome: projection.outcome } satisfies PaymentsWebhookAck,
3469
+ 200,
3470
+ );
2842
3471
  }
2843
3472
  return await acknowledge({
2844
3473
  error: `${noteText(notification.note) ?? "voided purchase"} — no purchase is stored under that order id.`,
@@ -2945,7 +3574,7 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
2945
3574
  projected: true,
2946
3575
  },
2947
3576
  });
2948
- return c.json({ received: true, projected: true, outcome: projection.outcome }, 200);
3577
+ return c.json({ received: true, projected: true, outcome: projection.outcome } satisfies PaymentsWebhookAck, 200);
2949
3578
  };
2950
3579
  }
2951
3580
  }