@pithy-sh/payments 0.4.0 → 0.6.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 (180) hide show
  1. package/README.md +10 -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 +19 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +34 -1
  16. package/dist/client/hooks.d.ts +20 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +40 -2
  19. package/dist/client/projection.d.ts +29 -0
  20. package/dist/client/projection.d.ts.map +1 -1
  21. package/dist/config/allowances.d.ts +71 -0
  22. package/dist/config/allowances.d.ts.map +1 -0
  23. package/dist/config/allowances.js +115 -0
  24. package/dist/config/config.d.ts +155 -9
  25. package/dist/config/config.d.ts.map +1 -1
  26. package/dist/config/config.js +164 -14
  27. package/dist/data/meterCounter.d.ts +34 -0
  28. package/dist/data/meterCounter.d.ts.map +1 -0
  29. package/dist/data/meterCounter.js +33 -0
  30. package/dist/data/override.d.ts +56 -0
  31. package/dist/data/override.d.ts.map +1 -0
  32. package/dist/data/override.js +58 -0
  33. package/dist/data/period.d.ts +10 -0
  34. package/dist/data/period.d.ts.map +1 -0
  35. package/dist/data/period.js +37 -0
  36. package/dist/data/purchase.d.ts +2 -1
  37. package/dist/data/purchase.d.ts.map +1 -1
  38. package/dist/data/purchase.js +1 -0
  39. package/dist/data/tables.d.ts +17 -1
  40. package/dist/data/tables.d.ts.map +1 -1
  41. package/dist/data/tables.js +24 -4
  42. package/dist/data/usageReport.d.ts +68 -0
  43. package/dist/data/usageReport.d.ts.map +1 -0
  44. package/dist/data/usageReport.js +55 -0
  45. package/dist/data/usageRun.d.ts +77 -0
  46. package/dist/data/usageRun.d.ts.map +1 -0
  47. package/dist/data/usageRun.js +50 -0
  48. package/dist/data/webhookEvent.d.ts +1 -1
  49. package/dist/entitlement/allowance.d.ts +100 -0
  50. package/dist/entitlement/allowance.d.ts.map +1 -0
  51. package/dist/entitlement/allowance.js +171 -0
  52. package/dist/entitlement/manual.d.ts +5 -5
  53. package/dist/entitlement/manual.js +3 -3
  54. package/dist/entitlement/meter.d.ts +98 -0
  55. package/dist/entitlement/meter.d.ts.map +1 -0
  56. package/dist/entitlement/meter.js +177 -0
  57. package/dist/entitlement/override.d.ts +119 -0
  58. package/dist/entitlement/override.d.ts.map +1 -0
  59. package/dist/entitlement/override.js +256 -0
  60. package/dist/entitlement/resolver.d.ts +2 -1
  61. package/dist/entitlement/resolver.d.ts.map +1 -1
  62. package/dist/entitlement/resolver.js +32 -1
  63. package/dist/error/errors.d.ts +23 -3
  64. package/dist/error/errors.d.ts.map +1 -1
  65. package/dist/error/errors.js +35 -2
  66. package/dist/http/responses.d.ts +367 -0
  67. package/dist/http/responses.d.ts.map +1 -1
  68. package/dist/http/responses.js +146 -7
  69. package/dist/http/routes.d.ts.map +1 -1
  70. package/dist/http/routes.js +270 -16
  71. package/dist/http/schemas.d.ts +54 -0
  72. package/dist/http/schemas.d.ts.map +1 -1
  73. package/dist/http/schemas.js +61 -2
  74. package/dist/http/scopes.d.ts +25 -0
  75. package/dist/http/scopes.d.ts.map +1 -1
  76. package/dist/http/scopes.js +60 -1
  77. package/dist/http/view.d.ts +22 -4
  78. package/dist/http/view.d.ts.map +1 -1
  79. package/dist/http/view.js +88 -7
  80. package/dist/index.d.ts +2 -1
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +3 -2
  83. package/dist/migrations/0002_allowances.d.ts +26 -0
  84. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  85. package/dist/migrations/0002_allowances.js +62 -0
  86. package/dist/peer.d.ts +2 -1
  87. package/dist/peer.d.ts.map +1 -1
  88. package/dist/projection/event.d.ts +1 -0
  89. package/dist/projection/event.d.ts.map +1 -1
  90. package/dist/projection/event.js +1 -0
  91. package/dist/projection/writer.d.ts.map +1 -1
  92. package/dist/projection/writer.js +3 -1
  93. package/dist/rails/contract.d.ts +6 -0
  94. package/dist/rails/contract.d.ts.map +1 -1
  95. package/dist/rails/google/playApi.d.ts.map +1 -1
  96. package/dist/rails/google/playApi.js +2 -0
  97. package/dist/rails/paddle/objects.d.ts +2 -0
  98. package/dist/rails/paddle/objects.d.ts.map +1 -1
  99. package/dist/rails/paddle/objects.js +7 -2
  100. package/dist/rails/paddle/usage.d.ts +11 -0
  101. package/dist/rails/paddle/usage.d.ts.map +1 -0
  102. package/dist/rails/paddle/usage.js +49 -0
  103. package/dist/rails/quantity.d.ts +12 -0
  104. package/dist/rails/quantity.d.ts.map +1 -0
  105. package/dist/rails/quantity.js +16 -0
  106. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  107. package/dist/rails/stripe/checkout.js +1 -1
  108. package/dist/rails/stripe/objects.d.ts.map +1 -1
  109. package/dist/rails/stripe/objects.js +3 -0
  110. package/dist/rails/stripe/usage.d.ts +10 -0
  111. package/dist/rails/stripe/usage.d.ts.map +1 -0
  112. package/dist/rails/stripe/usage.js +49 -0
  113. package/dist/usage/pass.d.ts +120 -0
  114. package/dist/usage/pass.d.ts.map +1 -0
  115. package/dist/usage/pass.js +363 -0
  116. package/dist/usage/reporter.d.ts +36 -0
  117. package/dist/usage/reporter.d.ts.map +1 -0
  118. package/dist/usage/reporter.js +2 -0
  119. package/dist/version.generated.d.ts +1 -1
  120. package/dist/version.generated.js +1 -1
  121. package/dist/workflows/report.d.ts.map +1 -1
  122. package/dist/workflows/specs.d.ts +28 -0
  123. package/dist/workflows/specs.d.ts.map +1 -1
  124. package/dist/workflows/specs.js +26 -1
  125. package/dist/workflows/usage.d.ts +38 -0
  126. package/dist/workflows/usage.d.ts.map +1 -0
  127. package/dist/workflows/usage.js +77 -0
  128. package/dist/workflows/worker.js +2 -2
  129. package/docs/entitlements.md +249 -0
  130. package/docs/lemon-squeezy.md +1 -0
  131. package/docs/paddle.md +1 -0
  132. package/package.json +5 -5
  133. package/pithy.manifest.json +3 -8
  134. package/src/admin/coverage.ts +28 -0
  135. package/src/admin/read.ts +173 -1
  136. package/src/audit/actions.ts +13 -0
  137. package/src/capability.ts +87 -9
  138. package/src/client/api.ts +44 -0
  139. package/src/client/hooks.ts +44 -0
  140. package/src/client/projection.ts +31 -0
  141. package/src/config/allowances.ts +211 -0
  142. package/src/config/config.ts +283 -15
  143. package/src/data/meterCounter.ts +38 -0
  144. package/src/data/override.ts +74 -0
  145. package/src/data/period.ts +53 -0
  146. package/src/data/purchase.ts +9 -0
  147. package/src/data/tables.ts +25 -1
  148. package/src/data/usageReport.ts +64 -0
  149. package/src/data/usageRun.ts +66 -0
  150. package/src/entitlement/allowance.ts +213 -0
  151. package/src/entitlement/manual.ts +6 -6
  152. package/src/entitlement/meter.ts +252 -0
  153. package/src/entitlement/override.ts +381 -0
  154. package/src/entitlement/resolver.ts +43 -2
  155. package/src/error/errors.ts +48 -4
  156. package/src/http/responses.ts +305 -4
  157. package/src/http/routes.ts +365 -11
  158. package/src/http/schemas.ts +139 -1
  159. package/src/http/scopes.ts +68 -0
  160. package/src/http/view.ts +112 -7
  161. package/src/index.ts +18 -0
  162. package/src/migrations/0002_allowances.ts +149 -0
  163. package/src/projection/event.ts +9 -0
  164. package/src/projection/writer.ts +4 -0
  165. package/src/rails/contract.ts +6 -0
  166. package/src/rails/google/playApi.ts +2 -0
  167. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  168. package/src/rails/paddle/objects.ts +6 -0
  169. package/src/rails/paddle/usage.ts +66 -0
  170. package/src/rails/quantity.ts +14 -0
  171. package/src/rails/stripe/checkout.ts +3 -1
  172. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  173. package/src/rails/stripe/objects.ts +4 -0
  174. package/src/rails/stripe/usage.ts +61 -0
  175. package/src/usage/pass.ts +539 -0
  176. package/src/usage/reporter.ts +38 -0
  177. package/src/version.generated.ts +1 -1
  178. package/src/workflows/report.ts +4 -2
  179. package/src/workflows/specs.ts +34 -0
  180. package/src/workflows/usage.ts +97 -0
@@ -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
+ }
@@ -2,11 +2,18 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
5
- import type { Entitlement, EntitlementHolder, EntitlementResolver } from "@pithy-sh/core/src/entitlement/entitlement";
5
+ import type {
6
+ Entitlement,
7
+ EntitlementHolder,
8
+ EntitlementResolver,
9
+ MeterLimit,
10
+ } from "@pithy-sh/core/src/entitlement/entitlement";
6
11
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
7
12
  import { encodeSubjectReference, type PaymentsSubject } from "../data/subject";
8
13
  import type { PaymentsDatabase } from "../data/tables";
9
14
  import { resolveEntitlements } from "../projection/resolve";
15
+ import { requireDeclaredFeature, requireDeclaredQuota, resolveFeature, resolveQuota } from "./allowance";
16
+ import { allowanceInputFor, meterLimitFor, type PaymentsAllowances } from "./meter";
10
17
  import { type PaymentsSubjectSeam, resolvePaymentsSubject } from "./subjectSeam";
11
18
 
12
19
  /**
@@ -81,7 +88,11 @@ export function createPaymentsEntitlementResolver(
81
88
  * neither is a composition problem, and reporting `null` here would send an operator looking for a missing
82
89
  * capability.
83
90
  */
84
- export function installEntitlementResolver(database: string, seam: PaymentsSubjectSeam): PithyMiddleware {
91
+ export function installEntitlementResolver(
92
+ database: string,
93
+ seam: PaymentsSubjectSeam,
94
+ allowances: PaymentsAllowances = { declarations: { entitlements: {} }, meters: {} },
95
+ ): PithyMiddleware {
85
96
  return (app) => {
86
97
  app.use("*", async (c, next) => {
87
98
  // **One resolution per request, shared by `list()` and `holder()`.** The seam is the adopter's and
@@ -93,8 +104,38 @@ export function installEntitlementResolver(database: string, seam: PaymentsSubje
93
104
  resolving ??= resolvePaymentsSubject(c, seam);
94
105
  return resolving;
95
106
  };
107
+ /** The database, or the wiring fault — checked only once a read actually needs one. */
108
+ const appDatabase = (): PaymentsDatabase => {
109
+ const db = (c.var.db as Record<string, PaymentsDatabase>)[database];
110
+ if (!db) {
111
+ throw new InternalError({
112
+ message: "Payments is not configured.",
113
+ action: "Bind a D1 database named DB in wrangler.jsonc.",
114
+ detail: `No \`${database}\` database on c.var.db; payments cannot resolve allowances.`,
115
+ });
116
+ }
117
+ return db;
118
+ };
96
119
  c.set("entitlements", {
97
120
  provider: PAYMENTS_ENTITLEMENT_PROVIDER,
121
+ // **The name is checked before anything is read**, so a typo is a hard failure on every request
122
+ // rather than only on the ones that reach D1 — and never a 0 or an unlimited.
123
+ quota: async (name: string): Promise<number | null> => {
124
+ requireDeclaredQuota(allowances.declarations, name);
125
+ const subject = await subjectOnce();
126
+ const input = await allowanceInputFor(subject && appDatabase(), allowances.declarations, subject, new Date());
127
+ return resolveQuota(input, name).effective.value;
128
+ },
129
+ feature: async (name: string): Promise<boolean> => {
130
+ requireDeclaredFeature(allowances.declarations, name);
131
+ const subject = await subjectOnce();
132
+ const input = await allowanceInputFor(subject && appDatabase(), allowances.declarations, subject, new Date());
133
+ return resolveFeature(input, name).effective.value;
134
+ },
135
+ meterLimit: async (meter: string): Promise<MeterLimit> => {
136
+ const subject = await subjectOnce();
137
+ return meterLimitFor(appDatabase(), allowances, subject, meter, new Date());
138
+ },
98
139
  // Who the read answered for, for the log and the trail alone. `undefined` is a real answer and a
99
140
  // different one from "holds nothing": it is a caller acting for no organization, which is what
100
141
  // lets core's denial say so instead of reporting an empty list twice over.
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { PithyError } from "@pithy-sh/core/src/error/pithyError";
5
5
  import type { MessageParams } from "@pithy-sh/core/src/i18n/catalog";
6
+ import type { UnmarkedString } from "@pithy-sh/core/src/privacy/types";
6
7
 
7
8
  /**
8
9
  * `@pithy-sh/payments` throw sugar. The `payments/*` codes live in core's closed `KitErrorPayload` union
@@ -22,9 +23,9 @@ import type { MessageParams } from "@pithy-sh/core/src/i18n/catalog";
22
23
  */
23
24
 
24
25
  interface PaymentsErrorArgs {
25
- message?: string;
26
- action?: string;
27
- detail?: string;
26
+ message?: UnmarkedString;
27
+ action?: UnmarkedString;
28
+ detail?: UnmarkedString;
28
29
  /**
29
30
  * Values a translating client interpolates into its own wording for this code. Client-facing, so —
30
31
  * unlike `action` and `detail` — these cross the boundary with `message`.
@@ -256,7 +257,7 @@ export class PaymentsEntitlementNotInCatalogError extends PithyError {
256
257
  message: args.message ?? "That entitlement is not one this project defines.",
257
258
  action:
258
259
  args.action ??
259
- "Grant a key one of the catalog's products lists, or declare it in `manualEntitlements` in pithy.config.ts.",
260
+ "Grant a key the `entitlements` map in pithy.config.ts declares, or declare it there — a declared key no product sells is grantable by hand.",
260
261
  detail: args.detail,
261
262
  params: args.params,
262
263
  },
@@ -419,3 +420,46 @@ export class PaymentsSubscriptionChangeRefusedError extends PithyError {
419
420
  );
420
421
  }
421
422
  }
423
+
424
+ /**
425
+ * An override set named a version behind the row it would change. Two operators share one customer: both
426
+ * opened `emails`, and the second would silently win while the first believes they succeeded. So the set is
427
+ * refused and nothing is written, and the caller re-reads before it tries again.
428
+ */
429
+ export class PaymentsOverrideStaleError extends PithyError {
430
+ constructor(args: PaymentsErrorArgs = {}, options?: { cause?: unknown }) {
431
+ super(
432
+ {
433
+ code: "payments/override_stale",
434
+ status: 409,
435
+ message: args.message ?? "That override changed since it was read.",
436
+ action: args.action ?? "Read the subject's entitlements again, then set the override against the new version.",
437
+ detail: args.detail,
438
+ params: args.params,
439
+ },
440
+ options,
441
+ );
442
+ }
443
+ }
444
+
445
+ /**
446
+ * An enforced meter refused: the subject's effective quota for this period does not allow more. 402, because
447
+ * the caller's plan does not allow it and the remedy is a purchase — a bigger tier, or a pinned number.
448
+ */
449
+ export class PaymentsQuotaExceededError extends PithyError {
450
+ constructor(args: PaymentsErrorArgs = {}, options?: { cause?: unknown }) {
451
+ super(
452
+ {
453
+ code: "payments/quota_exceeded",
454
+ status: 402,
455
+ message: args.message ?? "This plan's allowance is used up for this period.",
456
+ action:
457
+ args.action ??
458
+ "Upgrade the plan, or pin a larger allowance for this subject from the control plane. The meter resets when the period does.",
459
+ detail: args.detail,
460
+ params: args.params,
461
+ },
462
+ options,
463
+ );
464
+ }
465
+ }