@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
@@ -6,10 +6,13 @@ import { providerProductId, railEnabled, resolveProduct } from "../config/config
6
6
  import { PaymentsPurchase } from "../data/purchase.js";
7
7
  import { WEBHOOK_EVENT_ORPHANED } from "../data/webhookEvent.js";
8
8
  import { PAYMENTS_PURCHASES_TABLE, paymentsDatabase } from "../data/tables.js";
9
- import { resolveEntitlements } from "../projection/resolve.js";
10
9
  import { PaymentsEntitlementNotInCatalogError, PaymentsProductNotFoundError, PaymentsRailNotConfiguredError, PaymentsReceiptAlreadyOwnedError, PaymentsReconcileNotProvisionedError, PaymentsSubscriptionChangeRefusedError } from "../error/errors.js";
10
+ import { resolveEntitlements } from "../projection/resolve.js";
11
+ import { resolveAllowances } from "../entitlement/allowance.js";
12
+ import { allowanceOverride, clearOverride, overrideCeiling, overrideVersion, readOverride, setOverride, setUnrestricted } from "../entitlement/override.js";
13
+ import { allowanceInputFor } from "../entitlement/meter.js";
11
14
  import { requirePaymentsSubject, resolvePaymentsSubject } from "../entitlement/subjectSeam.js";
12
- import { listEntitlements, listPurchases, listReconcileRuns, listSubscriptions, readEntitlements } from "../admin/read.js";
15
+ import { lastReports, listEntitlements, listOverrides, listPurchases, listReconcileRuns, listSubscriptions, listUsageRuns, readEntitlements, unrestrictedSubjects } from "../admin/read.js";
13
16
  import { PaymentsAuditActions } from "../audit/actions.js";
14
17
  import { nextSubscriptionEvent } from "../data/subscription.js";
15
18
  import { grantEntitlement, revokeEntitlement } from "../entitlement/manual.js";
@@ -22,16 +25,18 @@ import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/reg
22
25
  import { resolveRailProvider } from "../rails/providers.js";
23
26
  import { PAYMENTS_CAPABILITY, paymentsWorkflows } from "../workflows/specs.js";
24
27
  import { requireAuth } from "./guards.js";
25
- import { AdminDiscountsQuery, AdminEntitlementsQuery, AdminPurchasesQuery, AdminReconcileRunsQuery, AdminSubjectParam, AdminSubscriptionsQuery, AppleWebhookNotification, CheckoutRequest, DiscountCreateRequest, EntitlementGrantRequest, EntitlementRevokeRequest, GoogleWebhookNotification, LemonSqueezyWebhookNotification, PaddleWebhookNotification, PurchaseSubmission, RestoreRequest, StripeWebhookNotification, SubscriptionCancelRequest, SubscriptionChangeRequest, SubscriptionPreviewRequest } from "./schemas.js";
26
- import { PAYMENTS_CATALOG_READ_SCOPE, PAYMENTS_DISCOUNT_CREATE_SCOPE, PAYMENTS_DISCOUNT_READ_SCOPE, PAYMENTS_ENTITLEMENTS_READ_SCOPE, PAYMENTS_ENTITLEMENT_GRANT_SCOPE, PAYMENTS_ENTITLEMENT_REVOKE_SCOPE, PAYMENTS_PURCHASES_READ_SCOPE, PAYMENTS_RECONCILE_READ_SCOPE, PAYMENTS_RECONCILE_RUN_SCOPE, PAYMENTS_SUBSCRIPTIONS_READ_SCOPE } from "./scopes.js";
27
- import { adminCatalogView, adminEntitlementView, adminPurchaseView, adminReconcileRunView, entitlementView, purchaseView } from "./view.js";
28
+ import { PaymentsAdminCatalogResponse, PaymentsAdminDiscountsResponse, PaymentsAdminEntitlementsResponse, PaymentsAdminOverridesResponse, PaymentsAdminPurchasesResponse, PaymentsAdminReconcileRunStarted, PaymentsAdminReconcileRunsResponse, PaymentsAdminSubjectEntitlementsResponse, PaymentsAdminSubscriptionsResponse, PaymentsAdminUsageRunsResponse, PaymentsCheckoutHandoffResponse, PaymentsDiscountResponse, PaymentsEntitlementResponse, PaymentsEntitlementsResponse, PaymentsOverrideResponse, PaymentsPortalHandoffResponse, PaymentsPricingEnvelope, PaymentsPurchaseResponse, PaymentsRefundResponse, PaymentsRestoreResponse, PaymentsSubscriptionQuoteResponse, PaymentsSubscriptionResponse, PaymentsSubscriptionStandingResponse, PaymentsWebhookAck } from "./responses.js";
29
+ import { AdminDiscountsQuery, AdminEntitlementsQuery, AdminOverridesQuery, AdminPurchasesQuery, AdminReconcileRunsQuery, AdminSubjectParam, AdminSubscriptionsQuery, AdminUsageRunsQuery, AppleWebhookNotification, CheckoutRequest, DiscountCreateRequest, EntitlementGrantRequest, EntitlementRevokeRequest, GoogleWebhookNotification, LemonSqueezyWebhookNotification, OverrideClearRequest, OverrideSetRequest, OverrideUnrestrictedRequest, PaddleResumeQuery, PaddleWebhookNotification, PurchaseSubmission, RestoreRequest, StripeWebhookNotification, SubscriptionCancelRequest, SubscriptionChangeRequest, SubscriptionPreviewRequest } from "./schemas.js";
30
+ import { PAYMENTS_CATALOG_READ_SCOPE, PAYMENTS_DISCOUNT_CREATE_SCOPE, PAYMENTS_DISCOUNT_READ_SCOPE, PAYMENTS_ENTITLEMENTS_READ_SCOPE, PAYMENTS_ENTITLEMENT_GRANT_SCOPE, PAYMENTS_ENTITLEMENT_REVOKE_SCOPE, PAYMENTS_OVERRIDE_CLEAR_SCOPE, PAYMENTS_OVERRIDE_SET_SCOPE, PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE, PAYMENTS_PURCHASES_READ_SCOPE, PAYMENTS_RECONCILE_READ_SCOPE, PAYMENTS_RECONCILE_RUN_SCOPE, PAYMENTS_SUBSCRIPTIONS_READ_SCOPE, PAYMENTS_USAGE_READ_SCOPE } from "./scopes.js";
31
+ import { adminAllowancesView, adminCatalogView, adminEntitlementView, adminOverrideView, adminPurchaseView, adminReconcileRunView, adminUsageRunView, entitlementView, overrideView, purchaseView } from "./view.js";
28
32
  import { completeWebhook, requireSignedWebhook, verifiedWebhook } from "./webhookGuard.js";
29
33
  import { InternalError, NotFoundError, PithyError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
30
- import { zValidator } from "@hono/zod-validator";
34
+ import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
31
35
  import { safeEmit } from "@pithy-sh/core/src/controlPlane/audit/actions";
32
36
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
33
37
  import { memoryJwksCache } from "@pithy-sh/core/src/http/oidcWebhook";
34
- import { validationHook } from "@pithy-sh/core/src/http/validation";
38
+ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
39
+ import { validate } from "@pithy-sh/core/src/http/validation";
35
40
  import { resolveWorkflowBinding } from "@pithy-sh/core/src/workflow/dispatch";
36
41
  import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
37
42
  //#region src/http/routes.ts
@@ -784,7 +789,12 @@ function registerPaymentsRoutes(options) {
784
789
  * No query at all, and none to add: the catalog is small, fixed at deploy, and has no page. What
785
790
  * crosses is decided by `adminCatalogView` and asserted as an invariant rather than as a field list.
786
791
  */
787
- app.get(`${base}/admin/catalog`, requireControlPlane(PAYMENTS_CATALOG_READ_SCOPE), async (c) => {
792
+ app.get(`${base}/admin/catalog`, describeRoute({
793
+ summary: "Read what this project sells, and the keys it comps by hand.",
794
+ verification: "control-plane",
795
+ scopes: [PAYMENTS_CATALOG_READ_SCOPE],
796
+ responses: { 200: PaymentsAdminCatalogResponse }
797
+ }), requireControlPlane(PAYMENTS_CATALOG_READ_SCOPE), async (c) => {
788
798
  const view = adminCatalogView(config);
789
799
  await recordRead(c, PaymentsAuditActions.catalogRead, null, { products: view.enabled ? view.products.length : 0 });
790
800
  return c.json(view, 200);
@@ -797,7 +807,12 @@ function registerPaymentsRoutes(options) {
797
807
  * would have been needed for. `environment` is unfiltered by default on purpose — hiding sandbox
798
808
  * transactions would hide the single thing an operator most needs to notice on a production board.
799
809
  */
800
- app.get(`${base}/admin/purchases`, requireControlPlane(PAYMENTS_PURCHASES_READ_SCOPE), zValidator("query", AdminPurchasesQuery, validationHook), async (c) => {
810
+ app.get(`${base}/admin/purchases`, describeRoute({
811
+ summary: "Read the purchase log, newest first.",
812
+ verification: "control-plane",
813
+ scopes: [PAYMENTS_PURCHASES_READ_SCOPE],
814
+ responses: { 200: PaymentsAdminPurchasesResponse }
815
+ }), requireControlPlane(PAYMENTS_PURCHASES_READ_SCOPE), validate("query", AdminPurchasesQuery), async (c) => {
801
816
  const query = c.req.valid("query");
802
817
  const subject = subjectFilter(query);
803
818
  const page = await listPurchases(database(c), {
@@ -816,7 +831,7 @@ function registerPaymentsRoutes(options) {
816
831
  }
817
832
  });
818
833
  return c.json({
819
- purchases: page.items.map(adminPurchaseView),
834
+ purchases: page.items.map((row) => adminPurchaseView(row)),
820
835
  nextCursor: page.nextCursor
821
836
  }, 200);
822
837
  });
@@ -829,13 +844,22 @@ function registerPaymentsRoutes(options) {
829
844
  * is applied by `listSubscriptions` rather than by a `type` filter the request could name, so the
830
845
  * wider read is not reachable through this scope by construction.
831
846
  */
832
- app.get(`${base}/admin/subscriptions`, requireControlPlane(PAYMENTS_SUBSCRIPTIONS_READ_SCOPE), zValidator("query", AdminSubscriptionsQuery, validationHook), async (c) => {
847
+ app.get(`${base}/admin/subscriptions`, describeRoute({
848
+ summary: "Read the purchases that renew, newest first.",
849
+ verification: "control-plane",
850
+ scopes: [PAYMENTS_SUBSCRIPTIONS_READ_SCOPE],
851
+ responses: { 200: PaymentsAdminSubscriptionsResponse }
852
+ }), requireControlPlane(PAYMENTS_SUBSCRIPTIONS_READ_SCOPE), validate("query", AdminSubscriptionsQuery), async (c) => {
833
853
  const query = c.req.valid("query");
834
854
  const subject = subjectFilter(query);
835
855
  const page = await listSubscriptions(database(c), {
836
856
  ...query,
837
857
  subject
838
858
  });
859
+ const reported = await lastReports(database(c), page.items.flatMap((row) => row.originalTransactionId === null ? [] : [{
860
+ rail: row.rail,
861
+ providerSubscriptionId: row.originalTransactionId
862
+ }]));
839
863
  await recordRead(c, PaymentsAuditActions.subscriptionsRead, subject === void 0 ? null : encodeSubjectReference(subject), {
840
864
  returned: page.items.length,
841
865
  resumed: query.cursor !== void 0,
@@ -846,7 +870,7 @@ function registerPaymentsRoutes(options) {
846
870
  }
847
871
  });
848
872
  return c.json({
849
- subscriptions: page.items.map(adminPurchaseView),
873
+ subscriptions: page.items.map((row) => adminPurchaseView(row, reported.get(`${row.rail}:${row.originalTransactionId}`) ?? null)),
850
874
  nextCursor: page.nextCursor
851
875
  }, 200);
852
876
  });
@@ -857,7 +881,12 @@ function registerPaymentsRoutes(options) {
857
881
  * resolves it. A dashboard that recomputed it from the stored flag would eventually disagree with that
858
882
  * gate, and the customer would believe the dashboard.
859
883
  */
860
- app.get(`${base}/admin/entitlements`, requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE), zValidator("query", AdminEntitlementsQuery, validationHook), async (c) => {
884
+ app.get(`${base}/admin/entitlements`, describeRoute({
885
+ summary: "Read the entitlement model, page by page.",
886
+ verification: "control-plane",
887
+ scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
888
+ responses: { 200: PaymentsAdminEntitlementsResponse }
889
+ }), requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE), validate("query", AdminEntitlementsQuery), async (c) => {
861
890
  const query = c.req.valid("query");
862
891
  const now = clock();
863
892
  const subject = subjectFilter(query);
@@ -865,6 +894,7 @@ function registerPaymentsRoutes(options) {
865
894
  ...query,
866
895
  subject
867
896
  });
897
+ const unrestricted = await unrestrictedSubjects(database(c), page.items);
868
898
  await recordRead(c, PaymentsAuditActions.entitlementsRead, subject === void 0 ? null : encodeSubjectReference(subject), {
869
899
  returned: page.items.length,
870
900
  resumed: query.cursor !== void 0,
@@ -875,7 +905,48 @@ function registerPaymentsRoutes(options) {
875
905
  }
876
906
  });
877
907
  return c.json({
878
- entitlements: page.items.map((row) => adminEntitlementView(row, now)),
908
+ entitlements: page.items.map((row) => adminEntitlementView(row, now, unrestricted.has(encodeSubjectReference(row)))),
909
+ nextCursor: page.nextCursor
910
+ }, 200);
911
+ });
912
+ /**
913
+ * CONTROL PLANE. Every subject's override, most recently changed first.
914
+ *
915
+ * The read the override writes are paired with, on the entitlement read's scope: what a subject may have
916
+ * is one question with its entitlements, and an operator who can see one can see the other. Filterable to
917
+ * `unrestricted=true`, because "who holds the whole product" must be a question anyone holding this scope
918
+ * can answer in one request.
919
+ */
920
+ app.get(`${base}/admin/overrides`, describeRoute({
921
+ summary: "Read every subject's override, page by page.",
922
+ verification: "control-plane",
923
+ scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
924
+ responses: { 200: PaymentsAdminOverridesResponse }
925
+ }), requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE), validate("query", AdminOverridesQuery), async (c) => {
926
+ const query = c.req.valid("query");
927
+ const subject = subjectFilter(query);
928
+ const unrestricted = query.unrestricted === void 0 ? void 0 : query.unrestricted === "true";
929
+ const page = await listOverrides(database(c), {
930
+ ...subject ? { subject } : {},
931
+ ...unrestricted === void 0 ? {} : { unrestricted },
932
+ ...query.cursor ? { cursor: query.cursor } : {},
933
+ ...query.limit ? { limit: query.limit } : {}
934
+ });
935
+ await recordRead(c, PaymentsAuditActions.entitlementsRead, subject === void 0 ? null : encodeSubjectReference(subject), {
936
+ returned: page.items.length,
937
+ resumed: query.cursor !== void 0,
938
+ filters: {
939
+ subjectType: subject?.subjectType ?? null,
940
+ subjectId: subject?.subjectId ?? null,
941
+ unrestricted: unrestricted ?? null
942
+ }
943
+ });
944
+ return c.json({
945
+ overrides: page.items.map((row) => ({
946
+ subjectType: row.subjectType,
947
+ subjectId: row.subjectId,
948
+ override: overrideView(row)
949
+ })),
879
950
  nextCursor: page.nextCursor
880
951
  }, 200);
881
952
  });
@@ -894,18 +965,42 @@ function registerPaymentsRoutes(options) {
894
965
  * its absence is not a missing holder — and a 404 would make this surface an existence oracle for user and
895
966
  * organization ids alike.
896
967
  */
897
- app.get(`${base}/admin/entitlements/:subjectType/:subjectId`, requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE), zValidator("param", AdminSubjectParam, validationHook), async (c) => {
968
+ app.get(`${base}/admin/entitlements/:subjectType/:subjectId`, describeRoute({
969
+ summary: "Read one subject's entitlements, resolved now.",
970
+ verification: "control-plane",
971
+ scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
972
+ responses: { 200: PaymentsAdminSubjectEntitlementsResponse }
973
+ }), requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE), validate("param", AdminSubjectParam), async (c) => {
898
974
  const subject = c.req.valid("param");
899
975
  const now = clock();
900
- const rows = await readEntitlements(database(c), subject);
976
+ const d1 = database(c);
977
+ const rows = await readEntitlements(d1, subject);
978
+ const override = await readOverride(paymentsDatabase(d1), subject);
979
+ const held = grantedEntitlementKeys(rows.map((row) => ({
980
+ key: row.entitlement,
981
+ active: row.active,
982
+ expiresAt: row.expiresAt,
983
+ source: null
984
+ })), now);
985
+ const resolved = resolveAllowances({
986
+ declarations: config,
987
+ held,
988
+ override: allowanceOverride(override)
989
+ });
990
+ const unrestricted = override?.unrestricted === true;
901
991
  await recordRead(c, PaymentsAuditActions.entitlementsRead, encodeSubjectReference(subject), {
902
992
  subjectType: subject.subjectType,
903
993
  subjectId: subject.subjectId,
904
- returned: rows.length
994
+ returned: rows.length,
995
+ unrestricted
905
996
  });
906
997
  return c.json({
907
998
  ...subject,
908
- entitlements: rows.map((row) => adminEntitlementView(row, now))
999
+ entitlements: rows.map((row) => adminEntitlementView(row, now, unrestricted)),
1000
+ unrestricted,
1001
+ overrideVersion: overrideVersion(override),
1002
+ override: adminOverrideView(override),
1003
+ allowances: adminAllowancesView(resolved, (name) => overrideCeiling(config, held, name))
909
1004
  }, 200);
910
1005
  });
911
1006
  /**
@@ -918,7 +1013,12 @@ function registerPaymentsRoutes(options) {
918
1013
  * Its own scope: a run names no account, no transaction and no amount, so a health monitor can be granted
919
1014
  * exactly this without acquiring the purchase log.
920
1015
  */
921
- app.get(`${base}/admin/reconcile-runs`, requireControlPlane(PAYMENTS_RECONCILE_READ_SCOPE), zValidator("query", AdminReconcileRunsQuery, validationHook), async (c) => {
1016
+ app.get(`${base}/admin/reconcile-runs`, describeRoute({
1017
+ summary: "Read the reconciliation passes this deployment has run.",
1018
+ verification: "control-plane",
1019
+ scopes: [PAYMENTS_RECONCILE_READ_SCOPE],
1020
+ responses: { 200: PaymentsAdminReconcileRunsResponse }
1021
+ }), requireControlPlane(PAYMENTS_RECONCILE_READ_SCOPE), validate("query", AdminReconcileRunsQuery), async (c) => {
922
1022
  const query = c.req.valid("query");
923
1023
  const page = await listReconcileRuns(database(c), query);
924
1024
  await recordRead(c, PaymentsAuditActions.reconcileRunsRead, null, {
@@ -935,6 +1035,30 @@ function registerPaymentsRoutes(options) {
935
1035
  }, 200);
936
1036
  });
937
1037
  /**
1038
+ * CONTROL PLANE. What usage reporting has done — the passes this Worker has run, newest first.
1039
+ *
1040
+ * Its own scope, separate from the reconciliation log's: a run's findings name the subjects it did not
1041
+ * report and why, which is what an operator answering "why was this customer not billed" needs and what a
1042
+ * health monitor does not.
1043
+ */
1044
+ app.get(`${base}/admin/usage-runs`, describeRoute({
1045
+ summary: "Read the usage-reporting passes this deployment has run.",
1046
+ verification: "control-plane",
1047
+ scopes: [PAYMENTS_USAGE_READ_SCOPE],
1048
+ responses: { 200: PaymentsAdminUsageRunsResponse }
1049
+ }), requireControlPlane(PAYMENTS_USAGE_READ_SCOPE), validate("query", AdminUsageRunsQuery), async (c) => {
1050
+ const query = c.req.valid("query");
1051
+ const page = await listUsageRuns(database(c), query);
1052
+ await recordRead(c, PaymentsAuditActions.usageRunsRead, null, {
1053
+ returned: page.items.length,
1054
+ resumed: query.cursor !== void 0
1055
+ });
1056
+ return c.json({
1057
+ runs: page.items.map(adminUsageRunView),
1058
+ nextCursor: page.nextCursor
1059
+ }, 200);
1060
+ });
1061
+ /**
938
1062
  * CONTROL PLANE WRITE. Start a reconciliation pass now.
939
1063
  *
940
1064
  * **The counterpart to the read above, and a different power.** Reading the log says whether the nightly
@@ -952,10 +1076,15 @@ function registerPaymentsRoutes(options) {
952
1076
  * pass happen, and answering 202 while nothing started is the failure this codebase spends its comments
953
1077
  * avoiding — so the binding is resolved directly and its absence is a refusal naming what to deploy.
954
1078
  *
955
- * Idempotent, like the pass itself. A second press while one is in flight starts nothing and says
956
- * `started: false`, which is a true sentence rather than a 409 that reads as a fault.
1079
+ * Every press that is not refused starts a pass and answers `started: true`. A second press while one is
1080
+ * in flight starts a second: the pass is idempotent, so two converge on the same repairs.
957
1081
  */
958
- app.post(`${base}/admin/reconcile-runs`, requireControlPlane(PAYMENTS_RECONCILE_RUN_SCOPE), async (c) => {
1082
+ app.post(`${base}/admin/reconcile-runs`, describeRoute({
1083
+ summary: "Start a reconciliation pass now.",
1084
+ verification: "control-plane",
1085
+ scopes: [PAYMENTS_RECONCILE_RUN_SCOPE],
1086
+ responses: { 202: PaymentsAdminReconcileRunStarted }
1087
+ }), requireControlPlane(PAYMENTS_RECONCILE_RUN_SCOPE), async (c) => {
959
1088
  const spec = paymentsWorkflows.reconcile;
960
1089
  const binding = resolveWorkflowBinding(c.env, {
961
1090
  binding: spec.binding,
@@ -986,7 +1115,11 @@ function registerPaymentsRoutes(options) {
986
1115
  * existing purchase — the write path is idempotent, so a repeat is not an error. A receipt belonging to
987
1116
  * somebody else is a 409, audited as denied.
988
1117
  */
989
- app.post(`${base}/purchases`, requireAuth(), zValidator("json", PurchaseSubmission, validationHook), async (c) => {
1118
+ app.post(`${base}/purchases`, describeRoute({
1119
+ summary: "Verify a receipt and project the purchase.",
1120
+ verification: ["bearer", "session"],
1121
+ responses: { 200: PaymentsPurchaseResponse }
1122
+ }), requireAuth(), validate("json", PurchaseSubmission), async (c) => {
990
1123
  const input = c.req.valid("json");
991
1124
  const subject = await requirePaymentsSubject(c, seam);
992
1125
  try {
@@ -1044,11 +1177,29 @@ function registerPaymentsRoutes(options) {
1044
1177
  * already answers for somebody who has bought nothing — and a 403 here would make a paywall render an
1045
1178
  * error where it should render the paywall.
1046
1179
  */
1047
- app.get(`${base}/entitlements`, requireAuth(), async (c) => {
1180
+ app.get(`${base}/entitlements`, describeRoute({
1181
+ summary: "Read the caller's own entitlements.",
1182
+ verification: ["bearer", "session"],
1183
+ responses: { 200: PaymentsEntitlementsResponse }
1184
+ }), requireAuth(), async (c) => {
1048
1185
  const subject = await resolvePaymentsSubject(c, seam);
1049
- if (subject === void 0) return c.json({ entitlements: [] }, 200);
1050
- const entitlements = await resolveEntitlements(paymentsDatabase(database(c)), subject, clock());
1051
- return c.json({ entitlements: entitlements.map(entitlementView) }, 200);
1186
+ const now = clock();
1187
+ const db = subject === void 0 ? void 0 : paymentsDatabase(database(c));
1188
+ const input = await allowanceInputFor(db, config, subject, now);
1189
+ const resolved = resolveAllowances(input);
1190
+ const allowances = {
1191
+ quotas: Object.fromEntries(resolved.quotas.map((entry) => [entry.name, entry.effective.value])),
1192
+ features: Object.fromEntries(resolved.features.map((entry) => [entry.name, entry.effective.value]))
1193
+ };
1194
+ if (subject === void 0 || db === void 0) return c.json({
1195
+ entitlements: [],
1196
+ ...allowances
1197
+ }, 200);
1198
+ const entitlements = await resolveEntitlements(db, subject, now);
1199
+ return c.json({
1200
+ entitlements: entitlements.map(entitlementView),
1201
+ ...allowances
1202
+ }, 200);
1052
1203
  });
1053
1204
  /**
1054
1205
  * AUTHED WRITE. Restore Purchases, client-driven because only the device can enumerate what its store
@@ -1059,7 +1210,11 @@ function registerPaymentsRoutes(options) {
1059
1210
  * success would hide it. Every receipt that did project stays projected — the writer is idempotent, so the
1060
1211
  * client simply retries.
1061
1212
  */
1062
- app.post(`${base}/restore`, requireAuth(), zValidator("json", RestoreRequest, validationHook), async (c) => {
1213
+ app.post(`${base}/restore`, describeRoute({
1214
+ summary: "Restore purchases onto the caller's own holder.",
1215
+ verification: ["bearer", "session"],
1216
+ responses: { 200: PaymentsRestoreResponse }
1217
+ }), requireAuth(), validate("json", RestoreRequest), async (c) => {
1063
1218
  const input = c.req.valid("json");
1064
1219
  const subject = await requirePaymentsSubject(c, seam);
1065
1220
  const purchases = [];
@@ -1086,11 +1241,15 @@ function registerPaymentsRoutes(options) {
1086
1241
  /**
1087
1242
  * SIGNED WEBHOOK — Apple. App Store Server Notifications V2, signed as a JWS against Apple's pinned chain.
1088
1243
  */
1089
- app.post(`${base}/webhooks/apple`, requireSignedWebhook("apple", {
1244
+ app.post(`${base}/webhooks/apple`, describeRoute({
1245
+ summary: "Receive an App Store Server Notification.",
1246
+ verification: "signed-webhook",
1247
+ responses: { 200: PaymentsWebhookAck }
1248
+ }), requireSignedWebhook("apple", {
1090
1249
  config,
1091
1250
  now: clock,
1092
1251
  trust
1093
- }), zValidator("json", AppleWebhookNotification, validationHook), webhookHandler("apple"));
1252
+ }), validate("json", AppleWebhookNotification), webhookHandler("apple"));
1094
1253
  /**
1095
1254
  * SIGNED WEBHOOK — Google. A Pub/Sub push whose OIDC token the guard verified, audience and all.
1096
1255
  *
@@ -1098,11 +1257,15 @@ function registerPaymentsRoutes(options) {
1098
1257
  * already turned Play's pointer into a normalized event through the Play Developer API, so there is nothing
1099
1258
  * Google-shaped left to branch on.
1100
1259
  */
1101
- app.post(`${base}/webhooks/google`, requireSignedWebhook("google", {
1260
+ app.post(`${base}/webhooks/google`, describeRoute({
1261
+ summary: "Receive a Play notification, pushed through Pub/Sub.",
1262
+ verification: "signed-webhook",
1263
+ responses: { 200: PaymentsWebhookAck }
1264
+ }), requireSignedWebhook("google", {
1102
1265
  config,
1103
1266
  now: clock,
1104
1267
  trust
1105
- }), zValidator("json", GoogleWebhookNotification, validationHook), webhookHandler("google"));
1268
+ }), validate("json", GoogleWebhookNotification), webhookHandler("google"));
1106
1269
  /**
1107
1270
  * SIGNED WEBHOOK — Stripe. An HMAC in `Stripe-Signature`, over the exact received bytes and dated, which the
1108
1271
  * guard has checked inside the replay window before this validator ever parses the body.
@@ -1111,11 +1274,15 @@ function registerPaymentsRoutes(options) {
1111
1274
  * this is where most Stripe purchases enter the system — and it is still nothing but a verified notification
1112
1275
  * by the time the handler runs.
1113
1276
  */
1114
- app.post(`${base}/webhooks/stripe`, requireSignedWebhook("stripe", {
1277
+ app.post(`${base}/webhooks/stripe`, describeRoute({
1278
+ summary: "Receive a Stripe event.",
1279
+ verification: "signed-webhook",
1280
+ responses: { 200: PaymentsWebhookAck }
1281
+ }), requireSignedWebhook("stripe", {
1115
1282
  config,
1116
1283
  now: clock,
1117
1284
  trust
1118
- }), zValidator("json", StripeWebhookNotification, validationHook), webhookHandler("stripe"));
1285
+ }), validate("json", StripeWebhookNotification), webhookHandler("stripe"));
1119
1286
  /**
1120
1287
  * SIGNED WEBHOOK — Lemon Squeezy. A bare HMAC in `X-Signature`, over the exact received bytes, which the
1121
1288
  * guard has checked before this validator ever parses the body.
@@ -1129,11 +1296,15 @@ function registerPaymentsRoutes(options) {
1129
1296
  * has no client-submission path at all: its order ids are sequential integers, so no submitted receipt
1130
1297
  * could be trusted.
1131
1298
  */
1132
- app.post(`${base}/webhooks/lemon-squeezy`, requireSignedWebhook("lemonSqueezy", {
1299
+ app.post(`${base}/webhooks/lemon-squeezy`, describeRoute({
1300
+ summary: "Receive a Lemon Squeezy event.",
1301
+ verification: "signed-webhook",
1302
+ responses: { 200: PaymentsWebhookAck }
1303
+ }), requireSignedWebhook("lemonSqueezy", {
1133
1304
  config,
1134
1305
  now: clock,
1135
1306
  trust
1136
- }), zValidator("json", LemonSqueezyWebhookNotification, validationHook), webhookHandler("lemonSqueezy"));
1307
+ }), validate("json", LemonSqueezyWebhookNotification), webhookHandler("lemonSqueezy"));
1137
1308
  /**
1138
1309
  * SIGNED WEBHOOK — Paddle. `Paddle-Signature: ts=…;h1=…`, an HMAC-SHA256 over `${ts}:${exact received
1139
1310
  * bytes}`, which the guard has checked inside the freshness window before this validator ever parses the
@@ -1149,11 +1320,15 @@ function registerPaymentsRoutes(options) {
1149
1320
  * Squeezy this rail has a submittable receipt, because a `txn_…` checked against a *proven* ownership
1150
1321
  * stamp is safe where an unguessable order id is not.
1151
1322
  */
1152
- app.post(`${base}/webhooks/paddle`, requireSignedWebhook("paddle", {
1323
+ app.post(`${base}/webhooks/paddle`, describeRoute({
1324
+ summary: "Receive a Paddle event.",
1325
+ verification: "signed-webhook",
1326
+ responses: { 200: PaymentsWebhookAck }
1327
+ }), requireSignedWebhook("paddle", {
1153
1328
  config,
1154
1329
  now: clock,
1155
1330
  trust
1156
- }), zValidator("json", PaddleWebhookNotification, validationHook), webhookHandler("paddle"));
1331
+ }), validate("json", PaddleWebhookNotification), webhookHandler("paddle"));
1157
1332
  /**
1158
1333
  * AUTHED WRITE — Stripe only. Create a hosted Checkout Session and hand back where to send the browser.
1159
1334
  *
@@ -1167,7 +1342,11 @@ function registerPaymentsRoutes(options) {
1167
1342
  * be charged as, and refusing before the 404 keeps this from answering what a project sells to somebody it
1168
1343
  * cannot bill.
1169
1344
  */
1170
- app.post(`${base}/checkout`, requireAuth(), zValidator("json", CheckoutRequest, validationHook), async (c) => {
1345
+ app.post(`${base}/checkout`, describeRoute({
1346
+ summary: "Start a hosted checkout for one catalog product.",
1347
+ verification: ["bearer", "session"],
1348
+ responses: { 200: PaymentsCheckoutHandoffResponse }
1349
+ }), requireAuth(), validate("json", CheckoutRequest), async (c) => {
1171
1350
  const input = c.req.valid("json");
1172
1351
  const subject = await requirePaymentsSubject(c, seam);
1173
1352
  const entry = product(config, input.productId);
@@ -1178,6 +1357,7 @@ function registerPaymentsRoutes(options) {
1178
1357
  const handoff = await (await checkoutRail(c, rail)).createCheckoutSession({
1179
1358
  providerProductId: sku,
1180
1359
  subscription: entry.product.type === "subscription",
1360
+ reported: entry.product.billing?.kind === "reported",
1181
1361
  subject,
1182
1362
  providerAccountId: await accountFor(c, rail, subject),
1183
1363
  successUrl: settings.successUrl,
@@ -1207,13 +1387,65 @@ function registerPaymentsRoutes(options) {
1207
1387
  return c.json(handoff, 200);
1208
1388
  });
1209
1389
  /**
1390
+ * PUBLIC READ — Paddle only. What a page needs to resume a transaction Paddle itself created.
1391
+ *
1392
+ * **`#680`.** Paddle appends `?_ptxn=<transaction_id>` to a seller's *Default payment link* and expects
1393
+ * the page it lands on to open a checkout for that transaction. Those links are the ones Paddle sends
1394
+ * rather than the ones this kit opens — a past-due dunning mail, a manually-collected invoice, the
1395
+ * payment-method-update link minted for a subscription — and until this route existed the kit could not
1396
+ * use one: `POST {base}/checkout` mints a transaction, and here the transaction already exists.
1397
+ *
1398
+ * **Unauthenticated, and that is the point rather than an oversight.** The buyer following a dunning
1399
+ * link is frequently signed out — that is the population this serves, so `requireAuth()` would break it
1400
+ * for exactly them. It is safe because it discloses nothing: `clientToken` is publishable by design,
1401
+ * `environment`, `displayMode` and `successUrl` are config constants identical for every transaction,
1402
+ * and the id is the caller's own, echoed. The sum of what a stranger learns is this project's Paddle
1403
+ * account, which every pricing page already ships.
1404
+ *
1405
+ * **It must never read the transaction from Paddle**, and that is the one line to defend in review. A
1406
+ * lookup would turn an unauthenticated route into an oracle for whether a transaction id exists, and
1407
+ * then for what it costs. Shape is checked; existence is Paddle's to tell the buyer, inside the
1408
+ * checkout, where it is already their own transaction.
1409
+ *
1410
+ * **Nothing about a session is read, structurally.** No `requireAuth`, no `requirePaymentsSubject`, and
1411
+ * `PaddleResumeQuery` has no holder field for one — so a resume cannot stamp the current user onto a
1412
+ * transaction that arrived in a URL, which is the way this route could have been used to claim somebody
1413
+ * else's payment.
1414
+ *
1415
+ * **`hosted` refuses.** In that mode this kit never opens a checkout in the page: it redirects to
1416
+ * Paddle's own, at a URL only a transaction read would yield — the read this route may not do. A buyer
1417
+ * on a hosted-mode project is already on Paddle's page, so there is nothing here to resume.
1418
+ */
1419
+ app.get(`${base}/checkout/resume`, describeRoute({
1420
+ summary: "Resume a Paddle transaction a payment link arrived for.",
1421
+ verification: "public",
1422
+ responses: { 200: PaymentsCheckoutHandoffResponse }
1423
+ }), validate("query", PaddleResumeQuery), (c) => {
1424
+ const { transaction } = c.req.valid("query");
1425
+ if (config.paddle === void 0) throw new PaymentsRailNotConfiguredError({ detail: "The paddle rail is off in this project's config, so there is no payment link to resume." });
1426
+ if (config.paddle.checkout === "hosted") throw new PaymentsRailNotConfiguredError({ detail: "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." });
1427
+ const handoff = {
1428
+ kind: "paddle",
1429
+ transactionId: transaction,
1430
+ clientToken: config.paddle.clientToken,
1431
+ environment: config.paddle.environment,
1432
+ displayMode: config.paddle.checkout,
1433
+ successUrl: config.paddle.successUrl
1434
+ };
1435
+ return c.json(handoff, 200);
1436
+ });
1437
+ /**
1210
1438
  * AUTHED WRITE — Stripe only. Open the Billing Portal for the caller's own store account.
1211
1439
  *
1212
1440
  * No body at all, and that is the request contract: there is exactly one customer this caller may manage,
1213
1441
  * and it comes from the provider-account map. A `customer` field here would be the whole vulnerability —
1214
1442
  * any signed-in caller could open a session against somebody else's billing history and cancel it.
1215
1443
  */
1216
- app.post(`${base}/portal`, requireAuth(), async (c) => {
1444
+ app.post(`${base}/portal`, describeRoute({
1445
+ summary: "Open the billing portal for the caller's own store account.",
1446
+ verification: ["bearer", "session"],
1447
+ responses: { 200: PaymentsPortalHandoffResponse }
1448
+ }), requireAuth(), async (c) => {
1217
1449
  const subject = await requirePaymentsSubject(c, seam);
1218
1450
  const enabled = PAYMENTS_HOSTED_RAILS.filter((rail) => railEnabled(config, rail));
1219
1451
  if (enabled.length === 0) throw new PaymentsRailNotConfiguredError({ detail: "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`." });
@@ -1298,7 +1530,11 @@ function registerPaymentsRoutes(options) {
1298
1530
  * bought anything has no pricing and may still have no customer, and somebody mid-subscription has
1299
1531
  * both. Nesting one in the other would make the common case unreachable.
1300
1532
  */
1301
- app.get(`${base}/pricing`, requireAuth(), async (c) => {
1533
+ app.get(`${base}/pricing`, describeRoute({
1534
+ summary: "Read what the caller's own subscription pays, and when that changes.",
1535
+ verification: ["bearer", "session"],
1536
+ responses: { 200: PaymentsPricingEnvelope }
1537
+ }), requireAuth(), async (c) => {
1302
1538
  const subject = await resolvePaymentsSubject(c, seam);
1303
1539
  if (subject === void 0) return c.json({
1304
1540
  pricing: null,
@@ -1357,7 +1593,11 @@ function registerPaymentsRoutes(options) {
1357
1593
  * shape of this request that reads somebody else's. Nobody resolved is the empty answer rather than a
1358
1594
  * refusal, which is the read half of the seam's rule and what `GET {base}/entitlements` already does.
1359
1595
  */
1360
- app.get(`${base}/subscription`, requireAuth(), async (c) => {
1596
+ app.get(`${base}/subscription`, describeRoute({
1597
+ summary: "Read where the caller's own subscription stands, live from the store.",
1598
+ verification: ["bearer", "session"],
1599
+ responses: { 200: PaymentsSubscriptionResponse }
1600
+ }), requireAuth(), async (c) => {
1361
1601
  const subject = await resolvePaymentsSubject(c, seam);
1362
1602
  if (subject === void 0) return c.json({ subscription: null }, 200);
1363
1603
  const target = await changeableSubscription(database(c), subject, clock());
@@ -1368,7 +1608,16 @@ function registerPaymentsRoutes(options) {
1368
1608
  deployment: deploymentName(c)
1369
1609
  });
1370
1610
  if (standing === void 0) return c.json({ subscription: null }, 200);
1371
- return c.json({ subscription: subscriptionView(target.purchase.productId, standing) }, 200);
1611
+ const subscriptionId = target.purchase.originalTransactionId;
1612
+ const last = subscriptionId === null ? void 0 : (await lastReports(database(c), [{
1613
+ rail: target.purchase.rail,
1614
+ providerSubscriptionId: subscriptionId
1615
+ }])).get(`${target.purchase.rail}:${subscriptionId}`);
1616
+ return c.json({ subscription: {
1617
+ ...subscriptionView(target.purchase.productId, standing),
1618
+ reportedQuantity: last?.quantity ?? null,
1619
+ reportedAt: last?.reportedAt.toISOString() ?? null
1620
+ } }, 200);
1372
1621
  });
1373
1622
  /**
1374
1623
  * AUTHED READ — what moving to one catalog product would cost, as the store previews it.
@@ -1392,7 +1641,11 @@ function registerPaymentsRoutes(options) {
1392
1641
  * `payments/subject_unresolved` says exactly that, where a 404 would claim the caller has no
1393
1642
  * subscription anywhere.
1394
1643
  */
1395
- app.post(`${base}/subscription/preview`, requireAuth(), zValidator("json", SubscriptionPreviewRequest, validationHook), async (c) => {
1644
+ app.post(`${base}/subscription/preview`, describeRoute({
1645
+ summary: "Preview what moving to one catalog product would cost.",
1646
+ verification: ["bearer", "session"],
1647
+ responses: { 200: PaymentsSubscriptionQuoteResponse }
1648
+ }), requireAuth(), validate("json", SubscriptionPreviewRequest), async (c) => {
1396
1649
  const input = c.req.valid("json");
1397
1650
  const subject = await requirePaymentsSubject(c, seam);
1398
1651
  const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
@@ -1434,7 +1687,11 @@ function registerPaymentsRoutes(options) {
1434
1687
  * its own row rather than from the rail, which reports no such flag, and the residual gap is stated at
1435
1688
  * {@link changedPlan}.
1436
1689
  */
1437
- app.post(`${base}/subscription/change`, requireAuth(), zValidator("json", SubscriptionChangeRequest, validationHook), async (c) => {
1690
+ app.post(`${base}/subscription/change`, describeRoute({
1691
+ summary: "Move the caller's own subscription onto one catalog product.",
1692
+ verification: ["bearer", "session"],
1693
+ responses: { 200: PaymentsSubscriptionStandingResponse }
1694
+ }), requireAuth(), validate("json", SubscriptionChangeRequest), async (c) => {
1438
1695
  const input = c.req.valid("json");
1439
1696
  const subject = await requirePaymentsSubject(c, seam);
1440
1697
  const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
@@ -1489,7 +1746,11 @@ function registerPaymentsRoutes(options) {
1489
1746
  *
1490
1747
  * Writes no purchase row, as every route here does not: the webhook owns it.
1491
1748
  */
1492
- app.post(`${base}/subscription/cancel`, requireAuth(), zValidator("json", SubscriptionCancelRequest, validationHook), async (c) => {
1749
+ app.post(`${base}/subscription/cancel`, describeRoute({
1750
+ summary: "Stop the caller's own subscription renewing.",
1751
+ verification: ["bearer", "session"],
1752
+ responses: { 200: PaymentsSubscriptionStandingResponse }
1753
+ }), requireAuth(), validate("json", SubscriptionCancelRequest), async (c) => {
1493
1754
  const input = c.req.valid("json");
1494
1755
  const subject = await requirePaymentsSubject(c, seam);
1495
1756
  const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
@@ -1544,7 +1805,11 @@ function registerPaymentsRoutes(options) {
1544
1805
  * A subscription with nothing scheduled is the no-op rather than a refusal — it already renews, which
1545
1806
  * is what the caller asked for — and it writes no audit row, for {@link standingMoved}'s reason.
1546
1807
  */
1547
- app.post(`${base}/subscription/keep`, requireAuth(), async (c) => {
1808
+ app.post(`${base}/subscription/keep`, describeRoute({
1809
+ summary: "Withdraw a scheduled cancellation.",
1810
+ verification: ["bearer", "session"],
1811
+ responses: { 200: PaymentsSubscriptionStandingResponse }
1812
+ }), requireAuth(), async (c) => {
1548
1813
  const subject = await requirePaymentsSubject(c, seam);
1549
1814
  const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
1550
1815
  const provider = await subscriptionRail(c, purchase.rail);
@@ -1603,7 +1868,11 @@ function registerPaymentsRoutes(options) {
1603
1868
  * already standing is the state the caller wanted, and a trail claiming two of them is worse than one
1604
1869
  * claiming none.
1605
1870
  */
1606
- app.post(`${base}/subscription/refund`, requireAuth(), async (c) => {
1871
+ app.post(`${base}/subscription/refund`, describeRoute({
1872
+ summary: "Ask the store to refund the payments on the caller's own subscription.",
1873
+ verification: ["bearer", "session"],
1874
+ responses: { 200: PaymentsRefundResponse }
1875
+ }), requireAuth(), async (c) => {
1607
1876
  const subject = await requirePaymentsSubject(c, seam);
1608
1877
  const purchase = requireOneSubscription(await changeableSubscription(database(c), subject, clock()));
1609
1878
  const provider = await refundRail(c, purchase.rail);
@@ -1653,7 +1922,12 @@ function registerPaymentsRoutes(options) {
1653
1922
  * issue. Never reaches a browser — the set of codes an adopter has issued is a commercial fact, and the
1654
1923
  * client projection draws the same line here it draws for SKUs.
1655
1924
  */
1656
- app.get(`${base}/admin/discounts`, requireControlPlane(PAYMENTS_DISCOUNT_READ_SCOPE), zValidator("query", AdminDiscountsQuery, validationHook), async (c) => {
1925
+ app.get(`${base}/admin/discounts`, describeRoute({
1926
+ summary: "Read the discount codes this project has issued at one store.",
1927
+ verification: "control-plane",
1928
+ scopes: [PAYMENTS_DISCOUNT_READ_SCOPE],
1929
+ responses: { 200: PaymentsAdminDiscountsResponse }
1930
+ }), requireControlPlane(PAYMENTS_DISCOUNT_READ_SCOPE), validate("query", AdminDiscountsQuery), async (c) => {
1657
1931
  const { rail } = c.req.valid("query");
1658
1932
  const provider = resolveRailProvider(rail, config, await credentials(c), trust);
1659
1933
  if (!isDiscountRail(provider)) throw new PaymentsRailNotConfiguredError({ detail: `The ${provider.rail} rail does not mint discounts.` });
@@ -1682,7 +1956,12 @@ function registerPaymentsRoutes(options) {
1682
1956
  * Applying a code does **not** go through here and does not require this scope. An adopter whose codes
1683
1957
  * are minted by hand in a provider dashboard is fully served by `/checkout`'s `discountCode`.
1684
1958
  */
1685
- app.post(`${base}/admin/discounts`, requireControlPlane(PAYMENTS_DISCOUNT_CREATE_SCOPE), zValidator("json", DiscountCreateRequest, validationHook), async (c) => {
1959
+ app.post(`${base}/admin/discounts`, describeRoute({
1960
+ summary: "Mint a discount code at one store.",
1961
+ verification: "control-plane",
1962
+ scopes: [PAYMENTS_DISCOUNT_CREATE_SCOPE],
1963
+ responses: { 200: PaymentsDiscountResponse }
1964
+ }), requireControlPlane(PAYMENTS_DISCOUNT_CREATE_SCOPE), validate("json", DiscountCreateRequest), async (c) => {
1686
1965
  const input = c.req.valid("json");
1687
1966
  const provider = resolveRailProvider(input.rail, config, await credentials(c), trust);
1688
1967
  if (!isDiscountRail(provider)) throw new PaymentsRailNotConfiguredError({ detail: `The ${provider.rail} rail does not mint discounts.` });
@@ -1708,7 +1987,12 @@ function registerPaymentsRoutes(options) {
1708
1987
  rail: input.rail
1709
1988
  }, 200);
1710
1989
  });
1711
- app.post(`${base}/entitlements/grant`, requireControlPlane(PAYMENTS_ENTITLEMENT_GRANT_SCOPE), zValidator("json", EntitlementGrantRequest, validationHook), async (c) => {
1990
+ app.post(`${base}/entitlements/grant`, describeRoute({
1991
+ summary: "Grant an entitlement by hand.",
1992
+ verification: "control-plane",
1993
+ scopes: [PAYMENTS_ENTITLEMENT_GRANT_SCOPE],
1994
+ responses: { 200: PaymentsEntitlementResponse }
1995
+ }), requireControlPlane(PAYMENTS_ENTITLEMENT_GRANT_SCOPE), validate("json", EntitlementGrantRequest), async (c) => {
1712
1996
  const input = c.req.valid("json");
1713
1997
  const caller = controlPlaneCaller(c);
1714
1998
  if (input.subjectType !== config.billingSubject) throw new ValidationError({
@@ -1773,7 +2057,12 @@ function registerPaymentsRoutes(options) {
1773
2057
  * from a live customer and handing product out for free are different mistakes with different victims, and
1774
2058
  * an adopter's refund tooling has no business being able to make the second one.
1775
2059
  */
1776
- app.post(`${base}/entitlements/revoke`, requireControlPlane(PAYMENTS_ENTITLEMENT_REVOKE_SCOPE), zValidator("json", EntitlementRevokeRequest, validationHook), async (c) => {
2060
+ app.post(`${base}/entitlements/revoke`, describeRoute({
2061
+ summary: "Revoke an entitlement by hand.",
2062
+ verification: "control-plane",
2063
+ scopes: [PAYMENTS_ENTITLEMENT_REVOKE_SCOPE],
2064
+ responses: { 200: PaymentsEntitlementResponse }
2065
+ }), requireControlPlane(PAYMENTS_ENTITLEMENT_REVOKE_SCOPE), validate("json", EntitlementRevokeRequest), async (c) => {
1777
2066
  const input = c.req.valid("json");
1778
2067
  const caller = controlPlaneCaller(c);
1779
2068
  const revoked = await revokeEntitlement(database(c), {
@@ -1802,6 +2091,143 @@ function registerPaymentsRoutes(options) {
1802
2091
  expiresAt: revoked.expiresAt
1803
2092
  }) }, 200);
1804
2093
  });
2094
+ /**
2095
+ * The billing-kind check every override write shares, refused exactly as a grant refuses it. An override
2096
+ * keyed on a kind no read path resolves would shade nobody's numbers and answer 200.
2097
+ */
2098
+ function requireBilledKind(subjectType) {
2099
+ if (subjectType === config.billingSubject) return;
2100
+ throw new ValidationError({
2101
+ message: `This project bills ${config.billingSubject}s, not ${subjectType}s.`,
2102
+ action: "Send `subjectType` as the kind this project bills, or change `billingSubject` in pithy.config.ts.",
2103
+ 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.`
2104
+ });
2105
+ }
2106
+ /** What every override write answers. */
2107
+ function overrideResponse(subject, change) {
2108
+ return {
2109
+ ...subject,
2110
+ override: adminOverrideView(change.after),
2111
+ version: overrideVersion(change.after)
2112
+ };
2113
+ }
2114
+ /**
2115
+ * The audit event every override write emits — the subject, the mode, the before and the after, and the
2116
+ * reason verbatim. Severity `warning`, as a comp is: nothing else here changes what a customer may have
2117
+ * with no money moving.
2118
+ */
2119
+ async function emitOverride(c, action, subject, mode, reason, change) {
2120
+ const caller = controlPlaneCaller(c);
2121
+ await c.var.emit({
2122
+ action,
2123
+ outcome: "success",
2124
+ severity: "warning",
2125
+ actorType: "control-plane",
2126
+ actorId: caller.subject,
2127
+ resourceType: "entitlement_override",
2128
+ resourceId: encodeSubjectReference(subject),
2129
+ metadata: {
2130
+ connectionId: caller.connectionId,
2131
+ subjectType: subject.subjectType,
2132
+ subjectId: subject.subjectId,
2133
+ mode,
2134
+ reason,
2135
+ before: adminOverrideView(change.before),
2136
+ after: adminOverrideView(change.after)
2137
+ }
2138
+ });
2139
+ }
2140
+ /**
2141
+ * CONTROL PLANE. Pin a negotiated number or switch for one subject.
2142
+ *
2143
+ * **A merge by name, never a replace.** Only the names sent change; every other pin stands and every name
2144
+ * never pinned keeps tracking the plan, so an upgrade still reaches a customer whose email allowance was
2145
+ * negotiated. **Version-checked**: the body names the version it read, and a set behind the row is
2146
+ * `payments/override_stale` with nothing written. **Bounded**: a number past a declared `overrideMax` is a
2147
+ * 400 naming the limit. **Explained**: `reason` is required and the audit event carries it.
2148
+ *
2149
+ * It does not set `unrestricted`, and a body that tries is a 400 rather than a field quietly dropped:
2150
+ * that is the other route, behind its own scope.
2151
+ */
2152
+ app.post(`${base}/entitlements/overrides`, describeRoute({
2153
+ summary: "Pin quotas and features for one subject.",
2154
+ verification: "control-plane",
2155
+ scopes: [PAYMENTS_OVERRIDE_SET_SCOPE],
2156
+ responses: { 200: PaymentsOverrideResponse }
2157
+ }), requireControlPlane(PAYMENTS_OVERRIDE_SET_SCOPE), validate("json", OverrideSetRequest), async (c) => {
2158
+ const input = c.req.valid("json");
2159
+ requireBilledKind(input.subjectType);
2160
+ const subject = {
2161
+ subjectType: input.subjectType,
2162
+ subjectId: input.subjectId
2163
+ };
2164
+ const change = await setOverride(database(c), config, {
2165
+ subject,
2166
+ version: input.version,
2167
+ reason: input.reason,
2168
+ ...input.quotas ? { quotas: input.quotas } : {},
2169
+ ...input.features ? { features: input.features } : {}
2170
+ }, { now: clock() });
2171
+ await emitOverride(c, PaymentsAuditActions.overrideSet, subject, "patch", input.reason, change);
2172
+ return c.json(overrideResponse(subject, change), 200);
2173
+ });
2174
+ /**
2175
+ * CONTROL PLANE. Grant one subject the whole product, or take it back.
2176
+ *
2177
+ * **Its own route and its own scope**, because it is the largest grant the kit has and the only one whose
2178
+ * reach grows by itself as names are declared: a credential that may raise one email cap must not be able
2179
+ * to do this. Never bounded by `overrideMax` — being unbounded is the point. It grants no entitlement key:
2180
+ * a subject holding nothing is still refused at every gate.
2181
+ */
2182
+ app.post(`${base}/entitlements/overrides/unrestricted`, describeRoute({
2183
+ summary: "Turn unrestricted on or off for one subject.",
2184
+ verification: "control-plane",
2185
+ scopes: [PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE],
2186
+ responses: { 200: PaymentsOverrideResponse }
2187
+ }), requireControlPlane(PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE), validate("json", OverrideUnrestrictedRequest), async (c) => {
2188
+ const input = c.req.valid("json");
2189
+ requireBilledKind(input.subjectType);
2190
+ const subject = {
2191
+ subjectType: input.subjectType,
2192
+ subjectId: input.subjectId
2193
+ };
2194
+ const change = await setUnrestricted(database(c), {
2195
+ subject,
2196
+ version: input.version,
2197
+ reason: input.reason,
2198
+ unrestricted: input.unrestricted
2199
+ }, { now: clock() });
2200
+ await emitOverride(c, PaymentsAuditActions.overrideSet, subject, "unrestricted", input.reason, change);
2201
+ return c.json(overrideResponse(subject, change), 200);
2202
+ });
2203
+ /**
2204
+ * CONTROL PLANE. Unpin names for one subject, or clear its override.
2205
+ *
2206
+ * **Idempotent**: a subject with no override answers 200 with nothing changed — the state the caller asked
2207
+ * for — and writes no audit row, because nothing moved. A name unpinned resolves from the plan again.
2208
+ */
2209
+ app.post(`${base}/entitlements/overrides/clear`, describeRoute({
2210
+ summary: "Unpin allowances for one subject, or clear its override.",
2211
+ verification: "control-plane",
2212
+ scopes: [PAYMENTS_OVERRIDE_CLEAR_SCOPE],
2213
+ responses: { 200: PaymentsOverrideResponse }
2214
+ }), requireControlPlane(PAYMENTS_OVERRIDE_CLEAR_SCOPE), validate("json", OverrideClearRequest), async (c) => {
2215
+ const input = c.req.valid("json");
2216
+ requireBilledKind(input.subjectType);
2217
+ const subject = {
2218
+ subjectType: input.subjectType,
2219
+ subjectId: input.subjectId
2220
+ };
2221
+ const change = await clearOverride(database(c), {
2222
+ subject,
2223
+ ...input.version !== void 0 ? { version: input.version } : {},
2224
+ ...input.quotas ? { quotas: input.quotas } : {},
2225
+ ...input.features ? { features: input.features } : {},
2226
+ ...input.reason ? { reason: input.reason } : {}
2227
+ }, { now: clock() });
2228
+ if (change.before !== void 0) await emitOverride(c, PaymentsAuditActions.overrideCleared, subject, "clear", input.reason ?? null, change);
2229
+ return c.json(overrideResponse(subject, change), 200);
2230
+ });
1805
2231
  };
1806
2232
  /**
1807
2233
  * The webhook handler, once, for every rail.