@pithy-sh/payments 0.2.0 → 0.3.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 (53) hide show
  1. package/dist/capability.d.ts.map +1 -1
  2. package/dist/capability.js +3 -0
  3. package/dist/config/config.d.ts.map +1 -1
  4. package/dist/config/config.js +2 -1
  5. package/dist/http/routes.d.ts.map +1 -1
  6. package/dist/http/routes.js +32 -1
  7. package/dist/http/webhookGuard.d.ts +9 -6
  8. package/dist/http/webhookGuard.d.ts.map +1 -1
  9. package/dist/http/webhookGuard.js +44 -8
  10. package/dist/rails/apple/x509.d.ts.map +1 -1
  11. package/dist/rails/apple/x509.js +6 -0
  12. package/dist/rails/google/oidc.d.ts +91 -31
  13. package/dist/rails/google/oidc.d.ts.map +1 -1
  14. package/dist/rails/google/oidc.js +144 -127
  15. package/dist/rails/google/playApi.js +1 -1
  16. package/dist/rails/google/rail.d.ts +25 -0
  17. package/dist/rails/google/rail.d.ts.map +1 -1
  18. package/dist/rails/google/rail.js +2 -1
  19. package/dist/rails/paddle/rail.d.ts +10 -1
  20. package/dist/rails/paddle/rail.d.ts.map +1 -1
  21. package/dist/rails/paddle/signature.d.ts +8 -2
  22. package/dist/rails/paddle/signature.d.ts.map +1 -1
  23. package/dist/rails/paddle/signature.js +17 -2
  24. package/dist/rails/providers.d.ts +15 -0
  25. package/dist/rails/providers.d.ts.map +1 -1
  26. package/dist/rails/providers.js +2 -1
  27. package/dist/rails/stripe/rail.d.ts +11 -1
  28. package/dist/rails/stripe/rail.d.ts.map +1 -1
  29. package/dist/rails/stripe/signature.d.ts +8 -1
  30. package/dist/rails/stripe/signature.d.ts.map +1 -1
  31. package/dist/secret/branches.d.ts +39 -0
  32. package/dist/secret/branches.d.ts.map +1 -0
  33. package/dist/secret/branches.js +46 -0
  34. package/dist/secret/registry.d.ts.map +1 -1
  35. package/dist/secret/registry.js +15 -15
  36. package/dist/version.generated.d.ts +1 -1
  37. package/dist/version.generated.js +1 -1
  38. package/package.json +11 -9
  39. package/src/capability.ts +7 -0
  40. package/src/config/config.ts +10 -1
  41. package/src/http/routes.ts +32 -1
  42. package/src/http/webhookGuard.ts +40 -7
  43. package/src/rails/apple/x509.ts +18 -0
  44. package/src/rails/google/oidc.ts +194 -218
  45. package/src/rails/google/rail.ts +28 -0
  46. package/src/rails/paddle/rail.ts +10 -1
  47. package/src/rails/paddle/signature.ts +39 -3
  48. package/src/rails/providers.ts +16 -0
  49. package/src/rails/stripe/rail.ts +11 -1
  50. package/src/rails/stripe/signature.ts +8 -1
  51. package/src/secret/branches.ts +48 -0
  52. package/src/secret/registry.ts +24 -2
  53. package/src/version.generated.ts +1 -1
@@ -1,10 +1,11 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { WebhookUnverifiedError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { type JwksCache, OidcClaims, OidcJwk, OidcJwks, verifyOidcToken } from "@pithy-sh/core/src/http/oidcWebhook";
4
6
  import { z } from "zod";
5
- import { PaymentsInvalidReceiptError, PaymentsVerificationFailedError } from "../../error/errors";
6
- import { type GoogleHttpFetch, googleHttpFetch, googleJson } from "./http";
7
- import { base64UrlDecode, decodeJwtJson, splitJwt } from "./jwt";
7
+ import { PaymentsVerificationFailedError } from "../../error/errors";
8
+ import type { GoogleHttpFetch } from "./http";
8
9
 
9
10
  /**
10
11
  * The authenticity boundary on Google's webhook: the OIDC token a Pub/Sub push carries.
@@ -21,21 +22,47 @@ import { base64UrlDecode, decodeJwtJson, splitJwt } from "./jwt";
21
22
  * for. Verify the signature and skip the audience and you have built an endpoint that accepts notifications
22
23
  * from any Google customer who points a subscription at it.
23
24
  *
24
- * Four checks, in this order, and the order is deliberate:
25
+ * ## Everything above is `@pithy-sh/core/src/http/oidcWebhook`, and none of it is here
25
26
  *
26
- * 1. **Pin the algorithm before touching a key.** `alg` arrives in a header nobody has verified, so it is
27
- * parsed against a literal `RS256` rather than looked up. That is what makes the two published confusions
28
- * unreachable — `none`, which asks for the signature to be skipped, and `HS256`, which asks the verifier to
29
- * HMAC with the public key as if it were a shared secret. Neither survives a literal.
30
- * 2. **Resolve the key by `kid` from Google's published set.** Never from the token, which is why there is no
31
- * `jwk`/`x5u` handling here: a token that carries its own key is a token that verifies itself.
32
- * 3. **Verify the signature over the exact received segments** — `header.claims` as encoded.
33
- * 4. **Then read the claims,** and only then, because a claim from an unverified token means nothing.
27
+ * Algorithm pinning, key resolution by `kid`, signature verification, issuer, audience, `exp`, `nbf`, `iat`,
28
+ * the JWKS fetch and its cache: one implementation, in core, shared with every other OIDC sender the kit
29
+ * verifies. This module is the **Google specialization** — two issuer spellings, a key endpoint, an audience,
30
+ * and the one claim pair Google's own guidance adds — and nothing else. A second copy of a verifier is a
31
+ * second thing to keep current, and the thing that would drift here is an authentication boundary (#520).
34
32
  *
35
- * A failure to *read* the token is `payments/invalid_receipt`; a token that is well-formed and does not check
36
- * out is `payments/verification_failed`. On the webhook path the guard maps either to
37
- * `payments/webhook_unverified` (401), so the distinction serves the operator reading `detail` rather than the
38
- * caller — and a forger is told nothing about how close it got.
33
+ * Core is stricter than the copy it replaced, deliberately: `nbf` is honored, a non-finite skew or key-set
34
+ * lifetime is refused rather than silently disabling the freshness checks, and a claim outside `Date`'s range
35
+ * is quoted as a number rather than throwing a `RangeError` while composing the refusal it had already
36
+ * decided on.
37
+ *
38
+ * ## What a refusal is called
39
+ *
40
+ * Core answers `core/webhook_unverified` for every failing step. The rail re-codes that to
41
+ * **`payments/verification_failed`**, so the audit trail's `metadata.step` stays a `payments/*` value and the
42
+ * webhook guard's pass-through set governs the rest. Core's `detail` rides along under a `Google:` prefix.
43
+ *
44
+ * `payments/invalid_receipt` no longer appears on this path, and that is a deliberate contract change rather
45
+ * than something the refactor dropped. It meant *the token could not be read*, which is a **receipt**
46
+ * distinction: `PaymentsRailProvider.verify` uses it for a client submission, where telling a developer that
47
+ * their payload is malformed is useful. A Pub/Sub push token is not a receipt, it is a webhook credential, and
48
+ * on the webhook path the guard already collapsed both codes to `payments/webhook_unverified` (401) before
49
+ * anything reached the sender — so no caller ever saw the difference, and core's own argument for one code
50
+ * applies with full force: a forger must not learn which check it tripped. Both codes were 400 and
51
+ * `verifyGoogleOidcToken` is not exported from the package, so the change is visible in exactly one place,
52
+ * the audit row's `metadata.step`.
53
+ *
54
+ * Two codes come from core untouched, because neither is a statement about the sender and both are already in
55
+ * the webhook guard's pass-through set: `core/internal` (500) for an endpoint of ours that is not configured
56
+ * to verify anything, and `core/upstream_failed` (502) for Google's key endpoint failing to answer. The
57
+ * second replaces `payments/provider_unavailable` (503) on the JWKS hop alone — CLAUDE.md §Errors gives the
58
+ * upstream pair exactly this job, and the Play Developer API hop is untouched and still 503.
59
+ *
60
+ * **A pass-through code is a code an anonymous caller must not be able to choose**, and that is what decided
61
+ * where the line sits. A published key that is not RSA, or will not import, used to be core's 502 and is
62
+ * core's 401 now: the key was reached because a `kid` in an unverified header selected it, so a 502 there
63
+ * let a forger pick a code this rail passes through — out of the audit trail, and into Pub/Sub's indefinite
64
+ * retry — by naming one `kid` instead of another. Nothing a `kid` can steer stays in the pass-through set.
65
+ * What is left in it is failure nobody chose: the endpoint being unreachable, and our own configuration.
39
66
  */
40
67
 
41
68
  /** Where Google publishes the keys that sign an OIDC token. Public, so it is pinned here rather than stored. */
@@ -47,89 +74,39 @@ export const GOOGLE_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs";
47
74
  */
48
75
  export const GOOGLE_OIDC_ISSUERS: readonly string[] = ["https://accounts.google.com", "accounts.google.com"];
49
76
 
50
- /** How long a fetched key set is reused. Google rotates slowly, and an unknown `kid` forces a refresh anyway. */
51
- const JWKS_TTL_MS = 60 * 60 * 1000;
52
-
53
- /** Tolerance on `exp` and `iat`. A minute covers clock drift; an hour would cover a replay. */
54
- const DEFAULT_CLOCK_SKEW_SECONDS = 60;
55
-
56
- /** RSASSA-PKCS1-v1_5 with SHA-256 — the one algorithm `alg: RS256` names, fixed here rather than derived. */
57
- const RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } as const;
58
-
59
- /**
60
- * The header of a Pub/Sub push token, as tightly as it can be stated. `alg` is a literal for the reason in the
61
- * module doc; `kid` is required because a key is resolved by it and a token that names no key cannot be
62
- * checked against one.
63
- */
64
- const GoogleOidcHeader = z
65
- .object({
66
- alg: z
67
- .literal("RS256")
68
- .describe(
69
- "The signing algorithm. A literal, not a lookup: `alg` arrives in an unverified header, and accepting `none` or `HS256` from it is how JWS verifiers are bypassed.",
70
- ),
71
- kid: z
72
- .string()
73
- .min(1)
74
- .describe("Which of Google's published keys signed the token. Resolved against Google's key endpoint."),
75
- })
76
- .loose()
77
- .describe("The header of a Google-signed OIDC token, constrained to the one shape Pub/Sub sends.");
78
-
79
77
  /**
80
- * One published RSA verification key, in the shape Google's key endpoint returns. `.loose()` because Google
81
- * adds fields and a key set must not be rejected for carrying something new.
78
+ * One published RSA verification key, and the key set Google's endpoint returns.
79
+ *
80
+ * Core's schemas under the rail's published names, not copies of them. The shape is the JWKS shape — it
81
+ * belongs to RFC 7517 rather than to Google — and two declarations of one wire format is the same drift this
82
+ * module exists to remove, one layer down. The names stay because they are `@pithy-sh/payments`' public
83
+ * surface and an adopter typing a Pub/Sub emulator's key against `GoogleJwk` should not have to learn a
84
+ * second one.
82
85
  */
83
- export const GoogleJwk = z
84
- .object({
85
- kid: z.string().min(1).describe("The key id a token header names."),
86
- kty: z.string().min(1).describe("The key type. Only `RSA` is accepted — Google signs these with RSA keys."),
87
- n: z.string().min(1).describe("The RSA modulus, base64url."),
88
- e: z.string().min(1).describe("The RSA public exponent, base64url."),
89
- alg: z.string().min(1).optional().describe("The algorithm the key is published for, when stated."),
90
- use: z.string().min(1).optional().describe("What the key is published for — `sig` for a signing key."),
91
- })
92
- .loose()
93
- .describe("One of Google's published OIDC verification keys.");
94
- export type GoogleJwk = z.infer<typeof GoogleJwk>;
95
-
96
- /** Google's published key set. At least one key: an empty set is an endpoint that is not answering properly. */
97
- export const GoogleJwks = z
98
- .object({
99
- keys: z.array(GoogleJwk).min(1).describe("Every key currently signing Google OIDC tokens."),
100
- })
101
- .loose()
102
- .describe("The response of Google's OIDC key endpoint.");
103
- export type GoogleJwks = z.infer<typeof GoogleJwks>;
86
+ export const GoogleJwk = OidcJwk;
87
+ export type GoogleJwk = OidcJwk;
88
+ export const GoogleJwks = OidcJwks;
89
+ export type GoogleJwks = OidcJwks;
104
90
 
105
91
  /**
106
- * The claims a Pub/Sub push token carries, narrowed to the ones that decide anything. `.loose()` keeps the
107
- * rest — the whole token is never stored, but a claim set must not be refused for being richer than expected.
92
+ * The claims a Pub/Sub push token carries: core's, plus the two Google adds.
93
+ *
94
+ * `email` and `email_verified` are the extension, and they are the reason this schema exists at all — core
95
+ * reads what every OIDC token has and hands the rest to a predicate. Extended rather than redeclared, so
96
+ * `iss`/`aud`/`exp`/`nbf`/`iat` have one definition in the kit. Still `.loose()`: the whole token is never
97
+ * stored, and a claim set must not be refused for being richer than expected.
108
98
  */
109
- export const GoogleOidcClaims = z
110
- .object({
111
- iss: z.string().min(1).describe("Who issued the token. One of Google's two issuer spellings, and nothing else."),
112
- aud: z
113
- .string()
114
- .min(1)
115
- .describe(
116
- "Who the token was minted for — the audience configured on the push subscription. The claim that makes a token ours rather than merely Google's.",
117
- ),
118
- exp: z.number().int().describe("When the token expires, in seconds since the epoch."),
119
- iat: z.number().int().optional().describe("When the token was issued, in seconds since the epoch."),
120
- email: z
121
- .string()
122
- .min(1)
123
- .optional()
124
- .describe("The service account Pub/Sub used to mint the token. Checked against the configured one."),
125
- email_verified: z
126
- .boolean()
127
- .optional()
128
- .describe("Whether Google vouches for that address. Always true on a real push token."),
129
- sub: z.string().min(1).optional().describe("The service account's numeric id."),
130
- })
131
- .loose()
132
- .describe("The claims on a Pub/Sub push OIDC token, narrowed to the ones verification depends on.");
99
+ export const GoogleOidcClaims = OidcClaims.extend({
100
+ email: z
101
+ .string()
102
+ .min(1)
103
+ .optional()
104
+ .describe("The service account Pub/Sub used to mint the token. Checked against the configured one."),
105
+ email_verified: z
106
+ .boolean()
107
+ .optional()
108
+ .describe("Whether Google vouches for that address. Always true on a real push token."),
109
+ }).describe("The claims on a Pub/Sub push OIDC token, narrowed to the ones verification depends on.");
133
110
  export type GoogleOidcClaims = z.infer<typeof GoogleOidcClaims>;
134
111
 
135
112
  /** What verifying a push token needs. Everything is explicit, so verification is deterministic in a test. */
@@ -146,155 +123,146 @@ export interface VerifyGoogleOidcOptions {
146
123
  * Keys accepted **in addition to** Google's published set, matched by `kid`.
147
124
  *
148
125
  * Additive, so nothing can narrow production's trust: a token whose `kid` these do not cover still resolves
149
- * against Google. Two callers have a real reason — the tests, which mint their own key so the signature check
150
- * is exercised for real, and a local Pub/Sub emulator, whose tokens are signed by a key Google never saw.
126
+ * against Google. Two callers have a real reason — the tests, which mint their own key so the signature
127
+ * check is exercised for real, and a local Pub/Sub emulator, whose tokens are signed by a key Google never
128
+ * saw.
151
129
  */
152
130
  trustedKeys?: readonly GoogleJwk[];
153
- /** Tolerance on `exp` and `iat`, in seconds. Defaults to a minute. */
131
+ /**
132
+ * Tolerance on `exp`, `nbf` and `iat`, in seconds. Defaults to a minute, and must be a finite number from 0
133
+ * to core's maximum; anything else is `core/internal`, because this is the second operand of all three
134
+ * freshness comparisons and one `NaN` turns them into no-ops together.
135
+ */
154
136
  clockSkewSeconds?: number;
137
+ /**
138
+ * How long a fetched key set is held. Defaults to core's hour, and must be a finite number of seconds — a
139
+ * `NaN` is an entry that never expires, which pins a key Google has rotated out.
140
+ */
141
+ jwksTtlSeconds?: number;
142
+ /**
143
+ * Where Google's fetched keys are held between deliveries.
144
+ *
145
+ * **Injected, and there is no default**, which is the point: this used to be a module variable no caller
146
+ * owned, and the only way a test suite could stop inheriting the previous one's keys was an exported
147
+ * `resetGoogleJwksCache` whose sole purpose was to undo it. With no cache the verifier fetches per call,
148
+ * which is correct and slow; a Worker that verifies more than one notification per hour passes a
149
+ * `memoryJwksCache` built once at module scope, or one over KV to share it across isolates.
150
+ *
151
+ * It is two bounds in one object: what Google published, and when Google was last asked. The second is
152
+ * what a token naming a `kid` nobody published runs into, and with no store there is no second bound
153
+ * either — which is why the webhook path is given one and the `verify` path is not.
154
+ */
155
+ jwksCache?: JwksCache;
155
156
  }
156
157
 
157
158
  /**
158
- * Google's published keys, cached per isolate.
159
+ * Verify one Pub/Sub push OIDC token and return its claims.
159
160
  *
160
- * A cache of *public* keys is not the thing CLAUDE.md's secrets rule forbids — nothing here is confidential,
161
- * and the whole point of the endpoint is that anyone may read it. What the cache buys is one round-trip per
162
- * hour instead of one per notification, on a path that already has a mandatory Play API call in it.
161
+ * @throws {@link PaymentsVerificationFailedError} when the sender did not prove itself — an unreadable token,
162
+ * an unknown key, a key that cannot verify an `RS256` signature, a bad signature, the wrong audience, the
163
+ * wrong issuer, an expiry, the wrong service account.
164
+ * @throws `core/internal` (500) when this endpoint is not configured to verify anything — an audience that is
165
+ * empty, a clock that is not a clock, a skew or key-set lifetime that is not a number.
166
+ * @throws `core/upstream_failed` (502) when Google's key endpoint could not be read.
163
167
  */
164
- let publishedKeys: { keys: GoogleJwk[]; expiresAt: number } | null = null;
165
-
166
- /** Drop the cached key set. For tests, which must not inherit another suite's keys. */
167
- export function resetGoogleJwksCache(): void {
168
- publishedKeys = null;
169
- }
170
-
171
- /** Fetch and validate Google's key set, replacing the cache. */
172
- async function refreshPublishedKeys(transport: GoogleHttpFetch, now: Date): Promise<GoogleJwk[]> {
173
- const body = await googleJson(transport, GOOGLE_JWKS_URL, { what: "Google's OIDC verification keys" });
174
- const parsed = GoogleJwks.safeParse(body);
175
- if (!parsed.success) {
176
- // Fail closed. A verifier that cannot read a key set must deny, not wave the token through.
177
- throw new PaymentsVerificationFailedError({
178
- detail: `Google: the OIDC key endpoint answered an unexpected shape — ${issues(parsed.error)}.`,
168
+ export async function verifyGoogleOidcToken(
169
+ token: string,
170
+ options: VerifyGoogleOidcOptions,
171
+ ): Promise<GoogleOidcClaims> {
172
+ let verified: OidcClaims;
173
+ try {
174
+ verified = await verifyOidcToken(token, {
175
+ issuers: GOOGLE_OIDC_ISSUERS,
176
+ jwksUrl: GOOGLE_JWKS_URL,
177
+ audience: options.audience,
178
+ claims: (claims) => acceptedByThisEndpoint(claims, options.serviceAccountEmail),
179
+ skewSeconds: options.clockSkewSeconds,
180
+ jwksTtlSeconds: options.jwksTtlSeconds,
181
+ jwksCache: googleKeySource(options.trustedKeys, options.jwksCache),
182
+ transport: options.transport,
183
+ now: options.now,
179
184
  });
185
+ } catch (error) {
186
+ throw railCode(error);
180
187
  }
181
- publishedKeys = { keys: parsed.data.keys, expiresAt: now.getTime() + JWKS_TTL_MS };
182
- return parsed.data.keys;
188
+ // Core verified and returned the claim set; this is the Google *view* of the same object, and it cannot
189
+ // fail — `acceptedByThisEndpoint` already read both extension fields off it.
190
+ const parsed = GoogleOidcClaims.safeParse(verified);
191
+ if (!parsed.success) {
192
+ throw failed(`the token claims are not those of a Pub/Sub push token — ${issues(parsed.error)}.`);
193
+ }
194
+ return parsed.data;
183
195
  }
184
196
 
185
197
  /**
186
- * The key a token's `kid` names.
198
+ * Google's own second check, run last and handed only claims core has already proven.
199
+ *
200
+ * It **throws** rather than answering `false`. Core's own refusal for a rejected predicate names the subject
201
+ * and nothing else, which is right for a rule it cannot see inside — and wrong here, where the two things
202
+ * being asserted are named claims and an operator reading the log needs to know which one failed. A predicate
203
+ * that throws a `PaymentsVerificationFailedError` leaves `verifyOidcToken` as itself, past
204
+ * {@link railCode}'s `instanceof`, with the sentence the old verifier wrote.
187
205
  *
188
- * A `kid` the cache does not hold triggers **exactly one** refresh, which is what makes Google's key rotation
189
- * invisible: a new signing key appears in a token before anything tells us to look for it. Exactly one,
190
- * because otherwise a stream of forged tokens naming random `kid`s is a way to make us hammer Google.
206
+ * The audience says which endpoint the token was minted for; the email says which identity minted it. Both
207
+ * are always present on a real push token.
191
208
  */
192
- async function resolveKey(kid: string, options: VerifyGoogleOidcOptions): Promise<GoogleJwk> {
193
- const configured = options.trustedKeys?.find((key) => key.kid === kid);
194
- if (configured) return configured;
195
-
196
- const transport = options.transport ?? googleHttpFetch;
197
- const fresh = publishedKeys !== null && publishedKeys.expiresAt > options.now.getTime();
198
- if (fresh) {
199
- const cached = publishedKeys?.keys.find((key) => key.kid === kid);
200
- if (cached) return cached;
209
+ function acceptedByThisEndpoint(claims: OidcClaims, serviceAccountEmail: string): true {
210
+ // `.loose()`, so Google's extra claims survive core's parse as `unknown` rather than as strings.
211
+ const email = typeof claims.email === "string" ? claims.email : undefined;
212
+ if (email !== serviceAccountEmail) {
213
+ throw failed(`the token names service account "${snippet(email ?? "none")}", not the configured one.`);
201
214
  }
202
-
203
- const refreshed = await refreshPublishedKeys(transport, options.now);
204
- const found = refreshed.find((key) => key.kid === kid);
205
- if (!found) {
206
- throw new PaymentsVerificationFailedError({
207
- detail: `Google: no published key matches the token's kid "${kid}".`,
208
- });
215
+ if (claims.email_verified !== true) {
216
+ throw failed("the token's service-account address is not marked verified by Google.");
209
217
  }
210
- return found;
218
+ return true;
211
219
  }
212
220
 
213
- /** Import one published JWK as a verification key. A non-RSA key is refused rather than handed to WebCrypto. */
214
- async function importKey(jwk: GoogleJwk): Promise<CryptoKey> {
215
- if (jwk.kty !== "RSA") {
216
- throw new PaymentsVerificationFailedError({
217
- detail: `Google: published key "${jwk.kid}" is ${jwk.kty}, and only RSA keys sign an OIDC token.`,
218
- });
219
- }
220
- try {
221
- return await crypto.subtle.importKey("jwk", { ...jwk, alg: "RS256" }, RS256, false, ["verify"]);
222
- } catch (cause) {
223
- throw new PaymentsVerificationFailedError(
224
- { detail: `Google: published key "${jwk.kid}" could not be imported.` },
225
- { cause },
226
- );
227
- }
221
+ /**
222
+ * The configured keys, presented to core as a key source rather than seeded into its cache.
223
+ *
224
+ * Seeding is the obvious shape and the wrong one, because a cache is **shared** and `trustedKeys` is not. A
225
+ * key written into the store reads back to every other verifier holding that store as a key *Google
226
+ * publishes* — so a Pub/Sub emulator's key, or a suite's, would be trusted by a rail instance nobody handed
227
+ * it to. A wrapper keeps `trustedKeys` additive for its own caller and invisible to everyone else, and it is
228
+ * additive **by construction**: core still fetches for a `kid` the configured keys do not cover, and core's
229
+ * own write-back cannot evict them.
230
+ *
231
+ * No keys and no cache is `undefined`, which is core's "fetch per call" and not a cache that never holds
232
+ * anything.
233
+ *
234
+ * **The refresh claim is delegated, never answered here**, and that is the same rule one axis over: the
235
+ * window belongs to the store, because it is what bounds every caller sharing it. Answering `true` would
236
+ * hand each configured-key caller its own window, which for a store shared across isolates is the bound
237
+ * dissolved by a wrapper nobody thought was one. With no store behind it there is no window to claim and no
238
+ * bound to keep, which is core's own fetch-per-call state.
239
+ */
240
+ function googleKeySource(
241
+ trustedKeys: readonly GoogleJwk[] | undefined,
242
+ cache: JwksCache | undefined,
243
+ ): JwksCache | undefined {
244
+ if (trustedKeys === undefined || trustedKeys.length === 0) return cache;
245
+ return {
246
+ get: async (url) => [...trustedKeys, ...((await cache?.get(url)) ?? [])],
247
+ set: async (url, keys, ttlSeconds) => cache?.set(url, keys, ttlSeconds),
248
+ claimRefresh: async (url, seconds) => (await cache?.claimRefresh(url, seconds)) ?? true,
249
+ };
228
250
  }
229
251
 
230
252
  /**
231
- * Verify one Pub/Sub push OIDC token and return its claims.
253
+ * Core's refusal under the rail's own code.
232
254
  *
233
- * @throws {@link PaymentsInvalidReceiptError} when the token cannot be read — wrong segment count, a header
234
- * Google would never send, a non-JSON segment.
235
- * @throws {@link PaymentsVerificationFailedError} when it is well-formed and does not check out — an unknown
236
- * key, a bad signature, the wrong audience, the wrong issuer, an expiry, the wrong service account.
255
+ * Only `core/webhook_unverified` is re-coded, and it is re-coded by **class** rather than by reading core's
256
+ * prose — matching on a sentence is the drift this module was written to delete. `core/internal` and
257
+ * `core/upstream_failed` pass through untouched: neither is the sender's failure, both are already in the
258
+ * webhook guard's pass-through set, and re-coding either would name a culprit that is not there.
237
259
  */
238
- export async function verifyGoogleOidcToken(
239
- token: string,
240
- options: VerifyGoogleOidcOptions,
241
- ): Promise<GoogleOidcClaims> {
242
- const { head, body, mac } = splitJwt(token);
243
-
244
- const header = GoogleOidcHeader.safeParse(decodeJwtJson(head, "the token header"));
245
- if (!header.success) {
246
- throw new PaymentsInvalidReceiptError({
247
- detail: `Google: the token header is not one Pub/Sub sends — ${issues(header.error)}.`,
248
- });
249
- }
250
-
251
- const key = await importKey(await resolveKey(header.data.kid, options));
252
- const verified = await crypto.subtle.verify(
253
- RS256.name,
254
- key,
255
- base64UrlDecode(mac, "the token signature") as unknown as ArrayBuffer,
256
- new TextEncoder().encode(`${head}.${body}`) as unknown as ArrayBuffer,
260
+ function railCode(error: unknown): unknown {
261
+ if (!(error instanceof WebhookUnverifiedError)) return error;
262
+ return new PaymentsVerificationFailedError(
263
+ { detail: `Google: ${error.payload.detail ?? "the push token did not verify."}` },
264
+ { cause: error },
257
265
  );
258
- if (!verified) {
259
- throw new PaymentsVerificationFailedError({
260
- detail: `Google: the token signature does not match the signed segments under key "${header.data.kid}".`,
261
- });
262
- }
263
-
264
- // Only now. A claim read from a token whose signature has not been checked is a claim an attacker wrote.
265
- const parsed = GoogleOidcClaims.safeParse(decodeJwtJson(body, "the token claims"));
266
- if (!parsed.success) {
267
- throw new PaymentsVerificationFailedError({
268
- detail: `Google: the token claims are not those of a Pub/Sub push token — ${issues(parsed.error)}.`,
269
- });
270
- }
271
- const claims = parsed.data;
272
- const skew = options.clockSkewSeconds ?? DEFAULT_CLOCK_SKEW_SECONDS;
273
- const seconds = Math.floor(options.now.getTime() / 1000);
274
-
275
- if (!GOOGLE_OIDC_ISSUERS.includes(claims.iss)) {
276
- throw failed(`the token issuer is "${claims.iss}", not one of Google's.`);
277
- }
278
- // The boundary. Everything above proves Google minted the token; this is what proves it was minted for us.
279
- if (claims.aud !== options.audience) {
280
- throw failed(`the token audience is "${claims.aud}", and this endpoint expects "${options.audience}".`);
281
- }
282
- if (claims.exp + skew < seconds) {
283
- throw failed(`the token expired at ${new Date(claims.exp * 1000).toISOString()}.`);
284
- }
285
- if (claims.iat !== undefined && claims.iat - skew > seconds) {
286
- throw failed(`the token was issued at ${new Date(claims.iat * 1000).toISOString()}, which is in the future.`);
287
- }
288
- // Google's own guidance, and a second, independent statement: the audience says which endpoint the token was
289
- // minted for, the email says which identity minted it. Both are always present on a real push token.
290
- if (claims.email !== options.serviceAccountEmail) {
291
- throw failed(`the token names service account "${claims.email ?? "none"}", not the configured one.`);
292
- }
293
- if (claims.email_verified !== true) {
294
- throw failed("the token's service-account address is not marked verified by Google.");
295
- }
296
-
297
- return claims;
298
266
  }
299
267
 
300
268
  /** A post-signature refusal. `Google:` prefixed, and the token itself never appears. */
@@ -306,3 +274,11 @@ function failed(detail: string): PaymentsVerificationFailedError {
306
274
  function issues(error: z.ZodError): string {
307
275
  return error.issues.map((issue) => `${issue.path.join(".") || "<root>"}:${issue.code}`).join(", ");
308
276
  }
277
+
278
+ /** How much of a token-supplied value a refusal may quote. Enough to diagnose, too little to fill a log. */
279
+ const SNIPPET_LENGTH = 120;
280
+
281
+ /** A token-supplied value, bounded, so a refusal names what failed without becoming the log. */
282
+ function snippet(value: string): string {
283
+ return value.length > SNIPPET_LENGTH ? `${value.slice(0, SNIPPET_LENGTH)}…` : value;
284
+ }
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import type { JwksCache } from "@pithy-sh/core/src/http/oidcWebhook";
4
5
  import type { PaymentsPurchase } from "../../data/purchase";
5
6
  import { PaymentsVerificationFailedError } from "../../error/errors";
6
7
  import type { PaymentsGoogleCredentials } from "../../secret/registry";
@@ -68,6 +69,30 @@ export interface GoogleRailOptions {
68
69
  * Passed down by the reconciliation Workflow; absent everywhere else, where one call mints its own.
69
70
  */
70
71
  accessToken?: string;
72
+ /**
73
+ * Where Google's published keys are held between deliveries, and it is **not optional on the webhook path**.
74
+ *
75
+ * A rail is built per request — `resolveRailProvider` runs inside the guard — so this object cannot own the
76
+ * store, and a cache hung here would be one that has never held anything. It is passed in instead, from
77
+ * whatever *does* outlive a request: `registerPaymentsRoutes` builds one per registered route tree, which is
78
+ * once per isolate, and an adopter wanting a harder bound hands `RailTrustOptions.googleJwksCache` a store
79
+ * over KV.
80
+ *
81
+ * Absent is core's fetch-per-call, which is correct on the `verify` and `refresh` paths (one caller, one
82
+ * purchase, no flood to absorb) and is an outbound amplifier on the webhook: `parseNotification` resolves a
83
+ * key *before* it can check a signature, so a 49-byte forged token buys a round trip to
84
+ * `https://www.googleapis.com/oauth2/v3/certs`, 1:1, until Google rate-limits us and the genuine deliveries
85
+ * 502 alongside the forgeries — and a 502 is in the webhook guard's pass-through set, so Pub/Sub redelivers
86
+ * into the same uncached path. That is the hazard core's own `JwksCache` doc names, and this is the seam
87
+ * that answers it here.
88
+ *
89
+ * **Whatever the `kid` claims**, which is the half the first round of this missed. Holding Google's keys
90
+ * answers a token naming one of them and nothing else, and a `kid` is attacker-chosen: a random one is a
91
+ * miss, and a miss is a refresh. So the store carries a refresh window too (`JwksCache.claimRefresh`), and
92
+ * the bound it keeps is one ask per `OIDC_JWKS_MIN_REFRESH_SECONDS` per key endpoint rather than one per
93
+ * `kid` somebody invents.
94
+ */
95
+ jwksCache?: JwksCache;
71
96
  }
72
97
 
73
98
  /** The `Authorization` scheme a Pub/Sub push uses for its OIDC token. */
@@ -109,6 +134,9 @@ export function googleRail(
109
134
  now: context.now,
110
135
  transport: options.transport,
111
136
  trustedKeys: options.trustedKeys,
137
+ // The store the route owns, so one key fetch covers every delivery in its lifetime rather than one
138
+ // per delivery. See {@link GoogleRailOptions.jwksCache} for why it cannot be built here.
139
+ jwksCache: options.jwksCache,
112
140
  });
113
141
 
114
142
  const parsed = parseGoogleNotification(delivery.body, { packageName: credentials.packageName });
@@ -82,7 +82,16 @@ export interface PaddleRailOptions {
82
82
  clientToken: string;
83
83
  /** Whether checkout opens as an overlay, inline, or on Paddle's own hosted page. */
84
84
  checkout: "overlay" | "inline" | "hosted";
85
- /** How many seconds either side of now a delivery may be dated. Undefined uses the rail's 300. */
85
+ /**
86
+ * How many seconds either side of now a delivery may be dated. Undefined uses the rail's 300.
87
+ *
88
+ * Threaded down unchanged through `webhook.ts` and validated in one place, `signature.ts`, where the
89
+ * comparison is — a non-finite, negative, or over-wide window is `core/internal` there, refused before any
90
+ * delivery is judged. The layers between only apply defaults with `??`, which catches `undefined` and never
91
+ * `NaN`; one place that refuses beats three that each half-check. `paddle.webhookFreshnessSeconds` reaches
92
+ * this field and is deliberately **not** bounded again in `PaymentsPaddleSettings`: that schema parses at
93
+ * module scope, so a bound there refuses the whole Worker for one webhook route's knob.
94
+ */
86
95
  freshnessSeconds?: number;
87
96
  /**
88
97
  * The currency this project's Paddle catalog prices in, when the project declared one.
@@ -1,6 +1,8 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { SIGNED_WEBHOOK_MAX_TOLERANCE_SECONDS } from "@pithy-sh/core/src/http/webhookWindow";
4
6
  import { PaymentsVerificationFailedError } from "../../error/errors";
5
7
 
6
8
  /**
@@ -41,7 +43,9 @@ import { PaymentsVerificationFailedError } from "../../error/errors";
41
43
  * The window still earns its place, in both directions. It bounds how long a captured-but-never-delivered
42
44
  * signature stays usable, and it refuses a far-future timestamp — either a broken clock or somebody trying
43
45
  * to mint a delivery that never goes stale. Configurable, so an adopter who wants Paddle's number can set
44
- * it.
46
+ * it — bounded, and checked before it is used, because a window is only a boundary while it is a number. A
47
+ * non-finite tolerance makes `drift > tolerance` false for every delivery ever signed, which is not a wider
48
+ * window but no window at all.
45
49
  *
46
50
  * Paddle re-signs each retry attempt with a fresh `ts`, which is the only way a three-day retry window and
47
51
  * a five-second SDK tolerance could both be coherent — so the window does not silently reject retries.
@@ -82,7 +86,11 @@ export interface VerifyPaddleSignatureOptions {
82
86
  secret: string;
83
87
  /** The clock, for the freshness window. Injected so verification is deterministic. */
84
88
  now: Date;
85
- /** How many seconds either side of `now` a delivery may be dated. Undefined uses the default. */
89
+ /**
90
+ * How many seconds either side of `now` a delivery may be dated. Undefined uses the default, and anything
91
+ * present must be a finite number from 0 to {@link SIGNED_WEBHOOK_MAX_TOLERANCE_SECONDS} — anything else is
92
+ * `core/internal`, because a `NaN` here does not widen the window, it removes it.
93
+ */
86
94
  toleranceSeconds?: number;
87
95
  }
88
96
 
@@ -192,8 +200,36 @@ export async function verifyPaddleSignature(
192
200
  const parsed = header === null ? undefined : parse(header.trim());
193
201
  if (parsed === undefined) throw new PaymentsVerificationFailedError({ detail: refusal("unreadable") });
194
202
 
203
+ // Both operands of the window comparison, checked before it runs. This is the one thing this module does
204
+ // import from the core primitive, and it imports the *policy* rather than the format: `drift > tolerance` is
205
+ // false when either side is `NaN`, so a non-finite number here does not widen the window — it deletes it, and
206
+ // a captured `subscription.canceled` verifies forever. The realistic source is `Number(env.PADDLE_FRESHNESS)`
207
+ // on a variable nobody set, threaded down through two layers of `??` that each catch `undefined` and never
208
+ // `NaN`. Refused as our fault with our code, because the sender did nothing wrong.
209
+ //
210
+ // **This is the only place the bound is applied, including for the config path.** `PaymentsPaddleSettings`
211
+ // could carry a `.max()` and deliberately does not: it parses at module scope, so refusing there refuses the
212
+ // Worker — every route, over one webhook knob. Here the blast radius is the Paddle webhook endpoint, which is
213
+ // the endpoint the number is about, and Paddle redelivers for three days while it is fixed. The refusal is no
214
+ // weaker for moving: there is no way to reach the comparison below without coming through this function.
195
215
  const tolerance = options.toleranceSeconds ?? PADDLE_DEFAULT_FRESHNESS_SECONDS;
196
- const drift = Math.abs(Math.floor(options.now.getTime() / 1000) - parsed.timestamp);
216
+ if (!Number.isFinite(tolerance) || tolerance < 0 || tolerance > SIGNED_WEBHOOK_MAX_TOLERANCE_SECONDS) {
217
+ throw new InternalError({
218
+ message: "This webhook endpoint is not configured.",
219
+ action: `Give the Paddle webhook a freshness window between 0 and ${SIGNED_WEBHOOK_MAX_TOLERANCE_SECONDS} seconds.`,
220
+ detail: `Paddle: the signature check was given a freshness window of ${String(tolerance)} seconds, and a window must be a number from 0 to ${SIGNED_WEBHOOK_MAX_TOLERANCE_SECONDS}.`,
221
+ });
222
+ }
223
+ const nowSeconds = Math.floor(options.now.getTime() / 1000);
224
+ if (!Number.isFinite(nowSeconds)) {
225
+ throw new InternalError({
226
+ message: "This webhook endpoint is not configured.",
227
+ action: "Give the Paddle webhook a valid clock.",
228
+ detail:
229
+ "Paddle: the signature check was handed a clock that is not a valid Date, so no delivery's freshness can be judged.",
230
+ });
231
+ }
232
+ const drift = Math.abs(nowSeconds - parsed.timestamp);
197
233
  if (drift > tolerance) throw new PaymentsVerificationFailedError({ detail: refusal("stale") });
198
234
 
199
235
  // The timestamp is inside the signed message, so a captured signature cannot be re-dated to slip