@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
@@ -5,7 +5,9 @@ import { JsonDate } from "@pithy-sh/core/src/data/codecs";
5
5
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
6
6
  import { EntitlementKey } from "@pithy-sh/core/src/entitlement/entitlement";
7
7
  import { z } from "zod";
8
+ import { AllowanceName, QuotaValue } from "../config/allowances";
8
9
  import { DiscountCode, DiscountTerms } from "../data/discount";
10
+ import { isPaddleTransactionId } from "../data/paddleIds";
9
11
  import { PurchaseEnvironment } from "../data/purchase";
10
12
  import { PaymentsHostedRail, PaymentsRail } from "../data/rail";
11
13
  import { PurchaseStatus } from "../data/status";
@@ -170,7 +172,7 @@ export type CheckoutRequest = z.infer<typeof CheckoutRequest>;
170
172
  *
171
173
  * **No body at all on `keep`.** Withdrawing a scheduled cancellation takes no parameters: which
172
174
  * subscription is the server's answer, and there is nothing to say about it but *do not*. So that route
173
- * declares no schema and no `zValidator("json", …)`, exactly as `POST {base}/portal` does. A
175
+ * declares no schema and no `validate("json", …)`, exactly as `POST {base}/portal` does. A
174
176
  * `z.object({})` would read as a refusal of everything and be neither — Zod strips rather than refuses —
175
177
  * while making a POST with no body at all a 400 on a route that wants nothing.
176
178
  */
@@ -401,7 +403,7 @@ export const EntitlementGrantRequest = z
401
403
  "The subject to grant. Support acts on somebody else's holding, so this is one of the two routes where the subject is a request field rather than the server's own answer.",
402
404
  ),
403
405
  entitlement: EntitlementKey.describe(
404
- "The entitlement key to grant, as gating code names it. Not a store SKU. It must be one this project defines — a key some product grants, or one the adopter declared in `manualEntitlements` — and anything else is a 400 naming the key. Comping a key nothing sells is still the durable case; declaring it is how a project says so.",
406
+ "The entitlement key to grant, as gating code names it. Not a store SKU. It must be one the `entitlements` map declares, and anything else is a 400 naming the key. Comping a key nothing sells is still the durable case; declaring it with no product behind it is how a project says so.",
405
407
  ),
406
408
  expiresAt: JsonDate.optional().describe(
407
409
  "When the grant lapses, as an ISO 8601 timestamp. Omit for a comp that never ends. A past timestamp writes a row that grants nothing, which is a slower way of revoking.",
@@ -430,6 +432,124 @@ export const EntitlementRevokeRequest = z
430
432
  .describe("A control-plane request to revoke one entitlement from one subject, effective immediately.");
431
433
  export type EntitlementRevokeRequest = z.output<typeof EntitlementRevokeRequest>;
432
434
 
435
+ /**
436
+ * ## The override writes
437
+ *
438
+ * Three routes, three scopes, and the split is the security core of them. **Set** pins numbers and switches;
439
+ * **unrestricted** hands a subject the whole product; **clear** removes pins. A credential that may raise one
440
+ * customer's email cap must not, by that fact, be able to hand anybody everything — so `unrestricted` is not a
441
+ * field on the set, and every one of these is a `strictObject`: a set body carrying `unrestricted: true` is a
442
+ * 400, never a field quietly dropped while the caller believes it took.
443
+ *
444
+ * **Both halves of the subject, a version, and on a set a reason.** The version is the one the caller read;
445
+ * a write behind the row is refused as stale. The reason is required because an override is a sentence about a
446
+ * commercial decision, and the audit event records it verbatim.
447
+ *
448
+ * Whether a name is declared, and whether a number is under its ceiling, are config-backed questions and stay
449
+ * in the handler: a schema constrains a value, it never replaces a lookup. What the schema does refuse is the
450
+ * shape — a float, a negative, a string where a quota belongs — as `validation/invalid_input`.
451
+ */
452
+
453
+ /** The longest reason a write may carry. A sentence, a ticket number, a contract reference — not a document. */
454
+ const MAX_OVERRIDE_REASON_LENGTH = 500;
455
+
456
+ /** The most names one write may carry. Far past any real catalog; bounded because a verified client can still loop. */
457
+ const MAX_OVERRIDE_NAMES = 100;
458
+
459
+ const OverrideSubjectType = PaymentsSubject.shape.subjectType.describe(
460
+ "Which kind of holder the override is for. Named, never assumed — and refused when it is not the kind this project bills.",
461
+ );
462
+ const OverrideSubjectId = PaymentsSubject.shape.subjectId.describe("The subject whose allowances this shades.");
463
+ const OverrideVersion = z
464
+ .number()
465
+ .int()
466
+ .min(0)
467
+ .describe(
468
+ "The override version the caller read — `0` when the subject had none. A write naming a version behind the row is refused with `payments/override_stale` and changes nothing.",
469
+ );
470
+ const OverrideReason = z
471
+ .string()
472
+ .trim()
473
+ .min(1)
474
+ .max(MAX_OVERRIDE_REASON_LENGTH)
475
+ .describe("Why — a contract, a goodwill credit, a migration. Required, and recorded verbatim on the audit event.");
476
+
477
+ export const OverrideSetRequest = z
478
+ .strictObject({
479
+ subjectType: OverrideSubjectType,
480
+ subjectId: OverrideSubjectId,
481
+ version: OverrideVersion,
482
+ reason: OverrideReason,
483
+ quotas: z
484
+ .record(AllowanceName, QuotaValue)
485
+ .optional()
486
+ .describe(
487
+ "Quotas to pin, by name — a whole number from 0, or null for unlimited. Merged: a name absent here keeps whatever it had.",
488
+ ),
489
+ features: z
490
+ .record(AllowanceName, z.boolean().describe("Whether the switch is on."))
491
+ .optional()
492
+ .describe("Features to pin, by name. Merged: a name absent here keeps whatever it had."),
493
+ })
494
+ .refine((body) => Object.keys(body.quotas ?? {}).length + Object.keys(body.features ?? {}).length > 0, {
495
+ message: "Name at least one quota or feature to pin.",
496
+ })
497
+ .refine(
498
+ (body) => Object.keys(body.quotas ?? {}).length + Object.keys(body.features ?? {}).length <= MAX_OVERRIDE_NAMES,
499
+ {
500
+ message: `Pin at most ${MAX_OVERRIDE_NAMES} names in one write.`,
501
+ },
502
+ )
503
+ .describe(
504
+ "A control-plane request to pin quotas and features for one subject. A merge by name, version-checked, with a reason.",
505
+ );
506
+ export type OverrideSetRequest = z.output<typeof OverrideSetRequest>;
507
+
508
+ export const OverrideUnrestrictedRequest = z
509
+ .strictObject({
510
+ subjectType: OverrideSubjectType,
511
+ subjectId: OverrideSubjectId,
512
+ version: OverrideVersion,
513
+ reason: OverrideReason,
514
+ unrestricted: z
515
+ .boolean()
516
+ .describe(
517
+ "True grants every quota unlimited and every feature on, for every name declared now and later, except the names the override pins. False takes it back and leaves the pins.",
518
+ ),
519
+ })
520
+ .describe(
521
+ "A control-plane request to turn `unrestricted` on or off for one subject. Its own route, behind its own scope.",
522
+ );
523
+ export type OverrideUnrestrictedRequest = z.output<typeof OverrideUnrestrictedRequest>;
524
+
525
+ export const OverrideClearRequest = z
526
+ .strictObject({
527
+ subjectType: OverrideSubjectType,
528
+ subjectId: OverrideSubjectId,
529
+ version: OverrideVersion.optional().describe(
530
+ "The override version the caller read. Optional: sent, a clear behind the row is refused as stale; omitted, the clear is not checked, which is safe because a clear can only move a subject back toward its plan — unpinning a name on an unrestricted subject is refused.",
531
+ ),
532
+ reason: OverrideReason.optional().describe("Why, when the caller says. Recorded on the audit event."),
533
+ quotas: z
534
+ .array(AllowanceName)
535
+ .max(MAX_OVERRIDE_NAMES)
536
+ .optional()
537
+ .describe(
538
+ "Quota pins to remove. Each resolves from the plan again. Refused on an unrestricted subject, where it would resolve to unlimited.",
539
+ ),
540
+ features: z
541
+ .array(AllowanceName)
542
+ .max(MAX_OVERRIDE_NAMES)
543
+ .optional()
544
+ .describe(
545
+ "Feature pins to remove. Each resolves from the plan again. Refused on an unrestricted subject, where it would resolve to on.",
546
+ ),
547
+ })
548
+ .describe(
549
+ "A control-plane request to unpin names, or — naming neither list — to clear the subject's override entirely, `unrestricted` included. Idempotent: clearing nothing answers 200. A clear never resets the version.",
550
+ );
551
+ export type OverrideClearRequest = z.output<typeof OverrideClearRequest>;
552
+
433
553
  /**
434
554
  * ## The management read queries
435
555
  *
@@ -538,6 +658,20 @@ export const AdminEntitlementsQuery = z
538
658
  .describe("The entitlement query: what to narrow it to, and where to resume.");
539
659
  export type AdminEntitlementsQuery = z.output<typeof AdminEntitlementsQuery>;
540
660
 
661
+ export const AdminOverridesQuery = z
662
+ .object({
663
+ ...SUBJECT_FILTER,
664
+ unrestricted: z
665
+ .enum(["true", "false"])
666
+ .optional()
667
+ .describe("`true` lists only the subjects that are `unrestricted` — the largest grant the kit has."),
668
+ cursor: Cursor,
669
+ limit: Limit,
670
+ })
671
+ .refine(subjectFilterIsWhole, SUBJECT_FILTER_RULE)
672
+ .describe("The override listing query: a holder, whether unrestricted, and where to resume.");
673
+ export type AdminOverridesQuery = z.output<typeof AdminOverridesQuery>;
674
+
541
675
  export const AdminReconcileRunsQuery = z
542
676
  .object({
543
677
  rail: PaymentsRail.optional().describe(
@@ -552,6 +686,11 @@ export const AdminReconcileRunsQuery = z
552
686
  .describe("The reconciliation-run query: what to narrow it to, and where to resume.");
553
687
  export type AdminReconcileRunsQuery = z.output<typeof AdminReconcileRunsQuery>;
554
688
 
689
+ export const AdminUsageRunsQuery = z
690
+ .object({ cursor: Cursor, limit: Limit })
691
+ .describe("The usage-run query: where to resume, and how many.");
692
+ export type AdminUsageRunsQuery = z.output<typeof AdminUsageRunsQuery>;
693
+
555
694
  /**
556
695
  * The two path segments on the per-subject management read: `…/entitlements/:subjectType/:subjectId`.
557
696
  *
@@ -575,3 +714,33 @@ export const AdminSubjectParam = z
575
714
  })
576
715
  .describe("The `:subjectType/:subjectId` path segments on the per-subject management read.");
577
716
  export type AdminSubjectParam = z.output<typeof AdminSubjectParam>;
717
+
718
+ /**
719
+ * The transaction a Paddle payment link put in the URL — the `?transaction=` query on the resume read.
720
+ *
721
+ * **The id is the whole request, and it came from outside.** Paddle appends `?_ptxn=<transaction_id>` to a
722
+ * seller's Default payment link; the browser reads it and sends it here. So this is attacker-supplied text
723
+ * on an unauthenticated route, and the shape check is what makes it safe to echo back into a handoff a page
724
+ * will hand to `Paddle.Checkout.open`.
725
+ *
726
+ * **Checked against the rail's own primitive**, `isPaddleTransactionId`, rather than a regex written here:
727
+ * `rails/paddle/verify.ts` asks the same question of a submitted receipt, and two copies of one rule is the
728
+ * defect class this repository has paid for four times.
729
+ *
730
+ * **It names no holder, and that is structural rather than remembered.** The resume route takes no session
731
+ * and resolves no subject, so there is no field here for one — which `routeContract.test.ts`'s subject sweep
732
+ * asserts from the other side, by finding none.
733
+ */
734
+ export const PaddleResumeQuery = z
735
+ .object({
736
+ transaction: z
737
+ .string()
738
+ .refine(isPaddleTransactionId, {
739
+ message: "Not a Paddle transaction id. Expected the `txn_…` Paddle put in `_ptxn`.",
740
+ })
741
+ .describe(
742
+ "The Paddle transaction to resume — the `_ptxn` value, `txn_…`. Publishable: Paddle itself put it in a URL it mailed to the buyer.",
743
+ ),
744
+ })
745
+ .describe("The resume read's query: which transaction a Paddle payment link arrived for.");
746
+ export type PaddleResumeQuery = z.output<typeof PaddleResumeQuery>;
@@ -143,6 +143,35 @@ export const PAYMENTS_RECONCILE_READ_SCOPE: ControlPlaneScope = "payments:reconc
143
143
  */
144
144
  export const PAYMENTS_RECONCILE_RUN_SCOPE: ControlPlaneScope = "payments:reconcile:run";
145
145
 
146
+ /**
147
+ * Pin a number or a switch for one subject — a negotiated email allowance, a goodwill seat. A merge by name,
148
+ * version-checked, with a reason on the record and bounded by any `overrideMax` the catalog declares.
149
+ *
150
+ * **It does not confer `unrestricted`.** A credential that may raise one customer's email cap must not, by
151
+ * that fact, be able to hand anybody the entire product.
152
+ */
153
+ export const PAYMENTS_OVERRIDE_SET_SCOPE: ControlPlaneScope = "payments:overrides:set";
154
+
155
+ /**
156
+ * Turn `unrestricted` on or off for one subject: every quota unlimited and every feature on, for every name
157
+ * declared now and every name declared later. **The largest grant the kit has**, and the only one whose reach
158
+ * grows by itself, which is why it is its own scope and its own route — never a field on the set.
159
+ */
160
+ export const PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE: ControlPlaneScope = "payments:overrides:unrestricted";
161
+
162
+ /**
163
+ * Remove pins from one subject's override, or the whole override. Separate from setting, the way revoke is
164
+ * separate from grant: a tool that tidies up after a contract ends needs to clear and has no business
165
+ * pinning.
166
+ */
167
+ export const PAYMENTS_OVERRIDE_CLEAR_SCOPE: ControlPlaneScope = "payments:overrides:clear";
168
+
169
+ /**
170
+ * Read the usage-reporting run log — when each pass ran, what it reported, and which subjects it skipped and
171
+ * why. Its own scope, separate from the reconciliation log's: its findings name subjects.
172
+ */
173
+ export const PAYMENTS_USAGE_READ_SCOPE: ControlPlaneScope = "payments:usage:read";
174
+
146
175
  /**
147
176
  * Every control-plane scope payments defines — what `pithy dashboard connect` offers for this capability, and
148
177
  * the list a manifest or a doc quotes rather than re-typing. Core's `SEAM_SCOPES` is the same idea for the
@@ -158,8 +187,12 @@ export const PAYMENTS_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
158
187
  PAYMENTS_ENTITLEMENTS_READ_SCOPE,
159
188
  PAYMENTS_DISCOUNT_READ_SCOPE,
160
189
  PAYMENTS_RECONCILE_READ_SCOPE,
190
+ PAYMENTS_USAGE_READ_SCOPE,
161
191
  PAYMENTS_ENTITLEMENT_GRANT_SCOPE,
162
192
  PAYMENTS_ENTITLEMENT_REVOKE_SCOPE,
193
+ PAYMENTS_OVERRIDE_SET_SCOPE,
194
+ PAYMENTS_OVERRIDE_CLEAR_SCOPE,
195
+ PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE,
163
196
  PAYMENTS_DISCOUNT_CREATE_SCOPE,
164
197
  PAYMENTS_RECONCILE_RUN_SCOPE,
165
198
  ];
@@ -256,5 +289,40 @@ export function paymentsAdminRoutes(basePath: string): AdminRoute[] {
256
289
  scope: PAYMENTS_ENTITLEMENT_REVOKE_SCOPE,
257
290
  summary: "Take an entitlement back, effective immediately.",
258
291
  },
292
+ {
293
+ method: "GET",
294
+ path: `${basePath}/admin/usage-runs`,
295
+ scope: PAYMENTS_USAGE_READ_SCOPE,
296
+ summary:
297
+ "The usage-reporting passes this deployment has run — what each reported, and which subjects it skipped and why. The answer to why a quantity-billed customer was not billed.",
298
+ },
299
+ {
300
+ method: "GET",
301
+ path: `${basePath}/admin/overrides`,
302
+ scope: PAYMENTS_ENTITLEMENTS_READ_SCOPE,
303
+ summary:
304
+ "Page every subject's override — the numbers negotiated per customer, and which subjects are unrestricted.",
305
+ },
306
+ {
307
+ method: "POST",
308
+ path: `${basePath}/entitlements/overrides`,
309
+ scope: PAYMENTS_OVERRIDE_SET_SCOPE,
310
+ summary:
311
+ "Pin a negotiated number or switch for one subject, with a reason on the record. Merges by name; every other allowance keeps tracking the plan.",
312
+ },
313
+ {
314
+ method: "POST",
315
+ path: `${basePath}/entitlements/overrides/unrestricted`,
316
+ scope: PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE,
317
+ summary:
318
+ "Grant one subject the whole product — every quota unlimited and every feature on, including names declared later — or take it back.",
319
+ },
320
+ {
321
+ method: "POST",
322
+ path: `${basePath}/entitlements/overrides/clear`,
323
+ scope: PAYMENTS_OVERRIDE_CLEAR_SCOPE,
324
+ summary:
325
+ "Unpin allowances for one subject, or clear its override entirely. Unpinned names follow the plan again.",
326
+ },
259
327
  ];
260
328
  }
package/src/http/view.ts CHANGED
@@ -2,15 +2,21 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { PaymentsPurchaseRecord } from "../admin/read";
5
- import type { PaymentsConfig } from "../config/config";
5
+ import { compOnlyEntitlements, type PaymentsConfig } from "../config/config";
6
6
  import type { PaymentsEntitlement } from "../data/entitlement";
7
+ import { isEmptyOverride, type PaymentsOverride } from "../data/override";
7
8
  import type { PaymentsReconcileRun } from "../data/reconcileRun";
9
+ import type { PaymentsUsageRun } from "../data/usageRun";
10
+ import type { ResolvedAllowances } from "../entitlement/allowance";
8
11
  import type { PurchaseProjection } from "../projection/writer";
9
12
  import type {
13
+ PaymentsAdminAllowancesView,
10
14
  PaymentsAdminCatalogResponse,
11
15
  PaymentsAdminEntitlementView,
16
+ PaymentsAdminOverrideView,
12
17
  PaymentsAdminPurchaseView,
13
18
  PaymentsAdminReconcileRunView,
19
+ PaymentsAdminUsageRunView,
14
20
  PaymentsEntitlementView,
15
21
  PaymentsPurchaseView,
16
22
  } from "./responses";
@@ -109,16 +115,43 @@ export function adminCatalogView(config: PaymentsConfig): PaymentsAdminCatalogRe
109
115
  name: product.name,
110
116
  entitlements: [...product.entitlements],
111
117
  }));
112
- const manualEntitlements = [...config.manualEntitlements];
113
- if (products.length === 0 && manualEntitlements.length === 0) return { enabled: false };
118
+ const compOnly = compOnlyEntitlements(config);
119
+ const sold = new Set(products.flatMap((product) => product.entitlements));
120
+ const entitlements = Object.entries(config.entitlements).map(([key, declaration]) => ({
121
+ key,
122
+ name: declaration.name,
123
+ quotas: { ...declaration.quotas },
124
+ features: { ...declaration.features },
125
+ overrideMax: { ...(declaration.overrideMax ?? {}) },
126
+ sold: sold.has(key),
127
+ }));
128
+ if (products.length === 0 && entitlements.length === 0) return { enabled: false };
114
129
  // Catalog order, not sorted: the order an adopter wrote their products in is the order a list should
115
- // show them, exactly as the client projection argues.
116
- return { enabled: true, products, manualEntitlements };
130
+ // show them, exactly as the client projection argues. Declarations keep the order they were written in
131
+ // for the same reason.
132
+ return {
133
+ enabled: true,
134
+ products,
135
+ manualEntitlements: compOnly,
136
+ entitlements,
137
+ defaults:
138
+ config.defaults === undefined
139
+ ? null
140
+ : { quotas: { ...config.defaults.quotas }, features: { ...config.defaults.features } },
141
+ };
117
142
  }
118
143
 
119
144
  /** Project one purchase for a management client. The record's columns, verbatim, with dates as strings. */
120
- export function adminPurchaseView(purchase: PaymentsPurchaseRecord): PaymentsAdminPurchaseView {
145
+ export function adminPurchaseView(
146
+ purchase: PaymentsPurchaseRecord,
147
+ reported?: { quantity: number; reportedAt: Date } | null,
148
+ ): PaymentsAdminPurchaseView {
121
149
  return {
150
+ quantity: purchase.quantity ?? null,
151
+ // Only a subscription read has asked; the purchase log leaves both absent rather than claiming none.
152
+ ...(reported === undefined
153
+ ? {}
154
+ : { reportedQuantity: reported?.quantity ?? null, reportedAt: reported?.reportedAt.toISOString() ?? null }),
122
155
  id: purchase.id,
123
156
  subjectType: purchase.subjectType,
124
157
  subjectId: purchase.subjectId,
@@ -147,7 +180,11 @@ export function adminPurchaseView(purchase: PaymentsPurchaseRecord): PaymentsAdm
147
180
  * and the gate the adopter's own app calls applies the timestamp on every request. A dashboard that
148
181
  * rendered the flag would disagree with that gate, and the customer would believe the dashboard.
149
182
  */
150
- export function adminEntitlementView(row: PaymentsEntitlement, now: Date): PaymentsAdminEntitlementView {
183
+ export function adminEntitlementView(
184
+ row: PaymentsEntitlement,
185
+ now: Date,
186
+ unrestricted = false,
187
+ ): PaymentsAdminEntitlementView {
151
188
  const lapsed = row.expiresAt !== null && row.expiresAt.getTime() <= now.getTime();
152
189
  return {
153
190
  subjectType: row.subjectType,
@@ -157,6 +194,74 @@ export function adminEntitlementView(row: PaymentsEntitlement, now: Date): Payme
157
194
  expiresAt: row.expiresAt?.toISOString() ?? null,
158
195
  manual: row.manual,
159
196
  source: row.sourcePurchaseId,
197
+ unrestricted,
198
+ };
199
+ }
200
+
201
+ /** Project one usage run for a management client. The row's columns, dates as ISO strings. */
202
+ export function adminUsageRunView(run: PaymentsUsageRun): PaymentsAdminUsageRunView {
203
+ return {
204
+ id: run.id,
205
+ startedAt: run.startedAt.toISOString(),
206
+ finishedAt: run.finishedAt.toISOString(),
207
+ scanned: run.scanned,
208
+ reported: run.reported,
209
+ sampled: run.sampled,
210
+ alreadyReported: run.alreadyReported,
211
+ skipped: run.skipped,
212
+ invalid: run.invalid,
213
+ failed: run.failed,
214
+ findings: run.findings.map((finding) => ({ ...finding })),
215
+ };
216
+ }
217
+
218
+ /** Project one subject's override for a management client, or null when it has none. */
219
+ export function adminOverrideView(row: PaymentsOverride | undefined): PaymentsAdminOverrideView | null {
220
+ // A cleared row is kept only for its version — it overrides nothing, so it shows as no override.
221
+ return row === undefined || isEmptyOverride(row) ? null : overrideView(row);
222
+ }
223
+
224
+ /** Project one override row for a management client. */
225
+ export function overrideView(row: PaymentsOverride): PaymentsAdminOverrideView {
226
+ return {
227
+ version: row.version,
228
+ unrestricted: row.unrestricted,
229
+ quotas: { ...row.quotas },
230
+ features: { ...row.features },
231
+ reason: row.reason,
232
+ updatedAt: row.updatedAt.toISOString(),
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Project every declared allowance for one subject: effective, provenance and inherited per name, plus the
238
+ * ceiling an override of each quota is bounded by for this subject. What an override editor draws its rows
239
+ * from.
240
+ */
241
+ export function adminAllowancesView(
242
+ resolved: ResolvedAllowances,
243
+ ceiling: (name: string) => number | undefined,
244
+ ): PaymentsAdminAllowancesView {
245
+ return {
246
+ quotas: resolved.quotas.map((quota) => ({
247
+ name: quota.name,
248
+ effective: quota.effective.value,
249
+ source: quota.effective.source,
250
+ key: quota.effective.key,
251
+ inherited: quota.inherited.value,
252
+ inheritedSource: quota.inherited.source,
253
+ inheritedKey: quota.inherited.key,
254
+ overrideMax: ceiling(quota.name) ?? null,
255
+ })),
256
+ features: resolved.features.map((feature) => ({
257
+ name: feature.name,
258
+ effective: feature.effective.value,
259
+ source: feature.effective.source,
260
+ key: feature.effective.key,
261
+ inherited: feature.inherited.value,
262
+ inheritedSource: feature.inherited.source,
263
+ inheritedKey: feature.inherited.key,
264
+ })),
160
265
  };
161
266
  }
162
267
 
@@ -18,6 +18,7 @@ import { PaymentsWebhookUnverifiedError } from "../error/errors";
18
18
  import type { VerifiedNotification } from "../rails/contract";
19
19
  import { type RailTrustOptions, resolveRailProvider } from "../rails/providers";
20
20
  import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/registry";
21
+ import type { PaymentsWebhookAck } from "./responses";
21
22
 
22
23
  /**
23
24
  * The `signed-webhook` gate — the repo's first, and the shape the Google and Stripe webhooks will reuse.
@@ -32,7 +33,7 @@ import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/reg
32
33
  * it.
33
34
  *
34
35
  * `c.req.text()` rather than `c.req.raw.text()`, and that distinction matters. Hono caches its own body reads,
35
- * so the route's `zValidator("json", …)` afterwards is served from the same cache and sees identical bytes.
36
+ * so the route's `validate("json", …)` afterwards is served from the same cache and sees identical bytes.
36
37
  * Reading `c.req.raw` directly would consume the stream and leave the validator with nothing.
37
38
  *
38
39
  * ## Why it persists before it hands off
@@ -291,7 +292,7 @@ export function requireSignedWebhook(
291
292
  // been projected, and short-circuiting them made a redelivery — and a manual replay, which reuses the
292
293
  // provider's event id — the one thing that could never repair them.
293
294
  if (isWebhookEventFinished(webhookEventState(stored))) {
294
- return c.json({ received: true, duplicate: true }, 200);
295
+ return c.json({ received: true, duplicate: true } satisfies PaymentsWebhookAck, 200);
295
296
  }
296
297
 
297
298
  verified.set(c.req.raw, { rail, notification, eventRowId: stored.id });
package/src/index.ts CHANGED
@@ -30,8 +30,20 @@ export {
30
30
  payments,
31
31
  } from "./capability";
32
32
  export {
33
+ AllowanceName,
34
+ declaredFeatureNames,
35
+ declaredQuotaNames,
36
+ PaymentsAllowanceDefaults,
37
+ PaymentsEntitlementDeclaration,
38
+ type PaymentsEntitlementDeclarationInput,
39
+ QuotaValue,
40
+ } from "./config/allowances";
41
+ export {
42
+ compOnlyEntitlements,
33
43
  entitlementsForProduct,
34
44
  grantableEntitlements,
45
+ KIT_METERS,
46
+ type KitMeter,
35
47
  PaymentsAppleProduct,
36
48
  type PaymentsCatalogEntry,
37
49
  PaymentsConfig,
@@ -41,6 +53,7 @@ export {
41
53
  PaymentsLedgerGrant,
42
54
  PaymentsLemonSqueezyProduct,
43
55
  PaymentsLemonSqueezySettings,
56
+ PaymentsMeters,
44
57
  PaymentsPaddleProduct,
45
58
  PaymentsPaddleSettings,
46
59
  type PaymentsPaddleSettingsInput,
@@ -49,12 +62,17 @@ export {
49
62
  PaymentsProductType,
50
63
  PaymentsRailToggles,
51
64
  type PaymentsRailTogglesInput,
65
+ PaymentsReportCadence,
66
+ PaymentsReportedBilling,
52
67
  PaymentsStripeProduct,
53
68
  PaymentsStripeSettings,
54
69
  type PaymentsStripeSettingsInput,
55
70
  productForProviderSku,
56
71
  providerProductId,
72
+ REPORTED_BILLING_RAILS,
57
73
  railEnabled,
74
+ reportedBillingProblems,
75
+ reportedProducts,
58
76
  resolveProduct,
59
77
  } from "./config/config";
60
78
  export { PaymentsEntitlement } from "./data/entitlement";