@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,252 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import { grantedEntitlementKeys, type MeterLimit } from "@pithy-sh/core/src/entitlement/entitlement";
6
+ import type { MeterCharge, UsageMeter } from "@pithy-sh/core/src/entitlement/meter";
7
+ import { InternalError, messageOf, PithyError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
8
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
9
+ import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
10
+ import { sql } from "kysely";
11
+ import type { AllowanceDeclarations } from "../config/allowances";
12
+ import type { KitMeter, PaymentsMeters } from "../config/config";
13
+ import { PaymentsMeterCounter } from "../data/meterCounter";
14
+ import { knownPeriodStart } from "../data/period";
15
+ import { PaymentsPurchase } from "../data/purchase";
16
+ import { grantingStatuses } from "../data/status";
17
+ import { encodeSubjectReference, PaymentsSubject } from "../data/subject";
18
+ import {
19
+ PAYMENTS_METER_COUNTERS_TABLE,
20
+ PAYMENTS_PURCHASES_TABLE,
21
+ type PaymentsDatabase,
22
+ paymentsDatabase,
23
+ } from "../data/tables";
24
+ import { PaymentsQuotaExceededError } from "../error/errors";
25
+ import { resolveEntitlements } from "../projection/resolve";
26
+ import { type AllowanceInput, resolveQuota } from "./allowance";
27
+ import { allowanceOverride, readOverride } from "./override";
28
+
29
+ /**
30
+ * The kit's own meters — what the kit counts because it writes the rows.
31
+ *
32
+ * | meter | counted from | enforced by |
33
+ * |----------------|-----------------------|---------------------------------------------|
34
+ * | `emails` | this table, per period | `@pithy-sh/email`, at enqueue, through {@link paymentsUsageMeter} |
35
+ * | `storageBytes` | `pithy_storage_objects` | `@pithy-sh/storage`, through `meterLimit` |
36
+ * | `mediaItems` | `pithy_media_*` | `@pithy-sh/media`, through `meterLimit` |
37
+ *
38
+ * The two that are levels — bytes held, items held — are counted by the capability that holds them, in the
39
+ * statement that writes the row, which is the only place a concurrent burst cannot walk past. Payments only
40
+ * says what the ceiling is. The one that is a flow — emails sent this period — is counted here, in
41
+ * `pithy_payments_meter_counters`, because no row anybody keeps answers "how many this period" once the
42
+ * email capability has pruned its jobs.
43
+ *
44
+ * **Enforcement is opt-in per meter.** Declaring `quotas: { emails: 500 }` makes 500 readable; turning the
45
+ * `emails` meter on makes it binding. A cap that arrives by surprise breaks an adopter already over it.
46
+ *
47
+ * **A counter read that fails refuses, and logs.** Storage already says which way round to err: over-counting
48
+ * briefly and reclaiming is the right way round, and under-counting has no recovery. The cost is stated
49
+ * rather than discovered: a bug of ours becomes a refused send for a paying customer, and a password reset is
50
+ * a bad place to invent a failure. Opt-in enforcement bounds it — an adopter who would rather over-deliver
51
+ * than drop leaves the meter advisory and keeps the check in their own route. Whoever reverses this should
52
+ * have to argue with that paragraph first.
53
+ *
54
+ * **A meter refuses; it never bills.** Nothing here reports a count to a store, and the usage-reporting pass
55
+ * never reads this table: the kit does not sell overage.
56
+ */
57
+
58
+ /** What every allowance read and every meter needs from the config. */
59
+ export interface PaymentsAllowances {
60
+ /** The declarations. */
61
+ declarations: AllowanceDeclarations;
62
+ /** Which kit meters enforce. */
63
+ meters: PaymentsMeters;
64
+ }
65
+
66
+ /** Whether a kit meter is enforced in this config. Anything not a kit meter is not. */
67
+ export function meterEnforced(meters: PaymentsMeters, meter: string): meter is KitMeter {
68
+ return (meters as Record<string, { enforce?: boolean } | undefined>)[meter]?.enforce === true;
69
+ }
70
+
71
+ /**
72
+ * Everything resolution needs for one subject, read now: the keys granting access and the override row. A
73
+ * caller acting for nobody holds nothing and has no override, and resolves to the floor.
74
+ */
75
+ export async function allowanceInputFor(
76
+ db: PaymentsDatabase | undefined,
77
+ declarations: AllowanceDeclarations,
78
+ subject: PaymentsSubject | undefined,
79
+ now: Date,
80
+ ): Promise<AllowanceInput> {
81
+ if (subject === undefined || db === undefined) return { declarations, held: new Set(), override: null };
82
+ const [entitlements, override] = await Promise.all([
83
+ resolveEntitlements(db, subject, now),
84
+ readOverride(db, subject),
85
+ ]);
86
+ return { declarations, held: grantedEntitlementKeys(entitlements, now), override: allowanceOverride(override) };
87
+ }
88
+
89
+ /** The first instant of `now`'s calendar month, in UTC. The period of a subject payments knows no billing period for. */
90
+ export function calendarMonthStart(now: Date): Date {
91
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
92
+ }
93
+
94
+ /**
95
+ * When the subject's current period began: the start of its current billing period where payments knows one,
96
+ * the calendar month where it does not — a free-floor account still has a month.
97
+ *
98
+ * The current period is a granting subscription row whose window holds `now`; `data/period.ts` says which
99
+ * rails' rows state where that period began. Two at once — an upgrade overlapping an old subscription's tail —
100
+ * is answered by the newest, which is the one the customer is now paying for.
101
+ */
102
+ export async function meterPeriodStart(db: PaymentsDatabase, subject: PaymentsSubject, now: Date): Promise<Date> {
103
+ const at = now.getTime();
104
+ const row = await db
105
+ .selectFrom(PAYMENTS_PURCHASES_TABLE)
106
+ .select(["rail", "purchasedAt", "payload"])
107
+ .where("subjectType", "=", subject.subjectType)
108
+ .where("subjectId", "=", subject.subjectId)
109
+ .where("type", "=", "subscription")
110
+ .where("status", "in", grantingStatuses(true))
111
+ // biome-ignore lint/suspicious/noExplicitAny: ms-epoch numbers against the encoded columns.
112
+ .where("purchasedAt", "<=", at as any)
113
+ // biome-ignore lint/suspicious/noExplicitAny: as above.
114
+ .where("expiresAt", ">", at as any)
115
+ .orderBy("purchasedAt", "desc")
116
+ .limit(1)
117
+ .executeTakeFirst();
118
+ if (row === undefined) return calendarMonthStart(now);
119
+ const purchase = PaymentsPurchase.pick({ rail: true, purchasedAt: true, payload: true }).parse(row);
120
+ return knownPeriodStart(purchase) ?? calendarMonthStart(now);
121
+ }
122
+
123
+ /**
124
+ * Charge `amount` of `meter` against `subject` — or refuse, and write nothing.
125
+ *
126
+ * **The check and the write are one statement.** An upsert on `(subject, meter, periodStart)` whose update
127
+ * is conditioned on `used + amount <= limit`, with `RETURNING` to read back whether it landed. SQLite
128
+ * evaluates the condition under its write lock, so a burst of concurrent sends is serialized by the database
129
+ * and the first that would pass the limit changes nothing — the guarantee `@pithy-sh/storage`'s conditional
130
+ * insert makes, for the same reason: D1 has no interactive transaction to make two statements one.
131
+ *
132
+ * An unlimited subject — `null`, from a plan or from `unrestricted` — is counted and never refused.
133
+ */
134
+ export async function chargeMeter(
135
+ db: PaymentsDatabase,
136
+ allowances: PaymentsAllowances,
137
+ charge: { subject: PaymentsSubject; meter: string; amount: number; now: Date },
138
+ ): Promise<void> {
139
+ if (!meterEnforced(allowances.meters, charge.meter)) return;
140
+ const input = await allowanceInputFor(db, allowances.declarations, charge.subject, charge.now);
141
+ const limit = resolveQuota(input, charge.meter).effective.value;
142
+ const periodStart = await meterPeriodStart(db, charge.subject, charge.now);
143
+ const refused = () =>
144
+ new PaymentsQuotaExceededError({
145
+ params: { meter: charge.meter, limit: limit ?? 0 },
146
+ detail: `${encodeSubjectReference(charge.subject)} is at its ${charge.meter} quota of ${limit} for the period from ${periodStart.toISOString()}.`,
147
+ });
148
+ if (limit !== null && charge.amount > limit) throw refused();
149
+
150
+ const at = charge.now.getTime();
151
+ const record = PaymentsMeterCounter.encode({
152
+ id: crypto.randomUUID(),
153
+ subjectType: charge.subject.subjectType,
154
+ subjectId: charge.subject.subjectId,
155
+ meter: charge.meter,
156
+ periodStart,
157
+ used: charge.amount,
158
+ createdAt: charge.now,
159
+ updatedAt: charge.now,
160
+ });
161
+ const landed = await db
162
+ .insertInto(PAYMENTS_METER_COUNTERS_TABLE)
163
+ // biome-ignore lint/suspicious/noExplicitAny: the row is the schema's z.input side; Kysely's insert type derives from it.
164
+ .values(record as any)
165
+ .onConflict((oc) => {
166
+ const update = oc.columns(["subjectType", "subjectId", "meter", "periodStart"]).doUpdateSet({
167
+ // biome-ignore lint/suspicious/noExplicitAny: an expression, not a value.
168
+ used: sql`${sql.ref(`${PAYMENTS_METER_COUNTERS_TABLE}.used`)} + excluded.used` as any,
169
+ // biome-ignore lint/suspicious/noExplicitAny: as above.
170
+ updatedAt: at as any,
171
+ });
172
+ return limit === null
173
+ ? update
174
+ : update.where(sql<boolean>`${sql.ref(`${PAYMENTS_METER_COUNTERS_TABLE}.used`)} + excluded.used <= ${limit}`);
175
+ })
176
+ .returning("used")
177
+ .executeTakeFirst();
178
+ if (landed === undefined) throw refused();
179
+ }
180
+
181
+ /**
182
+ * The ceiling a capability enforces on a level it counts itself — `storageBytes`, `mediaItems` — for a
183
+ * subject, or `{ enforced: false }` where the meter is advisory and the capability keeps its own.
184
+ *
185
+ * **The ceiling names the organization it covers.** An organization's plan is the organization's, so the
186
+ * capability must sum every member's rows against it, not the caller's alone — `tenant` says so, the same
187
+ * value the holder's `tenant` carries. A user subject, or nobody, is `null`: the caller's own rows.
188
+ */
189
+ export async function meterLimitFor(
190
+ db: PaymentsDatabase,
191
+ allowances: PaymentsAllowances,
192
+ subject: PaymentsSubject | undefined,
193
+ meter: string,
194
+ now: Date,
195
+ ): Promise<MeterLimit> {
196
+ if (!meterEnforced(allowances.meters, meter)) return { enforced: false };
197
+ const input = await allowanceInputFor(db, allowances.declarations, subject, now);
198
+ return {
199
+ enforced: true,
200
+ limit: resolveQuota(input, meter).effective.value,
201
+ tenant: subject?.subjectType === "organization" ? subject.subjectId : null,
202
+ };
203
+ }
204
+
205
+ /**
206
+ * The meter `@pithy-sh/email` finds among the composed capabilities and charges at enqueue — the env-side
207
+ * half of the seam, for the callers with no request. See `@pithy-sh/core/src/entitlement/meter.ts`.
208
+ *
209
+ * A refusal is the provider's own `payments/quota_exceeded`. Anything else that goes wrong — a malformed
210
+ * holder, a D1 read that throws — is logged and refused as `core/internal`, never let through: see this
211
+ * module's note on which way round to err.
212
+ */
213
+ export function paymentsUsageMeter(allowances: PaymentsAllowances, database = "DB"): UsageMeter {
214
+ return {
215
+ provider: "payments",
216
+ async charge(env: Record<string, unknown>, charge: MeterCharge): Promise<void> {
217
+ if (!meterEnforced(allowances.meters, charge.meter)) return;
218
+ const log: Logger = charge.log ?? createWorkerLogger({ name: "payments" });
219
+ const subject = PaymentsSubject.safeParse(charge.subject);
220
+ if (!subject.success || !Number.isInteger(charge.amount) || charge.amount < 1) {
221
+ throw new ValidationError({
222
+ message: "That usage charge names no valid holder or amount.",
223
+ action: "Charge a whole amount from 1 against a subject the payments subject schema accepts.",
224
+ detail: `meter ${charge.meter}, amount ${charge.amount}`,
225
+ });
226
+ }
227
+ try {
228
+ const d1 = env[database] as D1Database | undefined;
229
+ if (!d1) {
230
+ throw new InternalError({
231
+ detail: `No \`${database}\` binding on env; the ${charge.meter} meter cannot count.`,
232
+ });
233
+ }
234
+ await chargeMeter(paymentsDatabase(d1), allowances, {
235
+ subject: subject.data,
236
+ meter: charge.meter,
237
+ amount: charge.amount,
238
+ now: charge.now ?? new Date(),
239
+ });
240
+ } catch (error) {
241
+ if (error instanceof PaymentsQuotaExceededError) throw error;
242
+ log.error("usage meter charge failed", { meter: charge.meter, cause: messageOf(error) });
243
+ if (error instanceof PithyError && error.payload.code !== "core/internal") throw error;
244
+ throw new InternalError({
245
+ message: "Usage could not be checked, so nothing was written.",
246
+ action: "Read the preceding log line for why the meter read failed.",
247
+ detail: `the ${charge.meter} meter could not be charged; refusing rather than serving unbounded.`,
248
+ });
249
+ }
250
+ },
251
+ };
252
+ }
@@ -0,0 +1,381 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import { withD1Retry } from "@pithy-sh/core/src/data/withD1Retry";
6
+ import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
7
+ import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
8
+ import {
9
+ type AllowanceDeclarations,
10
+ declaredFeatureNames,
11
+ declaredQuotaNames,
12
+ type FeatureMap,
13
+ type QuotaMap,
14
+ } from "../config/allowances";
15
+ import { isEmptyOverride, PaymentsOverride } from "../data/override";
16
+ import { encodeSubjectReference, type PaymentsSubject } from "../data/subject";
17
+ import { PAYMENTS_OVERRIDES_TABLE, type PaymentsDatabase, paymentsDatabase } from "../data/tables";
18
+ import { PaymentsOverrideStaleError } from "../error/errors";
19
+ import { resolveEntitlements } from "../projection/resolve";
20
+ import type { AllowanceOverride } from "./allowance";
21
+
22
+ /**
23
+ * Per-subject overrides — the writes behind the control plane's set and clear, and the read every resolver
24
+ * shares.
25
+ *
26
+ * **The first runtime-writable input to an entitlement decision in the kit**, so each rule below is one of the
27
+ * things that keeps it narrow:
28
+ *
29
+ * - **A name must be declared.** A patch naming `emals` is refused naming it and listing what is declared,
30
+ * the shape a grant of an unknown key already gets. `unrestricted` names nothing, so it is exempt.
31
+ * - **A ceiling is a ceiling.** Where a declaration states `overrideMax`, a set past it is refused naming the
32
+ * limit — never clamped, because a clamped number is a wrong number nobody chose.
33
+ * - **A write is a merge by name.** A set changes only the names it carries, so coming back months later to
34
+ * add 100 to one allowance is a request naming one allowance — and one operator's stale pane cannot erase
35
+ * another's pin by omission.
36
+ * - **A write names the version it read.** A version behind the row is `payments/override_stale`, and nothing
37
+ * is written. The compare is inside the write's own `WHERE`, so two writers racing on one row cannot both
38
+ * pass a check made a statement earlier.
39
+ * - **A version never repeats.** A clear keeps the row, empty, at the next version rather than deleting it,
40
+ * so a pane still holding a cleared row's version is behind, not current again.
41
+ * - **A clear only moves a subject back toward its plan.** Unpinning a name on an `unrestricted` subject
42
+ * would lift it to unlimited, which is the unrestricted scope's grant, so a clear naming such a pin is
43
+ * refused. A whole clear takes `unrestricted` with it, which narrows, and is allowed.
44
+ * - **A reason is required on every set**, and the audit event carries it. Six months later, the question
45
+ * anybody asks about an override is why.
46
+ */
47
+
48
+ /** A subject's override row, or undefined when it has none. */
49
+ export async function readOverride(
50
+ db: PaymentsDatabase,
51
+ subject: PaymentsSubject,
52
+ ): Promise<PaymentsOverride | undefined> {
53
+ const row = await db
54
+ .selectFrom(PAYMENTS_OVERRIDES_TABLE)
55
+ .selectAll()
56
+ .where("subjectType", "=", subject.subjectType)
57
+ .where("subjectId", "=", subject.subjectId)
58
+ .executeTakeFirst();
59
+ return row === undefined ? undefined : PaymentsOverride.parse(row);
60
+ }
61
+
62
+ /** The resolver's view of a row: the three facts resolution reads, or null for no override — a cleared row included. */
63
+ export function allowanceOverride(row: PaymentsOverride | undefined): AllowanceOverride | null {
64
+ if (row === undefined || isEmptyOverride(row)) return null;
65
+ return { unrestricted: row.unrestricted, quotas: row.quotas, features: row.features };
66
+ }
67
+
68
+ /** The version a write must name: the row's — a cleared row's included — or 0 when there has never been one. */
69
+ export function overrideVersion(row: PaymentsOverride | undefined): number {
70
+ return row?.version ?? 0;
71
+ }
72
+
73
+ /** What a set or a clear changed, for the audit event and the response. */
74
+ export interface OverrideChange {
75
+ /** The row before the write, or undefined when there was none. */
76
+ before: PaymentsOverride | undefined;
77
+ /**
78
+ * The row after the write, or undefined when the subject has never had one. A clear leaves an empty row
79
+ * ({@link isEmptyOverride}), which carries the version the next write must name.
80
+ */
81
+ after: PaymentsOverride | undefined;
82
+ }
83
+
84
+ /** The clock and the id minter. */
85
+ export interface OverrideWriteOptions {
86
+ /** The write timestamp. Defaults to now. */
87
+ now?: Date;
88
+ /** The id minter for a row that does not exist yet. Defaults to `crypto.randomUUID`. */
89
+ newId?: () => string;
90
+ }
91
+
92
+ /** A sparse patch: the names to pin, and nothing about the names it omits. */
93
+ export interface OverridePatch {
94
+ /** Quotas to pin, by name. */
95
+ quotas?: QuotaMap;
96
+ /** Features to pin, by name. */
97
+ features?: FeatureMap;
98
+ }
99
+
100
+ /** Refuse a patch naming anything the declarations do not mention, naming it and listing what is declared. */
101
+ function requireDeclaredNames(declarations: AllowanceDeclarations, patch: OverridePatch): void {
102
+ const quotas = declaredQuotaNames(declarations);
103
+ for (const name of Object.keys(patch.quotas ?? {})) {
104
+ if (quotas.includes(name)) continue;
105
+ throw new ValidationError({
106
+ message: `No quota "${name}" is declared. Declared quotas: ${quotas.join(", ") || "none"}.`,
107
+ action: "Override a quota this project declares, or declare it in pithy.config.ts first.",
108
+ });
109
+ }
110
+ const features = declaredFeatureNames(declarations);
111
+ for (const name of Object.keys(patch.features ?? {})) {
112
+ if (features.includes(name)) continue;
113
+ throw new ValidationError({
114
+ message: `No feature "${name}" is declared. Declared features: ${features.join(", ") || "none"}.`,
115
+ action: "Override a feature this project declares, or declare it in pithy.config.ts first.",
116
+ });
117
+ }
118
+ }
119
+
120
+ /**
121
+ * The ceiling an override of `name` is bounded by for a subject holding `held`, or undefined for none.
122
+ *
123
+ * **The keys the subject holds decide, because the ceiling belongs to the tier.** `growth` states that its
124
+ * customers' email allowance may be shaded up to 100,000. Among the held keys that declare the quota, the
125
+ * most permissive applies — and a held key declaring the quota with *no* ceiling leaves it unbounded, since a
126
+ * ceiling that gets in the way of a genuine deal is worse than none. A subject holding no key that declares
127
+ * the quota is bounded the same way by every declaration of it.
128
+ */
129
+ export function overrideCeiling(
130
+ declarations: AllowanceDeclarations,
131
+ held: ReadonlySet<string>,
132
+ name: string,
133
+ ): number | undefined {
134
+ const speaking = Object.entries(declarations.entitlements).filter(([, declaration]) => name in declaration.quotas);
135
+ const heldSpeaking = speaking.filter(([key]) => held.has(key));
136
+ const deciding = heldSpeaking.length > 0 ? heldSpeaking : speaking;
137
+ let ceiling: number | undefined;
138
+ for (const [, declaration] of deciding) {
139
+ const stated = declaration.overrideMax?.[name];
140
+ if (stated === undefined) return undefined;
141
+ ceiling = ceiling === undefined ? stated : Math.max(ceiling, stated);
142
+ }
143
+ return ceiling;
144
+ }
145
+
146
+ /** Refuse a quota pin past its ceiling, naming the limit. Unlimited (`null`) is past every ceiling. */
147
+ function requireWithinCeilings(declarations: AllowanceDeclarations, held: ReadonlySet<string>, quotas: QuotaMap): void {
148
+ for (const [name, value] of Object.entries(quotas)) {
149
+ const ceiling = overrideCeiling(declarations, held, name);
150
+ if (ceiling === undefined) continue;
151
+ if (value !== null && value <= ceiling) continue;
152
+ throw new ValidationError({
153
+ message: `"${name}" may be overridden up to ${ceiling}, and ${value === null ? "unlimited" : value} is past it.`,
154
+ action: `Send a number no larger than ${ceiling}, or raise \`overrideMax.${name}\` in pithy.config.ts. Unlimited for every name is \`unrestricted\`.`,
155
+ });
156
+ }
157
+ }
158
+
159
+ /** The three facts an override row holds. */
160
+ interface OverrideState {
161
+ unrestricted: boolean;
162
+ quotas: QuotaMap;
163
+ features: FeatureMap;
164
+ }
165
+
166
+ /** What a set carries besides the change itself. */
167
+ interface OverrideWrite {
168
+ /** Who. */
169
+ subject: PaymentsSubject;
170
+ /** The version the caller read. 0 when it read no override. */
171
+ version: number;
172
+ /** Why. */
173
+ reason: string;
174
+ }
175
+
176
+ /** The stale refusal, with the two versions in `detail`. */
177
+ function stale(subject: PaymentsSubject, sent: number, current: number): PaymentsOverrideStaleError {
178
+ return new PaymentsOverrideStaleError({
179
+ detail: `The override for ${encodeSubjectReference(subject)} is at version ${current}; the write named ${sent}.`,
180
+ });
181
+ }
182
+
183
+ /**
184
+ * Write `next` over the subject's row, but only if the row is still at `write.version`.
185
+ *
186
+ * The compare is the statement's own: an update `WHERE version = ?` on an existing row, and an insert that
187
+ * does nothing on conflict for a row that did not exist. Zero rows written is the stale answer either way,
188
+ * because the two writers it protects were never going to be serialized by anything else.
189
+ */
190
+ async function writeVersioned(
191
+ d1: D1Database,
192
+ write: OverrideWrite,
193
+ change: (before: PaymentsOverride | undefined) => OverrideState,
194
+ options: OverrideWriteOptions,
195
+ ): Promise<OverrideChange> {
196
+ const db = paymentsDatabase(d1);
197
+ const now = options.now ?? new Date();
198
+ const before = await readOverride(db, write.subject);
199
+ const current = overrideVersion(before);
200
+ if (write.version !== current) throw stale(write.subject, write.version, current);
201
+ // Computed from the row this write read and checked, never from an earlier read — so the merge base and
202
+ // the version the `WHERE` compares are the same row.
203
+ const next = change(before);
204
+
205
+ const record = PaymentsOverride.encode({
206
+ id: before?.id ?? (options.newId ?? (() => crypto.randomUUID()))(),
207
+ subjectType: write.subject.subjectType,
208
+ subjectId: write.subject.subjectId,
209
+ unrestricted: next.unrestricted,
210
+ quotas: next.quotas,
211
+ features: next.features,
212
+ version: current + 1,
213
+ reason: write.reason,
214
+ createdAt: before?.createdAt ?? now,
215
+ updatedAt: now,
216
+ });
217
+
218
+ const changes = {
219
+ unrestricted: record.unrestricted,
220
+ quotas: record.quotas,
221
+ features: record.features,
222
+ version: record.version,
223
+ reason: record.reason,
224
+ updatedAt: record.updatedAt,
225
+ };
226
+ const written = await withD1Retry(async () =>
227
+ before === undefined
228
+ ? db
229
+ .insertInto(PAYMENTS_OVERRIDES_TABLE)
230
+ // biome-ignore lint/suspicious/noExplicitAny: the row is the schema's z.input side; Kysely's insert type derives from it.
231
+ .values(record as any)
232
+ .onConflict((oc) => oc.columns(["subjectType", "subjectId"]).doNothing())
233
+ .returning("id")
234
+ .executeTakeFirst()
235
+ : db
236
+ .updateTable(PAYMENTS_OVERRIDES_TABLE)
237
+ // biome-ignore lint/suspicious/noExplicitAny: as above — an encoded row, not the app shape.
238
+ .set(changes as any)
239
+ .where("subjectType", "=", write.subject.subjectType)
240
+ .where("subjectId", "=", write.subject.subjectId)
241
+ .where("version", "=", current)
242
+ .returning("id")
243
+ .executeTakeFirst(),
244
+ );
245
+ if (written === undefined) {
246
+ const moved = await readOverride(db, write.subject);
247
+ throw stale(write.subject, write.version, overrideVersion(moved));
248
+ }
249
+
250
+ const after = await readOverride(db, write.subject);
251
+ if (after === undefined) {
252
+ throw new InternalError({
253
+ message: "The override could not be recorded.",
254
+ detail: `Wrote the override for ${encodeSubjectReference(write.subject)} but could not read it back.`,
255
+ });
256
+ }
257
+ return { before, after };
258
+ }
259
+
260
+ /** The keys a subject holds that grant access now — what a ceiling is decided by. */
261
+ async function heldNow(db: PaymentsDatabase, subject: PaymentsSubject, now: Date): Promise<Set<string>> {
262
+ return grantedEntitlementKeys(await resolveEntitlements(db, subject, now), now);
263
+ }
264
+
265
+ /**
266
+ * Pin numbers and switches for one subject. A merge: the names the patch carries change, every other pin
267
+ * stands, and every name never pinned keeps tracking the plan.
268
+ */
269
+ export async function setOverride(
270
+ d1: D1Database,
271
+ declarations: AllowanceDeclarations,
272
+ input: OverrideWrite & OverridePatch,
273
+ options: OverrideWriteOptions = {},
274
+ ): Promise<OverrideChange> {
275
+ requireDeclaredNames(declarations, input);
276
+ const now = options.now ?? new Date();
277
+ requireWithinCeilings(declarations, await heldNow(paymentsDatabase(d1), input.subject, now), input.quotas ?? {});
278
+ return writeVersioned(
279
+ d1,
280
+ input,
281
+ (before) => ({
282
+ unrestricted: before?.unrestricted ?? false,
283
+ quotas: { ...(before?.quotas ?? {}), ...(input.quotas ?? {}) },
284
+ features: { ...(before?.features ?? {}), ...(input.features ?? {}) },
285
+ }),
286
+ { ...options, now },
287
+ );
288
+ }
289
+
290
+ /**
291
+ * Turn `unrestricted` on or off for one subject. Its own write, behind its own scope: it is the largest grant
292
+ * the kit has, and the only one whose reach grows by itself as names are declared. Pins stand either way.
293
+ * Never bounded by `overrideMax` — being unbounded is what it is for.
294
+ */
295
+ export async function setUnrestricted(
296
+ d1: D1Database,
297
+ input: OverrideWrite & { unrestricted: boolean },
298
+ options: OverrideWriteOptions = {},
299
+ ): Promise<OverrideChange> {
300
+ return writeVersioned(
301
+ d1,
302
+ input,
303
+ (before) => ({ unrestricted: input.unrestricted, quotas: before?.quotas ?? {}, features: before?.features ?? {} }),
304
+ options,
305
+ );
306
+ }
307
+
308
+ /** What a clear names: some pins, or — with neither list — the whole override. */
309
+ export interface OverrideClear {
310
+ /** Who. */
311
+ subject: PaymentsSubject;
312
+ /** The version the caller read. Optional: a clear that names none is not checked. */
313
+ version?: number;
314
+ /** Quota pins to remove. */
315
+ quotas?: readonly string[];
316
+ /** Feature pins to remove. */
317
+ features?: readonly string[];
318
+ /** Why, when the caller says. A clear keeps the last set's reason otherwise. */
319
+ reason?: string;
320
+ }
321
+
322
+ /**
323
+ * Refuse a partial clear that would lift a pin on an `unrestricted` subject to unlimited.
324
+ *
325
+ * On an unrestricted row a pin is the one thing holding a name below unlimited, so removing it is not a move
326
+ * back toward the plan — it is the largest grant the kit has, made one name at a time, by a credential that
327
+ * holds only the clear scope. Turning `unrestricted` off first, behind its own scope, or clearing the whole
328
+ * override, are the two ways that narrow.
329
+ */
330
+ function requireNarrowingClear(row: PaymentsOverride, input: OverrideClear): void {
331
+ if (!row.unrestricted) return;
332
+ const lifted = [
333
+ ...(input.quotas ?? []).filter((name) => name in row.quotas),
334
+ ...(input.features ?? []).filter((name) => name in row.features),
335
+ ];
336
+ if (lifted.length === 0) return;
337
+ throw new ValidationError({
338
+ message: `This subject is unrestricted, so unpinning ${lifted.map((name) => `"${name}"`).join(", ")} would make it unlimited.`,
339
+ action:
340
+ "Turn unrestricted off first through its own route, or clear the whole override — both move the subject back toward its plan.",
341
+ detail: `A clear only narrows. On an unrestricted override a pin is all that holds a name below unlimited, and lifting that is the unrestricted scope's grant.`,
342
+ });
343
+ }
344
+
345
+ /**
346
+ * Remove pins, or the whole override. **Idempotent**: clearing an override that does not exist — or that a
347
+ * clear already emptied — is the state the caller asked for, and answers with nothing changed rather than a
348
+ * 404. A name unpinned resolves from the plan again on the next read.
349
+ *
350
+ * **A whole clear keeps the row**, empty, at the next version — see {@link isEmptyOverride} for why a version
351
+ * must never repeat. Every read treats that row as no override.
352
+ */
353
+ export async function clearOverride(
354
+ d1: D1Database,
355
+ input: OverrideClear,
356
+ options: OverrideWriteOptions = {},
357
+ ): Promise<OverrideChange> {
358
+ const db = paymentsDatabase(d1);
359
+ const before = await readOverride(db, input.subject);
360
+ if (before === undefined || isEmptyOverride(before)) return { before: undefined, after: before };
361
+ if (input.version !== undefined && input.version !== before.version) {
362
+ throw stale(input.subject, input.version, before.version);
363
+ }
364
+
365
+ const whole = input.quotas === undefined && input.features === undefined;
366
+ if (!whole) requireNarrowingClear(before, input);
367
+ return writeVersioned(
368
+ d1,
369
+ // The version just read and checked, so the write's own `WHERE` refuses a row that moved since.
370
+ { subject: input.subject, version: before.version, reason: input.reason ?? before.reason },
371
+ (current) => {
372
+ if (whole) return { unrestricted: false, quotas: {}, features: {} };
373
+ const quotas = { ...(current?.quotas ?? {}) };
374
+ for (const name of input.quotas ?? []) delete quotas[name];
375
+ const features = { ...(current?.features ?? {}) };
376
+ for (const name of input.features ?? []) delete features[name];
377
+ return { unrestricted: current?.unrestricted ?? false, quotas, features };
378
+ },
379
+ options,
380
+ );
381
+ }