@pithy-sh/payments 0.2.1 → 0.3.1

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.
@@ -1,11 +1,9 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { PaymentsInvalidReceiptError, PaymentsVerificationFailedError } from "../../error/errors.js";
4
- import { googleHttpFetch, googleJson } from "./http.js";
5
- import { base64UrlDecode, decodeJwtJson, splitJwt } from "./jwt.js";
6
- import { InternalError } from "@pithy-sh/core/src/error/pithyError";
3
+ import { PaymentsVerificationFailedError } from "../../error/errors.js";
4
+ import { WebhookUnverifiedError } from "@pithy-sh/core/src/error/pithyError";
7
5
  import { z } from "zod";
8
- import { OIDC_MAX_CLOCK_SKEW_SECONDS } from "@pithy-sh/core/src/http/oidcWebhook";
6
+ import { OidcClaims, OidcJwk, OidcJwks, verifyOidcToken } from "@pithy-sh/core/src/http/oidcWebhook";
9
7
  //#region src/rails/google/oidc.ts
10
8
  /**
11
9
  * The authenticity boundary on Google's webhook: the OIDC token a Pub/Sub push carries.
@@ -22,21 +20,47 @@ import { OIDC_MAX_CLOCK_SKEW_SECONDS } from "@pithy-sh/core/src/http/oidcWebhook
22
20
  * for. Verify the signature and skip the audience and you have built an endpoint that accepts notifications
23
21
  * from any Google customer who points a subscription at it.
24
22
  *
25
- * Four checks, in this order, and the order is deliberate:
26
- *
27
- * 1. **Pin the algorithm before touching a key.** `alg` arrives in a header nobody has verified, so it is
28
- * parsed against a literal `RS256` rather than looked up. That is what makes the two published confusions
29
- * unreachable — `none`, which asks for the signature to be skipped, and `HS256`, which asks the verifier to
30
- * HMAC with the public key as if it were a shared secret. Neither survives a literal.
31
- * 2. **Resolve the key by `kid` from Google's published set.** Never from the token, which is why there is no
32
- * `jwk`/`x5u` handling here: a token that carries its own key is a token that verifies itself.
33
- * 3. **Verify the signature over the exact received segments** — `header.claims` as encoded.
34
- * 4. **Then read the claims,** and only then, because a claim from an unverified token means nothing.
35
- *
36
- * A failure to *read* the token is `payments/invalid_receipt`; a token that is well-formed and does not check
37
- * out is `payments/verification_failed`. On the webhook path the guard maps either to
38
- * `payments/webhook_unverified` (401), so the distinction serves the operator reading `detail` rather than the
39
- * caller — and a forger is told nothing about how close it got.
23
+ * ## Everything above is `@pithy-sh/core/src/http/oidcWebhook`, and none of it is here
24
+ *
25
+ * Algorithm pinning, key resolution by `kid`, signature verification, issuer, audience, `exp`, `nbf`, `iat`,
26
+ * the JWKS fetch and its cache: one implementation, in core, shared with every other OIDC sender the kit
27
+ * verifies. This module is the **Google specialization** — two issuer spellings, a key endpoint, an audience,
28
+ * and the one claim pair Google's own guidance adds — and nothing else. A second copy of a verifier is a
29
+ * second thing to keep current, and the thing that would drift here is an authentication boundary (#520).
30
+ *
31
+ * Core is stricter than the copy it replaced, deliberately: `nbf` is honored, a non-finite skew or key-set
32
+ * lifetime is refused rather than silently disabling the freshness checks, and a claim outside `Date`'s range
33
+ * is quoted as a number rather than throwing a `RangeError` while composing the refusal it had already
34
+ * decided on.
35
+ *
36
+ * ## What a refusal is called
37
+ *
38
+ * Core answers `core/webhook_unverified` for every failing step. The rail re-codes that to
39
+ * **`payments/verification_failed`**, so the audit trail's `metadata.step` stays a `payments/*` value and the
40
+ * webhook guard's pass-through set governs the rest. Core's `detail` rides along under a `Google:` prefix.
41
+ *
42
+ * `payments/invalid_receipt` no longer appears on this path, and that is a deliberate contract change rather
43
+ * than something the refactor dropped. It meant *the token could not be read*, which is a **receipt**
44
+ * distinction: `PaymentsRailProvider.verify` uses it for a client submission, where telling a developer that
45
+ * their payload is malformed is useful. A Pub/Sub push token is not a receipt, it is a webhook credential, and
46
+ * on the webhook path the guard already collapsed both codes to `payments/webhook_unverified` (401) before
47
+ * anything reached the sender — so no caller ever saw the difference, and core's own argument for one code
48
+ * applies with full force: a forger must not learn which check it tripped. Both codes were 400 and
49
+ * `verifyGoogleOidcToken` is not exported from the package, so the change is visible in exactly one place,
50
+ * the audit row's `metadata.step`.
51
+ *
52
+ * Two codes come from core untouched, because neither is a statement about the sender and both are already in
53
+ * the webhook guard's pass-through set: `core/internal` (500) for an endpoint of ours that is not configured
54
+ * to verify anything, and `core/upstream_failed` (502) for Google's key endpoint failing to answer. The
55
+ * second replaces `payments/provider_unavailable` (503) on the JWKS hop alone — CLAUDE.md §Errors gives the
56
+ * upstream pair exactly this job, and the Play Developer API hop is untouched and still 503.
57
+ *
58
+ * **A pass-through code is a code an anonymous caller must not be able to choose**, and that is what decided
59
+ * where the line sits. A published key that is not RSA, or will not import, used to be core's 502 and is
60
+ * core's 401 now: the key was reached because a `kid` in an unverified header selected it, so a 502 there
61
+ * let a forger pick a code this rail passes through — out of the audit trail, and into Pub/Sub's indefinite
62
+ * retry — by naming one `kid` instead of another. Nothing a `kid` can steer stays in the pass-through set.
63
+ * What is left in it is failure nobody chose: the endpoint being unreachable, and our own configuration.
40
64
  */
41
65
  /** Where Google publishes the keys that sign an OIDC token. Public, so it is pinned here rather than stored. */
42
66
  const GOOGLE_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs";
@@ -45,141 +69,116 @@ const GOOGLE_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs";
45
69
  * decide, so both are accepted and nothing else is.
46
70
  */
47
71
  const GOOGLE_OIDC_ISSUERS = ["https://accounts.google.com", "accounts.google.com"];
48
- /** How long a fetched key set is reused. Google rotates slowly, and an unknown `kid` forces a refresh anyway. */
49
- const JWKS_TTL_MS = 36e5;
50
- /** Tolerance on `exp` and `iat`. A minute covers clock drift; an hour would cover a replay. */
51
- const DEFAULT_CLOCK_SKEW_SECONDS = 60;
52
- /** RSASSA-PKCS1-v1_5 with SHA-256 — the one algorithm `alg: RS256` names, fixed here rather than derived. */
53
- const RS256 = {
54
- name: "RSASSA-PKCS1-v1_5",
55
- hash: "SHA-256"
56
- };
57
- /**
58
- * The header of a Pub/Sub push token, as tightly as it can be stated. `alg` is a literal for the reason in the
59
- * module doc; `kid` is required because a key is resolved by it and a token that names no key cannot be
60
- * checked against one.
61
- */
62
- const GoogleOidcHeader = z.object({
63
- alg: z.literal("RS256").describe("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."),
64
- kid: z.string().min(1).describe("Which of Google's published keys signed the token. Resolved against Google's key endpoint.")
65
- }).loose().describe("The header of a Google-signed OIDC token, constrained to the one shape Pub/Sub sends.");
66
72
  /**
67
- * One published RSA verification key, in the shape Google's key endpoint returns. `.loose()` because Google
68
- * adds fields and a key set must not be rejected for carrying something new.
73
+ * One published RSA verification key, and the key set Google's endpoint returns.
74
+ *
75
+ * Core's schemas under the rail's published names, not copies of them. The shape is the JWKS shape — it
76
+ * belongs to RFC 7517 rather than to Google — and two declarations of one wire format is the same drift this
77
+ * module exists to remove, one layer down. The names stay because they are `@pithy-sh/payments`' public
78
+ * surface and an adopter typing a Pub/Sub emulator's key against `GoogleJwk` should not have to learn a
79
+ * second one.
69
80
  */
70
- const GoogleJwk = z.object({
71
- kid: z.string().min(1).describe("The key id a token header names."),
72
- kty: z.string().min(1).describe("The key type. Only `RSA` is accepted — Google signs these with RSA keys."),
73
- n: z.string().min(1).describe("The RSA modulus, base64url."),
74
- e: z.string().min(1).describe("The RSA public exponent, base64url."),
75
- alg: z.string().min(1).optional().describe("The algorithm the key is published for, when stated."),
76
- use: z.string().min(1).optional().describe("What the key is published for — `sig` for a signing key.")
77
- }).loose().describe("One of Google's published OIDC verification keys.");
78
- /** Google's published key set. At least one key: an empty set is an endpoint that is not answering properly. */
79
- const GoogleJwks = z.object({ keys: z.array(GoogleJwk).min(1).describe("Every key currently signing Google OIDC tokens.") }).loose().describe("The response of Google's OIDC key endpoint.");
81
+ const GoogleJwk = OidcJwk;
82
+ const GoogleJwks = OidcJwks;
80
83
  /**
81
- * The claims a Pub/Sub push token carries, narrowed to the ones that decide anything. `.loose()` keeps the
82
- * rest — the whole token is never stored, but a claim set must not be refused for being richer than expected.
84
+ * The claims a Pub/Sub push token carries: core's, plus the two Google adds.
85
+ *
86
+ * `email` and `email_verified` are the extension, and they are the reason this schema exists at all — core
87
+ * reads what every OIDC token has and hands the rest to a predicate. Extended rather than redeclared, so
88
+ * `iss`/`aud`/`exp`/`nbf`/`iat` have one definition in the kit. Still `.loose()`: the whole token is never
89
+ * stored, and a claim set must not be refused for being richer than expected.
83
90
  */
84
- const GoogleOidcClaims = z.object({
85
- iss: z.string().min(1).describe("Who issued the token. One of Google's two issuer spellings, and nothing else."),
86
- aud: z.string().min(1).describe("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."),
87
- exp: z.number().int().describe("When the token expires, in seconds since the epoch."),
88
- iat: z.number().int().optional().describe("When the token was issued, in seconds since the epoch."),
91
+ const GoogleOidcClaims = OidcClaims.extend({
89
92
  email: z.string().min(1).optional().describe("The service account Pub/Sub used to mint the token. Checked against the configured one."),
90
- email_verified: z.boolean().optional().describe("Whether Google vouches for that address. Always true on a real push token."),
91
- sub: z.string().min(1).optional().describe("The service account's numeric id.")
92
- }).loose().describe("The claims on a Pub/Sub push OIDC token, narrowed to the ones verification depends on.");
93
+ email_verified: z.boolean().optional().describe("Whether Google vouches for that address. Always true on a real push token.")
94
+ }).describe("The claims on a Pub/Sub push OIDC token, narrowed to the ones verification depends on.");
93
95
  /**
94
- * Google's published keys, cached per isolate.
96
+ * Verify one Pub/Sub push OIDC token and return its claims.
95
97
  *
96
- * A cache of *public* keys is not the thing CLAUDE.md's secrets rule forbids — nothing here is confidential,
97
- * and the whole point of the endpoint is that anyone may read it. What the cache buys is one round-trip per
98
- * hour instead of one per notification, on a path that already has a mandatory Play API call in it.
98
+ * @throws {@link PaymentsVerificationFailedError} when the sender did not prove itself — an unreadable token,
99
+ * an unknown key, a key that cannot verify an `RS256` signature, a bad signature, the wrong audience, the
100
+ * wrong issuer, an expiry, the wrong service account.
101
+ * @throws `core/internal` (500) when this endpoint is not configured to verify anything — an audience that is
102
+ * empty, a clock that is not a clock, a skew or key-set lifetime that is not a number.
103
+ * @throws `core/upstream_failed` (502) when Google's key endpoint could not be read.
99
104
  */
100
- let publishedKeys = null;
101
- /** Drop the cached key set. For tests, which must not inherit another suite's keys. */
102
- function resetGoogleJwksCache() {
103
- publishedKeys = null;
104
- }
105
- /** Fetch and validate Google's key set, replacing the cache. */
106
- async function refreshPublishedKeys(transport, now) {
107
- const body = await googleJson(transport, GOOGLE_JWKS_URL, { what: "Google's OIDC verification keys" });
108
- const parsed = GoogleJwks.safeParse(body);
109
- if (!parsed.success) throw new PaymentsVerificationFailedError({ detail: `Google: the OIDC key endpoint answered an unexpected shape — ${issues(parsed.error)}.` });
110
- publishedKeys = {
111
- keys: parsed.data.keys,
112
- expiresAt: now.getTime() + JWKS_TTL_MS
113
- };
114
- return parsed.data.keys;
105
+ async function verifyGoogleOidcToken(token, options) {
106
+ let verified;
107
+ try {
108
+ verified = await verifyOidcToken(token, {
109
+ issuers: GOOGLE_OIDC_ISSUERS,
110
+ jwksUrl: GOOGLE_JWKS_URL,
111
+ audience: options.audience,
112
+ claims: (claims) => acceptedByThisEndpoint(claims, options.serviceAccountEmail),
113
+ skewSeconds: options.clockSkewSeconds,
114
+ jwksTtlSeconds: options.jwksTtlSeconds,
115
+ jwksCache: googleKeySource(options.trustedKeys, options.jwksCache),
116
+ transport: options.transport,
117
+ now: options.now
118
+ });
119
+ } catch (error) {
120
+ throw railCode(error);
121
+ }
122
+ const parsed = GoogleOidcClaims.safeParse(verified);
123
+ if (!parsed.success) throw failed(`the token claims are not those of a Pub/Sub push token — ${issues(parsed.error)}.`);
124
+ return parsed.data;
115
125
  }
116
126
  /**
117
- * The key a token's `kid` names.
127
+ * Google's own second check, run last and handed only claims core has already proven.
128
+ *
129
+ * It **throws** rather than answering `false`. Core's own refusal for a rejected predicate names the subject
130
+ * and nothing else, which is right for a rule it cannot see inside — and wrong here, where the two things
131
+ * being asserted are named claims and an operator reading the log needs to know which one failed. A predicate
132
+ * that throws a `PaymentsVerificationFailedError` leaves `verifyOidcToken` as itself, past
133
+ * {@link railCode}'s `instanceof`, with the sentence the old verifier wrote.
118
134
  *
119
- * A `kid` the cache does not hold triggers **exactly one** refresh, which is what makes Google's key rotation
120
- * invisible: a new signing key appears in a token before anything tells us to look for it. Exactly one,
121
- * because otherwise a stream of forged tokens naming random `kid`s is a way to make us hammer Google.
135
+ * The audience says which endpoint the token was minted for; the email says which identity minted it. Both
136
+ * are always present on a real push token.
122
137
  */
123
- async function resolveKey(kid, options) {
124
- const configured = options.trustedKeys?.find((key) => key.kid === kid);
125
- if (configured) return configured;
126
- const transport = options.transport ?? googleHttpFetch;
127
- if (publishedKeys !== null && publishedKeys.expiresAt > options.now.getTime()) {
128
- const cached = publishedKeys?.keys.find((key) => key.kid === kid);
129
- if (cached) return cached;
130
- }
131
- const found = (await refreshPublishedKeys(transport, options.now)).find((key) => key.kid === kid);
132
- if (!found) throw new PaymentsVerificationFailedError({ detail: `Google: no published key matches the token's kid "${kid}".` });
133
- return found;
138
+ function acceptedByThisEndpoint(claims, serviceAccountEmail) {
139
+ const email = typeof claims.email === "string" ? claims.email : void 0;
140
+ if (email !== serviceAccountEmail) throw failed(`the token names service account "${snippet(email ?? "none")}", not the configured one.`);
141
+ if (claims.email_verified !== true) throw failed("the token's service-account address is not marked verified by Google.");
142
+ return true;
134
143
  }
135
- /** Import one published JWK as a verification key. A non-RSA key is refused rather than handed to WebCrypto. */
136
- async function importKey(jwk) {
137
- if (jwk.kty !== "RSA") throw new PaymentsVerificationFailedError({ detail: `Google: published key "${jwk.kid}" is ${jwk.kty}, and only RSA keys sign an OIDC token.` });
138
- try {
139
- return await crypto.subtle.importKey("jwk", {
140
- ...jwk,
141
- alg: "RS256"
142
- }, RS256, false, ["verify"]);
143
- } catch (cause) {
144
- throw new PaymentsVerificationFailedError({ detail: `Google: published key "${jwk.kid}" could not be imported.` }, { cause });
145
- }
144
+ /**
145
+ * The configured keys, presented to core as a key source rather than seeded into its cache.
146
+ *
147
+ * Seeding is the obvious shape and the wrong one, because a cache is **shared** and `trustedKeys` is not. A
148
+ * key written into the store reads back to every other verifier holding that store as a key *Google
149
+ * publishes* — so a Pub/Sub emulator's key, or a suite's, would be trusted by a rail instance nobody handed
150
+ * it to. A wrapper keeps `trustedKeys` additive for its own caller and invisible to everyone else, and it is
151
+ * additive **by construction**: core still fetches for a `kid` the configured keys do not cover, and core's
152
+ * own write-back cannot evict them.
153
+ *
154
+ * No keys and no cache is `undefined`, which is core's "fetch per call" and not a cache that never holds
155
+ * anything.
156
+ *
157
+ * **The refresh claim is delegated, never answered here**, and that is the same rule one axis over: the
158
+ * window belongs to the store, because it is what bounds every caller sharing it. Answering `true` would
159
+ * hand each configured-key caller its own window, which for a store shared across isolates is the bound
160
+ * dissolved by a wrapper nobody thought was one. With no store behind it there is no window to claim and no
161
+ * bound to keep, which is core's own fetch-per-call state.
162
+ */
163
+ function googleKeySource(trustedKeys, cache) {
164
+ if (trustedKeys === void 0 || trustedKeys.length === 0) return cache;
165
+ return {
166
+ get: async (url) => [...trustedKeys, ...await cache?.get(url) ?? []],
167
+ set: async (url, keys, ttlSeconds) => cache?.set(url, keys, ttlSeconds),
168
+ claimRefresh: async (url, seconds) => await cache?.claimRefresh(url, seconds) ?? true
169
+ };
146
170
  }
147
171
  /**
148
- * Verify one Pub/Sub push OIDC token and return its claims.
172
+ * Core's refusal under the rail's own code.
149
173
  *
150
- * @throws {@link PaymentsInvalidReceiptError} when the token cannot be read — wrong segment count, a header
151
- * Google would never send, a non-JSON segment.
152
- * @throws {@link PaymentsVerificationFailedError} when it is well-formed and does not check out — an unknown
153
- * key, a bad signature, the wrong audience, the wrong issuer, an expiry, the wrong service account.
174
+ * Only `core/webhook_unverified` is re-coded, and it is re-coded by **class** rather than by reading core's
175
+ * prose — matching on a sentence is the drift this module was written to delete. `core/internal` and
176
+ * `core/upstream_failed` pass through untouched: neither is the sender's failure, both are already in the
177
+ * webhook guard's pass-through set, and re-coding either would name a culprit that is not there.
154
178
  */
155
- async function verifyGoogleOidcToken(token, options) {
156
- const { head, body, mac } = splitJwt(token);
157
- const header = GoogleOidcHeader.safeParse(decodeJwtJson(head, "the token header"));
158
- if (!header.success) throw new PaymentsInvalidReceiptError({ detail: `Google: the token header is not one Pub/Sub sends — ${issues(header.error)}.` });
159
- const key = await importKey(await resolveKey(header.data.kid, options));
160
- if (!await crypto.subtle.verify(RS256.name, key, base64UrlDecode(mac, "the token signature"), new TextEncoder().encode(`${head}.${body}`))) throw new PaymentsVerificationFailedError({ detail: `Google: the token signature does not match the signed segments under key "${header.data.kid}".` });
161
- const parsed = GoogleOidcClaims.safeParse(decodeJwtJson(body, "the token claims"));
162
- if (!parsed.success) throw new PaymentsVerificationFailedError({ detail: `Google: the token claims are not those of a Pub/Sub push token — ${issues(parsed.error)}.` });
163
- const claims = parsed.data;
164
- const skew = options.clockSkewSeconds ?? DEFAULT_CLOCK_SKEW_SECONDS;
165
- if (!Number.isFinite(skew) || skew < 0 || skew > OIDC_MAX_CLOCK_SKEW_SECONDS) throw new InternalError({
166
- message: "This webhook endpoint is not configured.",
167
- action: `Give the Google Pub/Sub webhook a clock skew between 0 and ${OIDC_MAX_CLOCK_SKEW_SECONDS} seconds.`,
168
- detail: `Google: the push-token check was given a clock skew of ${String(skew)} seconds, and a tolerance must be a number from 0 to ${OIDC_MAX_CLOCK_SKEW_SECONDS}.`
169
- });
170
- const seconds = Math.floor(options.now.getTime() / 1e3);
171
- if (!Number.isFinite(seconds)) throw new InternalError({
172
- message: "This webhook endpoint is not configured.",
173
- action: "Give the Google Pub/Sub webhook a valid clock.",
174
- detail: "Google: the push-token check was handed a clock that is not a valid Date, so no token's freshness can be judged."
175
- });
176
- if (!GOOGLE_OIDC_ISSUERS.includes(claims.iss)) throw failed(`the token issuer is "${claims.iss}", not one of Google's.`);
177
- if (claims.aud !== options.audience) throw failed(`the token audience is "${claims.aud}", and this endpoint expects "${options.audience}".`);
178
- if (claims.exp + skew < seconds) throw failed(`the token expired at ${(/* @__PURE__ */ new Date(claims.exp * 1e3)).toISOString()}.`);
179
- if (claims.iat !== void 0 && claims.iat - skew > seconds) throw failed(`the token was issued at ${(/* @__PURE__ */ new Date(claims.iat * 1e3)).toISOString()}, which is in the future.`);
180
- if (claims.email !== options.serviceAccountEmail) throw failed(`the token names service account "${claims.email ?? "none"}", not the configured one.`);
181
- if (claims.email_verified !== true) throw failed("the token's service-account address is not marked verified by Google.");
182
- return claims;
179
+ function railCode(error) {
180
+ if (!(error instanceof WebhookUnverifiedError)) return error;
181
+ return new PaymentsVerificationFailedError({ detail: `Google: ${error.payload.detail ?? "the push token did not verify."}` }, { cause: error });
183
182
  }
184
183
  /** A post-signature refusal. `Google:` prefixed, and the token itself never appears. */
185
184
  function failed(detail) {
@@ -189,5 +188,11 @@ function failed(detail) {
189
188
  function issues(error) {
190
189
  return error.issues.map((issue) => `${issue.path.join(".") || "<root>"}:${issue.code}`).join(", ");
191
190
  }
191
+ /** How much of a token-supplied value a refusal may quote. Enough to diagnose, too little to fill a log. */
192
+ const SNIPPET_LENGTH = 120;
193
+ /** A token-supplied value, bounded, so a refusal names what failed without becoming the log. */
194
+ function snippet(value) {
195
+ return value.length > SNIPPET_LENGTH ? `${value.slice(0, SNIPPET_LENGTH)}…` : value;
196
+ }
192
197
  //#endregion
193
- export { GOOGLE_JWKS_URL, GOOGLE_OIDC_ISSUERS, GoogleJwk, GoogleJwks, GoogleOidcClaims, resetGoogleJwksCache, verifyGoogleOidcToken };
198
+ export { GOOGLE_JWKS_URL, GOOGLE_OIDC_ISSUERS, GoogleJwk, GoogleJwks, GoogleOidcClaims, verifyGoogleOidcToken };
@@ -1,9 +1,9 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { PaymentsProviderUnavailableError, PaymentsRailNotConfiguredError, PaymentsVerificationFailedError } from "../../error/errors.js";
4
+ import { pauseResumesAt } from "../../data/pause.js";
4
5
  import { googleHttpFetch, googleJson } from "./http.js";
5
6
  import { base64UrlEncode, pemPrivateKey } from "./jwt.js";
6
- import { pauseResumesAt } from "../../data/pause.js";
7
7
  import { z } from "zod";
8
8
  //#region src/rails/google/playApi.ts
9
9
  /**
@@ -1,5 +1,6 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
+ import type { JwksCache } from "@pithy-sh/core/src/http/oidcWebhook";
3
4
  import type { PaymentsGoogleCredentials } from "../../secret/registry";
4
5
  import type { PaymentsRailProvider } from "../contract";
5
6
  import type { GoogleHttpFetch } from "./http";
@@ -53,6 +54,30 @@ export interface GoogleRailOptions {
53
54
  * Passed down by the reconciliation Workflow; absent everywhere else, where one call mints its own.
54
55
  */
55
56
  accessToken?: string;
57
+ /**
58
+ * Where Google's published keys are held between deliveries, and it is **not optional on the webhook path**.
59
+ *
60
+ * A rail is built per request — `resolveRailProvider` runs inside the guard — so this object cannot own the
61
+ * store, and a cache hung here would be one that has never held anything. It is passed in instead, from
62
+ * whatever *does* outlive a request: `registerPaymentsRoutes` builds one per registered route tree, which is
63
+ * once per isolate, and an adopter wanting a harder bound hands `RailTrustOptions.googleJwksCache` a store
64
+ * over KV.
65
+ *
66
+ * Absent is core's fetch-per-call, which is correct on the `verify` and `refresh` paths (one caller, one
67
+ * purchase, no flood to absorb) and is an outbound amplifier on the webhook: `parseNotification` resolves a
68
+ * key *before* it can check a signature, so a 49-byte forged token buys a round trip to
69
+ * `https://www.googleapis.com/oauth2/v3/certs`, 1:1, until Google rate-limits us and the genuine deliveries
70
+ * 502 alongside the forgeries — and a 502 is in the webhook guard's pass-through set, so Pub/Sub redelivers
71
+ * into the same uncached path. That is the hazard core's own `JwksCache` doc names, and this is the seam
72
+ * that answers it here.
73
+ *
74
+ * **Whatever the `kid` claims**, which is the half the first round of this missed. Holding Google's keys
75
+ * answers a token naming one of them and nothing else, and a `kid` is attacker-chosen: a random one is a
76
+ * miss, and a miss is a refresh. So the store carries a refresh window too (`JwksCache.claimRefresh`), and
77
+ * the bound it keeps is one ask per `OIDC_JWKS_MIN_REFRESH_SECONDS` per key endpoint rather than one per
78
+ * `kid` somebody invents.
79
+ */
80
+ jwksCache?: JwksCache;
56
81
  }
57
82
  /** The Google Play rail. Verifies client submissions at Play, and Pub/Sub pushes on the webhook. */
58
83
  export declare function googleRail(credentials: PaymentsGoogleCredentials, options?: GoogleRailOptions): PaymentsRailProvider;
@@ -1 +1 @@
1
- {"version":3,"file":"rail.d.ts","sourceRoot":"","sources":["../../../src/rails/google/rail.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EACV,oBAAoB,EAMrB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,KAAK,SAAS,EAAyB,MAAM,QAAQ,CAAC;AAK/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH;;;;;;;GAOG;AACH,MAAM,WAAW,iBAAiB;IAChC,0FAA0F;IAC1F,WAAW,CAAC,EAAE,SAAS,SAAS,EAAE,CAAC;IACnC,mGAAmG;IACnG,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAKD,oGAAoG;AACpG,wBAAgB,UAAU,CACxB,WAAW,EAAE,yBAAyB,EACtC,OAAO,GAAE,iBAAsB,GAC9B,oBAAoB,CA8FtB"}
1
+ {"version":3,"file":"rail.d.ts","sourceRoot":"","sources":["../../../src/rails/google/rail.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qCAAqC,CAAC;AAGrE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EACV,oBAAoB,EAMrB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,KAAK,SAAS,EAAyB,MAAM,QAAQ,CAAC;AAK/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH;;;;;;;GAOG;AACH,MAAM,WAAW,iBAAiB;IAChC,0FAA0F;IAC1F,WAAW,CAAC,EAAE,SAAS,SAAS,EAAE,CAAC;IACnC,mGAAmG;IACnG,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,SAAS,CAAC,EAAE,SAAS,CAAC;CACvB;AAKD,oGAAoG;AACpG,wBAAgB,UAAU,CACxB,WAAW,EAAE,yBAAyB,EACtC,OAAO,GAAE,iBAAsB,GAC9B,oBAAoB,CAiGtB"}
@@ -27,7 +27,8 @@ function googleRail(credentials, options = {}) {
27
27
  serviceAccountEmail: credentials.serviceAccountEmail,
28
28
  now: context.now,
29
29
  transport: options.transport,
30
- trustedKeys: options.trustedKeys
30
+ trustedKeys: options.trustedKeys,
31
+ jwksCache: options.jwksCache
31
32
  });
32
33
  const parsed = parseGoogleNotification(delivery.body, { packageName: credentials.packageName });
33
34
  if (parsed.pointer === null) return {
@@ -1,5 +1,6 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
+ import type { JwksCache } from "@pithy-sh/core/src/http/oidcWebhook";
3
4
  import type { PaymentsConfig } from "../config/config";
4
5
  import type { PaymentsRail } from "../data/rail";
5
6
  import { type PaymentsProviderCredentials } from "../secret/registry";
@@ -56,6 +57,20 @@ export interface RailTrustOptions {
56
57
  googleTransport?: GoogleHttpFetch;
57
58
  /** A Play access token already minted, so a batch of Google refreshes pays for one. */
58
59
  googleAccessToken?: string;
60
+ /**
61
+ * Where the Google rail holds Google's published verification keys between deliveries.
62
+ *
63
+ * **The third kind of seam, and the only one that is about availability rather than trust or cost.** A rail
64
+ * is built per request, so it cannot own a store that outlives one; the webhook path resolves a key before
65
+ * it can check a signature; and therefore with no store an anonymous POST buys a round trip to Google,
66
+ * 1:1 — whether it names a `kid` Google publishes, which the held keys answer, or one nobody ever
67
+ * published, which only the store's refresh window does. `registerPaymentsRoutes` supplies one per
68
+ * registered route tree when a caller gives none; this parameter is for the caller that wants a harder
69
+ * bound than an isolate's memory, a store over KV or the Cache API that every isolate shares — and sharing
70
+ * it shares the window with it. Additive to nothing and narrowing nothing: core still fetches for a `kid`
71
+ * the store does not hold once the window is over, which is how key rotation stays invisible.
72
+ */
73
+ googleJwksCache?: JwksCache;
59
74
  /** The HTTP transport the Stripe rail reaches Stripe's API through. Defaults to `fetch`. */
60
75
  stripeTransport?: StripeHttpFetch;
61
76
  /** The HTTP transport the Lemon Squeezy rail reaches its API through. Defaults to `fetch`. */
@@ -1 +1 @@
1
- {"version":3,"file":"providers.d.ts","sourceRoot":"","sources":["../../src/rails/providers.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,EAAE,KAAK,2BAA2B,EAAmB,MAAM,oBAAoB,CAAC;AACvF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAEnD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAEhE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAGpD;;;;;;;;;;;GAWG;AAEH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,WAAW,gBAAgB;IAC/B,mFAAmF;IACnF,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,uGAAuG;IACvG,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,6FAA6F;IAC7F,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,4FAA4F;IAC5F,iBAAiB,CAAC,EAAE,SAAS,SAAS,EAAE,CAAC;IACzC,kGAAkG;IAClG,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,uFAAuF;IACvF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,4FAA4F;IAC5F,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,8FAA8F;IAC9F,qBAAqB,CAAC,EAAE,qBAAqB,CAAC;IAC9C,uFAAuF;IACvF,eAAe,CAAC,EAAE,eAAe,CAAC;CACnC;AAgED,+EAA+E;AAC/E,wBAAgB,gBAAgB,IAAI,SAAS,YAAY,EAAE,CAE1D;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,cAAc,EACtB,WAAW,EAAE,2BAA2B,EACxC,KAAK,GAAE,gBAAqB,GAC3B,oBAAoB,CAatB"}
1
+ {"version":3,"file":"providers.d.ts","sourceRoot":"","sources":["../../src/rails/providers.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qCAAqC,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,EAAE,KAAK,2BAA2B,EAAmB,MAAM,oBAAoB,CAAC;AACvF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAEnD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAEhE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAGpD;;;;;;;;;;;GAWG;AAEH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,WAAW,gBAAgB;IAC/B,mFAAmF;IACnF,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,uGAAuG;IACvG,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,6FAA6F;IAC7F,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,4FAA4F;IAC5F,iBAAiB,CAAC,EAAE,SAAS,SAAS,EAAE,CAAC;IACzC,kGAAkG;IAClG,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,uFAAuF;IACvF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;;;;;;;;;;OAYG;IACH,eAAe,CAAC,EAAE,SAAS,CAAC;IAC5B,4FAA4F;IAC5F,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,8FAA8F;IAC9F,qBAAqB,CAAC,EAAE,qBAAqB,CAAC;IAC9C,uFAAuF;IACvF,eAAe,CAAC,EAAE,eAAe,CAAC;CACnC;AAiED,+EAA+E;AAC/E,wBAAgB,gBAAgB,IAAI,SAAS,YAAY,EAAE,CAE1D;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,cAAc,EACtB,WAAW,EAAE,2BAA2B,EACxC,KAAK,GAAE,gBAAqB,GAC3B,oBAAoB,CAatB"}
@@ -23,7 +23,8 @@ const RAIL_FACTORIES = {
23
23
  google: (credentials, trust) => googleRail(railCredentials(credentials, "google"), {
24
24
  trustedKeys: trust.googleTrustedKeys,
25
25
  transport: trust.googleTransport,
26
- accessToken: trust.googleAccessToken
26
+ accessToken: trust.googleAccessToken,
27
+ jwksCache: trust.googleJwksCache
27
28
  }),
28
29
  stripe: (credentials, trust) => stripeRail(railCredentials(credentials, "stripe"), { transport: trust.stripeTransport }),
29
30
  lemonSqueezy: (credentials, trust, config) => lemonSqueezyRail(railCredentials(credentials, "lemonSqueezy"), {
@@ -20,4 +20,20 @@ import type { PaymentsRailToggles } from "../config/config";
20
20
  * order every other per-rail sweep in this package uses.
21
21
  */
22
22
  export declare function paymentsSecretBranches(rails: PaymentsRailToggles): SecretBranchSeam;
23
+ /**
24
+ * **The same question one level up: is the secret reachable at all (#541).**
25
+ *
26
+ * {@link paymentsSecretBranches} says which *blocks* of the bundle a project will be asked for. With
27
+ * every rail off there are none — and the bundle itself is then a value nothing will ever read, because
28
+ * every read of it is behind a rail: the checkout routes, the webhook guard, and the reconciliation
29
+ * Workflow each refuse before they reach the store. Every toggle defaults `false`, so this is the state
30
+ * `pithy add payments` leaves a project in until a rail is named, and `pithy doctor` listed the
31
+ * credential as outstanding work under *"fine to leave until you need it"* for the whole of it.
32
+ *
33
+ * Declared here rather than derived by the CLI from an empty branch list, for
34
+ * {@link paymentsSecretBranches}' own reason: an empty list is *no blocks to ask for*, which is not the
35
+ * same claim as *nothing reads this*, and a reporting command that conflated the two would be right by
36
+ * luck. The capability holds the toggles, so the capability answers.
37
+ */
38
+ export declare function paymentsInapplicableSecrets(rails: PaymentsRailToggles): Record<string, string>;
23
39
  //# sourceMappingURL=branches.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"branches.d.ts","sourceRoot":"","sources":["../../src/secret/branches.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AACjF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAI5D;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,mBAAmB,GAAG,gBAAgB,CAEnF"}
1
+ {"version":3,"file":"branches.d.ts","sourceRoot":"","sources":["../../src/secret/branches.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AACjF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAI5D;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,mBAAmB,GAAG,gBAAgB,CAEnF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,mBAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAG9F"}
@@ -23,5 +23,24 @@ import { PAYMENTS_PROVIDER_SECRET } from "./registry.js";
23
23
  function paymentsSecretBranches(rails) {
24
24
  return { [PAYMENTS_PROVIDER_SECRET]: PAYMENTS_RAILS.filter((rail) => rails[rail]) };
25
25
  }
26
+ /**
27
+ * **The same question one level up: is the secret reachable at all (#541).**
28
+ *
29
+ * {@link paymentsSecretBranches} says which *blocks* of the bundle a project will be asked for. With
30
+ * every rail off there are none — and the bundle itself is then a value nothing will ever read, because
31
+ * every read of it is behind a rail: the checkout routes, the webhook guard, and the reconciliation
32
+ * Workflow each refuse before they reach the store. Every toggle defaults `false`, so this is the state
33
+ * `pithy add payments` leaves a project in until a rail is named, and `pithy doctor` listed the
34
+ * credential as outstanding work under *"fine to leave until you need it"* for the whole of it.
35
+ *
36
+ * Declared here rather than derived by the CLI from an empty branch list, for
37
+ * {@link paymentsSecretBranches}' own reason: an empty list is *no blocks to ask for*, which is not the
38
+ * same claim as *nothing reads this*, and a reporting command that conflated the two would be right by
39
+ * luck. The capability holds the toggles, so the capability answers.
40
+ */
41
+ function paymentsInapplicableSecrets(rails) {
42
+ if (PAYMENTS_RAILS.some((rail) => rails[rail])) return {};
43
+ return { [PAYMENTS_PROVIDER_SECRET]: "payments() enables no rail, so no code path reads a credential" };
44
+ }
26
45
  //#endregion
27
- export { paymentsSecretBranches };
46
+ export { paymentsInapplicableSecrets, paymentsSecretBranches };
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/payments";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.2.1";
6
+ export declare const PACKAGE_VERSION = "0.3.1";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/payments";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.2.1";
7
+ const PACKAGE_VERSION = "0.3.1";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/payments",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,8 +36,15 @@
36
36
  "clean": "rm -rf dist .turbo",
37
37
  "reset": "bun run clean && rm -rf node_modules"
38
38
  },
39
+ "dependencies": {
40
+ "@cloudflare/workers-types": "^5.20260729.1",
41
+ "@hono/zod-validator": "^0.9.0",
42
+ "@paddle/paddle-js": "^1.6.4"
43
+ },
39
44
  "peerDependencies": {
40
- "@pithy-sh/ledger": "^0.1.6",
45
+ "@pithy-sh/core": "^0.5.0",
46
+ "@pithy-sh/ledger": "^0.2.1",
47
+ "@pithy-sh/secrets": "^0.2.1",
41
48
  "hono": "^4.13.2",
42
49
  "kysely": "^0.29.0",
43
50
  "react": "^19.0.0",
@@ -51,16 +58,11 @@
51
58
  "optional": true
52
59
  }
53
60
  },
54
- "dependencies": {
55
- "@cloudflare/workers-types": "^5.20260729.1",
56
- "@hono/zod-validator": "^0.9.0",
57
- "@paddle/paddle-js": "^1.6.4",
58
- "@pithy-sh/core": "^0.3.0",
59
- "@pithy-sh/secrets": "^0.1.6"
60
- },
61
61
  "devDependencies": {
62
62
  "@cloudflare/vitest-plugin": "^1.0.0",
63
+ "@pithy-sh/core": "workspace:*",
63
64
  "@pithy-sh/ledger": "workspace:*",
65
+ "@pithy-sh/secrets": "workspace:*",
64
66
  "@pithy-sh/tsconfig": "workspace:*",
65
67
  "@types/node": "^22.15.0",
66
68
  "@types/react": "^19.2.17",
package/src/capability.ts CHANGED
@@ -22,7 +22,7 @@ import { paymentsManifestConfig } from "./http/manifestConfig";
22
22
  import { registerPaymentsRoutes } from "./http/routes";
23
23
  import { paymentsAdminRoutes } from "./http/scopes";
24
24
  import { payments_0001_purchases } from "./migrations/0001_purchases";
25
- import { paymentsSecretBranches } from "./secret/branches";
25
+ import { paymentsInapplicableSecrets, paymentsSecretBranches } from "./secret/branches";
26
26
  import { paymentsSecretsRegistry } from "./secret/registry";
27
27
  import { paymentsExampleSeed } from "./seeds/example";
28
28
  import { PACKAGE_VERSION } from "./version.generated";
@@ -347,6 +347,9 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
347
347
  // Which rails' credentials `pithy secrets create payments-provider-credentials` asks for. The
348
348
  // schema knows five are possible; only this catalog knows which are on. See `secret/branches.ts`.
349
349
  secretBranches: paymentsSecretBranches(resolved.rails),
350
+ // And whether the bundle is reachable at all. With every rail off, every read of it is behind a
351
+ // refusal — so it is not outstanding work, and `pithy doctor` asked for it anyway (#541).
352
+ inapplicableSecrets: paymentsInapplicableSecrets(resolved.rails),
350
353
  // The one durable job: the nightly reconciliation pass. Declared here so `createBackend` derives its
351
354
  // binding and types `c.var.workflows.trigger("payments/reconcile", …)` precisely.
352
355
  workflows: paymentsWorkflows,