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

main
ts 173 lines 6.56 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import * as Output from "alchemy/Output";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as HttpClient from "effect/http/HttpClient";
6 import * as HttpClientRequest from "effect/http/HttpClientRequest";
7 import type { HttpServerRequest } from "effect/http/HttpServerRequest";
8 import * as HttpServerResponse from "effect/http/HttpServerResponse";
9 import { isGcpListenHost, type GcpHostRuntimeContext } from "./HostContext.ts";
10 import { Member } from "./IAM/Member.ts";
11 import { unverifiedAudience, verifyGoogleIdToken } from "./Oidc.ts";
12
13 /**
14 * Shared scaffolding for event sources that deliver over HTTPS to a GCP
15 * host (Pub/Sub push, Cloud Scheduler): the host's endpoint and push
16 * identity, the `run.invoker` grant, the delivery path, and per-request
17 * OIDC verification.
18 *
19 * NOT exported from `index.ts`.
20 */
21
22 /** An HTTP-serving GCP host: `GCP.Run.Service` or `GCP.CloudFunctions.Function`. */
23 export type PushHost = GcpHostRuntimeContext & {
24 LogicalId: string;
25 Type: string;
26 };
27
28 export class PushHostRequired extends Data.TaggedError("PushHostRequired")<{
29 readonly source: string;
30 readonly host: string | undefined;
31 }> {
32 override get message() {
33 return `${this.source} delivers over HTTPS and needs a GCP.Run.Service (GCP.Function) or GCP.CloudFunctions.Function host; got ${this.host ?? "no host"}. Use GCP.Run.TopicPullEventSource on Jobs and WorkerPools.`;
34 }
35 }
36
37 /** The ambient push host, or a defect naming what is missing. */
38 export const pushHost = (source: string) =>
39 Effect.gen(function* () {
40 const host = yield* Binding.Host;
41 if (!isGcpListenHost(host)) {
42 return yield* Effect.die(
43 new PushHostRequired({ source, host: (host as { Type?: string })?.Type }),
44 );
45 }
46 return host as PushHost;
47 });
48
49 /**
50 * Deploy-time outputs of the host an event source delivers to. The host's
51 * runtime service account is the push identity, so no extra account is
52 * minted and the runtime can check the token's email against its own.
53 */
54 export const hostEndpoint = (host: PushHost) => {
55 const attrs = host as unknown as Record<string, Output.Output<string>>;
56 return host.Type === "GCP.CloudFunctions.Function"
57 ? {
58 // The function's Cloud Run URL: the address Cloud Run's front end
59 // validates token audiences against.
60 url: attrs.uri!,
61 serviceAccount: attrs.serviceAccountEmail!,
62 // Gen2 functions are invoked through their Cloud Run service.
63 invokerService: attrs.service!,
64 }
65 : {
66 url: attrs.uri!,
67 serviceAccount: attrs.serviceAccount!,
68 invokerService: attrs.name!,
69 };
70 };
71
72 /** Deterministic path segment for a logical id. */
73 export const pathSegment = (value: string) => value.replace(/[^a-zA-Z0-9_-]/g, "-").toLowerCase();
74
75 /**
76 * OIDC audience for one delivery route: the route's own URL on the host.
77 * Cloud Run's front end only accepts tokens addressed to the service's
78 * URL (or a configured custom audience) when the invoker check is on, and
79 * binding the path means a token minted for one route is rejected on
80 * every other.
81 */
82 export const deliveryAudience = (url: Output.Output<string>, path: string) =>
83 Output.interpolate`${url}${path}`;
84
85 /**
86 * The audience a delivery to `path` must carry. Cloud Run routes on the
87 * `Host` header, so it names the URL the sender addressed — the same URL
88 * `deliveryAudience` pinned into the push config.
89 */
90 const expectedAudience = (request: HttpServerRequest, path: string) =>
91 `https://${request.headers["host"] ?? ""}${path}`;
92
93 /**
94 * Let the host's runtime service account invoke the host, so Cloud Run
95 * accepts the OIDC-authenticated deliveries even when the service requires
96 * authentication.
97 */
98 export const grantSelfInvoker = (host: PushHost) =>
99 Effect.gen(function* () {
100 const endpoint = hostEndpoint(host);
101 yield* Member(`${host.LogicalId}-PushInvoker`, {
102 kind: "run.service",
103 name: endpoint.invokerService,
104 role: "roles/run.invoker",
105 member: Output.interpolate`serviceAccount:${endpoint.serviceAccount}`,
106 });
107 });
108
109 let runtimeEmail: string | undefined;
110
111 /** The instance's own service account email, from the metadata server. */
112 const ownServiceAccount = Effect.gen(function* () {
113 if (runtimeEmail !== undefined) return runtimeEmail;
114 const http = yield* HttpClient.HttpClient;
115 const response = yield* http.execute(
116 HttpClientRequest.get(
117 "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email",
118 ).pipe(HttpClientRequest.setHeader("Metadata-Flavor", "Google")),
119 );
120 const email = (yield* response.text).trim();
121 runtimeEmail = email;
122 return email;
123 });
124
125 const unauthorized = HttpServerResponse.text("unauthorized", { status: 401 });
126 const unavailable = HttpServerResponse.text("unavailable", { status: 503 });
127
128 /**
129 * Claim `POST {path}` deliveries: verify the OIDC token (audience + the
130 * host's own service account), then run `handle`. Any other request is
131 * left for the next listener or the user's `fetch`.
132 */
133 export const listenForDeliveries = (
134 host: PushHost,
135 path: string,
136 handle: (
137 request: HttpServerRequest,
138 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, any>,
139 ) =>
140 host.listen((request) => {
141 const pathname = new URL(request.url, "http://host").pathname;
142 if (pathname !== path) return undefined;
143 return Effect.gen(function* () {
144 if (request.method !== "POST") {
145 return HttpServerResponse.text("method not allowed", { status: 405 });
146 }
147 // Infrastructure failures (metadata server, Google's signing keys)
148 // answer 503 so the sender retries instead of dropping the event.
149 const email = yield* ownServiceAccount.pipe(
150 Effect.tapError((error) =>
151 Effect.logWarning("Cannot read the instance service account", error),
152 ),
153 Effect.option,
154 );
155 if (email._tag === "None") return unavailable;
156 const verified = yield* verifyGoogleIdToken({
157 authorization: request.headers["authorization"],
158 audience: expectedAudience(request, path),
159 email: email.value,
160 }).pipe(
161 Effect.tapError((error) => Effect.logWarning("Cannot load Google's signing keys", error)),
162 Effect.option,
163 );
164 if (verified._tag === "None") return unavailable;
165 if (!verified.value) {
166 yield* Effect.logWarning(
167 `Rejected delivery to ${path}: invalid OIDC token (aud=${unverifiedAudience(request.headers["authorization"]) ?? "none"})`,
168 );
169 return unauthorized;
170 }
171 return yield* handle(request);
172 });
173 });