@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.
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +2 -1
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +32 -1
- package/dist/rails/google/oidc.d.ts +89 -33
- package/dist/rails/google/oidc.d.ts.map +1 -1
- package/dist/rails/google/oidc.js +144 -139
- package/dist/rails/google/playApi.js +1 -1
- package/dist/rails/google/rail.d.ts +25 -0
- package/dist/rails/google/rail.d.ts.map +1 -1
- package/dist/rails/google/rail.js +2 -1
- package/dist/rails/providers.d.ts +15 -0
- package/dist/rails/providers.d.ts.map +1 -1
- package/dist/rails/providers.js +2 -1
- package/dist/secret/branches.d.ts +16 -0
- package/dist/secret/branches.d.ts.map +1 -1
- package/dist/secret/branches.js +20 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/package.json +11 -9
- package/src/capability.ts +4 -1
- package/src/http/routes.ts +32 -1
- package/src/rails/google/oidc.ts +192 -243
- package/src/rails/google/rail.ts +28 -0
- package/src/rails/providers.ts +16 -0
- package/src/secret/branches.ts +20 -0
- package/src/version.generated.ts +1 -1
package/src/http/routes.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { safeEmit } from "@pithy-sh/core/src/controlPlane/audit/actions";
|
|
|
8
8
|
import type { ControlPlaneContext } from "@pithy-sh/core/src/controlPlane/context";
|
|
9
9
|
import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
|
|
10
10
|
import { InternalError, NotFoundError, PithyError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
11
|
+
import { memoryJwksCache } from "@pithy-sh/core/src/http/oidcWebhook";
|
|
11
12
|
import { validationHook } from "@pithy-sh/core/src/http/validation";
|
|
12
13
|
import { resolveWorkflowBinding } from "@pithy-sh/core/src/workflow/dispatch";
|
|
13
14
|
import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
|
|
@@ -909,7 +910,37 @@ export function registerPaymentsRoutes(options: PaymentsRoutesOptions): (app: Ho
|
|
|
909
910
|
const { config } = options;
|
|
910
911
|
const base = options.basePath ?? config.basePath;
|
|
911
912
|
const clock = options.now ?? (() => new Date());
|
|
912
|
-
|
|
913
|
+
/**
|
|
914
|
+
* The caller's seams, plus the one thing a per-request rail cannot own: Google's key store.
|
|
915
|
+
*
|
|
916
|
+
* **Built here because this is the first thing in the chain that outlives a request.** `payments()` calls
|
|
917
|
+
* `registerPaymentsRoutes` once, at composition, so this object is constructed once per isolate and every
|
|
918
|
+
* delivery the Google webhook sees shares it. The rail below it is rebuilt per request by
|
|
919
|
+
* `resolveRailProvider` — a cache hung on that would be one that has never held anything — and the module
|
|
920
|
+
* variable that used to hold it is exactly what #520 deleted, because state no caller owns needs an
|
|
921
|
+
* exported `reset` for every suite that inherits it.
|
|
922
|
+
*
|
|
923
|
+
* **Owning the store is not the same as having none.** That is core's sentence, on `JwksCache`, about the
|
|
924
|
+
* surface anonymous traffic arrives on, and the Google webhook is one: the OIDC guard resolves a key by
|
|
925
|
+
* `kid` *before* it can check a signature, so with no store a forged token buys a round trip to Google,
|
|
926
|
+
* 1:1. Google rate-limits us, `fetchJwks` maps that to `core/upstream_failed`, and that code is in the
|
|
927
|
+
* webhook guard's pass-through set — so Pub/Sub redelivers the genuine notifications into the same
|
|
928
|
+
* uncached path. One anonymous caller, the whole rail down.
|
|
929
|
+
*
|
|
930
|
+
* **The store answers both floods, and only one of them is about a published `kid`.** What it holds
|
|
931
|
+
* collapses a forgery naming a key Google really publishes; `JwksCache.claimRefresh` — the window, one ask
|
|
932
|
+
* per `OIDC_JWKS_MIN_REFRESH_SECONDS` — collapses the cheaper one, the token naming a `kid` nobody has
|
|
933
|
+
* ever published, which is a miss and was therefore a fetch apiece however much was cached. Both live in
|
|
934
|
+
* this object, so a route passing its own store passes both bounds together.
|
|
935
|
+
*
|
|
936
|
+
* On `clock`, not wall time, so a suite injecting a clock governs the expiry too. A route wanting a bound
|
|
937
|
+
* harder than one isolate's memory — shared across isolates, or rate-limiting — passes its own
|
|
938
|
+
* `trust.googleJwksCache` and this one is never built.
|
|
939
|
+
*/
|
|
940
|
+
const trust: RailTrustOptions = {
|
|
941
|
+
...(options.trust ?? {}),
|
|
942
|
+
googleJwksCache: options.trust?.googleJwksCache ?? memoryJwksCache({ now: clock }),
|
|
943
|
+
};
|
|
913
944
|
/** The seam `payments()` built, or the resolver-less one this config implies. See {@link PaymentsRoutesOptions.subject}. */
|
|
914
945
|
const seam: PaymentsSubjectSeam = options.subject ?? { billingSubject: config.billingSubject };
|
|
915
946
|
|
package/src/rails/google/oidc.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
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";
|
|
6
6
|
import { z } from "zod";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { base64UrlDecode, decodeJwtJson, splitJwt } from "./jwt";
|
|
7
|
+
import { PaymentsVerificationFailedError } from "../../error/errors";
|
|
8
|
+
import type { GoogleHttpFetch } from "./http";
|
|
10
9
|
|
|
11
10
|
/**
|
|
12
11
|
* The authenticity boundary on Google's webhook: the OIDC token a Pub/Sub push carries.
|
|
@@ -23,21 +22,47 @@ import { base64UrlDecode, decodeJwtJson, splitJwt } from "./jwt";
|
|
|
23
22
|
* for. Verify the signature and skip the audience and you have built an endpoint that accepts notifications
|
|
24
23
|
* from any Google customer who points a subscription at it.
|
|
25
24
|
*
|
|
26
|
-
*
|
|
25
|
+
* ## Everything above is `@pithy-sh/core/src/http/oidcWebhook`, and none of it is here
|
|
27
26
|
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* `jwk`/`x5u` handling here: a token that carries its own key is a token that verifies itself.
|
|
34
|
-
* 3. **Verify the signature over the exact received segments** — `header.claims` as encoded.
|
|
35
|
-
* 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).
|
|
36
32
|
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
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.
|
|
41
66
|
*/
|
|
42
67
|
|
|
43
68
|
/** Where Google publishes the keys that sign an OIDC token. Public, so it is pinned here rather than stored. */
|
|
@@ -49,89 +74,39 @@ export const GOOGLE_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs";
|
|
|
49
74
|
*/
|
|
50
75
|
export const GOOGLE_OIDC_ISSUERS: readonly string[] = ["https://accounts.google.com", "accounts.google.com"];
|
|
51
76
|
|
|
52
|
-
/** How long a fetched key set is reused. Google rotates slowly, and an unknown `kid` forces a refresh anyway. */
|
|
53
|
-
const JWKS_TTL_MS = 60 * 60 * 1000;
|
|
54
|
-
|
|
55
|
-
/** Tolerance on `exp` and `iat`. A minute covers clock drift; an hour would cover a replay. */
|
|
56
|
-
const DEFAULT_CLOCK_SKEW_SECONDS = 60;
|
|
57
|
-
|
|
58
|
-
/** RSASSA-PKCS1-v1_5 with SHA-256 — the one algorithm `alg: RS256` names, fixed here rather than derived. */
|
|
59
|
-
const RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } as const;
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* The header of a Pub/Sub push token, as tightly as it can be stated. `alg` is a literal for the reason in the
|
|
63
|
-
* module doc; `kid` is required because a key is resolved by it and a token that names no key cannot be
|
|
64
|
-
* checked against one.
|
|
65
|
-
*/
|
|
66
|
-
const GoogleOidcHeader = z
|
|
67
|
-
.object({
|
|
68
|
-
alg: z
|
|
69
|
-
.literal("RS256")
|
|
70
|
-
.describe(
|
|
71
|
-
"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.",
|
|
72
|
-
),
|
|
73
|
-
kid: z
|
|
74
|
-
.string()
|
|
75
|
-
.min(1)
|
|
76
|
-
.describe("Which of Google's published keys signed the token. Resolved against Google's key endpoint."),
|
|
77
|
-
})
|
|
78
|
-
.loose()
|
|
79
|
-
.describe("The header of a Google-signed OIDC token, constrained to the one shape Pub/Sub sends.");
|
|
80
|
-
|
|
81
77
|
/**
|
|
82
|
-
* One published RSA verification key,
|
|
83
|
-
*
|
|
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.
|
|
84
85
|
*/
|
|
85
|
-
export const GoogleJwk =
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
n: z.string().min(1).describe("The RSA modulus, base64url."),
|
|
90
|
-
e: z.string().min(1).describe("The RSA public exponent, base64url."),
|
|
91
|
-
alg: z.string().min(1).optional().describe("The algorithm the key is published for, when stated."),
|
|
92
|
-
use: z.string().min(1).optional().describe("What the key is published for — `sig` for a signing key."),
|
|
93
|
-
})
|
|
94
|
-
.loose()
|
|
95
|
-
.describe("One of Google's published OIDC verification keys.");
|
|
96
|
-
export type GoogleJwk = z.infer<typeof GoogleJwk>;
|
|
97
|
-
|
|
98
|
-
/** Google's published key set. At least one key: an empty set is an endpoint that is not answering properly. */
|
|
99
|
-
export const GoogleJwks = z
|
|
100
|
-
.object({
|
|
101
|
-
keys: z.array(GoogleJwk).min(1).describe("Every key currently signing Google OIDC tokens."),
|
|
102
|
-
})
|
|
103
|
-
.loose()
|
|
104
|
-
.describe("The response of Google's OIDC key endpoint.");
|
|
105
|
-
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;
|
|
106
90
|
|
|
107
91
|
/**
|
|
108
|
-
* The claims a Pub/Sub push token carries,
|
|
109
|
-
*
|
|
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.
|
|
110
98
|
*/
|
|
111
|
-
export const GoogleOidcClaims =
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
email: z
|
|
123
|
-
.string()
|
|
124
|
-
.min(1)
|
|
125
|
-
.optional()
|
|
126
|
-
.describe("The service account Pub/Sub used to mint the token. Checked against the configured one."),
|
|
127
|
-
email_verified: z
|
|
128
|
-
.boolean()
|
|
129
|
-
.optional()
|
|
130
|
-
.describe("Whether Google vouches for that address. Always true on a real push token."),
|
|
131
|
-
sub: z.string().min(1).optional().describe("The service account's numeric id."),
|
|
132
|
-
})
|
|
133
|
-
.loose()
|
|
134
|
-
.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.");
|
|
135
110
|
export type GoogleOidcClaims = z.infer<typeof GoogleOidcClaims>;
|
|
136
111
|
|
|
137
112
|
/** What verifying a push token needs. Everything is explicit, so verification is deterministic in a test. */
|
|
@@ -148,180 +123,146 @@ export interface VerifyGoogleOidcOptions {
|
|
|
148
123
|
* Keys accepted **in addition to** Google's published set, matched by `kid`.
|
|
149
124
|
*
|
|
150
125
|
* Additive, so nothing can narrow production's trust: a token whose `kid` these do not cover still resolves
|
|
151
|
-
* against Google. Two callers have a real reason — the tests, which mint their own key so the signature
|
|
152
|
-
* is exercised for real, and a local Pub/Sub emulator, whose tokens are signed by a key Google never
|
|
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.
|
|
153
129
|
*/
|
|
154
130
|
trustedKeys?: readonly GoogleJwk[];
|
|
155
131
|
/**
|
|
156
|
-
* Tolerance on `exp` and `iat`, in seconds. Defaults to a minute, and must be a finite number from 0
|
|
157
|
-
*
|
|
158
|
-
*
|
|
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.
|
|
159
135
|
*/
|
|
160
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;
|
|
161
156
|
}
|
|
162
157
|
|
|
163
158
|
/**
|
|
164
|
-
*
|
|
159
|
+
* Verify one Pub/Sub push OIDC token and return its claims.
|
|
165
160
|
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
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.
|
|
169
167
|
*/
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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,
|
|
185
184
|
});
|
|
185
|
+
} catch (error) {
|
|
186
|
+
throw railCode(error);
|
|
186
187
|
}
|
|
187
|
-
|
|
188
|
-
|
|
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;
|
|
189
195
|
}
|
|
190
196
|
|
|
191
197
|
/**
|
|
192
|
-
*
|
|
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.
|
|
193
205
|
*
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
* 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.
|
|
197
208
|
*/
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const fresh = publishedKeys !== null && publishedKeys.expiresAt > options.now.getTime();
|
|
204
|
-
if (fresh) {
|
|
205
|
-
const cached = publishedKeys?.keys.find((key) => key.kid === kid);
|
|
206
|
-
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.`);
|
|
207
214
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
const found = refreshed.find((key) => key.kid === kid);
|
|
211
|
-
if (!found) {
|
|
212
|
-
throw new PaymentsVerificationFailedError({
|
|
213
|
-
detail: `Google: no published key matches the token's kid "${kid}".`,
|
|
214
|
-
});
|
|
215
|
+
if (claims.email_verified !== true) {
|
|
216
|
+
throw failed("the token's service-account address is not marked verified by Google.");
|
|
215
217
|
}
|
|
216
|
-
return
|
|
218
|
+
return true;
|
|
217
219
|
}
|
|
218
220
|
|
|
219
|
-
/**
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
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
|
+
};
|
|
234
250
|
}
|
|
235
251
|
|
|
236
252
|
/**
|
|
237
|
-
*
|
|
253
|
+
* Core's refusal under the rail's own code.
|
|
238
254
|
*
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
*
|
|
242
|
-
*
|
|
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.
|
|
243
259
|
*/
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
const header = GoogleOidcHeader.safeParse(decodeJwtJson(head, "the token header"));
|
|
251
|
-
if (!header.success) {
|
|
252
|
-
throw new PaymentsInvalidReceiptError({
|
|
253
|
-
detail: `Google: the token header is not one Pub/Sub sends — ${issues(header.error)}.`,
|
|
254
|
-
});
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
const key = await importKey(await resolveKey(header.data.kid, options));
|
|
258
|
-
const verified = await crypto.subtle.verify(
|
|
259
|
-
RS256.name,
|
|
260
|
-
key,
|
|
261
|
-
base64UrlDecode(mac, "the token signature") as unknown as ArrayBuffer,
|
|
262
|
-
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 },
|
|
263
265
|
);
|
|
264
|
-
if (!verified) {
|
|
265
|
-
throw new PaymentsVerificationFailedError({
|
|
266
|
-
detail: `Google: the token signature does not match the signed segments under key "${header.data.kid}".`,
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// Only now. A claim read from a token whose signature has not been checked is a claim an attacker wrote.
|
|
271
|
-
const parsed = GoogleOidcClaims.safeParse(decodeJwtJson(body, "the token claims"));
|
|
272
|
-
if (!parsed.success) {
|
|
273
|
-
throw new PaymentsVerificationFailedError({
|
|
274
|
-
detail: `Google: the token claims are not those of a Pub/Sub push token — ${issues(parsed.error)}.`,
|
|
275
|
-
});
|
|
276
|
-
}
|
|
277
|
-
const claims = parsed.data;
|
|
278
|
-
// Both operands of both time checks, and both fail open unguarded: `exp + NaN < seconds` and
|
|
279
|
-
// `iat - NaN > seconds` are false alike, so one unchecked number does not widen the window — it deletes it,
|
|
280
|
-
// and a captured Play RTDN push replays forever under a signature that is genuinely Google's. Everything
|
|
281
|
-
// above still holds; freshness is precisely what is lost, which is the half nothing else here recovers.
|
|
282
|
-
// Our fault, our code: a 401 would send an operator hunting a forger who is not there. The ceiling is the
|
|
283
|
-
// kit's, imported rather than restated, because a skew is a replay window in the plainest possible units.
|
|
284
|
-
const skew = options.clockSkewSeconds ?? DEFAULT_CLOCK_SKEW_SECONDS;
|
|
285
|
-
if (!Number.isFinite(skew) || skew < 0 || skew > OIDC_MAX_CLOCK_SKEW_SECONDS) {
|
|
286
|
-
throw new InternalError({
|
|
287
|
-
message: "This webhook endpoint is not configured.",
|
|
288
|
-
action: `Give the Google Pub/Sub webhook a clock skew between 0 and ${OIDC_MAX_CLOCK_SKEW_SECONDS} seconds.`,
|
|
289
|
-
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}.`,
|
|
290
|
-
});
|
|
291
|
-
}
|
|
292
|
-
const seconds = Math.floor(options.now.getTime() / 1000);
|
|
293
|
-
if (!Number.isFinite(seconds)) {
|
|
294
|
-
throw new InternalError({
|
|
295
|
-
message: "This webhook endpoint is not configured.",
|
|
296
|
-
action: "Give the Google Pub/Sub webhook a valid clock.",
|
|
297
|
-
detail:
|
|
298
|
-
"Google: the push-token check was handed a clock that is not a valid Date, so no token's freshness can be judged.",
|
|
299
|
-
});
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
if (!GOOGLE_OIDC_ISSUERS.includes(claims.iss)) {
|
|
303
|
-
throw failed(`the token issuer is "${claims.iss}", not one of Google's.`);
|
|
304
|
-
}
|
|
305
|
-
// The boundary. Everything above proves Google minted the token; this is what proves it was minted for us.
|
|
306
|
-
if (claims.aud !== options.audience) {
|
|
307
|
-
throw failed(`the token audience is "${claims.aud}", and this endpoint expects "${options.audience}".`);
|
|
308
|
-
}
|
|
309
|
-
if (claims.exp + skew < seconds) {
|
|
310
|
-
throw failed(`the token expired at ${new Date(claims.exp * 1000).toISOString()}.`);
|
|
311
|
-
}
|
|
312
|
-
if (claims.iat !== undefined && claims.iat - skew > seconds) {
|
|
313
|
-
throw failed(`the token was issued at ${new Date(claims.iat * 1000).toISOString()}, which is in the future.`);
|
|
314
|
-
}
|
|
315
|
-
// Google's own guidance, and a second, independent statement: the audience says which endpoint the token was
|
|
316
|
-
// minted for, the email says which identity minted it. Both are always present on a real push token.
|
|
317
|
-
if (claims.email !== options.serviceAccountEmail) {
|
|
318
|
-
throw failed(`the token names service account "${claims.email ?? "none"}", not the configured one.`);
|
|
319
|
-
}
|
|
320
|
-
if (claims.email_verified !== true) {
|
|
321
|
-
throw failed("the token's service-account address is not marked verified by Google.");
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
return claims;
|
|
325
266
|
}
|
|
326
267
|
|
|
327
268
|
/** A post-signature refusal. `Google:` prefixed, and the token itself never appears. */
|
|
@@ -333,3 +274,11 @@ function failed(detail: string): PaymentsVerificationFailedError {
|
|
|
333
274
|
function issues(error: z.ZodError): string {
|
|
334
275
|
return error.issues.map((issue) => `${issue.path.join(".") || "<root>"}:${issue.code}`).join(", ");
|
|
335
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
|
+
}
|
package/src/rails/google/rail.ts
CHANGED
|
@@ -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 });
|