@pithy-sh/payments 0.6.0 → 0.7.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 (87) hide show
  1. package/README.md +6 -1
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +13 -7
  4. package/dist/admin/read.d.ts +60 -0
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +86 -2
  7. package/dist/audit/actions.d.ts +5 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +6 -1
  10. package/dist/capability.d.ts +3 -3
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +14 -7
  13. package/dist/client/api.d.ts +25 -9
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +68 -12
  16. package/dist/client/hooks.d.ts +27 -39
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +166 -315
  19. package/dist/client/projection.d.ts +25 -18
  20. package/dist/client/projection.d.ts.map +1 -1
  21. package/dist/client/railChoice.d.ts +46 -0
  22. package/dist/client/railChoice.d.ts.map +1 -0
  23. package/dist/client/railChoice.js +48 -0
  24. package/dist/data/webhookEvent.d.ts +67 -0
  25. package/dist/data/webhookEvent.d.ts.map +1 -1
  26. package/dist/data/webhookEvent.js +76 -1
  27. package/dist/http/responses.d.ts +64 -0
  28. package/dist/http/responses.d.ts.map +1 -1
  29. package/dist/http/responses.js +34 -1
  30. package/dist/http/routes.d.ts +1 -0
  31. package/dist/http/routes.d.ts.map +1 -1
  32. package/dist/http/routes.js +64 -11
  33. package/dist/http/schemas.d.ts +19 -0
  34. package/dist/http/schemas.d.ts.map +1 -1
  35. package/dist/http/schemas.js +18 -1
  36. package/dist/http/scopes.d.ts +15 -6
  37. package/dist/http/scopes.d.ts.map +1 -1
  38. package/dist/http/scopes.js +55 -5
  39. package/dist/http/view.d.ts +9 -2
  40. package/dist/http/view.d.ts.map +1 -1
  41. package/dist/http/view.js +29 -1
  42. package/dist/http/webhookGuard.d.ts +7 -1
  43. package/dist/http/webhookGuard.d.ts.map +1 -1
  44. package/dist/http/webhookGuard.js +3 -2
  45. package/dist/migrations/0003_webhook_targets.d.ts +19 -0
  46. package/dist/migrations/0003_webhook_targets.d.ts.map +1 -0
  47. package/dist/migrations/0003_webhook_targets.js +29 -0
  48. package/dist/processing/activities.d.ts +9 -0
  49. package/dist/processing/activities.d.ts.map +1 -0
  50. package/dist/processing/activities.js +30 -0
  51. package/dist/projection/orphans.d.ts.map +1 -1
  52. package/dist/projection/orphans.js +15 -6
  53. package/dist/projection/targets.d.ts +50 -0
  54. package/dist/projection/targets.d.ts.map +1 -0
  55. package/dist/projection/targets.js +50 -0
  56. package/dist/purge/contribution.d.ts +32 -0
  57. package/dist/purge/contribution.d.ts.map +1 -0
  58. package/dist/purge/contribution.js +120 -0
  59. package/dist/version.generated.d.ts +1 -1
  60. package/dist/version.generated.js +1 -1
  61. package/dist/workflows/paddleSweep.d.ts.map +1 -1
  62. package/dist/workflows/paddleSweep.js +20 -9
  63. package/docs/lemon-squeezy.md +1 -1
  64. package/docs/paddle.md +2 -0
  65. package/package.json +6 -4
  66. package/src/admin/coverage.ts +13 -9
  67. package/src/admin/read.ts +135 -0
  68. package/src/audit/actions.ts +5 -0
  69. package/src/capability.ts +25 -15
  70. package/src/client/api.ts +74 -11
  71. package/src/client/hooks.ts +206 -301
  72. package/src/client/projection.ts +25 -18
  73. package/src/client/railChoice.ts +72 -0
  74. package/src/data/webhookEvent.ts +115 -0
  75. package/src/http/responses.ts +66 -0
  76. package/src/http/routes.ts +73 -11
  77. package/src/http/schemas.ts +26 -0
  78. package/src/http/scopes.ts +58 -6
  79. package/src/http/view.ts +31 -1
  80. package/src/http/webhookGuard.ts +23 -3
  81. package/src/migrations/0003_webhook_targets.ts +34 -0
  82. package/src/processing/activities.ts +34 -0
  83. package/src/projection/orphans.ts +28 -11
  84. package/src/projection/targets.ts +66 -0
  85. package/src/purge/contribution.ts +135 -0
  86. package/src/version.generated.ts +1 -1
  87. package/src/workflows/paddleSweep.ts +39 -14
@@ -8,11 +8,10 @@
8
8
  * catalog of one product infers one product's shape, and every branch the next product would have taken
9
9
  * — an empty `entitlements`, a SKU on a rail the first product does not sell — is simply not in it.
10
10
  *
11
- * **It is annotated on the `.map` callback, not on the array it builds.** Measured, and the difference
12
- * matters: `const products: PaymentsClientProduct[] = …map(…)` type-checks the *result*, by which point
13
- * the element literals are no longer fresh, so a product that grew an `apple` SKU passed silently. On the
14
- * callback's own return type the literal is checked where it is written, and the store-only field is a
15
- * compile error at the line that added it.
11
+ * **It is annotated on the `.map` callback, not on the array it builds.** `const products:
12
+ * PaymentsClientProduct[] = …map(…)` type-checks the *result*, by which point the element literals are no
13
+ * longer fresh, so an extra field passes silently. On the callback's own return type the literal is
14
+ * checked where it is written, and an undeclared field is a compile error at the line that added it.
16
15
  */
17
16
  export type PaymentsClientProduct = {
18
17
  /** The logical product id — what `/payments/checkout` is asked for. */
@@ -24,13 +23,21 @@ export type PaymentsClientProduct = {
24
23
  /** The display name a paywall renders. */
25
24
  name: string;
26
25
  /**
27
- * This product's SKU on each web rail, or null where it is not sold. Keyed by rail rather than one
28
- * field per rail, so a screen asks `skus[rail]` and a new rail cannot leave a `purchasable()` check
29
- * silently out of date. Every id here is publishable by design — each is what a checkout names.
30
- *
31
- * Apple's and Google's product ids are deliberately absent: a browser cannot open either store.
26
+ * This product's SKU on each rail, or null where it is not sold. Keyed by rail rather than one field per
27
+ * rail, so a screen asks `skus[rail]` and a new rail cannot leave a `purchasable()` check silently out of
28
+ * date. Every id here is publishable by design — each is what a checkout or a store purchase names.
32
29
  */
33
30
  skus: {
31
+ /**
32
+ * The App Store product id a native app buys with StoreKit. Optional: a Worker on an older kit does
33
+ * not project it, and absent reads the same as null.
34
+ */
35
+ apple?: string | null;
36
+ /**
37
+ * The Play product id a native app buys with Play Billing. Optional: a Worker on an older kit does not
38
+ * project it, and absent reads the same as null.
39
+ */
40
+ google?: string | null;
34
41
  /** The Stripe price id. */
35
42
  stripe: string | null;
36
43
  /** The Lemon Squeezy variant id. */
@@ -71,8 +78,8 @@ export type PaymentsClientEntitlement = {
71
78
  * Nothing sensitive is in reach of the producer to begin with: Apple's issuer key, Google's service
72
79
  * account, and Stripe's secret and signing keys live in the secrets store behind
73
80
  * `paymentsSecretsRegistry`, not in the config the closure can see. What this type covers is the rest of
74
- * the catalog — the `grants` block and the store-only SKUs, which are omissions of judgment rather than
75
- * of reach, and so are the ones worth writing down.
81
+ * the catalog — the `grants` block, an omission of judgment rather than of reach, and so the one worth
82
+ * writing down.
76
83
  *
77
84
  * **`billingSubject` is a third omission of judgment, and it is deliberate.** The subject *id* obviously
78
85
  * never crosses — it is a fact about one caller, and this projection is inlined into a bundle every caller
@@ -106,12 +113,12 @@ export type PaymentsClientProjection =
106
113
  /**
107
114
  * Which rails this project sells through. Apple and Google are display-only on the web — a
108
115
  * paywall shows such a product as owned-elsewhere rather than offering a buy button nothing on
109
- * the web can honor.
116
+ * the web can honor. A native app buys on them.
110
117
  */
111
118
  rails: {
112
- /** Whether the App Store rail is on. Display-only in a browser. */
119
+ /** Whether the App Store rail is on. Display-only in a browser; a native app buys on it. */
113
120
  apple: boolean;
114
- /** Whether the Play Store rail is on. Display-only in a browser. */
121
+ /** Whether the Play Store rail is on. Display-only in a browser; a native app buys on it. */
115
122
  google: boolean;
116
123
  /** Whether the Stripe rail is on. */
117
124
  stripe: boolean;
@@ -143,9 +150,9 @@ export type PaymentsClientProjection =
143
150
  /** Where the payments routes mount, e.g. `/payments`. */
144
151
  basePath: string;
145
152
  /**
146
- * The catalog, browser-safe, in the order the adopter wrote it. A web rail's price id is
147
- * publishable by design — a checkout names one. Apple's and Google's SKUs, and anything a
148
- * purchase fulfills beyond its entitlements, stay server-side.
153
+ * The catalog, client-safe, in the order the adopter wrote it. Every rail's SKU is publishable by
154
+ * design — a checkout or a store purchase names one. Anything a purchase fulfills beyond its
155
+ * entitlements stays server-side.
149
156
  */
150
157
  products: PaymentsClientProduct[];
151
158
  /**
@@ -0,0 +1,72 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { PaymentsClientRail, PaymentsHostedRail } from "./api";
5
+ import type { PaymentsClientProduct } from "./projection";
6
+
7
+ /** The platform a screen renders on, as React Native's `Platform.OS` names the three it supports. */
8
+ export type PaymentsPlatform = "ios" | "android" | "web";
9
+
10
+ /** The rail a platform sells through, or `none` for a consumption-only build: plan shown, nothing sold. */
11
+ export type PaymentsRailChoice = PaymentsClientRail | "none";
12
+
13
+ /** One rail per platform, as a native app's `pithy-config` names them. */
14
+ export type PaymentsPlatformRails = Readonly<Record<PaymentsPlatform, PaymentsRailChoice>>;
15
+
16
+ /**
17
+ * How a screen sells one product on this platform.
18
+ *
19
+ * `store` buys in the app through StoreKit or Play Billing, with the store's own product id. `hosted` asks
20
+ * the Worker for a checkout on that rail and opens it — in the browser on native. `none` is the
21
+ * consumption-only build: no price, no button, no link. `unavailable` is a product this platform cannot sell:
22
+ * its rail is off on the backend, the product has no SKU there, or the rail is a store this platform does
23
+ * not run.
24
+ */
25
+ export type PaymentsPurchasePath =
26
+ | { kind: "store"; rail: "apple" | "google"; sku: string }
27
+ | { kind: "hosted"; rail: PaymentsHostedRail }
28
+ | { kind: "none" }
29
+ | { kind: "unavailable" };
30
+
31
+ /** The store each platform runs. The web runs neither. */
32
+ const PLATFORM_STORE: Readonly<Record<PaymentsPlatform, "apple" | "google" | null>> = {
33
+ ios: "apple",
34
+ android: "google",
35
+ web: null,
36
+ };
37
+
38
+ /** The rails a platform defaults to: its own store on iOS and Android, and the project's web rail on the web. */
39
+ export function defaultPlatformRails(web: PaymentsRailChoice): PaymentsPlatformRails {
40
+ return { ios: "apple", android: "google", web };
41
+ }
42
+
43
+ /** A SKU worth buying with: a non-empty string. Absent, null and empty all mean not sold there. */
44
+ function skuOf(value: string | null | undefined): string | null {
45
+ return typeof value === "string" && value !== "" ? value : null;
46
+ }
47
+
48
+ /**
49
+ * How to sell `product` on `platform`, given the rail each platform is set to and the rails the backend has on.
50
+ *
51
+ * Pure, so a screen calls it while rendering and a test states every case. The backend's refusal is still the
52
+ * boundary: this only decides what a screen offers.
53
+ */
54
+ export function purchasePathFor(input: {
55
+ platform: PaymentsPlatform;
56
+ rails: PaymentsPlatformRails;
57
+ enabled: Readonly<Record<PaymentsClientRail, boolean>>;
58
+ product: Pick<PaymentsClientProduct, "skus">;
59
+ }): PaymentsPurchasePath {
60
+ const { platform, rails, enabled, product } = input;
61
+ const rail = rails[platform];
62
+ if (rail === "none") return { kind: "none" };
63
+ if (!enabled[rail]) return { kind: "unavailable" };
64
+
65
+ if (rail === "apple" || rail === "google") {
66
+ if (PLATFORM_STORE[platform] !== rail) return { kind: "unavailable" };
67
+ const sku = skuOf(product.skus[rail]);
68
+ return sku === null ? { kind: "unavailable" } : { kind: "store", rail, sku };
69
+ }
70
+
71
+ return skuOf(product.skus[rail]) === null ? { kind: "unavailable" } : { kind: "hosted", rail };
72
+ }
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { SQLiteDate, sqliteJson } from "@pithy-sh/core/src/data/codecs";
5
+ import { KitErrorPayload } from "@pithy-sh/core/src/error/payload";
5
6
  import { z } from "zod";
6
7
  import { PaymentsRail } from "./rail";
7
8
 
@@ -10,6 +11,52 @@ const NotificationPayload = z
10
11
  .record(z.string(), z.unknown())
11
12
  .describe("The notification body as received, before any rail-specific interpretation.");
12
13
 
14
+ /**
15
+ * What one event changed when it projected — every purchase row it wrote, split by whether the row renews.
16
+ *
17
+ * **A list, because one notification can touch several rows.** Lemon Squeezy's refund writes the invoice row
18
+ * and the subscription's standing row from one delivery, and a list of one would have to pick. Split the way
19
+ * the management reads split — `payments:purchases:read` and `payments:subscriptions:read` — so a client
20
+ * holding only the narrower grant can still follow the ids it is allowed to open. Disjoint: a subscription
21
+ * row's id is in `subscriptionIds` and nowhere else.
22
+ *
23
+ * A row the projection read and left alone — an exact replay, an event older than the row — is not a row
24
+ * this event changed, so it is not listed. Two empty lists is a real answer: the event finished and changed
25
+ * nothing. That is a different fact from the column being null, which is an event finished before #830
26
+ * recorded anything.
27
+ */
28
+ export const PaymentsWebhookEventTargets = z
29
+ .object({
30
+ purchaseIds: z
31
+ .array(z.string())
32
+ .describe("The purchase rows this event created or moved that do not renew — their own UUIDs."),
33
+ subscriptionIds: z
34
+ .array(z.string())
35
+ .describe("The purchase rows this event created or moved that renew — the ids the subscription read lists."),
36
+ })
37
+ .describe("Every purchase and subscription row one event changed when it projected.");
38
+ export type PaymentsWebhookEventTargets = z.output<typeof PaymentsWebhookEventTargets>;
39
+
40
+ /** The `projected_targets` column: the targets as JSON text, Zod-validated on write and on read. */
41
+ const WebhookEventTargetsColumn = sqliteJson(PaymentsWebhookEventTargets);
42
+
43
+ /**
44
+ * The column value a finishing writer stores. One encoder for the three writers that finish an event — the
45
+ * webhook, the Paddle sweep, the orphan repair — so they cannot write the JSON three ways, and it goes
46
+ * through the codec the row schema reads it back with.
47
+ */
48
+ export function encodeWebhookEventTargets(targets: PaymentsWebhookEventTargets): string {
49
+ // The codec's encode side is the JSON text; its declared output admits the decoded object too, because the
50
+ // decode side accepts an already-parsed value.
51
+ return WebhookEventTargetsColumn.encode(targets) as string;
52
+ }
53
+
54
+ /** The answer for an event that finished and changed nothing — recorded, and empty. */
55
+ export const NO_WEBHOOK_EVENT_TARGETS: PaymentsWebhookEventTargets = Object.freeze({
56
+ purchaseIds: [],
57
+ subscriptionIds: [],
58
+ }) as PaymentsWebhookEventTargets;
59
+
13
60
  /**
14
61
  * One received provider notification — the row in `pithy_payments_webhook_events`, keyed
15
62
  * `UNIQUE (rail, providerEventId)`.
@@ -78,6 +125,11 @@ export const PaymentsWebhookEvent = z
78
125
  .describe(
79
126
  "How many times a repair pass has tried this event and failed. Optional because the webhook path neither retries nor counts, and the column defaults to 0 for it; the sweep uses it to bound how long one unprojectable event may hold the stream up before it is quarantined.",
80
127
  ),
128
+ projectedTargets: WebhookEventTargetsColumn.nullable()
129
+ .optional()
130
+ .describe(
131
+ "What this event changed when it finished — every purchase and subscription row it wrote — or null when nothing was recorded: an event not finished yet, or one finished before `payments_0003_webhook_targets` added the column. Written by every finishing path, so it is the join from a notification to the rows it explains.",
132
+ ),
81
133
  createdAt: SQLiteDate.describe("When this row was written."),
82
134
  })
83
135
  .describe("One received provider notification — the row in `pithy_payments_webhook_events`, the replay source.");
@@ -125,6 +177,33 @@ export function webhookEventState(row: PaymentsWebhookEventProgress): PaymentsWe
125
177
  return "pending";
126
178
  }
127
179
 
180
+ /**
181
+ * What a management read says a recorded delivery became (#830). **Three answers**, the ones a client acts on:
182
+ *
183
+ * - `projected` — finished: it became a purchase, or there was nothing in it to become one. What it changed is
184
+ * in `projectedTargets`.
185
+ * - `pending` — arrived and not finished, whether or not it has been tried. `attempts` says how often.
186
+ * - `abandoned` — a repair pass gave up on it. Still repairable by a delivery, and the reason is on the row.
187
+ *
188
+ * `failed` and `pending` are one answer here because the difference between them is a repair pass's
189
+ * bookkeeping, and the count beside the state already carries it.
190
+ */
191
+ export type PaymentsWebhookEventReadState = "projected" | "pending" | "abandoned";
192
+
193
+ /** Classify one recorded delivery for a management read. Derived from {@link webhookEventState}, never stored. */
194
+ export function webhookEventReadState(row: PaymentsWebhookEventProgress): PaymentsWebhookEventReadState {
195
+ const state = webhookEventState(row);
196
+ switch (state) {
197
+ case "finished":
198
+ return "projected";
199
+ case "pending":
200
+ case "failed":
201
+ return "pending";
202
+ case "abandoned":
203
+ return "abandoned";
204
+ }
205
+ }
206
+
128
207
  /**
129
208
  * May a redelivery be answered as a duplicate without running anything?
130
209
  *
@@ -160,6 +239,42 @@ export function isWebhookEventFinished(state: PaymentsWebhookEventState): boolea
160
239
  */
161
240
  export const WEBHOOK_EVENT_ORPHANED = "orphaned:";
162
241
 
242
+ /**
243
+ * The word the Paddle sweep writes at the head of `error` when it gives up on an event after a bounded number
244
+ * of attempts. Here beside {@link WEBHOOK_EVENT_ORPHANED} rather than private to the sweep, because a reader —
245
+ * {@link webhookEventErrorCode} — names it, and a writer and a reader spelling one word twice drift.
246
+ */
247
+ export const WEBHOOK_EVENT_QUARANTINED = "quarantined";
248
+
249
+ /** Every code the kit defines. A prefix is published only when it is one of these. */
250
+ const KIT_ERROR_CODES: ReadonlySet<string> = new Set(
251
+ KitErrorPayload.options.map((member) => member.shape.code.value as string),
252
+ );
253
+
254
+ /**
255
+ * What a management read may say about a stored `error`: **its code, never its sentence**. (#830)
256
+ *
257
+ * The column is operator text, and the sentence after the code is throw-site context — a store's
258
+ * transaction ids, an amount, a SKU — which is exactly what `clientError` strips from every other surface.
259
+ * So the read publishes a classification and nothing more:
260
+ *
261
+ * - the kit error code a projection failure was recorded under (`payments/product_not_found`), and only
262
+ * when the prefix is one the kit's own union defines — so text that merely *looks* like a code is not
263
+ * promoted onto the wire by its shape;
264
+ * - `orphaned` or `quarantined`, the two markers this package writes for itself;
265
+ * - `unclassified` for everything else — a rail's note, prose from an older build.
266
+ *
267
+ * Null when there is no error at all.
268
+ */
269
+ export function webhookEventErrorCode(error: string | null | undefined): string | null {
270
+ if (error === null || error === undefined) return null;
271
+ if (error.startsWith(WEBHOOK_EVENT_ORPHANED)) return "orphaned";
272
+ if (error.startsWith(`${WEBHOOK_EVENT_QUARANTINED}:`)) return "quarantined";
273
+ const colon = error.indexOf(":");
274
+ const head = colon === -1 ? error : error.slice(0, colon);
275
+ return KIT_ERROR_CODES.has(head) ? head : "unclassified";
276
+ }
277
+
163
278
  /**
164
279
  * Is this event outstanding for want of an owner, rather than for want of anything else?
165
280
  *
@@ -1402,6 +1402,72 @@ export const PaymentsAdminUsageRunsResponse = z
1402
1402
  .describe("A page of the usage-reporting run log.");
1403
1403
  export type PaymentsAdminUsageRunsResponse = z.output<typeof PaymentsAdminUsageRunsResponse>;
1404
1404
 
1405
+ /**
1406
+ * One recorded notification, as a management client sees it (#830).
1407
+ *
1408
+ * **What crosses is a classification, never a document.** The provider's payload carries the customer's
1409
+ * details and is not selected; the event's type is read out of it by the database and published only in the
1410
+ * shape of an event name. The stored `error` is the store's or the throw site's sentence, so it crosses as its
1411
+ * code alone — the way a refund refused by the store crosses with no reason.
1412
+ *
1413
+ * New in #830, so every field is required: no Worker answered this route before it existed.
1414
+ */
1415
+ export const PaymentsAdminWebhookEventView = z
1416
+ .object({
1417
+ id: z.string().describe("The event row's UUID."),
1418
+ rail: PaymentsRail.describe("Which store sent the notification."),
1419
+ providerEventId: z
1420
+ .string()
1421
+ .describe("The store's own id for the notification — what an operator searches the store's dashboard for."),
1422
+ eventType: z
1423
+ .string()
1424
+ .nullable()
1425
+ .describe(
1426
+ "The store's name for what happened — `customer.subscription.updated`, `DID_RENEW`, `subscription.4` — or null when the notification names none in that shape.",
1427
+ ),
1428
+ receivedAt: z.iso.datetime().describe("When the notification reached this Worker, ISO-8601."),
1429
+ state: z
1430
+ .enum(["projected", "pending", "abandoned"])
1431
+ .describe(
1432
+ "`projected` — finished: it became a purchase, or there was nothing in it to become one. `pending` — arrived and not finished; `attempts` says how often it was tried. `abandoned` — a repair pass gave up on it; a later delivery can still project it.",
1433
+ ),
1434
+ attempts: z
1435
+ .number()
1436
+ .int()
1437
+ .nonnegative()
1438
+ .describe("How many times a repair pass tried it and failed. 0 for a delivery nothing retried."),
1439
+ errorCode: z
1440
+ .string()
1441
+ .nullable()
1442
+ .describe(
1443
+ "Why it did not project, as a code: a kit error code (`payments/product_not_found`), `orphaned` for a notification nobody could be resolved for, `quarantined` for one a repair pass gave up on, or `unclassified`. Null when nothing went wrong. Never the sentence behind it.",
1444
+ ),
1445
+ targets: z
1446
+ .object({
1447
+ purchaseIds: z
1448
+ .array(z.string())
1449
+ .describe("The purchase rows it created or moved that do not renew — ids `payments:purchases:read` lists."),
1450
+ subscriptionIds: z
1451
+ .array(z.string())
1452
+ .describe("The rows it created or moved that renew — ids `payments:subscriptions:read` lists."),
1453
+ })
1454
+ .nullable()
1455
+ .describe(
1456
+ "What it changed when it finished. Two empty lists: it finished and changed nothing. Null: nothing recorded — not finished, or finished before the Worker recorded targets.",
1457
+ ),
1458
+ })
1459
+ .describe("One notification a store sent, and what became of it. Never the payload, never an error's sentence.");
1460
+ export type PaymentsAdminWebhookEventView = z.output<typeof PaymentsAdminWebhookEventView>;
1461
+
1462
+ /** `GET {base}/admin/webhook-events`. */
1463
+ export const PaymentsAdminWebhookEventsResponse = z
1464
+ .object({
1465
+ events: z.array(PaymentsAdminWebhookEventView).describe("The page, most recently received first."),
1466
+ nextCursor: NextCursor,
1467
+ })
1468
+ .describe("A page of the webhook-event log.");
1469
+ export type PaymentsAdminWebhookEventsResponse = z.output<typeof PaymentsAdminWebhookEventsResponse>;
1470
+
1405
1471
  /** `GET {base}/admin/purchases`. */
1406
1472
  export const PaymentsAdminPurchasesResponse = z
1407
1473
  .object({
@@ -23,6 +23,7 @@ import {
23
23
  listReconcileRuns,
24
24
  listSubscriptions,
25
25
  listUsageRuns,
26
+ listWebhookEvents,
26
27
  readEntitlements,
27
28
  unrestrictedSubjects,
28
29
  } from "../admin/read";
@@ -54,7 +55,7 @@ import {
54
55
  type SubscriptionStanding,
55
56
  } from "../data/subscription";
56
57
  import { PAYMENTS_PURCHASES_TABLE, paymentsDatabase } from "../data/tables";
57
- import { WEBHOOK_EVENT_ORPHANED } from "../data/webhookEvent";
58
+ import { NO_WEBHOOK_EVENT_TARGETS, WEBHOOK_EVENT_ORPHANED } from "../data/webhookEvent";
58
59
  import { resolveAllowances } from "../entitlement/allowance";
59
60
  import { grantEntitlement, revokeEntitlement } from "../entitlement/manual";
60
61
  import { allowanceInputFor } from "../entitlement/meter";
@@ -82,6 +83,7 @@ import type { PaymentsLedgerPeer } from "../grants/ledgerSeam";
82
83
  import { repairOrphanedEvents } from "../projection/orphans";
83
84
  import { linkProviderAccount, providerAccountForSubject, resolveNotificationOwner } from "../projection/owner";
84
85
  import { resolveEntitlements } from "../projection/resolve";
86
+ import { notificationTargets, projectionTargets } from "../projection/targets";
85
87
  import { type PurchaseProjection, projectPurchase } from "../projection/writer";
86
88
  import {
87
89
  type CheckoutRail,
@@ -110,6 +112,7 @@ import {
110
112
  PaymentsAdminSubjectEntitlementsResponse,
111
113
  PaymentsAdminSubscriptionsResponse,
112
114
  PaymentsAdminUsageRunsResponse,
115
+ PaymentsAdminWebhookEventsResponse,
113
116
  PaymentsCheckoutHandoffResponse,
114
117
  PaymentsDiscountResponse,
115
118
  PaymentsEntitlementResponse,
@@ -139,6 +142,7 @@ import {
139
142
  AdminSubjectParam,
140
143
  AdminSubscriptionsQuery,
141
144
  AdminUsageRunsQuery,
145
+ AdminWebhookEventsQuery,
142
146
  AppleWebhookNotification,
143
147
  CheckoutRequest,
144
148
  DiscountCreateRequest,
@@ -173,6 +177,7 @@ import {
173
177
  PAYMENTS_RECONCILE_RUN_SCOPE,
174
178
  PAYMENTS_SUBSCRIPTIONS_READ_SCOPE,
175
179
  PAYMENTS_USAGE_READ_SCOPE,
180
+ PAYMENTS_WEBHOOKS_READ_SCOPE,
176
181
  } from "./scopes";
177
182
  import {
178
183
  adminAllowancesView,
@@ -182,6 +187,7 @@ import {
182
187
  adminPurchaseView,
183
188
  adminReconcileRunView,
184
189
  adminUsageRunView,
190
+ adminWebhookEventView,
185
191
  entitlementView,
186
192
  overrideView,
187
193
  purchaseView,
@@ -231,6 +237,7 @@ import { completeWebhook, requireSignedWebhook, verifiedWebhook } from "./webhoo
231
237
  * GET /payments/admin/entitlements/:subjectType/:subjectId
232
238
  * → one subject's entitlements (control-plane: payments:entitlements:read) param: AdminSubjectParam
233
239
  * GET /payments/admin/reconcile-runs → the reconciliation run log (control-plane: payments:reconcile:read) query: AdminReconcileRunsQuery
240
+ * GET /payments/admin/webhook-events → every store notification (control-plane: payments:webhooks:read) query: AdminWebhookEventsQuery
234
241
  * GET /payments/admin/discounts → the codes this project issued (control-plane: payments:discounts:read) query: AdminDiscountsQuery
235
242
  * POST /payments/admin/discounts → mint one at a store (control-plane: payments:discounts:create) json: DiscountCreateRequest
236
243
  *
@@ -1736,6 +1743,50 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
1736
1743
  },
1737
1744
  );
1738
1745
 
1746
+ /**
1747
+ * CONTROL PLANE. Every notification a store sent, newest received first (#830).
1748
+ *
1749
+ * **The read that explains the other two revenue-integrity findings.** A purchase paid and not entitled, or
1750
+ * entitled and not paid, is usually a notification that arrived and never projected — and that row was
1751
+ * invisible to every management client. Here it reads as `pending` with its attempts or `abandoned`, never
1752
+ * as missing, and a projected one names the purchase and subscription rows it changed.
1753
+ *
1754
+ * Its own scope. The rows name no subject, but they are every customer's commerce as the stores reported it.
1755
+ * The payload is never selected, and the stored error crosses as its code alone — see `adminWebhookEventView`.
1756
+ */
1757
+ app.get(
1758
+ `${base}/admin/webhook-events`,
1759
+ describeRoute({
1760
+ summary: "Read every notification a store sent, and what became of it.",
1761
+ verification: "control-plane",
1762
+ scopes: [PAYMENTS_WEBHOOKS_READ_SCOPE],
1763
+ responses: { 200: PaymentsAdminWebhookEventsResponse },
1764
+ }),
1765
+ requireControlPlane(PAYMENTS_WEBHOOKS_READ_SCOPE),
1766
+ validate("query", AdminWebhookEventsQuery),
1767
+ async (c) => {
1768
+ const query = c.req.valid("query");
1769
+ const page = await listWebhookEvents(database(c), query);
1770
+ await recordRead(c, PaymentsAuditActions.webhookEventsRead, null, {
1771
+ returned: page.items.length,
1772
+ resumed: query.cursor !== undefined,
1773
+ filters: {
1774
+ rail: query.rail ?? null,
1775
+ state: query.state ?? null,
1776
+ since: query.since?.toISOString() ?? null,
1777
+ until: query.until?.toISOString() ?? null,
1778
+ },
1779
+ });
1780
+ return c.json(
1781
+ {
1782
+ events: page.items.map(adminWebhookEventView),
1783
+ nextCursor: page.nextCursor,
1784
+ } satisfies PaymentsAdminWebhookEventsResponse,
1785
+ 200,
1786
+ );
1787
+ },
1788
+ );
1789
+
1739
1790
  /**
1740
1791
  * CONTROL PLANE WRITE. Start a reconciliation pass now.
1741
1792
  *
@@ -3371,7 +3422,8 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
3371
3422
  ? { at: now, error: outcome.error }
3372
3423
  : outcome.note !== undefined
3373
3424
  ? { at: now, note: outcome.note }
3374
- : { at: now },
3425
+ : // About no transaction and unexplained: finished, and it changed nothing.
3426
+ { at: now, targets: NO_WEBHOOK_EVENT_TARGETS },
3375
3427
  );
3376
3428
  await c.var.emit({
3377
3429
  action: PaymentsAuditActions.webhookReceived,
@@ -3447,7 +3499,10 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
3447
3499
  { config, environment: deploymentEnvironment(c), now },
3448
3500
  );
3449
3501
  await fulfill(c, projection);
3450
- await completeWebhook(d1, eventRowId, { at: now });
3502
+ await completeWebhook(d1, eventRowId, {
3503
+ at: now,
3504
+ targets: projectionTargets([{ projection, eventAt: now }]),
3505
+ });
3451
3506
  await c.var.emit({
3452
3507
  action: PaymentsAuditActions.webhookReceived,
3453
3508
  outcome: "success",
@@ -3542,13 +3597,13 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
3542
3597
  // Projected with the same owner, and outside the catch above on purpose: it is the half that revokes
3543
3598
  // access, so a failure must reach the store as a non-2xx and be redelivered rather than be acknowledged
3544
3599
  // as handled. Never fulfilled — a `state` row refuses both credit and clawback by role.
3545
- if (notification.stateEvent) {
3546
- await projectPurchase(
3547
- d1,
3548
- { ...notification.stateEvent, ...subject },
3549
- { config, environment: deploymentEnvironment(c), now },
3550
- );
3551
- }
3600
+ const standing = notification.stateEvent
3601
+ ? await projectPurchase(
3602
+ d1,
3603
+ { ...notification.stateEvent, ...subject },
3604
+ { config, environment: deploymentEnvironment(c), now },
3605
+ )
3606
+ : undefined;
3552
3607
 
3553
3608
  // Fulfillment sits outside that catch, and the asymmetry is deliberate. Every refusal the catch answers
3554
3609
  // is deterministic — an unmapped SKU, a sandbox transaction — so a retry reproduces it and a 200 is the
@@ -3557,7 +3612,14 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
3557
3612
  // non-2xx and be redelivered, which the stable grant ref makes free.
3558
3613
  await fulfill(c, projection);
3559
3614
 
3560
- await completeWebhook(d1, eventRowId, { at: now });
3615
+ // Every row this delivery moved — the charge, and the standing beside it where there is one (#830).
3616
+ await completeWebhook(d1, eventRowId, {
3617
+ at: now,
3618
+ targets: notificationTargets(
3619
+ { event: notification.event, projection },
3620
+ { event: notification.stateEvent, projection: standing },
3621
+ ),
3622
+ });
3561
3623
  await c.var.emit({
3562
3624
  action: PaymentsAuditActions.webhookReceived,
3563
3625
  outcome: "success",
@@ -686,6 +686,32 @@ export const AdminReconcileRunsQuery = z
686
686
  .describe("The reconciliation-run query: what to narrow it to, and where to resume.");
687
687
  export type AdminReconcileRunsQuery = z.output<typeof AdminReconcileRunsQuery>;
688
688
 
689
+ /**
690
+ * A window bound, as ISO-8601, decoded to a `Date` by the schema rather than by the handler — the handler takes
691
+ * typed values, so no handler parses a caller's string.
692
+ */
693
+ const WindowBound = z.iso.datetime({ offset: true }).transform((value) => new Date(value));
694
+
695
+ export const AdminWebhookEventsQuery = z
696
+ .object({
697
+ rail: PaymentsRail.optional().describe("Restrict to the notifications one store sent."),
698
+ state: z
699
+ .enum(["projected", "pending", "abandoned"])
700
+ .optional()
701
+ .describe(
702
+ "Restrict to one state: `projected` — finished; `pending` — arrived and not finished, tried or not; `abandoned` — a repair pass gave up on it.",
703
+ ),
704
+ since: WindowBound.optional().describe("Received at or after this instant, ISO-8601. Inclusive."),
705
+ until: WindowBound.optional().describe("Received before this instant, ISO-8601. Exclusive."),
706
+ cursor: Cursor,
707
+ limit: Limit,
708
+ })
709
+ .refine((query) => query.since === undefined || query.until === undefined || query.since < query.until, {
710
+ message: "`since` must be before `until`. A window that ends before it starts holds nothing.",
711
+ })
712
+ .describe("The webhook-event query: which store, which state, which window of receipt, and where to resume.");
713
+ export type AdminWebhookEventsQuery = z.output<typeof AdminWebhookEventsQuery>;
714
+
689
715
  export const AdminUsageRunsQuery = z
690
716
  .object({ cursor: Cursor, limit: Limit })
691
717
  .describe("The usage-run query: where to resume, and how many.");