@pithy-sh/payments 0.3.9 → 0.4.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 (62) hide show
  1. package/README.md +1 -0
  2. package/dist/client/api.d.ts +19 -0
  3. package/dist/client/api.d.ts.map +1 -1
  4. package/dist/client/api.js +26 -1
  5. package/dist/client/hooks.d.ts +43 -0
  6. package/dist/client/hooks.d.ts.map +1 -1
  7. package/dist/client/hooks.js +58 -2
  8. package/dist/client/paddleLink.d.ts +31 -0
  9. package/dist/client/paddleLink.d.ts.map +1 -0
  10. package/dist/client/paddleLink.js +37 -0
  11. package/dist/data/paddleIds.d.ts +28 -0
  12. package/dist/data/paddleIds.d.ts.map +1 -0
  13. package/dist/data/paddleIds.js +73 -0
  14. package/dist/entitlement/unimplementedSubject.d.ts.map +1 -1
  15. package/dist/entitlement/unimplementedSubject.js +3 -2
  16. package/dist/http/responses.d.ts +23 -5
  17. package/dist/http/responses.d.ts.map +1 -1
  18. package/dist/http/responses.js +24 -7
  19. package/dist/http/routes.d.ts +6 -2
  20. package/dist/http/routes.d.ts.map +1 -1
  21. package/dist/http/routes.js +210 -38
  22. package/dist/http/schemas.d.ts +21 -1
  23. package/dist/http/schemas.d.ts.map +1 -1
  24. package/dist/http/schemas.js +20 -2
  25. package/dist/http/webhookGuard.d.ts.map +1 -1
  26. package/dist/http/webhookGuard.js +1 -1
  27. package/dist/rails/paddle/events.d.ts.map +1 -1
  28. package/dist/rails/paddle/events.js +2 -1
  29. package/dist/rails/paddle/refresh.d.ts +10 -5
  30. package/dist/rails/paddle/refresh.d.ts.map +1 -1
  31. package/dist/rails/paddle/refresh.js +8 -5
  32. package/dist/rails/paddle/refund.d.ts.map +1 -1
  33. package/dist/rails/paddle/refund.js +10 -2
  34. package/dist/rails/paddle/subscription.d.ts.map +1 -1
  35. package/dist/rails/paddle/subscription.js +8 -3
  36. package/dist/rails/paddle/verify.d.ts.map +1 -1
  37. package/dist/rails/paddle/verify.js +2 -3
  38. package/dist/secret/registry.d.ts.map +1 -1
  39. package/dist/secret/registry.js +3 -2
  40. package/dist/version.generated.d.ts +1 -1
  41. package/dist/version.generated.js +1 -1
  42. package/dist/workflows/workerConfig.d.ts.map +1 -1
  43. package/dist/workflows/workerConfig.js +8 -2
  44. package/docs/paddle.md +17 -2
  45. package/package.json +6 -6
  46. package/src/client/api.ts +35 -0
  47. package/src/client/hooks.ts +78 -0
  48. package/src/client/paddleLink.ts +41 -0
  49. package/src/data/paddleIds.ts +74 -0
  50. package/src/entitlement/unimplementedSubject.ts +3 -4
  51. package/src/http/responses.ts +33 -6
  52. package/src/http/routes.ts +729 -454
  53. package/src/http/schemas.ts +32 -1
  54. package/src/http/webhookGuard.ts +3 -2
  55. package/src/rails/paddle/events.ts +2 -1
  56. package/src/rails/paddle/refresh.ts +17 -10
  57. package/src/rails/paddle/refund.ts +10 -2
  58. package/src/rails/paddle/subscription.ts +8 -3
  59. package/src/rails/paddle/verify.ts +6 -4
  60. package/src/secret/registry.ts +3 -2
  61. package/src/version.generated.ts +1 -1
  62. package/src/workflows/workerConfig.ts +9 -3
@@ -6,6 +6,7 @@ import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
6
6
  import { EntitlementKey } from "@pithy-sh/core/src/entitlement/entitlement";
7
7
  import { z } from "zod";
8
8
  import { DiscountCode, DiscountTerms } from "../data/discount";
9
+ import { isPaddleTransactionId } from "../data/paddleIds";
9
10
  import { PurchaseEnvironment } from "../data/purchase";
10
11
  import { PaymentsHostedRail, PaymentsRail } from "../data/rail";
11
12
  import { PurchaseStatus } from "../data/status";
@@ -170,7 +171,7 @@ export type CheckoutRequest = z.infer<typeof CheckoutRequest>;
170
171
  *
171
172
  * **No body at all on `keep`.** Withdrawing a scheduled cancellation takes no parameters: which
172
173
  * subscription is the server's answer, and there is nothing to say about it but *do not*. So that route
173
- * declares no schema and no `zValidator("json", …)`, exactly as `POST {base}/portal` does. A
174
+ * declares no schema and no `validate("json", …)`, exactly as `POST {base}/portal` does. A
174
175
  * `z.object({})` would read as a refusal of everything and be neither — Zod strips rather than refuses —
175
176
  * while making a POST with no body at all a 400 on a route that wants nothing.
176
177
  */
@@ -575,3 +576,33 @@ export const AdminSubjectParam = z
575
576
  })
576
577
  .describe("The `:subjectType/:subjectId` path segments on the per-subject management read.");
577
578
  export type AdminSubjectParam = z.output<typeof AdminSubjectParam>;
579
+
580
+ /**
581
+ * The transaction a Paddle payment link put in the URL — the `?transaction=` query on the resume read.
582
+ *
583
+ * **The id is the whole request, and it came from outside.** Paddle appends `?_ptxn=<transaction_id>` to a
584
+ * seller's Default payment link; the browser reads it and sends it here. So this is attacker-supplied text
585
+ * on an unauthenticated route, and the shape check is what makes it safe to echo back into a handoff a page
586
+ * will hand to `Paddle.Checkout.open`.
587
+ *
588
+ * **Checked against the rail's own primitive**, `isPaddleTransactionId`, rather than a regex written here:
589
+ * `rails/paddle/verify.ts` asks the same question of a submitted receipt, and two copies of one rule is the
590
+ * defect class this repository has paid for four times.
591
+ *
592
+ * **It names no holder, and that is structural rather than remembered.** The resume route takes no session
593
+ * and resolves no subject, so there is no field here for one — which `routeContract.test.ts`'s subject sweep
594
+ * asserts from the other side, by finding none.
595
+ */
596
+ export const PaddleResumeQuery = z
597
+ .object({
598
+ transaction: z
599
+ .string()
600
+ .refine(isPaddleTransactionId, {
601
+ message: "Not a Paddle transaction id. Expected the `txn_…` Paddle put in `_ptxn`.",
602
+ })
603
+ .describe(
604
+ "The Paddle transaction to resume — the `_ptxn` value, `txn_…`. Publishable: Paddle itself put it in a URL it mailed to the buyer.",
605
+ ),
606
+ })
607
+ .describe("The resume read's query: which transaction a Paddle payment link arrived for.");
608
+ export type PaddleResumeQuery = z.output<typeof PaddleResumeQuery>;
@@ -18,6 +18,7 @@ import { PaymentsWebhookUnverifiedError } from "../error/errors";
18
18
  import type { VerifiedNotification } from "../rails/contract";
19
19
  import { type RailTrustOptions, resolveRailProvider } from "../rails/providers";
20
20
  import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/registry";
21
+ import type { PaymentsWebhookAck } from "./responses";
21
22
 
22
23
  /**
23
24
  * The `signed-webhook` gate — the repo's first, and the shape the Google and Stripe webhooks will reuse.
@@ -32,7 +33,7 @@ import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/reg
32
33
  * it.
33
34
  *
34
35
  * `c.req.text()` rather than `c.req.raw.text()`, and that distinction matters. Hono caches its own body reads,
35
- * so the route's `zValidator("json", …)` afterwards is served from the same cache and sees identical bytes.
36
+ * so the route's `validate("json", …)` afterwards is served from the same cache and sees identical bytes.
36
37
  * Reading `c.req.raw` directly would consume the stream and leave the validator with nothing.
37
38
  *
38
39
  * ## Why it persists before it hands off
@@ -291,7 +292,7 @@ export function requireSignedWebhook(
291
292
  // been projected, and short-circuiting them made a redelivery — and a manual replay, which reuses the
292
293
  // provider's event id — the one thing that could never repair them.
293
294
  if (isWebhookEventFinished(webhookEventState(stored))) {
294
- return c.json({ received: true, duplicate: true }, 200);
295
+ return c.json({ received: true, duplicate: true } satisfies PaymentsWebhookAck, 200);
295
296
  }
296
297
 
297
298
  verified.set(c.req.raw, { rail, notification, eventRowId: stored.id });
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { commandName } from "@pithy-sh/core/src/cli/command";
4
5
  import { z } from "zod";
5
6
  import type { PaymentsPaddleCredentials } from "../../secret/registry";
6
7
  import type { VerifiedNotification } from "../contract";
@@ -198,7 +199,7 @@ export async function sweepPaddleEvents(options: PaddleSweepOptions): Promise<Pa
198
199
  events: [],
199
200
  cursor: options.cursor,
200
201
  hasMore: false,
201
- gap: `Paddle no longer knows event ${options.cursor}, so the sweep cannot resume from it. Paddle retains ${PADDLE_EVENT_RETENTION_DAYS} days of events, and anything between that cursor and the retention window is gone. Reconcile the affected purchases with \`pithy payments reconcile --rail paddle\`, then clear the cursor to restart from the oldest retained event.`,
202
+ gap: `Paddle no longer knows event ${options.cursor}, so the sweep cannot resume from it. Paddle retains ${PADDLE_EVENT_RETENTION_DAYS} days of events, and anything between that cursor and the retention window is gone. Reconcile the affected purchases with \`${commandName("payments reconcile")}\`, passing --rail paddle and this environment's --env, then clear the cursor to restart from the oldest retained event.`,
202
203
  };
203
204
  }
204
205
  throw cause;
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { SubscriptionPricing } from "../../data/discount";
5
+ import { isPaddleSubscriptionId, isPaddleTransactionId } from "../../data/paddleIds";
5
6
  import type { PaymentsPurchase } from "../../data/purchase";
6
7
  import type { PaymentsPaddleCredentials } from "../../secret/registry";
7
8
  import type { UnboundProviderEvent } from "../contract";
@@ -18,9 +19,12 @@ import { readSubscription, readTransaction } from "./read";
18
19
  *
19
20
  * ## Which rows it can answer for
20
21
  *
21
- * Paddle's ids are globally prefixed, so the row's own key says what to ask: `sub_…` is a subscription,
22
- * `txn_…` is a transaction. Both are addressable, so both are re-read — unlike Lemon Squeezy, where a
23
- * money row records a closed period and has nothing to re-read.
22
+ * Paddle's ids are globally prefixed, so the row's own key says what to ask: a subscription id is a
23
+ * subscription, a transaction id is a transaction. Both are addressable, so both are re-read — unlike
24
+ * Lemon Squeezy, where a money row records a closed period and has nothing to re-read. **What counts as
25
+ * one of those keys is `data/paddleIds.ts`'s to say**, not this module's: a prefix test here accepted the
26
+ * bare prefix and an uppercase id, and spent a round trip finding out the store had never issued it
27
+ * (#681).
24
28
  *
25
29
  * A **subscription** transaction's money row is born `expired`, which is in the Workflow's terminal set,
26
30
  * so the pass never selects one. Should one reach here it is answered honestly rather than skipped: a
@@ -61,20 +65,21 @@ export async function refreshPaddlePurchase(
61
65
  const id = purchase.providerTransactionId;
62
66
  const environment = options.environment === "production" ? "production" : "sandbox";
63
67
 
64
- if (id.startsWith("sub_")) {
68
+ if (isPaddleSubscriptionId(id)) {
65
69
  const subscription = await readSubscription(id, read);
66
70
  if (subscription === undefined) return undefined;
67
71
  return { ...subscriptionEvent(subscription, options.now, environment), providerEventAt: options.now };
68
72
  }
69
73
 
70
- if (id.startsWith("txn_")) {
74
+ if (isPaddleTransactionId(id)) {
71
75
  const transaction = await readTransaction(id, read);
72
76
  if (transaction === undefined) return undefined;
73
77
  return { ...transactionEvent(transaction, options.now, environment), providerEventAt: options.now };
74
78
  }
75
79
 
76
- // A prefix a later build wrote. Nothing to re-read, which the contract defines as "the store has
77
- // nothing to say about this purchase" and which leaves the row exactly as it stands.
80
+ // A key neither primitive recognizes: a prefix a later build wrote, or a value too mangled to be an
81
+ // id Paddle issued. Nothing to re-read, which the contract defines as "the store has nothing to say
82
+ // about this purchase" and which leaves the row exactly as it stands.
78
83
  return undefined;
79
84
  }
80
85
 
@@ -86,15 +91,17 @@ export async function refreshPaddlePurchase(
86
91
  * list price. Nothing here multiplies a price by a percentage — a second calculation would be a second
87
92
  * answer to the one question a customer checks against their statement.
88
93
  *
89
- * Only a `sub_…` row can be asked. A transaction records one closed period and has no "next", so it
90
- * answers `undefined` — the same "nothing to say about this purchase" the refresh path uses.
94
+ * Only a subscription row can be asked, and `data/paddleIds.ts` says which rows those are. A transaction
95
+ * records one closed period and has no "next", so it answers `undefined` — the same "nothing to say about
96
+ * this purchase" the refresh path uses, and the same answer a column holding something Paddle never
97
+ * issued now gets without a round trip (#681).
91
98
  */
92
99
  export async function readPaddlePricing(
93
100
  purchase: PaymentsPurchase,
94
101
  options: RefreshPaddleOptions,
95
102
  ): Promise<SubscriptionPricing | undefined> {
96
103
  const id = purchase.providerTransactionId;
97
- if (!id.startsWith("sub_")) return undefined;
104
+ if (!isPaddleSubscriptionId(id)) return undefined;
98
105
 
99
106
  const answer = await paddleJson(options.transport ?? paddleHttpFetch, `/subscriptions/${encodeURIComponent(id)}`, {
100
107
  what: `subscription ${id}'s pricing`,
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { isPaddleTransactionId } from "../../data/paddleIds";
4
5
  import type { PaymentsPurchase } from "../../data/purchase";
5
6
  import { RefundRequest, type RefundRequestOutcome, type RefundRequestStatus } from "../../data/subscription";
6
7
  import { PaymentsProviderUnavailableError, PaymentsSubscriptionChangeRefusedError } from "../../error/errors";
@@ -101,10 +102,17 @@ function refuse(detail: string): never {
101
102
  });
102
103
  }
103
104
 
104
- /** The transaction this purchase row names, or null when it names none. */
105
+ /**
106
+ * The transaction this purchase row names, or null when it names none.
107
+ *
108
+ * **The primitive decides, not a prefix test here.** `startsWith` accepted the bare prefix and Paddle's
109
+ * alphabet in uppercase, neither of which is an id the store can hold — so a malformed row cost a
110
+ * `GET /transactions/{id}` and then refused on the 404, naming the store rather than the row (#681).
111
+ * `data/paddleIds.ts` is the one place that says what a transaction id is.
112
+ */
105
113
  function transactionIdOf(purchase: PaymentsPurchase): string | null {
106
114
  const id = purchase.providerTransactionId;
107
- return id.startsWith("txn_") ? id : null;
115
+ return isPaddleTransactionId(id) ? id : null;
108
116
  }
109
117
 
110
118
  /**
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { z } from "zod";
5
+ import { isPaddleSubscriptionId } from "../../data/paddleIds";
5
6
  import type { PaymentsPurchase } from "../../data/purchase";
6
7
  import { renderMoney } from "../../data/renderMoney";
7
8
  import {
@@ -219,12 +220,16 @@ function orNull(value: string | null | undefined): string | null {
219
220
  * The subscription this purchase names, or null when it names none.
220
221
  *
221
222
  * Paddle's ids are globally prefixed, so the row's own key says what it is — `refreshPaddlePurchase`'s rule,
222
- * and for the same reason: a money row's family key is `sub_…`, and falling back to it would act on a
223
- * subscription from a row that is not one.
223
+ * and for the same reason: a money row's family key is the subscription's, and falling back to it would act
224
+ * on a subscription from a row that is not one.
225
+ *
226
+ * **`isPaddleSubscriptionId` rather than a prefix test, and all five callers feel it.** The prefix alone,
227
+ * and an id in an alphabet Paddle does not issue, used to read as subscriptions here: the read answered
228
+ * after a wasted round trip, and the other four refused on the store's answer instead of on the row (#681).
224
229
  */
225
230
  function subscriptionIdOf(purchase: PaymentsPurchase): string | null {
226
231
  const id = purchase.providerTransactionId;
227
- return id.startsWith("sub_") ? id : null;
232
+ return isPaddleSubscriptionId(id) ? id : null;
228
233
  }
229
234
 
230
235
  /** The subscription, or a refusal. Used by the write verbs, which have nothing to do without it. */
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { isPaddleTransactionId } from "../../data/paddleIds";
4
5
  import type { PurchaseEnvironment } from "../../data/purchase";
5
6
  import { PaymentsInvalidReceiptError, PaymentsVerificationFailedError } from "../../error/errors";
6
7
  import type { PaymentsPaddleCredentials } from "../../secret/registry";
@@ -51,16 +52,17 @@ export interface VerifyPaddleTransactionOptions {
51
52
  transport: PaddleHttpFetch;
52
53
  }
53
54
 
54
- /** Paddle's transaction ids. Checked before a round trip, so a malformed one costs nothing. */
55
- const TRANSACTION_ID = /^txn_[a-z0-9]+$/;
56
-
57
55
  /** Verify one submitted Paddle transaction id, and report who it says it belongs to. */
58
56
  export async function verifyPaddleTransaction(
59
57
  receipt: string,
60
58
  options: VerifyPaddleTransactionOptions,
61
59
  ): Promise<VerifiedPurchase> {
62
60
  const id = receipt.trim();
63
- if (!TRANSACTION_ID.test(id)) {
61
+ // **Checked before a round trip, so a malformed receipt costs nothing.** The pattern left this module for
62
+ // `../../data/paddleIds.ts` when the `_ptxn` reader needed the same question answered about a value out of
63
+ // a query string — one rule, several callers, rather than regexes that drift. The rest of this rail reads
64
+ // it now too, and `data/paddleIds.test.ts` is the sweep that keeps it the only answer (#681).
65
+ if (!isPaddleTransactionId(id)) {
64
66
  throw new PaymentsInvalidReceiptError({
65
67
  message: "That isn't a Paddle transaction.",
66
68
  action: "Submit the `txn_…` the checkout's completion callback handed back.",
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { pithyCommand } from "@pithy-sh/core/src/cli/command";
4
5
  import { defineSecretRegistry } from "@pithy-sh/secrets/src/registry";
5
6
  import { z } from "zod";
6
7
  import type { PaymentsRail } from "../data/rail";
@@ -289,8 +290,8 @@ export function railCredentials<R extends PaymentsRail>(
289
290
  const block = credentials[rail];
290
291
  if (!block) {
291
292
  throw new PaymentsRailNotConfiguredError({
292
- detail: `The ${rail} rail has no credentials in "${PAYMENTS_PROVIDER_SECRET}" for this environment. Run \`pithy secrets set\` for it.`,
293
- action: `Take the ${rail} credentials from ${PAYMENTS_RAIL_CONSOLES[rail]} and set them with \`pithy secrets set ${PAYMENTS_PROVIDER_SECRET}\`.`,
293
+ detail: `The ${rail} rail has no credentials in "${PAYMENTS_PROVIDER_SECRET}" for this environment. Run \`${pithyCommand("secrets update", { args: [PAYMENTS_PROVIDER_SECRET] })}\` for it.`,
294
+ action: `Take the ${rail} credentials from ${PAYMENTS_RAIL_CONSOLES[rail]} and set them with \`${pithyCommand("secrets update", { args: [PAYMENTS_PROVIDER_SECRET] })}\`.`,
294
295
  });
295
296
  }
296
297
  return block as NonNullable<PaymentsProviderCredentials[R]>;
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/payments";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.3.9";
16
+ export const PACKAGE_VERSION = "0.4.0";
@@ -2,10 +2,17 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
+ import { pithyCommandOf } from "@pithy-sh/core/src/cli/command";
5
6
  import { fromZodError, InternalError, messageOf } from "@pithy-sh/core/src/error/pithyError";
6
7
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
7
8
  import { PaymentsConfig } from "../config/config";
8
9
 
10
+ /**
11
+ * The provision that rewrites this host's config, as the host can name it: it cannot know the `apps/` directory
12
+ * of the app Worker that provisioned it, so it names no `--worker`, and the run asks (#711).
13
+ */
14
+ const PROVISION = pithyCommandOf("payments provision", {}, { runtime: true });
15
+
9
16
  /**
10
17
  * The reconcile worker's env, and the one function that reads its config out of a var.
11
18
  *
@@ -54,7 +61,7 @@ export function reconcileWorkerConfig(env: PaymentsWorkerEnv): PaymentsConfig {
54
61
  } catch (cause) {
55
62
  throw new InternalError({
56
63
  message: "The reconcile worker's PAYMENTS_CONFIG var is not valid JSON.",
57
- action: "Re-run `pithy payments provision` for this environment to rewrite it.",
64
+ action: `Re-run \`${PROVISION}\` for this environment to rewrite it.`,
58
65
  detail: messageOf(cause),
59
66
  });
60
67
  }
@@ -65,8 +72,7 @@ export function reconcileWorkerConfig(env: PaymentsWorkerEnv): PaymentsConfig {
65
72
  message: "The reconcile worker's PAYMENTS_CONFIG var is not a payments config this build can run.",
66
73
  // The two halves of the repair, in the order they have to happen: the value is the adopter's, and the
67
74
  // var is a copy of it. Fixing only the second is a provision that writes the same refusal back.
68
- action:
69
- "Set the missing keys in this Worker's pithy.config.ts — `billingSubject` is required — then re-run `pithy payments provision` for this environment.",
75
+ action: `Set the missing keys in this Worker's pithy.config.ts — \`billingSubject\` is required — then re-run \`${PROVISION}\` for this environment.`,
70
76
  });
71
77
  }
72
78
  return parsed.data;