The best way to control Claude Code, Codex and more from any computer or phone

main
ts 168 lines 5.75 KB
Raw
1 import * as Clock from "effect/Clock";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as HttpClient from "effect/http/HttpClient";
5 import * as HttpClientRequest from "effect/http/HttpClientRequest";
6
7 /**
8 * Verification of the Google-signed OIDC ID tokens that Pub/Sub push
9 * subscriptions and Cloud Scheduler attach to requests they deliver to a
10 * Cloud Run service or Cloud Function. Cloud Run only enforces them when
11 * the service requires authentication, so event sources verify every
12 * delivery themselves: public services stay safe, and a token minted for
13 * one subscription cannot be replayed against another path.
14 *
15 * NOT exported from `index.ts`.
16 */
17
18 const CERTS_URL = "https://www.googleapis.com/oauth2/v3/certs";
19 const ISSUERS = new Set(["https://accounts.google.com", "accounts.google.com"]);
20 const CLOCK_SKEW_SECONDS = 60;
21
22 interface Jwk {
23 kid: string;
24 kty: string;
25 n: string;
26 e: string;
27 alg?: string;
28 }
29
30 interface Claims {
31 iss?: string;
32 aud?: string;
33 email?: string;
34 email_verified?: boolean;
35 exp?: number;
36 iat?: number;
37 }
38
39 /**
40 * Google's signing keys could not be fetched or imported. Deliveries should
41 * be retried (answer 5xx), not rejected as unauthorized.
42 */
43 export class GoogleSigningKeysUnavailable extends Data.TaggedError(
44 "GCP.GoogleSigningKeysUnavailable",
45 )<{ message: string }> {}
46
47 const keysUnavailable = (cause: unknown) =>
48 new GoogleSigningKeysUnavailable({ message: String(cause) });
49
50 let certs: { keys: Map<string, CryptoKey>; fetchedAt: number } | undefined;
51
52 /** A JWT segment's JSON, or `undefined` when it isn't valid base64url JSON. */
53 const decodeSegment = (segment: string): unknown => {
54 try {
55 return JSON.parse(new TextDecoder().decode(base64UrlBytes(segment)));
56 } catch {
57 return undefined;
58 }
59 };
60
61 const base64UrlBytes = (segment: string): Uint8Array<ArrayBuffer> => {
62 const base64 = segment.replaceAll("-", "+").replaceAll("_", "/");
63 const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4));
64 const bytes = new Uint8Array(binary.length);
65 for (let index = 0; index < binary.length; index++) {
66 bytes[index] = binary.charCodeAt(index);
67 }
68 return bytes;
69 };
70
71 const loadKeys = (http: HttpClient.HttpClient, force: boolean) =>
72 Effect.gen(function* () {
73 const now = yield* Clock.currentTimeMillis;
74 if (!force && certs !== undefined && now - certs.fetchedAt < 3_600_000) {
75 return certs.keys;
76 }
77 const response = yield* http
78 .execute(HttpClientRequest.get(CERTS_URL))
79 .pipe(Effect.mapError(keysUnavailable));
80 const body = (yield* response.json.pipe(Effect.mapError(keysUnavailable))) as { keys?: Jwk[] };
81 const keys = new Map<string, CryptoKey>();
82 for (const jwk of body.keys ?? []) {
83 if (jwk.kty !== "RSA") continue;
84 const key = yield* Effect.tryPromise({
85 try: () =>
86 crypto.subtle.importKey(
87 "jwk",
88 { kty: jwk.kty, n: jwk.n, e: jwk.e, alg: "RS256", ext: true },
89 { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
90 false,
91 ["verify"],
92 ),
93 catch: keysUnavailable,
94 });
95 keys.set(jwk.kid, key);
96 }
97 certs = { keys, fetchedAt: now };
98 return keys;
99 });
100
101 /**
102 * True when `authorization` carries a valid Google ID token for `audience`
103 * whose verified email is `email`. A malformed, expired, mis-addressed, or
104 * badly signed token is `false`; failing to load Google's signing keys is a
105 * {@link GoogleSigningKeysUnavailable} error, so callers can ask the sender
106 * to retry.
107 */
108 export const verifyGoogleIdToken = (options: {
109 authorization: string | undefined;
110 audience: string;
111 email: string;
112 }) =>
113 Effect.gen(function* () {
114 const token = /^Bearer\s+(.+)$/i.exec(options.authorization ?? "")?.[1];
115 if (token === undefined) return false;
116 const [header, payload, signature] = token.split(".");
117 if (!header || !payload || !signature) return false;
118 const { kid, alg } = (decodeSegment(header) ?? {}) as {
119 kid?: string;
120 alg?: string;
121 };
122 if (alg !== "RS256" || kid === undefined) return false;
123 const claims = decodeSegment(payload) as Claims | undefined;
124 if (claims === undefined) return false;
125 // A malformed signature segment is an invalid token, not an error.
126 const signatureBytes = yield* Effect.try(() => base64UrlBytes(signature)).pipe(
127 Effect.orElseSucceed(() => undefined),
128 );
129 if (signatureBytes === undefined) return false;
130
131 const http = yield* HttpClient.HttpClient;
132 let key = (yield* loadKeys(http, false)).get(kid);
133 // Google rotates signing keys; refetch once for an unknown `kid`.
134 if (key === undefined) key = (yield* loadKeys(http, true)).get(kid);
135 if (key === undefined) return false;
136 const valid = yield* Effect.tryPromise({
137 try: () =>
138 crypto.subtle.verify(
139 "RSASSA-PKCS1-v1_5",
140 key,
141 signatureBytes,
142 new TextEncoder().encode(`${header}.${payload}`),
143 ),
144 catch: keysUnavailable,
145 });
146 if (!valid) return false;
147
148 const now = Math.floor((yield* Clock.currentTimeMillis) / 1000);
149 return (
150 ISSUERS.has(claims.iss ?? "") &&
151 claims.aud === options.audience &&
152 claims.email === options.email &&
153 claims.email_verified === true &&
154 (claims.exp ?? 0) + CLOCK_SKEW_SECONDS > now &&
155 (claims.iat ?? Number.POSITIVE_INFINITY) - CLOCK_SKEW_SECONDS <= now
156 );
157 });
158
159 /** The `aud` claim of a bearer token, unverified — for diagnostics only. */
160 export const unverifiedAudience = (authorization: string | undefined) => {
161 try {
162 const token = /^Bearer\s+(.+)$/i.exec(authorization ?? "")?.[1];
163 const payload = token?.split(".")[1];
164 return payload ? (decodeSegment(payload) as Claims).aud : undefined;
165 } catch {
166 return undefined;
167 }
168 };