@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
@@ -0,0 +1,149 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { type Kysely, sql } from "kysely";
5
+ import type { Migration } from "kysely/migration";
6
+
7
+ /**
8
+ * Allowances, meters and reported usage: four tables and one column.
9
+ *
10
+ * **A new migration, because `0001` is history.** Every payments chain has been running since 0.1.0, and
11
+ * reshaping `0001` would reshape a database somebody is already running. So everything lands here, with a
12
+ * tested `down`.
13
+ *
14
+ * - `pithy_payments_overrides` — one subject's override, `UNIQUE (subjectType, subjectId)`. Keyed on the
15
+ * subject rather than on an entitlement key, so it survives a tier change.
16
+ * - `pithy_payments_meter_counters` — one subject's use of one kit meter in one period,
17
+ * `UNIQUE (subjectType, subjectId, meter, periodStart)`. The period is half the key, which is what makes a
18
+ * new period start at zero with nothing to reset it.
19
+ * - `pithy_payments_usage_reports` — one reported period of one quantity-billed subscription,
20
+ * `UNIQUE (rail, providerSubscriptionId, period)`. The key is the idempotency: a replayed run finds the row.
21
+ * - `pithy_payments_usage_runs` — one reporting pass, its tally kept, the way reconcile runs are.
22
+ * - `pithy_payments_purchases.quantity` — how many were bought, as the store states it. Nullable, because
23
+ * rows written before this did not record one and no store is asked again to invent it.
24
+ *
25
+ * The subject kind is closed with a `CHECK` on every subject-bearing table, as `0001` closes it, and every
26
+ * count a row holds is checked non-negative: a negative usage is a bug in the writer, never a fact.
27
+ */
28
+ export const payments_0002_allowances: Migration = {
29
+ up: async (db: Kysely<unknown>): Promise<void> => {
30
+ await db.schema.alterTable("pithyPaymentsPurchases").addColumn("quantity", "integer").execute();
31
+
32
+ await db.schema
33
+ .createTable("pithyPaymentsOverrides")
34
+ .addColumn("id", "text", (c) => c.primaryKey())
35
+ .addColumn("subjectType", "text", (c) => c.notNull())
36
+ .addColumn("subjectId", "text", (c) => c.notNull())
37
+ .addColumn("unrestricted", "integer", (c) => c.notNull().defaultTo(0))
38
+ .addColumn("quotas", "text", (c) => c.notNull())
39
+ .addColumn("features", "text", (c) => c.notNull())
40
+ .addColumn("version", "integer", (c) => c.notNull())
41
+ .addColumn("reason", "text", (c) => c.notNull())
42
+ .addColumn("createdAt", "integer", (c) => c.notNull())
43
+ .addColumn("updatedAt", "integer", (c) => c.notNull())
44
+ // One override per subject. The conflict target every write is checked against, and the reason a
45
+ // tier change cannot take an override with it: nothing about a key is in it.
46
+ .addUniqueConstraint("pithyPaymentsOverridesSubjectIdx", ["subjectType", "subjectId"])
47
+ .addCheckConstraint("pithyPaymentsOverridesSubjectType", sql`subject_type in ('user', 'organization')`)
48
+ .addCheckConstraint("pithyPaymentsOverridesUnrestricted", sql`unrestricted in (0, 1)`)
49
+ .addCheckConstraint("pithyPaymentsOverridesVersion", sql`version >= 1`)
50
+ .execute();
51
+
52
+ // `GET {base}/admin/overrides`, newest change first, keyset-paged on the id like every listing here.
53
+ await db.schema
54
+ .createIndex("pithyPaymentsOverridesUpdatedIdx")
55
+ .on("pithyPaymentsOverrides")
56
+ .columns(["updatedAt", "id"])
57
+ .execute();
58
+
59
+ // `pithy doctor` names every unrestricted subject. The largest grant the kit has must never be a row
60
+ // nobody can find, so the read that finds them is an index range rather than a scan.
61
+ await db.schema
62
+ .createIndex("pithyPaymentsOverridesUnrestrictedIdx")
63
+ .on("pithyPaymentsOverrides")
64
+ .columns(["unrestricted", "subjectType", "subjectId"])
65
+ .execute();
66
+
67
+ await db.schema
68
+ .createTable("pithyPaymentsMeterCounters")
69
+ .addColumn("id", "text", (c) => c.primaryKey())
70
+ .addColumn("subjectType", "text", (c) => c.notNull())
71
+ .addColumn("subjectId", "text", (c) => c.notNull())
72
+ .addColumn("meter", "text", (c) => c.notNull())
73
+ .addColumn("periodStart", "integer", (c) => c.notNull())
74
+ .addColumn("used", "integer", (c) => c.notNull().defaultTo(0))
75
+ .addColumn("createdAt", "integer", (c) => c.notNull())
76
+ .addColumn("updatedAt", "integer", (c) => c.notNull())
77
+ // The upsert conflict target the conditional charge is written against. One row per period: the
78
+ // charge and the limit check are one statement on it, so a concurrent burst is serialized by SQLite.
79
+ .addUniqueConstraint("pithyPaymentsMeterCountersPeriodIdx", ["subjectType", "subjectId", "meter", "periodStart"])
80
+ .addCheckConstraint("pithyPaymentsMeterCountersSubjectType", sql`subject_type in ('user', 'organization')`)
81
+ .addCheckConstraint("pithyPaymentsMeterCountersUsed", sql`used >= 0`)
82
+ .execute();
83
+
84
+ await db.schema
85
+ .createTable("pithyPaymentsUsageReports")
86
+ .addColumn("id", "text", (c) => c.primaryKey())
87
+ .addColumn("rail", "text", (c) => c.notNull())
88
+ .addColumn("providerSubscriptionId", "text", (c) => c.notNull())
89
+ .addColumn("purchaseId", "text", (c) => c.notNull())
90
+ .addColumn("productId", "text", (c) => c.notNull())
91
+ .addColumn("subjectType", "text", (c) => c.notNull())
92
+ .addColumn("subjectId", "text", (c) => c.notNull())
93
+ .addColumn("cadence", "text", (c) => c.notNull())
94
+ .addColumn("period", "text", (c) => c.notNull())
95
+ .addColumn("quantity", "integer", (c) => c.notNull())
96
+ .addColumn("status", "text", (c) => c.notNull())
97
+ .addColumn("sampledAt", "integer", (c) => c.notNull())
98
+ .addColumn("reportedAt", "integer")
99
+ .addColumn("createdAt", "integer", (c) => c.notNull())
100
+ .addColumn("updatedAt", "integer", (c) => c.notNull())
101
+ // The idempotency key: one row per period of one subscription on one store. Reporting a period twice
102
+ // is a second insert against this, and it is refused.
103
+ .addUniqueConstraint("pithyPaymentsUsageReportsPeriodIdx", ["rail", "providerSubscriptionId", "period"])
104
+ .addCheckConstraint("pithyPaymentsUsageReportsSubjectType", sql`subject_type in ('user', 'organization')`)
105
+ .addCheckConstraint("pithyPaymentsUsageReportsCadence", sql`cadence in ('period-end', 'daily-peak')`)
106
+ .addCheckConstraint("pithyPaymentsUsageReportsStatus", sql`status in ('sampling', 'claimed', 'reported')`)
107
+ .addCheckConstraint("pithyPaymentsUsageReportsQuantity", sql`quantity >= 0`)
108
+ .execute();
109
+
110
+ // The subscription reads' "last reported count" is a subscription's newest report, which the unique's
111
+ // leading `(rail, providerSubscriptionId)` already answers as one index range — so no index of its own.
112
+
113
+ await db.schema
114
+ .createTable("pithyPaymentsUsageRuns")
115
+ .addColumn("id", "text", (c) => c.primaryKey())
116
+ .addColumn("startedAt", "integer", (c) => c.notNull())
117
+ .addColumn("finishedAt", "integer", (c) => c.notNull())
118
+ .addColumn("scanned", "integer", (c) => c.notNull().defaultTo(0))
119
+ .addColumn("reported", "integer", (c) => c.notNull().defaultTo(0))
120
+ .addColumn("sampled", "integer", (c) => c.notNull().defaultTo(0))
121
+ .addColumn("alreadyReported", "integer", (c) => c.notNull().defaultTo(0))
122
+ .addColumn("skipped", "integer", (c) => c.notNull().defaultTo(0))
123
+ .addColumn("invalid", "integer", (c) => c.notNull().defaultTo(0))
124
+ .addColumn("failed", "integer", (c) => c.notNull().defaultTo(0))
125
+ .addColumn("findings", "text", (c) => c.notNull())
126
+ .addColumn("createdAt", "integer", (c) => c.notNull())
127
+ .addCheckConstraint(
128
+ "pithyPaymentsUsageRunsCounts",
129
+ sql`scanned >= 0 and reported >= 0 and sampled >= 0 and already_reported >= 0 and skipped >= 0 and invalid >= 0 and failed >= 0`,
130
+ )
131
+ .execute();
132
+
133
+ await db.schema
134
+ .createIndex("pithyPaymentsUsageRunsStartedIdx")
135
+ .on("pithyPaymentsUsageRuns")
136
+ .columns(["startedAt", "id"])
137
+ .execute();
138
+ },
139
+ down: async (db: Kysely<unknown>): Promise<void> => {
140
+ await db.schema.dropIndex("pithyPaymentsUsageRunsStartedIdx").execute();
141
+ await db.schema.dropTable("pithyPaymentsUsageRuns").execute();
142
+ await db.schema.dropTable("pithyPaymentsUsageReports").execute();
143
+ await db.schema.dropTable("pithyPaymentsMeterCounters").execute();
144
+ await db.schema.dropIndex("pithyPaymentsOverridesUnrestrictedIdx").execute();
145
+ await db.schema.dropIndex("pithyPaymentsOverridesUpdatedIdx").execute();
146
+ await db.schema.dropTable("pithyPaymentsOverrides").execute();
147
+ await db.schema.alterTable("pithyPaymentsPurchases").dropColumn("quantity").execute();
148
+ },
149
+ };
@@ -85,6 +85,15 @@ export const ProviderEvent = z
85
85
  .nullable()
86
86
  .default(null)
87
87
  .describe("The ISO currency of `amountMinor`, or null when the rail did not report one."),
88
+ quantity: z
89
+ .number()
90
+ .int()
91
+ .positive()
92
+ .nullable()
93
+ .default(null)
94
+ .describe(
95
+ "How many were bought, as the store states it, or null where it does not say. Never invented: a rail that reads no quantity leaves this null rather than writing 1.",
96
+ ),
88
97
  providerEventAt: z
89
98
  .date()
90
99
  .describe(
@@ -188,6 +188,7 @@ export async function projectPurchase(
188
188
  originalTransactionId: event.originalTransactionId,
189
189
  amountMinor: event.amountMinor,
190
190
  currency: event.currency,
191
+ quantity: event.quantity,
191
192
  providerEventAt: event.providerEventAt,
192
193
  payload: event.payload,
193
194
  createdAt: existing?.createdAt ?? now,
@@ -400,6 +401,9 @@ function upsertPurchase(db: PaymentsDatabase, row: PaymentsPurchaseRow) {
400
401
  originalTransactionId: row.originalTransactionId,
401
402
  amountMinor: row.amountMinor,
402
403
  currency: row.currency,
404
+ // The newest event's statement, under the same monotonic rule as every column beside it — so a
405
+ // client submission, a webhook and a reconciliation pass converge on one quantity.
406
+ quantity: row.quantity,
403
407
  providerEventAt: row.providerEventAt,
404
408
  payload: row.payload,
405
409
  updatedAt: row.updatedAt,
@@ -368,6 +368,12 @@ export interface CheckoutSessionInput {
368
368
  providerProductId: string;
369
369
  /** Whether this buys a recurring subscription or a one-off. Decides the hosted flow the store presents. */
370
370
  subscription: boolean;
371
+ /**
372
+ * Whether the product bills by a reported quantity (`billing.kind: "reported"`). Such a price is metered on
373
+ * Stripe, and Stripe refuses a line quantity on a metered price — so the line goes out with none, and the
374
+ * count arrives later as reported usage. Absent is a flat-priced product.
375
+ */
376
+ reported?: boolean;
371
377
  /**
372
378
  * The subject the purchase is for — the authenticated caller, or the organization the project bills on
373
379
  * their behalf, as the configured subject seam resolved it.
@@ -12,6 +12,7 @@ import {
12
12
  } from "../../error/errors";
13
13
  import type { PaymentsGoogleCredentials } from "../../secret/registry";
14
14
  import type { UnboundProviderEvent } from "../contract";
15
+ import { statedQuantity } from "../quantity";
15
16
  import { type GoogleHttpFetch, googleHttpFetch, googleJson } from "./http";
16
17
  import { base64UrlEncode, pemPrivateKey } from "./jwt";
17
18
  import type { GoogleNotificationPointer } from "./rtdn";
@@ -508,6 +509,7 @@ export function playProductEvent(
508
509
  originalTransactionId: null,
509
510
  amountMinor: null,
510
511
  currency: null,
512
+ quantity: statedQuantity(purchase.quantity),
511
513
  providerEventAt: context.eventAt,
512
514
  payload: purchase as Record<string, unknown>,
513
515
  };
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { commandName } from "@pithy-sh/core/src/cli/command";
4
5
  import { z } from "zod";
5
6
  import type { PaymentsPaddleCredentials } from "../../secret/registry";
6
7
  import type { VerifiedNotification } from "../contract";
@@ -198,7 +199,7 @@ export async function sweepPaddleEvents(options: PaddleSweepOptions): Promise<Pa
198
199
  events: [],
199
200
  cursor: options.cursor,
200
201
  hasMore: false,
201
- gap: `Paddle no longer knows event ${options.cursor}, so the sweep cannot resume from it. Paddle retains ${PADDLE_EVENT_RETENTION_DAYS} days of events, and anything between that cursor and the retention window is gone. Reconcile the affected purchases with \`pithy payments reconcile --rail paddle\`, then clear the cursor to restart from the oldest retained event.`,
202
+ gap: `Paddle no longer knows event ${options.cursor}, so the sweep cannot resume from it. Paddle retains ${PADDLE_EVENT_RETENTION_DAYS} days of events, and anything between that cursor and the retention window is gone. Reconcile the affected purchases with \`${commandName("payments reconcile")}\`, passing --rail paddle and this environment's --env, then clear the cursor to restart from the oldest retained event.`,
202
203
  };
203
204
  }
204
205
  throw cause;
@@ -0,0 +1,19 @@
1
+ {
2
+ "data": {
3
+ "id": "sub_01hv8wptq8987qeep44cyrewp9",
4
+ "status": "active",
5
+ "customer_id": "ctm_01hv8wptq8987qeep44cyrewp9",
6
+ "currency_code": "USD",
7
+ "next_billed_at": "2026-11-05T09:00:00.000000Z",
8
+ "items": [
9
+ {
10
+ "status": "active",
11
+ "quantity": 1,
12
+ "recurring": true,
13
+ "price": { "id": "pri_01kzvyz9e21z9vbhd7xqq3csyh" }
14
+ }
15
+ ],
16
+ "scheduled_change": null
17
+ },
18
+ "meta": { "request_id": "8f2c7a1e-5d4b-4c3a-9b2e-1f0a9d8c7b6a" }
19
+ }
@@ -8,6 +8,7 @@ import type { PurchaseStatus } from "../../data/status";
8
8
  import { decodeSubjectReference } from "../../data/subject";
9
9
  import { PaymentsVerificationFailedError } from "../../error/errors";
10
10
  import type { UnboundProviderEvent } from "../contract";
11
+ import { statedQuantity } from "../quantity";
11
12
 
12
13
  /**
13
14
  * Paddle's objects, and the mapping from what its events say to what this package stores.
@@ -136,6 +137,7 @@ const PaddleTransactionItem = z
136
137
  .optional()
137
138
  .describe("The price object, which is where a transaction carries its SKU."),
138
139
  price_id: z.string().optional().describe("The price id, on the shapes that carry it flat."),
140
+ quantity: z.number().int().optional().describe("How many of the price this line sold."),
139
141
  })
140
142
  .loose()
141
143
  .describe("One line of a transaction. Single-product checkouts have exactly one.");
@@ -289,6 +291,7 @@ export const PaddleSubscription = z
289
291
  .optional()
290
292
  .describe("The price this item is billed at."),
291
293
  status: z.string().optional().describe("The item's own status, which can differ from the subscription's."),
294
+ quantity: z.number().int().optional().describe("How many of the price the subscription bills."),
292
295
  })
293
296
  .loose()
294
297
  .describe("One priced item on the subscription."),
@@ -641,6 +644,7 @@ export function transactionEvent(
641
644
  revokedAt: null,
642
645
  amountMinor: minorAmount(transaction.details?.totals?.grand_total),
643
646
  currency: currencyOf(transaction.details?.totals?.currency_code ?? transaction.currency_code),
647
+ quantity: statedQuantity(transaction.items?.[0]?.quantity),
644
648
  providerEventAt: occurredAt,
645
649
  payload: { ...transaction },
646
650
  };
@@ -745,6 +749,8 @@ export function subscriptionEvent(
745
749
  resumesAt: pauseResumesAt({ rail: "paddle", status, reported: subscriptionResumesAt(subscription) }),
746
750
  amountMinor: null,
747
751
  currency: null,
752
+ // The line's own quantity, the one a plan change carries back unchanged (`subscription.ts`).
753
+ quantity: statedQuantity(subscription.items?.[0]?.quantity),
748
754
  providerEventAt: occurredAt,
749
755
  payload: { ...subscription },
750
756
  };
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { SubscriptionPricing } from "../../data/discount";
5
+ import { isPaddleSubscriptionId, isPaddleTransactionId } from "../../data/paddleIds";
5
6
  import type { PaymentsPurchase } from "../../data/purchase";
6
7
  import type { PaymentsPaddleCredentials } from "../../secret/registry";
7
8
  import type { UnboundProviderEvent } from "../contract";
@@ -18,9 +19,12 @@ import { readSubscription, readTransaction } from "./read";
18
19
  *
19
20
  * ## Which rows it can answer for
20
21
  *
21
- * Paddle's ids are globally prefixed, so the row's own key says what to ask: `sub_…` is a subscription,
22
- * `txn_…` is a transaction. Both are addressable, so both are re-read — unlike Lemon Squeezy, where a
23
- * money row records a closed period and has nothing to re-read.
22
+ * Paddle's ids are globally prefixed, so the row's own key says what to ask: a subscription id is a
23
+ * subscription, a transaction id is a transaction. Both are addressable, so both are re-read — unlike
24
+ * Lemon Squeezy, where a money row records a closed period and has nothing to re-read. **What counts as
25
+ * one of those keys is `data/paddleIds.ts`'s to say**, not this module's: a prefix test here accepted the
26
+ * bare prefix and an uppercase id, and spent a round trip finding out the store had never issued it
27
+ * (#681).
24
28
  *
25
29
  * A **subscription** transaction's money row is born `expired`, which is in the Workflow's terminal set,
26
30
  * so the pass never selects one. Should one reach here it is answered honestly rather than skipped: a
@@ -61,20 +65,21 @@ export async function refreshPaddlePurchase(
61
65
  const id = purchase.providerTransactionId;
62
66
  const environment = options.environment === "production" ? "production" : "sandbox";
63
67
 
64
- if (id.startsWith("sub_")) {
68
+ if (isPaddleSubscriptionId(id)) {
65
69
  const subscription = await readSubscription(id, read);
66
70
  if (subscription === undefined) return undefined;
67
71
  return { ...subscriptionEvent(subscription, options.now, environment), providerEventAt: options.now };
68
72
  }
69
73
 
70
- if (id.startsWith("txn_")) {
74
+ if (isPaddleTransactionId(id)) {
71
75
  const transaction = await readTransaction(id, read);
72
76
  if (transaction === undefined) return undefined;
73
77
  return { ...transactionEvent(transaction, options.now, environment), providerEventAt: options.now };
74
78
  }
75
79
 
76
- // A prefix a later build wrote. Nothing to re-read, which the contract defines as "the store has
77
- // nothing to say about this purchase" and which leaves the row exactly as it stands.
80
+ // A key neither primitive recognizes: a prefix a later build wrote, or a value too mangled to be an
81
+ // id Paddle issued. Nothing to re-read, which the contract defines as "the store has nothing to say
82
+ // about this purchase" and which leaves the row exactly as it stands.
78
83
  return undefined;
79
84
  }
80
85
 
@@ -86,15 +91,17 @@ export async function refreshPaddlePurchase(
86
91
  * list price. Nothing here multiplies a price by a percentage — a second calculation would be a second
87
92
  * answer to the one question a customer checks against their statement.
88
93
  *
89
- * Only a `sub_…` row can be asked. A transaction records one closed period and has no "next", so it
90
- * answers `undefined` — the same "nothing to say about this purchase" the refresh path uses.
94
+ * Only a subscription row can be asked, and `data/paddleIds.ts` says which rows those are. A transaction
95
+ * records one closed period and has no "next", so it answers `undefined` — the same "nothing to say about
96
+ * this purchase" the refresh path uses, and the same answer a column holding something Paddle never
97
+ * issued now gets without a round trip (#681).
91
98
  */
92
99
  export async function readPaddlePricing(
93
100
  purchase: PaymentsPurchase,
94
101
  options: RefreshPaddleOptions,
95
102
  ): Promise<SubscriptionPricing | undefined> {
96
103
  const id = purchase.providerTransactionId;
97
- if (!id.startsWith("sub_")) return undefined;
104
+ if (!isPaddleSubscriptionId(id)) return undefined;
98
105
 
99
106
  const answer = await paddleJson(options.transport ?? paddleHttpFetch, `/subscriptions/${encodeURIComponent(id)}`, {
100
107
  what: `subscription ${id}'s pricing`,
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { isPaddleTransactionId } from "../../data/paddleIds";
4
5
  import type { PaymentsPurchase } from "../../data/purchase";
5
6
  import { RefundRequest, type RefundRequestOutcome, type RefundRequestStatus } from "../../data/subscription";
6
7
  import { PaymentsProviderUnavailableError, PaymentsSubscriptionChangeRefusedError } from "../../error/errors";
@@ -101,10 +102,17 @@ function refuse(detail: string): never {
101
102
  });
102
103
  }
103
104
 
104
- /** The transaction this purchase row names, or null when it names none. */
105
+ /**
106
+ * The transaction this purchase row names, or null when it names none.
107
+ *
108
+ * **The primitive decides, not a prefix test here.** `startsWith` accepted the bare prefix and Paddle's
109
+ * alphabet in uppercase, neither of which is an id the store can hold — so a malformed row cost a
110
+ * `GET /transactions/{id}` and then refused on the 404, naming the store rather than the row (#681).
111
+ * `data/paddleIds.ts` is the one place that says what a transaction id is.
112
+ */
105
113
  function transactionIdOf(purchase: PaymentsPurchase): string | null {
106
114
  const id = purchase.providerTransactionId;
107
- return id.startsWith("txn_") ? id : null;
115
+ return isPaddleTransactionId(id) ? id : null;
108
116
  }
109
117
 
110
118
  /**
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { z } from "zod";
5
+ import { isPaddleSubscriptionId } from "../../data/paddleIds";
5
6
  import type { PaymentsPurchase } from "../../data/purchase";
6
7
  import { renderMoney } from "../../data/renderMoney";
7
8
  import {
@@ -219,12 +220,16 @@ function orNull(value: string | null | undefined): string | null {
219
220
  * The subscription this purchase names, or null when it names none.
220
221
  *
221
222
  * Paddle's ids are globally prefixed, so the row's own key says what it is — `refreshPaddlePurchase`'s rule,
222
- * and for the same reason: a money row's family key is `sub_…`, and falling back to it would act on a
223
- * subscription from a row that is not one.
223
+ * and for the same reason: a money row's family key is the subscription's, and falling back to it would act
224
+ * on a subscription from a row that is not one.
225
+ *
226
+ * **`isPaddleSubscriptionId` rather than a prefix test, and all five callers feel it.** The prefix alone,
227
+ * and an id in an alphabet Paddle does not issue, used to read as subscriptions here: the read answered
228
+ * after a wasted round trip, and the other four refused on the store's answer instead of on the row (#681).
224
229
  */
225
230
  function subscriptionIdOf(purchase: PaymentsPurchase): string | null {
226
231
  const id = purchase.providerTransactionId;
227
- return id.startsWith("sub_") ? id : null;
232
+ return isPaddleSubscriptionId(id) ? id : null;
228
233
  }
229
234
 
230
235
  /** The subscription, or a refusal. Used by the write verbs, which have nothing to do without it. */
@@ -0,0 +1,66 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+ import { PaymentsProviderUnavailableError } from "../../error/errors";
6
+ import type { UsageReporter, UsageReportRequest } from "../../usage/reporter";
7
+ import { type PaddleEnvironment, type PaddleHttpFetch, paddleHttpFetch, paddleJson } from "./api";
8
+
9
+ /**
10
+ * Reporting a count to Paddle: one one-time charge per reported period, on the subscription's next bill.
11
+ *
12
+ * **One per billing period, whatever the cadence.** Every charge is its own line on the bill, so a charge
13
+ * per day would bill the sum of the days. The pass sends a `daily-peak` product's period once, at the
14
+ * highest day it sampled (`usage/pass.ts`).
15
+ *
16
+ * `POST /subscriptions/{id}/charge` with `effective_from: "next_billing_period"` and one item — the product's
17
+ * one-time per-unit price at the reported quantity. Paddle adds it to the next renewal's transaction.
18
+ *
19
+ * **It never rewrites the subscription's items.** That is the licensed-seat model, and the rail refuses to
20
+ * rewrite an items array for anything but a single line. A charge adds; it changes nothing that is there,
21
+ * so the recurring line keeps its quantity whatever is reported. The period's row id travels as the
22
+ * idempotency key, so a report sent twice is one charge.
23
+ */
24
+
25
+ /** As much of Paddle's answer as proves the charge landed on this subscription. */
26
+ const PaddleChargedSubscription = z
27
+ .object({ id: z.string().describe("The subscription the charge was added to.") })
28
+ .loose()
29
+ .describe("The subscription Paddle answers a one-time charge with.");
30
+
31
+ /** The Paddle reporter, over the API key, the account and a transport. */
32
+ export function paddleUsageReporter(options: {
33
+ apiKey: string;
34
+ environment: PaddleEnvironment;
35
+ transport?: PaddleHttpFetch;
36
+ }): UsageReporter {
37
+ const transport = options.transport ?? paddleHttpFetch;
38
+ return {
39
+ async report(request: UsageReportRequest): Promise<void> {
40
+ const priceId = request.billing.paddle?.priceId;
41
+ if (priceId === undefined) {
42
+ throw new PaymentsProviderUnavailableError({
43
+ detail: `Paddle usage for ${request.providerSubscriptionId} has no price to charge it at.`,
44
+ });
45
+ }
46
+ const answer = await paddleJson(
47
+ transport,
48
+ `/subscriptions/${encodeURIComponent(request.providerSubscriptionId)}/charge`,
49
+ {
50
+ what: "a one-time usage charge",
51
+ apiKey: options.apiKey,
52
+ environment: options.environment,
53
+ method: "POST",
54
+ body: { effective_from: "next_billing_period", items: [{ price_id: priceId, quantity: request.quantity }] },
55
+ idempotencyKey: request.idempotencyKey,
56
+ },
57
+ );
58
+ const charged = PaddleChargedSubscription.safeParse(answer?.data);
59
+ if (!charged.success || charged.data.id !== request.providerSubscriptionId) {
60
+ throw new PaymentsProviderUnavailableError({
61
+ detail: `Paddle answered the usage charge for ${request.providerSubscriptionId} with a different subscription.`,
62
+ });
63
+ }
64
+ },
65
+ };
66
+ }
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { isPaddleTransactionId } from "../../data/paddleIds";
4
5
  import type { PurchaseEnvironment } from "../../data/purchase";
5
6
  import { PaymentsInvalidReceiptError, PaymentsVerificationFailedError } from "../../error/errors";
6
7
  import type { PaymentsPaddleCredentials } from "../../secret/registry";
@@ -51,16 +52,17 @@ export interface VerifyPaddleTransactionOptions {
51
52
  transport: PaddleHttpFetch;
52
53
  }
53
54
 
54
- /** Paddle's transaction ids. Checked before a round trip, so a malformed one costs nothing. */
55
- const TRANSACTION_ID = /^txn_[a-z0-9]+$/;
56
-
57
55
  /** Verify one submitted Paddle transaction id, and report who it says it belongs to. */
58
56
  export async function verifyPaddleTransaction(
59
57
  receipt: string,
60
58
  options: VerifyPaddleTransactionOptions,
61
59
  ): Promise<VerifiedPurchase> {
62
60
  const id = receipt.trim();
63
- if (!TRANSACTION_ID.test(id)) {
61
+ // **Checked before a round trip, so a malformed receipt costs nothing.** The pattern left this module for
62
+ // `../../data/paddleIds.ts` when the `_ptxn` reader needed the same question answered about a value out of
63
+ // a query string — one rule, several callers, rather than regexes that drift. The rest of this rail reads
64
+ // it now too, and `data/paddleIds.test.ts` is the sweep that keeps it the only answer (#681).
65
+ if (!isPaddleTransactionId(id)) {
64
66
  throw new PaymentsInvalidReceiptError({
65
67
  message: "That isn't a Paddle transaction.",
66
68
  action: "Submit the `txn_…` the checkout's completion callback handed back.",
@@ -0,0 +1,14 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * The quantity a store stated, or null — never a default.
6
+ *
7
+ * Every rail but one parses a quantity that is sometimes absent: a metered Stripe price carries none, a Paddle
8
+ * line on an old shape carries none, a Play one-time purchase of one omits it. Writing `1` for absent would
9
+ * invent a fact the store did not state, and a seat count read off it would be a number nobody reported.
10
+ * So a positive whole number crosses and anything else is null.
11
+ */
12
+ export function statedQuantity(value: unknown): number | null {
13
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null;
14
+ }
@@ -91,7 +91,9 @@ export async function createStripeCheckoutSession(
91
91
 
92
92
  const form: StripeFormObject = {
93
93
  mode: input.subscription ? "subscription" : "payment",
94
- line_items: [{ price: input.providerProductId, quantity: 1 }],
94
+ // One of a flat price. A reported product's price is metered, and Stripe refuses a quantity on a metered
95
+ // line: the count is reported per period instead (`usage/pass.ts`).
96
+ line_items: [{ price: input.providerProductId, quantity: input.reported ? undefined : 1 }],
95
97
  success_url: input.successUrl,
96
98
  cancel_url: input.cancelUrl,
97
99
  // The resolved subject, both halves. Never a value from a request body — see the module doc.
@@ -0,0 +1,12 @@
1
+ {
2
+ "object": "billing.meter_event",
3
+ "created": 1792022399,
4
+ "event_name": "academy_students",
5
+ "identifier": "usage_8c1f2a4e-6b3d-4f5a-9e7c-2d1b0a9f8e7d",
6
+ "livemode": false,
7
+ "payload": {
8
+ "stripe_customer_id": "cus_PithyAcme",
9
+ "value": "25"
10
+ },
11
+ "timestamp": 1792022399
12
+ }
@@ -7,6 +7,7 @@ import type { PurchaseEnvironment } from "../../data/purchase";
7
7
  import { ACCESS_GRANTING_STATUSES, type PurchaseStatus } from "../../data/status";
8
8
  import { PaymentsVerificationFailedError } from "../../error/errors";
9
9
  import type { NotificationNote, UnboundProviderEvent } from "../contract";
10
+ import { statedQuantity } from "../quantity";
10
11
 
11
12
  /**
12
13
  * Stripe's objects, and the mapping from what Stripe calls a thing to what the projection stores.
@@ -386,6 +387,8 @@ export function mapStripeSubscription(subscription: StripeSubscription, eventAt:
386
387
  originalTransactionId: subscription.id,
387
388
  amountMinor: minorUnits(item.price.unit_amount ?? null, currency),
388
389
  currency,
390
+ // The seat count Stripe states on the item. A metered price carries none, and null says so.
391
+ quantity: statedQuantity(item.quantity),
389
392
  providerEventAt: eventAt,
390
393
  payload: subscription as Record<string, unknown>,
391
394
  },
@@ -465,6 +468,7 @@ export function mapStripeSession(session: StripeCheckoutSession, options: Stripe
465
468
  originalTransactionId: null,
466
469
  amountMinor: minorUnits(session.amount_total ?? null, currency),
467
470
  currency,
471
+ quantity: statedQuantity(session.line_items?.data[0]?.quantity),
468
472
  providerEventAt: options.eventAt ?? retrievedAt(session, charge, status, options.now),
469
473
  payload: session as Record<string, unknown>,
470
474
  },