@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
@@ -4,8 +4,15 @@
4
4
  import { EntitlementKey } from "@pithy-sh/core/src/entitlement/entitlement";
5
5
  import { SIGNED_WEBHOOK_MAX_TOLERANCE_SECONDS } from "@pithy-sh/core/src/http/webhookWindow";
6
6
  import { z } from "zod";
7
- import { PAYMENTS_RAILS, type PaymentsRail } from "../data/rail";
7
+ import { PAYMENTS_RAILS, PaymentsRail } from "../data/rail";
8
8
  import { PaymentsSubjectType } from "../data/subject";
9
+ import {
10
+ type DeclarationProblem,
11
+ declarationProblems,
12
+ declaredQuotaNames,
13
+ PaymentsAllowanceDefaults,
14
+ PaymentsEntitlementDeclaration,
15
+ } from "./allowances";
9
16
 
10
17
  /**
11
18
  * The payments capability's config — the catalog, and the thin surface an adopter owns in
@@ -250,6 +257,92 @@ export const PaymentsGrants = z
250
257
  .describe("What a purchase fulfills beyond its entitlements. Absent for the products that only unlock a feature.");
251
258
  export type PaymentsGrants = z.infer<typeof PaymentsGrants>;
252
259
 
260
+ /**
261
+ * The rails a reported quantity can be billed on. Stripe takes a meter event; Paddle takes a one-time charge
262
+ * against the subscription. **Apple and Google cannot**: in-app purchase has no concept of a seat, so a
263
+ * quantity-billed product is web-rails-only and says so at boot.
264
+ *
265
+ * **Lemon Squeezy is deferred, with the reason recorded on pithy-sh/pithy#561.** Its usage records are
266
+ * written against a subscription *item*, which the projection does not store, so the same call shape does
267
+ * not fit without a new column and a refresh of every Lemon Squeezy subscription. Named here so the refusal
268
+ * can say so, rather than reading as an oversight.
269
+ */
270
+ export const REPORTED_BILLING_RAILS = ["stripe", "paddle"] as const satisfies readonly PaymentsRail[];
271
+
272
+ /** How often a reported quantity goes to the store. */
273
+ export const PaymentsReportCadence = z
274
+ .enum(["period-end", "daily-peak"])
275
+ .describe(
276
+ "How often the count is reported. `period-end` sends one count per subscription per billing period — simplest, and what a store's metering expects to be fed. `daily-peak` samples every run and keeps each day's high-water mark, then sends the period's highest day once, in its last day — the period's peak, never the sum of its days. The day rows stay as the audit a customer disputing an invoice can check.",
277
+ );
278
+ export type PaymentsReportCadence = z.infer<typeof PaymentsReportCadence>;
279
+
280
+ export const PaymentsReportedBilling = z
281
+ .strictObject({
282
+ kind: z
283
+ .literal("reported")
284
+ .describe(
285
+ "The quantity is reported by payments, from a count the adopter's `resolveQuantity` computes. The only kind there is.",
286
+ ),
287
+ unit: z
288
+ .string()
289
+ .min(1)
290
+ .max(MAX_NAME_LENGTH)
291
+ .describe("What one unit is — `student`, `coach`, `seat`. For people reading the catalog and the run log."),
292
+ cadence: PaymentsReportCadence.default("period-end").describe(
293
+ "How often the count is reported. Defaults to `period-end`. Per product, because a project can sell two things metered differently.",
294
+ ),
295
+ min: z
296
+ .number()
297
+ .int()
298
+ .min(0)
299
+ .default(0)
300
+ .describe(
301
+ "The smallest count that may be reported. A resolver answering below it is skipped and logged — never clamped, because a clamped value is a wrong number billed silently.",
302
+ ),
303
+ max: z
304
+ .number()
305
+ .int()
306
+ .positive()
307
+ .describe(
308
+ "The largest count that may be reported. A resolver answering above it is skipped and logged — never clamped. A value that becomes money is bounded by somebody who meant it.",
309
+ ),
310
+ rails: z
311
+ .array(PaymentsRail)
312
+ .min(1)
313
+ .describe(
314
+ "Which rails report this product's count. Stripe and Paddle only — in-app purchase has no seats, and Lemon Squeezy is deferred.",
315
+ ),
316
+ stripe: z
317
+ .strictObject({
318
+ meterEventName: z
319
+ .string()
320
+ .min(1)
321
+ .max(100)
322
+ .describe(
323
+ "The `event_name` of the Stripe Billing Meter this product's metered price reads — what each report is sent as.",
324
+ ),
325
+ })
326
+ .optional()
327
+ .describe("How Stripe hears the count: the meter it is reported to. Required when `rails` lists stripe."),
328
+ paddle: z
329
+ .strictObject({
330
+ priceId: z
331
+ .string()
332
+ .min(1)
333
+ .max(MAX_SKU_LENGTH)
334
+ .describe(
335
+ "The one-time Paddle price charged per unit — `pri_01…`. Each report is a one-time charge of this price, at the reported quantity, on the subscription's next bill.",
336
+ ),
337
+ })
338
+ .optional()
339
+ .describe("How Paddle hears the count: the one-time price it is charged at. Required when `rails` lists paddle."),
340
+ })
341
+ .describe(
342
+ "Bill by a count the adopter's code owns. Payments asks `resolveQuantity` and reports the answer to the store; it never counts anybody's members itself, and never reports a number a kit meter counted.",
343
+ );
344
+ export type PaymentsReportedBilling = z.output<typeof PaymentsReportedBilling>;
345
+
253
346
  export const PaymentsProduct = z
254
347
  .object({
255
348
  type: PaymentsProductType.describe("What kind of product this is. Decides how a renewal and a restore behave."),
@@ -264,7 +357,7 @@ export const PaymentsProduct = z
264
357
  .array(EntitlementKey)
265
358
  .default([])
266
359
  .describe(
267
- "The entitlement keys this product grants. Many products across many rails may grant one key, which is the whole point — gating code names the key, never this product. Empty for a product that only credits a balance.",
360
+ "The entitlement keys this product grants — mentioned here, declared in the top-level `entitlements` map. Many products across many rails may grant one key, which is the whole point — gating code names the key, never this product. Every key must be declared. Empty for a product that only credits a balance.",
268
361
  ),
269
362
  apple: PaymentsAppleProduct.optional().describe("The Apple listing, if this product ships on the App Store."),
270
363
  google: PaymentsGoogleProduct.optional().describe("The Google listing, if this product ships on Google Play."),
@@ -276,6 +369,9 @@ export const PaymentsProduct = z
276
369
  grants: PaymentsGrants.optional().describe(
277
370
  "What this purchase fulfills beyond its entitlements. Opt-in per product; a subscription's grant fires once per billing period, since each renewal is a distinct provider transaction.",
278
371
  ),
372
+ billing: PaymentsReportedBilling.optional().describe(
373
+ "Bill this subscription by a reported quantity — students, coaches, seats — rather than a flat price. Requires `resolveQuantity` on `payments(...)`. Omit for a flat-priced product.",
374
+ ),
279
375
  clawback: z
280
376
  .boolean()
281
377
  .default(false)
@@ -286,6 +382,42 @@ export const PaymentsProduct = z
286
382
  .describe("One logical catalog product — what it is, what it grants, and how each store lists it.");
287
383
  export type PaymentsProduct = z.infer<typeof PaymentsProduct>;
288
384
 
385
+ /**
386
+ * The meters the kit counts itself, because the kit writes the rows they count. Everything the kit cannot
387
+ * see — seats, students, projects — is the adopter's count, read through `quota()`. Payments never counts
388
+ * members. Forever.
389
+ */
390
+ export const KIT_METERS = ["emails", "storageBytes", "mediaItems"] as const;
391
+ export type KitMeter = (typeof KIT_METERS)[number];
392
+
393
+ const MeterPolicy = z
394
+ .strictObject({
395
+ enforce: z
396
+ .boolean()
397
+ .default(false)
398
+ .describe(
399
+ "Whether the quota of the same name binds. Off by default: declaring a quota makes it readable, and turning this on makes it refuse. Two steps, because the first is a pricing decision and the second is a production one.",
400
+ ),
401
+ })
402
+ .describe("Whether one kit meter is enforced.");
403
+
404
+ export const PaymentsMeters = z
405
+ .strictObject({
406
+ emails: MeterPolicy.optional().describe(
407
+ "Emails enqueued through `@pithy-sh/email` for a subject, per billing period. Enforced at enqueue: past the quota the enqueue throws `payments/quota_exceeded` and writes no job.",
408
+ ),
409
+ storageBytes: MeterPolicy.optional().describe(
410
+ "Bytes the billing subject holds in `@pithy-sh/storage`: a user's own, or under organization billing every member's bytes stored for the organization. Enforced, the quota replaces the configured `bytesPerOwner` as the ceiling, and a write past it throws `payments/quota_exceeded`.",
411
+ ),
412
+ mediaItems: MeterPolicy.optional().describe(
413
+ "Media items the billing subject holds in `@pithy-sh/media`: a user's own, or under organization billing every member's records for the organization. Enforced at create: past the quota the create throws `payments/quota_exceeded`.",
414
+ ),
415
+ })
416
+ .describe(
417
+ "Which kit meters enforce their quota. Every meter is advisory until named here with `enforce: true`, because a cap that arrives by surprise breaks an adopter already over it. A meter refuses at its limit and never bills.",
418
+ );
419
+ export type PaymentsMeters = z.output<typeof PaymentsMeters>;
420
+
289
421
  export const PaymentsConfig = z
290
422
  .object({
291
423
  billingSubject: PaymentsSubjectType.describe(
@@ -304,11 +436,26 @@ export const PaymentsConfig = z
304
436
  .describe(
305
437
  "The catalog, keyed by logical product id — the id that lands in every purchase row. Keys are yours and outlive any store's SKU, so renaming a SKU in a console never rewrites history.",
306
438
  ),
439
+ entitlements: z
440
+ .record(EntitlementKey, PaymentsEntitlementDeclaration)
441
+ .default({})
442
+ .describe(
443
+ "What each entitlement key means — its display name, its numbered `quotas`, its `features` — declared once, however many products sell it. A key a product mentions must be declared here. A key declared here and sold by no product is comp-only: the control plane may grant it and no checkout sells it.",
444
+ ),
445
+ defaults: PaymentsAllowanceDefaults.optional().describe(
446
+ "The free floor: the quotas and features a caller holding no key gets. Optional. Without it an unentitled caller gets 0 of every quota and no feature, which is fail-closed and correct.",
447
+ ),
448
+ meters: PaymentsMeters.default({}).describe(
449
+ "Which kit meters — `emails`, `storageBytes`, `mediaItems` — enforce the quota of the same name. All advisory until named.",
450
+ ),
307
451
  manualEntitlements: z
308
- .array(EntitlementKey)
309
- .default([])
452
+ .never({
453
+ error:
454
+ "`manualEntitlements` is gone. Declare each comp-only key in the top-level `entitlements` map instead — a key declared there and sold by no product is grantable by hand.",
455
+ })
456
+ .optional()
310
457
  .describe(
311
- "Entitlement keys the control plane may grant that no product sells — a beta flag, an internal tier, a key that exists only to be comped. Declared, because the alternative to declaring is not checking: with this empty, a grant of any key outside the catalog is refused, which is what turns `pr` for `pro` into a 400 instead of a row nobody notices. Only grants are constrained; a revoke of a key the catalog has since dropped stays legal, or a catalog edit would be irreversible for everyone still holding it.",
458
+ "Removed. Declare each comp-only key in `entitlements` instead: a declared key no product sells is what this field used to mean. Refused rather than ignored, because ignoring it would drop a comp-only key and nobody would see it.",
312
459
  ),
313
460
  stripe: PaymentsStripeSettings.optional().describe(
314
461
  "Where Stripe's hosted Checkout and Billing Portal return the browser. Required when the Stripe rail is on — the two routes cannot create a session without them.",
@@ -401,6 +548,43 @@ export const PaymentsConfig = z
401
548
  });
402
549
  }
403
550
 
551
+ // A key is declared once and mentioned by products. A mention with no declaration is a key whose
552
+ // quotas, features and name exist nowhere, and a comp of it would be refused while a checkout sold it.
553
+ for (const [id, product] of entries) {
554
+ for (const key of product.entitlements) {
555
+ if (key in config.entitlements) continue;
556
+ ctx.issues.push({
557
+ code: "custom",
558
+ input: ctx.value,
559
+ path: ["products", id, "entitlements"],
560
+ message: `Product "${id}" grants "${key}", which \`entitlements\` does not declare. Declare it — \`entitlements: { ${key}: { name: "…" } }\` — or correct the product.`,
561
+ });
562
+ }
563
+ }
564
+
565
+ for (const problem of declarationProblems(config)) {
566
+ ctx.issues.push({ code: "custom", input: ctx.value, path: problem.path, message: problem.message });
567
+ }
568
+
569
+ // An enforced meter with no quota of its name would resolve every subject to the hard floor of zero and
570
+ // refuse every send. That is fail-closed and it is also an outage, caught here rather than in production.
571
+ const quotaNames = new Set(declaredQuotaNames(config));
572
+ for (const meter of KIT_METERS) {
573
+ if (config.meters[meter]?.enforce !== true || quotaNames.has(meter)) continue;
574
+ ctx.issues.push({
575
+ code: "custom",
576
+ input: ctx.value,
577
+ path: ["meters", meter],
578
+ message: `The ${meter} meter is enforced, and no quota named "${meter}" is declared. Declare one on an entitlement or in \`defaults\`, or leave the meter advisory — enforced with nothing declared, it would refuse everyone.`,
579
+ });
580
+ }
581
+
582
+ for (const [id, product] of entries) {
583
+ for (const problem of reportedBillingProblems(id, product, config)) {
584
+ ctx.issues.push({ code: "custom", input: ctx.value, path: problem.path, message: problem.message });
585
+ }
586
+ }
587
+
404
588
  for (const [id, product] of entries) {
405
589
  // A SKU for a rail the project turned off can never be bought, and the webhook that would carry it
406
590
  // is refused. Silently ignoring the block would leave a catalog that reads as selling something it
@@ -521,6 +705,81 @@ export function providerProductId(product: PaymentsProduct, rail: PaymentsRail):
521
705
  }
522
706
  }
523
707
 
708
+ /**
709
+ * What is wrong with one product's reported billing, as sentences naming the product — empty for a product
710
+ * that has none, or one that is sound.
711
+ *
712
+ * Every refusal here is at boot, because a reported product that cannot be reported is a subscription that
713
+ * bills nothing for a quantity the customer is using — invisible until somebody reads an invoice.
714
+ */
715
+ export function reportedBillingProblems(
716
+ id: string,
717
+ product: PaymentsProduct,
718
+ config: Pick<PaymentsConfig, "rails">,
719
+ ): DeclarationProblem[] {
720
+ const billing = product.billing;
721
+ if (billing === undefined) return [];
722
+ const problems: DeclarationProblem[] = [];
723
+ const at = (...rest: (string | number)[]) => ["products", id, "billing", ...rest];
724
+
725
+ if (product.type !== "subscription") {
726
+ problems.push({
727
+ path: at(),
728
+ message: `Product "${id}" reports a quantity and is a ${product.type}. A reported quantity is billed per period, so only a subscription can carry one.`,
729
+ });
730
+ }
731
+ if (billing.min > billing.max) {
732
+ problems.push({
733
+ path: at("min"),
734
+ message: `Product "${id}" reports between ${billing.min} and ${billing.max}. The minimum must not exceed the maximum.`,
735
+ });
736
+ }
737
+ for (const rail of billing.rails) {
738
+ if (rail === "apple" || rail === "google") {
739
+ problems.push({
740
+ path: at("rails"),
741
+ message: `Product "${id}" reports its quantity on ${rail}. In-app purchase has no concept of a seat, so a quantity-billed product sells on the web rails only. Remove ${rail} from \`billing.rails\`.`,
742
+ });
743
+ continue;
744
+ }
745
+ if (rail === "lemonSqueezy") {
746
+ problems.push({
747
+ path: at("rails"),
748
+ message: `Product "${id}" reports its quantity on lemonSqueezy, which payments does not report to yet: its usage records are written against a subscription item the projection does not store. Report on stripe or paddle.`,
749
+ });
750
+ continue;
751
+ }
752
+ if (!config.rails[rail] || product[rail] === undefined) {
753
+ problems.push({
754
+ path: at("rails"),
755
+ message: `Product "${id}" reports its quantity on ${rail}, and is not sold there. Enable \`rails.${rail}\` and give the product a \`${rail}\` block, or remove ${rail} from \`billing.rails\`.`,
756
+ });
757
+ }
758
+ }
759
+ if (billing.rails.includes("stripe") && billing.stripe === undefined) {
760
+ problems.push({
761
+ path: at("stripe"),
762
+ message: `Product "${id}" reports its quantity on stripe and names no meter. Set \`billing.stripe.meterEventName\` to the event name of the meter its price reads.`,
763
+ });
764
+ }
765
+ if (billing.rails.includes("paddle") && billing.paddle === undefined) {
766
+ problems.push({
767
+ path: at("paddle"),
768
+ message: `Product "${id}" reports its quantity on paddle and names no price to charge it at. Set \`billing.paddle.priceId\` to a one-time price.`,
769
+ });
770
+ }
771
+ return problems;
772
+ }
773
+
774
+ /** Every product billed by a reported quantity, with its id. */
775
+ export function reportedProducts(
776
+ config: PaymentsConfig,
777
+ ): (PaymentsCatalogEntry & { billing: PaymentsReportedBilling })[] {
778
+ return Object.entries(config.products).flatMap(([id, product]) =>
779
+ product.billing === undefined ? [] : [{ id, product, billing: product.billing }],
780
+ );
781
+ }
782
+
524
783
  /** The product with this logical id, or undefined. Ids come from config, so an unknown one is a 404. */
525
784
  export function resolveProduct(config: PaymentsConfig, id: string): PaymentsCatalogEntry | undefined {
526
785
  const product = config.products[id];
@@ -545,20 +804,29 @@ export function productForProviderSku(
545
804
  }
546
805
 
547
806
  /**
548
- * Every entitlement key this project defines — what the catalog's products grant, plus what the adopter
549
- * declared grantable with no sale behind it.
807
+ * Every entitlement key this project defines — the keys `entitlements` declares. Every key a product
808
+ * mentions is among them, because the config refuses a mention with no declaration.
550
809
  *
551
- * The set a manual grant is checked against, and the set the control-plane catalog read publishes the first
552
- * half of. Computed once per composition: the catalog is config, so it cannot change under a running Worker.
810
+ * The set a manual grant is checked against, and the set the control-plane catalog read publishes.
811
+ * Computed once per composition: the catalog is config, so it cannot change under a running Worker.
553
812
  *
554
- * **Empty is a real answer.** A project composing payments with nothing to sell and nothing declared defines
555
- * no keys, and every grant against it is refused — which is correct, because there is no vocabulary to grant
556
- * in. It is the same statement `clientProjection` makes as `{ enabled: false }`.
813
+ * **Empty is a real answer.** A project composing payments with nothing declared defines no keys, and every
814
+ * grant against it is refused — which is correct, because there is no vocabulary to grant in. It is the same
815
+ * statement `clientProjection` makes as `{ enabled: false }`.
557
816
  */
558
817
  export function grantableEntitlements(config: PaymentsConfig): ReadonlySet<string> {
559
- const keys = new Set<string>(config.manualEntitlements);
560
- for (const product of Object.values(config.products)) for (const key of product.entitlements) keys.add(key);
561
- return keys;
818
+ return new Set<string>(Object.keys(config.entitlements));
819
+ }
820
+
821
+ /**
822
+ * The declared keys no product sells — comp-only. Granted by hand through the control plane, sold by no
823
+ * checkout. What `manualEntitlements` used to list, said by the shape of the config rather than by a
824
+ * second list that could disagree with the first.
825
+ */
826
+ export function compOnlyEntitlements(config: PaymentsConfig): string[] {
827
+ const sold = new Set<string>();
828
+ for (const product of Object.values(config.products)) for (const key of product.entitlements) sold.add(key);
829
+ return Object.keys(config.entitlements).filter((key) => !sold.has(key));
562
830
  }
563
831
 
564
832
  /** The entitlement keys a product grants, or an empty list for an unknown product or one that grants none. */
@@ -0,0 +1,38 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ import { z } from "zod";
6
+ import { PaymentsSubject } from "./subject";
7
+
8
+ /**
9
+ * How much of one meter one subject used in one period — the row in `pithy_payments_meter_counters`, keyed
10
+ * `UNIQUE (subjectType, subjectId, meter, periodStart)`.
11
+ *
12
+ * **A counter, not a scan.** Counting a period's emails by reading the jobs table would be a range scan on
13
+ * every send, and it would count rows the email capability prunes. One row per period, incremented in the
14
+ * same statement that checks the limit, is both cheaper and the only shape a concurrent burst cannot walk
15
+ * past.
16
+ *
17
+ * **A new period starts at zero with nothing to reset it.** The period's start is half the key, so the first
18
+ * charge of a new period lands on a row that does not exist yet. There is no cron, no sweep, no reset job.
19
+ *
20
+ * **It refuses and never bills.** Nothing reads this table to report usage to a store: the kit does not sell
21
+ * overage, and a meter joined to a bill would make every counter a money path.
22
+ */
23
+ export const PaymentsMeterCounter = z
24
+ .object({
25
+ id: z.string().describe("The row's UUID."),
26
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
27
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject whose usage this counts."),
28
+ meter: z.string().describe("The meter counted — `emails`."),
29
+ periodStart: SQLiteDate.describe(
30
+ "When the period this row counts began: the subscription's billing period where payments knows one, the calendar month (UTC) where it does not.",
31
+ ),
32
+ used: z.number().int().nonnegative().describe("How many were charged against the meter in this period."),
33
+ createdAt: SQLiteDate.describe("When the period's first charge landed."),
34
+ updatedAt: SQLiteDate.describe("When the period's last charge landed."),
35
+ })
36
+ .describe("One subject's usage of one meter in one period — the row in `pithy_payments_meter_counters`.");
37
+ export type PaymentsMeterCounter = z.output<typeof PaymentsMeterCounter>;
38
+ export type PaymentsMeterCounterRow = z.input<typeof PaymentsMeterCounter>;
@@ -0,0 +1,74 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { SQLiteBoolean, SQLiteDate, sqliteJson } from "@pithy-sh/core/src/data/codecs";
5
+ import { z } from "zod";
6
+ import { FeatureMap, QuotaMap } from "../config/allowances";
7
+ import { PaymentsSubject } from "./subject";
8
+
9
+ /**
10
+ * One subject's allowance override — the row in `pithy_payments_overrides`, keyed `UNIQUE (subjectType,
11
+ * subjectId)`.
12
+ *
13
+ * **Keyed on the subject, never on an entitlement key.** An override survives a tier change, which is the
14
+ * whole point: a negotiated email allowance must still stand the day the customer upgrades. Keyed on a key,
15
+ * it would die with the old key at the worst possible moment. Its own table, too, so the entitlement
16
+ * projection never has to preserve a column it does not own.
17
+ *
18
+ * **It grants no key.** A subject with an override and no entitlement is still refused at every gate; the
19
+ * override only shades the numbers the subject's keys resolve to. It composes with a `manual` grant rather
20
+ * than replacing one: a comped `enterprise` key and a pinned email number are two rows in two tables.
21
+ *
22
+ * **Sparse.** `quotas` and `features` carry only what was negotiated, and every name they omit keeps
23
+ * tracking the plan. A full replacement would freeze every other allowance at the day it was written, and an
24
+ * upgrade would silently do nothing for this customer until somebody rewrote it by hand.
25
+ *
26
+ * **`unrestricted` is a mode, not a list** — unlimited and on for every name, including names declared after
27
+ * the row was written. An enumeration of today's names would quietly stop covering an enterprise contract the
28
+ * first release a name was added.
29
+ *
30
+ * **`version` is what makes a write safe for two operators.** The read carries it, a set must send it back,
31
+ * and a set naming a version behind this row's is refused rather than applied, so one operator's stale pane
32
+ * cannot silently overwrite another's pin.
33
+ *
34
+ * **So a version never repeats, and a cleared row is kept, empty.** Deleting it would put the subject back at
35
+ * version 0, the next set would write version 1 again, and a pane still holding the deleted row's 1 would pass
36
+ * the check and overwrite a newer pin. An empty row — not unrestricted, nothing pinned — is no override to
37
+ * every read ({@link isEmptyOverride}); it only remembers the version.
38
+ */
39
+ export const PaymentsOverride = z
40
+ .object({
41
+ id: z.string().describe("The row's UUID."),
42
+ subjectType: PaymentsSubject.shape.subjectType.describe(
43
+ "Whether `subjectId` names a user or an organization. Half the key — the id alone is ambiguous.",
44
+ ),
45
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject whose allowances this shades."),
46
+ unrestricted: SQLiteBoolean.describe(
47
+ "Whether every quota is unlimited and every feature on, for every name present and future, except the names `quotas` and `features` pin.",
48
+ ),
49
+ quotas: sqliteJson(QuotaMap).describe(
50
+ "Pinned quotas by name — a whole number from 0, or null for unlimited. A name absent here resolves normally.",
51
+ ),
52
+ features: sqliteJson(FeatureMap).describe("Pinned features by name. A name absent here resolves normally."),
53
+ version: z
54
+ .number()
55
+ .int()
56
+ .positive()
57
+ .describe("Advances on every write. A set must name the version it read, or it is refused as stale."),
58
+ reason: z
59
+ .string()
60
+ .describe("Why the last write was made — a contract, a goodwill credit, a migration. Required on every set."),
61
+ createdAt: SQLiteDate.describe("When this subject was first given an override."),
62
+ updatedAt: SQLiteDate.describe("When the override last changed."),
63
+ })
64
+ .describe("One subject's allowance override — the row in `pithy_payments_overrides`.");
65
+ export type PaymentsOverride = z.output<typeof PaymentsOverride>;
66
+ export type PaymentsOverrideRow = z.input<typeof PaymentsOverride>;
67
+
68
+ /**
69
+ * Whether a row overrides nothing: not unrestricted, and no name pinned. What a clear leaves behind — the row
70
+ * is kept so its version never repeats — and what every read treats as no override at all.
71
+ */
72
+ export function isEmptyOverride(row: PaymentsOverride): boolean {
73
+ return !row.unrestricted && Object.keys(row.quotas).length === 0 && Object.keys(row.features).length === 0;
74
+ }
@@ -0,0 +1,74 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * What a Paddle id looks like, in one place per kind of id.
6
+ *
7
+ * **Extracted because the rule had five producers and no two of them agreed.** `rails/paddle/verify.ts`
8
+ * held the transaction pattern as a module-private const, checking a receipt before spending a round trip
9
+ * on it; the `_ptxn` reader in `../client/paddleLink.ts` needs the same question answered about a value out
10
+ * of a query string (#680). Then `refund.ts`, `refresh.ts` and `subscription.ts` each answered it again
11
+ * with `startsWith`, which accepts the bare prefix and an alphabet Paddle does not issue — so one string
12
+ * was a transaction in `refund.ts` and not one in `verify.ts` (#681). A second regex is a second producer,
13
+ * and the ones that drift are always the copies nobody knew were copies.
14
+ *
15
+ * **Two kinds, two patterns, one rule.** Paddle's ids are globally prefixed and distinct, so the prefix is
16
+ * what says whether a row names a payment or the subscription it belongs to. Both predicates live here
17
+ * because that is one rule read two ways, not two rules: a caller asking "is this a transaction" is asking
18
+ * the question whose other half is "is this a subscription", and splitting them across modules is how the
19
+ * next build ends up with a tight transaction check beside a loose subscription one.
20
+ *
21
+ * **Deliberately `+` rather than `{26}`.** Paddle's API reference documents the ids as `^txn_[a-z\d]{26}$`
22
+ * and `^sub_[a-z\d]{26}$`, and every id seen from the live and sandbox accounts has been 26 characters
23
+ * after the prefix. These stay looser than the documentation on purpose: the length is Paddle's to change,
24
+ * a length that grew would make this kit reject transactions that are perfectly real, and nothing here
25
+ * depends on the count. The prefix and the alphabet are what distinguish a transaction from a
26
+ * subscription, a price or a URL, and they are what the callers actually need to know.
27
+ *
28
+ * **It lives in `data/` rather than in `rails/paddle/`, and the gate is why.** `client/sameOrigin.test.ts`
29
+ * freezes every specifier a browser module may import, and the one existing crossing out of `src/client/`
30
+ * is `wholeUnits.ts` reaching `../data/money` — permitted because that module imports nothing, so "a set of
31
+ * currency codes reaches the bundle, no graph behind it". This is the same shape and earns its place the
32
+ * same way: it imports nothing, so the browser half reaches a predicate and not a rail. Under
33
+ * `rails/paddle/` it made a browser module read the server rail, which the gate refused and was right to.
34
+ * **Nothing in this module may grow an import** — not a shared prefix constant, not a helper. The empty
35
+ * list at `sameOrigin.test.ts`'s `"src/data/paddleIds.ts"` is the whole reason the crossing is allowed.
36
+ *
37
+ * `paddleIds.test.ts` beside this file is also the sweep that keeps these two patterns the only ones:
38
+ * it fails when any other module in the package interrogates a Paddle id prefix.
39
+ */
40
+ const TRANSACTION_ID = /^txn_[a-z0-9]+$/;
41
+
42
+ /** A subscription, the other half of the same rule. See the module doc for why both live here. */
43
+ const SUBSCRIPTION_ID = /^sub_[a-z0-9]+$/;
44
+
45
+ /**
46
+ * Whether a value is shaped like a Paddle transaction id.
47
+ *
48
+ * Shape only. It says nothing about whether the transaction exists, who it belongs to, or what it is for —
49
+ * a caller acting on any of that has to ask Paddle, and `verify.ts` is what does. This is the cheap check
50
+ * that comes first.
51
+ *
52
+ * **`boolean`, deliberately, not `value is string`.** The predicate is the tempting signature and it makes
53
+ * the *false* branch `never` for a caller whose value is already a string — which is every caller that
54
+ * matters. `verify.ts` refuses a malformed receipt with a message naming `id.length`, and under a predicate
55
+ * that line stopped compiling. Nothing here needs the narrowing: the one caller holding `string | null` has
56
+ * already narrowed on `!== null` before asking, and Zod's `.refine` wants a boolean.
57
+ */
58
+ export function isPaddleTransactionId(value: unknown): boolean {
59
+ return typeof value === "string" && TRANSACTION_ID.test(value);
60
+ }
61
+
62
+ /**
63
+ * Whether a value is shaped like a Paddle subscription id.
64
+ *
65
+ * Shape only, and `boolean` rather than a type predicate, for the reasons {@link isPaddleTransactionId}
66
+ * gives — the three rail callers all hold a `string` already and want the false branch to stay reachable.
67
+ *
68
+ * The three callers read a purchase row's `providerTransactionId` and ask whether it names a subscription
69
+ * rather than one of its payments: `refresh.ts` to decide which endpoint to re-read, twice, and
70
+ * `subscription.ts` to decide whether there is a subscription to quote, change, cancel or keep at all.
71
+ */
72
+ export function isPaddleSubscriptionId(value: unknown): boolean {
73
+ return typeof value === "string" && SUBSCRIPTION_ID.test(value);
74
+ }
@@ -0,0 +1,53 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+ import type { PaymentsRail } from "./rail";
6
+
7
+ /**
8
+ * When a subscription's current billing period began — where payments knows, and only there.
9
+ *
10
+ * **The rails disagree about what a row is.** Stripe and Apple write a row per billing period, so a row's
11
+ * `purchasedAt` is its period's start. Paddle writes one state row per subscription and moves it forward at
12
+ * each renewal, so its `purchasedAt` is when the subscription was created — and the period it is in is in the
13
+ * stored subscription's `current_billing_period`. Google and Lemon Squeezy rows carry the subscription's
14
+ * start too, and no stored field states the current period's.
15
+ *
16
+ * So this answers for the first three and says nothing for the last two. A meter keyed on a `purchasedAt`
17
+ * that never moves would never start a new period — a customer's allowance used up once, forever — which is
18
+ * why an unknown start is `undefined` and the caller falls back to the calendar month rather than guessing.
19
+ */
20
+
21
+ /** The slice of a Paddle subscription this reads. */
22
+ const PaddleBillingPeriod = z
23
+ .object({
24
+ current_billing_period: z
25
+ .object({ starts_at: z.string().describe("When the period began, ISO-8601.") })
26
+ .nullish()
27
+ .describe("The period being billed."),
28
+ })
29
+ .loose()
30
+ .describe("The billing period a stored Paddle subscription is in.");
31
+
32
+ /** The current period's start for one subscription row, or undefined where the row does not state one. */
33
+ export function knownPeriodStart(row: {
34
+ rail: PaymentsRail;
35
+ purchasedAt: Date;
36
+ payload: Record<string, unknown>;
37
+ }): Date | undefined {
38
+ switch (row.rail) {
39
+ case "stripe":
40
+ case "apple":
41
+ return row.purchasedAt;
42
+ case "paddle": {
43
+ const parsed = PaddleBillingPeriod.safeParse(row.payload);
44
+ const starts = parsed.success ? parsed.data.current_billing_period?.starts_at : undefined;
45
+ if (starts === undefined) return undefined;
46
+ const at = new Date(starts);
47
+ return Number.isNaN(at.getTime()) ? undefined : at;
48
+ }
49
+ case "google":
50
+ case "lemonSqueezy":
51
+ return undefined;
52
+ }
53
+ }
@@ -117,6 +117,15 @@ export const PaymentsPurchase = z
117
117
  .string()
118
118
  .nullable()
119
119
  .describe("The ISO currency the amount is in, or null when the rail did not report one."),
120
+ quantity: z
121
+ .number()
122
+ .int()
123
+ .positive()
124
+ .nullable()
125
+ .optional()
126
+ .describe(
127
+ "How many were bought, as the store states it — a seat count, a line quantity. Null or absent where the store does not say, including every row written before the column existed. Converges like every other field: the newest event's statement wins, whichever path delivered it.",
128
+ ),
120
129
  providerEventAt: SQLiteDate.describe(
121
130
  "The provider's own timestamp for the event that produced this row. The monotonic write rule compares against it, so out-of-order delivery cannot revoke a live subscription.",
122
131
  ),