@pithy-sh/payments 0.6.1 → 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
@@ -1,13 +1,13 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import type { AdminRoute } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
4
+ import type { AdminRouteDeclaration } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
5
5
  import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/scope";
6
6
 
7
7
  /**
8
8
  * Payments' control-plane scopes, and the admin surface a manifest advertises.
9
9
  *
10
- * **Separate from `guards.ts` because a scope name is a client's business** (#315). A management
10
+ * **Separate from `guards.ts` because a scope name is a client's business**. A management
11
11
  * client reads these to render what a connection may do, and `pithy-sh/dashboard`'s scope builder
12
12
  * writes the `pithy dashboard connect --scope …` command from exactly these constants — in a browser
13
13
  * program, with the DOM lib and no Workers types. While they sat beside the Hono middleware, naming
@@ -51,7 +51,7 @@ export const PAYMENTS_DISCOUNT_CREATE_SCOPE: ControlPlaneScope = "payments:disco
51
51
  *
52
52
  * Separate from creating one, and strictly narrower: a pane that lists what was minted does not need the
53
53
  * power to mint. The read exists because the write does — a management client that can create a code and
54
- * never see it leaves a pane computing *absent* rather than blocked, which no grant repairs (#247).
54
+ * never see it leaves a pane computing *absent* rather than blocked, which no grant repairs.
55
55
  */
56
56
  export const PAYMENTS_DISCOUNT_READ_SCOPE: ControlPlaneScope = "payments:discounts:read";
57
57
 
@@ -135,8 +135,7 @@ export const PAYMENTS_RECONCILE_READ_SCOPE: ControlPlaneScope = "payments:reconc
135
135
  *
136
136
  * **A trigger exists because the cron is not enough.** `pithy payments reconcile` runs the same pass, and it
137
137
  * needs a laptop, a checkout, and a Cloudflare API token for the project — so the answer to "my subscription
138
- * isn't showing up" at 4pm on a Saturday is either this route or nothing until 04:00 UTC. Adopted from
139
- * `pithy-sh/dashboard#96`, where the operator with the run log open had no way to act on it.
138
+ * isn't showing up" at 4pm on a Saturday is either this route or nothing until 04:00 UTC.
140
139
  *
141
140
  * Idempotent by construction, so the scope carries no warning about pressing twice: `reconcilePayments` finds
142
141
  * a reconciled catalog already matching and writes nothing.
@@ -172,6 +171,17 @@ export const PAYMENTS_OVERRIDE_CLEAR_SCOPE: ControlPlaneScope = "payments:overri
172
171
  */
173
172
  export const PAYMENTS_USAGE_READ_SCOPE: ControlPlaneScope = "payments:usage:read";
174
173
 
174
+ /**
175
+ * Read the webhook-event log — every notification a store sent, whether it became a purchase, is still
176
+ * pending with its attempts, or was given up on, and which purchase and subscription rows it changed.
177
+ *
178
+ * Its own scope, and a read in kind. The rows name no subject, but they are a record of every customer's
179
+ * commerce as the stores reported it, so a tool reading them should hold exactly this — not the purchase log,
180
+ * which `scopeCovers` keeps separate. Neither the provider's payload nor the store's sentence about a failure
181
+ * crosses on it: the event's type, its state and the error's code do.
182
+ */
183
+ export const PAYMENTS_WEBHOOKS_READ_SCOPE: ControlPlaneScope = "payments:webhooks:read";
184
+
175
185
  /**
176
186
  * Every control-plane scope payments defines — what `pithy dashboard connect` offers for this capability, and
177
187
  * the list a manifest or a doc quotes rather than re-typing. Core's `SEAM_SCOPES` is the same idea for the
@@ -188,6 +198,7 @@ export const PAYMENTS_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
188
198
  PAYMENTS_DISCOUNT_READ_SCOPE,
189
199
  PAYMENTS_RECONCILE_READ_SCOPE,
190
200
  PAYMENTS_USAGE_READ_SCOPE,
201
+ PAYMENTS_WEBHOOKS_READ_SCOPE,
191
202
  PAYMENTS_ENTITLEMENT_GRANT_SCOPE,
192
203
  PAYMENTS_ENTITLEMENT_REVOKE_SCOPE,
193
204
  PAYMENTS_OVERRIDE_SET_SCOPE,
@@ -216,111 +227,152 @@ export const PAYMENTS_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
216
227
  * construction rather than by luck. It also keeps the reads at the shape a management client looks for: a
217
228
  * `GET`, with a declared scope, no `:` segment, ending in the resource's own noun.
218
229
  */
219
- export function paymentsAdminRoutes(basePath: string): AdminRoute[] {
230
+ export function paymentsAdminRoutes(basePath: string): AdminRouteDeclaration[] {
220
231
  return [
221
232
  {
222
233
  method: "GET",
234
+ operation: "catalog.read",
223
235
  path: `${basePath}/admin/catalog`,
224
236
  scope: PAYMENTS_CATALOG_READ_SCOPE,
237
+ kind: "reads",
225
238
  summary:
226
239
  "What this project sells — each product's id, kind, display name, and the entitlement keys it grants. The list a comp control fills its dropdown from.",
227
240
  },
228
241
  {
229
242
  method: "GET",
243
+ operation: "purchases.list",
230
244
  path: `${basePath}/admin/purchases`,
231
245
  scope: PAYMENTS_PURCHASES_READ_SCOPE,
246
+ kind: "reads",
232
247
  summary:
233
248
  "Page the purchase log — every verified transaction, newest first, filtered by holder (both halves of the subject), store, status or store environment.",
234
249
  },
235
250
  {
236
251
  method: "GET",
252
+ operation: "subscriptions.list",
237
253
  path: `${basePath}/admin/subscriptions`,
238
254
  scope: PAYMENTS_SUBSCRIPTIONS_READ_SCOPE,
255
+ kind: "reads",
239
256
  summary: "Page the purchases that renew — who is still paying, and when the period they paid for ends.",
240
257
  },
241
258
  {
242
259
  method: "GET",
260
+ operation: "entitlements.list",
243
261
  path: `${basePath}/admin/entitlements`,
244
262
  scope: PAYMENTS_ENTITLEMENTS_READ_SCOPE,
263
+ kind: "reads",
245
264
  summary: "Page what accounts hold — whether each entitlement grants right now, and which purchase is the reason.",
246
265
  },
247
266
  {
248
267
  method: "GET",
268
+ operation: "entitlements.read",
249
269
  path: `${basePath}/admin/entitlements/:subjectType/:subjectId`,
250
270
  scope: PAYMENTS_ENTITLEMENTS_READ_SCOPE,
271
+ kind: "reads",
251
272
  summary:
252
273
  "Everything one subject is entitled to, resolved now — addressed by both halves, `user`/`organization` and the id. The answer to “why can this person not use what they paid for”.",
253
274
  },
254
275
  {
255
276
  method: "GET",
277
+ operation: "discounts.list",
256
278
  path: `${basePath}/admin/discounts`,
257
279
  scope: PAYMENTS_DISCOUNT_READ_SCOPE,
280
+ kind: "reads",
258
281
  summary: "The discount codes this project has issued, read from the store that holds them.",
259
282
  },
260
283
  {
261
284
  method: "POST",
285
+ operation: "discounts.create",
262
286
  path: `${basePath}/admin/discounts`,
263
287
  scope: PAYMENTS_DISCOUNT_CREATE_SCOPE,
288
+ kind: "charges",
264
289
  summary: "Mint a discount code at one store, from terms stated in the units a customer experiences.",
265
290
  },
266
291
  {
267
292
  method: "GET",
293
+ operation: "reconcile_runs.list",
268
294
  path: `${basePath}/admin/reconcile-runs`,
269
295
  scope: PAYMENTS_RECONCILE_READ_SCOPE,
296
+ kind: "reads",
270
297
  summary:
271
298
  "The reconciliation passes this deployment has run — when each ran, what it compared, and what it had to repair. The answer to whether the nightly repair is still firing.",
272
299
  },
273
300
  {
274
301
  method: "POST",
302
+ operation: "reconcile_runs.start",
275
303
  path: `${basePath}/admin/reconcile-runs`,
276
304
  scope: PAYMENTS_RECONCILE_RUN_SCOPE,
305
+ kind: "writes",
277
306
  summary:
278
307
  "Start a reconciliation pass now, rather than waiting for the nightly one. The repair path for a purchase a dropped webhook never projected.",
279
308
  },
280
309
  {
281
310
  method: "POST",
311
+ operation: "entitlements.grant",
282
312
  path: `${basePath}/entitlements/grant`,
283
313
  scope: PAYMENTS_ENTITLEMENT_GRANT_SCOPE,
314
+ kind: "charges",
284
315
  summary: "Comp an entitlement, or repair a purchase that verified but never projected.",
285
316
  },
286
317
  {
287
318
  method: "POST",
319
+ operation: "entitlements.revoke",
288
320
  path: `${basePath}/entitlements/revoke`,
289
321
  scope: PAYMENTS_ENTITLEMENT_REVOKE_SCOPE,
322
+ kind: "charges",
290
323
  summary: "Take an entitlement back, effective immediately.",
291
324
  },
292
325
  {
293
326
  method: "GET",
327
+ operation: "usage_runs.list",
294
328
  path: `${basePath}/admin/usage-runs`,
295
329
  scope: PAYMENTS_USAGE_READ_SCOPE,
330
+ kind: "reads",
296
331
  summary:
297
332
  "The usage-reporting passes this deployment has run — what each reported, and which subjects it skipped and why. The answer to why a quantity-billed customer was not billed.",
298
333
  },
299
334
  {
300
335
  method: "GET",
336
+ operation: "webhook_events.list",
337
+ path: `${basePath}/admin/webhook-events`,
338
+ scope: PAYMENTS_WEBHOOKS_READ_SCOPE,
339
+ kind: "reads",
340
+ summary:
341
+ "Page every notification a store sent — whether it became a purchase, is still pending, or was given up on, and what it changed. The answer to why a purchase is paid and not entitled, or entitled and not paid.",
342
+ },
343
+ {
344
+ method: "GET",
345
+ operation: "overrides.list",
301
346
  path: `${basePath}/admin/overrides`,
302
347
  scope: PAYMENTS_ENTITLEMENTS_READ_SCOPE,
348
+ kind: "reads",
303
349
  summary:
304
350
  "Page every subject's override — the numbers negotiated per customer, and which subjects are unrestricted.",
305
351
  },
306
352
  {
307
353
  method: "POST",
354
+ operation: "overrides.set",
308
355
  path: `${basePath}/entitlements/overrides`,
309
356
  scope: PAYMENTS_OVERRIDE_SET_SCOPE,
357
+ kind: "charges",
310
358
  summary:
311
359
  "Pin a negotiated number or switch for one subject, with a reason on the record. Merges by name; every other allowance keeps tracking the plan.",
312
360
  },
313
361
  {
314
362
  method: "POST",
363
+ operation: "overrides.unrestricted",
315
364
  path: `${basePath}/entitlements/overrides/unrestricted`,
316
365
  scope: PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE,
366
+ kind: "charges",
317
367
  summary:
318
368
  "Grant one subject the whole product — every quota unlimited and every feature on, including names declared later — or take it back.",
319
369
  },
320
370
  {
321
371
  method: "POST",
372
+ operation: "overrides.clear",
322
373
  path: `${basePath}/entitlements/overrides/clear`,
323
374
  scope: PAYMENTS_OVERRIDE_CLEAR_SCOPE,
375
+ kind: "charges",
324
376
  summary:
325
377
  "Unpin allowances for one subject, or clear its override entirely. Unpinned names follow the plan again.",
326
378
  },
package/src/http/view.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import type { PaymentsPurchaseRecord } from "../admin/read";
4
+ import type { PaymentsPurchaseRecord, PaymentsWebhookEventListing } from "../admin/read";
5
5
  import { compOnlyEntitlements, type PaymentsConfig } from "../config/config";
6
6
  import type { PaymentsEntitlement } from "../data/entitlement";
7
7
  import { isEmptyOverride, type PaymentsOverride } from "../data/override";
8
8
  import type { PaymentsReconcileRun } from "../data/reconcileRun";
9
9
  import type { PaymentsUsageRun } from "../data/usageRun";
10
+ import { webhookEventErrorCode, webhookEventReadState } from "../data/webhookEvent";
10
11
  import type { ResolvedAllowances } from "../entitlement/allowance";
11
12
  import type { PurchaseProjection } from "../projection/writer";
12
13
  import type {
@@ -17,6 +18,7 @@ import type {
17
18
  PaymentsAdminPurchaseView,
18
19
  PaymentsAdminReconcileRunView,
19
20
  PaymentsAdminUsageRunView,
21
+ PaymentsAdminWebhookEventView,
20
22
  PaymentsEntitlementView,
21
23
  PaymentsPurchaseView,
22
24
  } from "./responses";
@@ -215,6 +217,34 @@ export function adminUsageRunView(run: PaymentsUsageRun): PaymentsAdminUsageRunV
215
217
  };
216
218
  }
217
219
 
220
+ /**
221
+ * Project one recorded notification for a management client (#830).
222
+ *
223
+ * The state is derived, the error is reduced to its code, and the targets are copied — so the stored sentence
224
+ * and the payload (which the read never selected) have no field to land in.
225
+ */
226
+ export function adminWebhookEventView(event: PaymentsWebhookEventListing): PaymentsAdminWebhookEventView {
227
+ const targets = event.projectedTargets ?? null;
228
+ return {
229
+ id: event.id,
230
+ rail: event.rail,
231
+ providerEventId: event.providerEventId,
232
+ eventType: event.eventType,
233
+ receivedAt: event.receivedAt.toISOString(),
234
+ state: webhookEventReadState({
235
+ processedAt: event.processedAt?.getTime() ?? null,
236
+ abandonedAt: event.abandonedAt?.getTime() ?? null,
237
+ error: event.error,
238
+ }),
239
+ attempts: event.attempts ?? 0,
240
+ errorCode: webhookEventErrorCode(event.error),
241
+ targets:
242
+ targets === null
243
+ ? null
244
+ : { purchaseIds: [...targets.purchaseIds], subscriptionIds: [...targets.subscriptionIds] },
245
+ };
246
+ }
247
+
218
248
  /** Project one subject's override for a management client, or null when it has none. */
219
249
  export function adminOverrideView(row: PaymentsOverride | undefined): PaymentsAdminOverrideView | null {
220
250
  // A cleared row is kept only for its version — it overrides nothing, so it shows as no override.
@@ -13,7 +13,14 @@ import { PaymentsAuditActions } from "../audit/actions";
13
13
  import type { PaymentsConfig } from "../config/config";
14
14
  import type { PaymentsRail } from "../data/rail";
15
15
  import { PAYMENTS_WEBHOOK_EVENTS_TABLE, paymentsDatabase } from "../data/tables";
16
- import { isWebhookEventFinished, PaymentsWebhookEvent, webhookEventState } from "../data/webhookEvent";
16
+ import {
17
+ encodeWebhookEventTargets,
18
+ isWebhookEventFinished,
19
+ NO_WEBHOOK_EVENT_TARGETS,
20
+ PaymentsWebhookEvent,
21
+ type PaymentsWebhookEventTargets,
22
+ webhookEventState,
23
+ } from "../data/webhookEvent";
17
24
  import { PaymentsWebhookUnverifiedError } from "../error/errors";
18
25
  import type { VerifiedNotification } from "../rails/contract";
19
26
  import { type RailTrustOptions, resolveRailProvider } from "../rails/providers";
@@ -303,7 +310,11 @@ export function requireSignedWebhook(
303
310
  /**
304
311
  * What became of a verified delivery, as the handler reports it. **Three cases, because there are three.**
305
312
  *
306
- * `{ at }` — it projected. Finished.
313
+ * `{ at, targets }` — it projected, and these are the purchase and subscription rows it changed (#830).
314
+ * Finished. `targets` is required rather than defaulted: a projecting path that forgot it would record
315
+ * "changed nothing" about an event that changed something, which is the one wrong answer worse than none.
316
+ * A delivery about no transaction at all passes {@link NO_WEBHOOK_EVENT_TARGETS} — it is finished, and it
317
+ * genuinely changed nothing.
307
318
  *
308
319
  * `{ at, note }` — it was never going to project, and here is why. The rail read the notification and said
309
320
  * it carries no transaction state: a partial refund that takes nothing away, a token Play will not show us
@@ -331,7 +342,7 @@ export function requireSignedWebhook(
331
342
  * decide what a row means that claims to be finished and failed at once. That contradiction was #337.
332
343
  */
333
344
  export type WebhookCompletion =
334
- | { readonly at: Date }
345
+ | { readonly at: Date; readonly targets: PaymentsWebhookEventTargets }
335
346
  | { readonly at: Date; readonly note: string }
336
347
  | { readonly at: Date; readonly error: string };
337
348
 
@@ -367,6 +378,15 @@ export async function completeWebhook(d1: D1Database, eventRowId: string, outcom
367
378
  processedAt: repairable ? null : outcome.at.getTime(),
368
379
  // One column: it is "why", and an operator reads it the same way whichever of the two it is.
369
380
  error: "error" in outcome ? outcome.error : "note" in outcome ? outcome.note : null,
381
+ // What the event changed, on every finish and on no failure (#830): a repairable row has changed
382
+ // nothing yet, and leaving the column alone keeps null meaning "nothing recorded".
383
+ ...(repairable
384
+ ? {}
385
+ : {
386
+ projectedTargets: encodeWebhookEventTargets(
387
+ "targets" in outcome ? outcome.targets : NO_WEBHOOK_EVENT_TARGETS,
388
+ ),
389
+ }),
370
390
  // biome-ignore lint/suspicious/noExplicitAny: encoded column values, not the app shape.
371
391
  } as any)
372
392
  .where("id", "=", eventRowId)
@@ -0,0 +1,34 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Kysely } from "kysely";
5
+ import type { Migration } from "kysely/migration";
6
+
7
+ /**
8
+ * What each webhook event changed, and the index its management read pages on (#830).
9
+ *
10
+ * **A new migration, because `0001` and `0002` are history.** Both have been running since they shipped, and
11
+ * reshaping either would reshape a database somebody is already running.
12
+ *
13
+ * - `pithy_payments_webhook_events.projected_targets` — the purchase and subscription row ids an event changed
14
+ * when it finished, as JSON (`data/webhookEvent.ts`'s `PaymentsWebhookEventTargets`). Nullable, and null on
15
+ * every row that exists when this runs: those events finished before anything recorded what they touched,
16
+ * and no store is asked again to reconstruct it. Null is *unrecorded*; two empty lists is *changed nothing*.
17
+ * - `pithy_payments_webhook_events_received_idx` on `(receivedAt, id)` — `GET {base}/admin/webhook-events`
18
+ * pages newest received first, keyset on the id like every listing here. The pending index `0001` made
19
+ * leads on `processedAt` and serves the repair passes, not a page of everything.
20
+ */
21
+ export const payments_0003_webhook_targets: Migration = {
22
+ up: async (db: Kysely<unknown>): Promise<void> => {
23
+ await db.schema.alterTable("pithyPaymentsWebhookEvents").addColumn("projectedTargets", "text").execute();
24
+ await db.schema
25
+ .createIndex("pithyPaymentsWebhookEventsReceivedIdx")
26
+ .on("pithyPaymentsWebhookEvents")
27
+ .columns(["receivedAt", "id"])
28
+ .execute();
29
+ },
30
+ down: async (db: Kysely<unknown>): Promise<void> => {
31
+ await db.schema.dropIndex("pithyPaymentsWebhookEventsReceivedIdx").execute();
32
+ await db.schema.alterTable("pithyPaymentsWebhookEvents").dropColumn("projectedTargets").execute();
33
+ },
34
+ };
@@ -0,0 +1,34 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { ProcessingActivityInput, ProcessingRecipientInput } from "@pithy-sh/core/src/processing/activity";
5
+ import { PAYMENTS_RAILS, type PaymentsRail } from "../data/rail";
6
+
7
+ /** Each rail, as an auditor would name the company behind it. */
8
+ const RAIL_NAMES: Readonly<Record<PaymentsRail, string>> = {
9
+ apple: "Apple App Store",
10
+ google: "Google Play",
11
+ stripe: "Stripe",
12
+ lemonSqueezy: "Lemon Squeezy",
13
+ paddle: "Paddle",
14
+ };
15
+
16
+ /** Every rail the config turns on, as a recipient of the purchases made on it. */
17
+ export function railRecipients(rails: Readonly<Record<PaymentsRail, boolean>>): ProcessingRecipientInput[] {
18
+ return PAYMENTS_RAILS.filter((rail) => rails[rail]).map((rail) => ({
19
+ name: RAIL_NAMES[rail],
20
+ receives: "Each purchase made on it, and the account id it is made for.",
21
+ }));
22
+ }
23
+
24
+ /** What payments does with personal data: it sells, and keeps each purchase and what it granted. */
25
+ export function paymentsProcessing(rails: Readonly<Record<PaymentsRail, boolean>>): ProcessingActivityInput[] {
26
+ return [
27
+ {
28
+ id: "payments.purchases",
29
+ purpose: "Sell to a person, keep each purchase and what it entitles them to, and keep it for tax law.",
30
+ legalBasis: "contract",
31
+ recipients: railRecipients(rails),
32
+ },
33
+ ];
34
+ }
@@ -7,9 +7,16 @@ import type { PaymentsConfig } from "../config/config";
7
7
  import type { PurchaseEnvironment } from "../data/purchase";
8
8
  import type { PaymentsRail } from "../data/rail";
9
9
  import { PAYMENTS_WEBHOOK_EVENTS_TABLE, paymentsDatabase } from "../data/tables";
10
- import { PaymentsWebhookEvent, WEBHOOK_EVENT_ORPHANED, webhookEventAwaitsOwner } from "../data/webhookEvent";
10
+ import {
11
+ encodeWebhookEventTargets,
12
+ PaymentsWebhookEvent,
13
+ type PaymentsWebhookEventTargets,
14
+ WEBHOOK_EVENT_ORPHANED,
15
+ webhookEventAwaitsOwner,
16
+ } from "../data/webhookEvent";
11
17
  import type { VerifiedNotification } from "../rails/contract";
12
18
  import { resolveNotificationOwner } from "./owner";
19
+ import { notificationTargets } from "./targets";
13
20
  import { type PurchaseProjection, projectPurchase } from "./writer";
14
21
 
15
22
  /**
@@ -174,19 +181,20 @@ export async function repairOrphanedEvents(
174
181
  }
175
182
 
176
183
  let projection: PurchaseProjection;
184
+ let standing: PurchaseProjection | undefined;
177
185
  try {
178
186
  projection = await projectPurchase(
179
187
  d1,
180
188
  { ...notification.event, ...subject },
181
189
  { config: options.config, environment: options.environment, now: options.now },
182
190
  );
183
- if (notification.stateEvent) {
184
- await projectPurchase(
185
- d1,
186
- { ...notification.stateEvent, ...subject },
187
- { config: options.config, environment: options.environment, now: options.now },
188
- );
189
- }
191
+ standing = notification.stateEvent
192
+ ? await projectPurchase(
193
+ d1,
194
+ { ...notification.stateEvent, ...subject },
195
+ { config: options.config, environment: options.environment, now: options.now },
196
+ )
197
+ : undefined;
190
198
  await options.fulfill?.(projection);
191
199
  } catch {
192
200
  // An unmapped SKU, a sandbox row in a production database, a ledger that would not assemble. None of
@@ -196,7 +204,15 @@ export async function repairOrphanedEvents(
196
204
  continue;
197
205
  }
198
206
 
199
- await finish(d1, row.id, options.now);
207
+ await finish(
208
+ d1,
209
+ row.id,
210
+ options.now,
211
+ notificationTargets(
212
+ { event: notification.event, projection },
213
+ { event: notification.stateEvent, projection: standing },
214
+ ),
215
+ );
200
216
  projected.push(row.providerEventId);
201
217
  }
202
218
 
@@ -214,12 +230,13 @@ export async function repairOrphanedEvents(
214
230
  * `abandonedAt` is left exactly where it was. A sweep having given up on this row is a fact about that pass
215
231
  * and a record of how close the purchase came to being lost; `finished` already wins over it by construction.
216
232
  */
217
- async function finish(d1: D1Database, id: string, now: Date): Promise<void> {
233
+ async function finish(d1: D1Database, id: string, now: Date, targets: PaymentsWebhookEventTargets): Promise<void> {
218
234
  await withD1Retry(() =>
219
235
  paymentsDatabase(d1)
220
236
  .updateTable(PAYMENTS_WEBHOOK_EVENTS_TABLE)
237
+ // What the repair projected, recorded the way a delivery records it (#830).
221
238
  // biome-ignore lint/suspicious/noExplicitAny: encoded column values, not the app shape.
222
- .set({ processedAt: now.getTime(), error: null } as any)
239
+ .set({ processedAt: now.getTime(), error: null, projectedTargets: encodeWebhookEventTargets(targets) } as any)
223
240
  .where("id", "=", id)
224
241
  .execute(),
225
242
  );
@@ -0,0 +1,66 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { PaymentsWebhookEventTargets } from "../data/webhookEvent";
5
+ import type { PurchaseProjection } from "./writer";
6
+
7
+ /** What the split reads off one projection: whether it wrote, and the row it wrote to or read. */
8
+ export type TargetedProjection = {
9
+ readonly outcome: PurchaseProjection["outcome"];
10
+ readonly purchase: Pick<PurchaseProjection["purchase"], "id" | "type" | "providerEventAt">;
11
+ };
12
+
13
+ /** One projection a finishing event made, beside the provider time of the event it projected. */
14
+ export type ProjectedEvent = {
15
+ readonly projection: TargetedProjection;
16
+ /** The `providerEventAt` of the event handed to the writer — the version the row carries if this event wrote it. */
17
+ readonly eventAt: Date;
18
+ };
19
+
20
+ /**
21
+ * Every purchase and subscription row a set of projections changed — what a finishing event records about
22
+ * itself (#830).
23
+ *
24
+ * **Changed, not touched.** A projection answering `ignored` wrote nothing on this attempt, but that is two
25
+ * cases. A row strictly newer than the event was moved by some later event, so listing it would claim a change
26
+ * that did not happen. A row carrying the event's *own* version is this event's write, made on an earlier
27
+ * attempt that projected and then failed after — a fulfillment that threw, the second half of a Lemon
28
+ * Squeezy refund — and left the row unfinished for the redelivery, the sweep or the repair to finish. That
29
+ * row is listed: recording two empty lists there would say the event finished and changed nothing, which is
30
+ * the one wrong answer worse than none.
31
+ *
32
+ * The split is on the row's own `type`, the same narrowing `payments:subscriptions:read` applies, so the two
33
+ * lists are disjoint and each id is one a client holding that read can open. A row written twice by one
34
+ * delivery is listed once, in the order it was first written.
35
+ */
36
+ export function projectionTargets(projected: readonly ProjectedEvent[]): PaymentsWebhookEventTargets {
37
+ const purchaseIds: string[] = [];
38
+ const subscriptionIds: string[] = [];
39
+ for (const { projection, eventAt } of projected) {
40
+ if (projection.outcome === "ignored" && projection.purchase.providerEventAt.getTime() !== eventAt.getTime()) {
41
+ continue;
42
+ }
43
+ const list = projection.purchase.type === "subscription" ? subscriptionIds : purchaseIds;
44
+ if (!list.includes(projection.purchase.id)) list.push(projection.purchase.id);
45
+ }
46
+ return { purchaseIds, subscriptionIds };
47
+ }
48
+
49
+ /** The provider time of an event, which is all {@link notificationTargets} reads off one. */
50
+ type Timed = { readonly providerEventAt: Date };
51
+
52
+ /**
53
+ * {@link projectionTargets} for the one shape every finishing path has: a notification's charge, and the
54
+ * standing beside it where the rail sent one. Each projection travels with the event it projected, so a
55
+ * caller cannot hand the charge's time to the standing's row.
56
+ */
57
+ export function notificationTargets(
58
+ charge: { readonly event: Timed; readonly projection: TargetedProjection },
59
+ standing: { readonly event?: Timed | null; readonly projection?: TargetedProjection | undefined },
60
+ ): PaymentsWebhookEventTargets {
61
+ const projected: ProjectedEvent[] = [{ projection: charge.projection, eventAt: charge.event.providerEventAt }];
62
+ if (standing.projection !== undefined && standing.event) {
63
+ projected.push({ projection: standing.projection, eventAt: standing.event.providerEventAt });
64
+ }
65
+ return projectionTargets(projected);
66
+ }