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

main
ts 238 lines 8.85 KB
Raw
1 import { makeFetchRpcStub } from "alchemy/Rpc";
2 import * as Clock from "effect/Clock";
3 import * as Effect from "effect/Effect";
4 import * as HttpClient from "effect/http/HttpClient";
5 import * as HttpClientRequest from "effect/http/HttpClientRequest";
6 import type * as HttpClientResponse from "effect/http/HttpClientResponse";
7 import type { HttpMethod } from "effect/http/HttpMethod";
8 import * as Layer from "effect/Layer";
9 import * as Ref from "effect/Ref";
10 import * as Semaphore from "effect/Semaphore";
11 import * as GCPBindings from "../GCPBindings.ts";
12 import { grantFor } from "../HttpBinding.ts";
13 import { makeHttpApiClient, makeRpcGroupClient } from "./EffectApis.ts";
14 import {
15 InvokeService,
16 type InvokeServiceClient,
17 type InvokeServiceOptions,
18 InvokeServiceError,
19 type InvokeServiceRequestInit,
20 type InvokeServiceResponse,
21 } from "./InvokeService.ts";
22 import type { Service } from "./Service.ts";
23
24 const IDENTITY_ENDPOINT =
25 "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity";
26
27 /** Refresh this long before the token's `exp`. */
28 const REFRESH_WINDOW_MS = 5 * 60 * 1000;
29
30 /** Google ID tokens live one hour; used when `exp` cannot be decoded. */
31 const DEFAULT_LIFETIME_MS = 55 * 60 * 1000;
32
33 interface CachedToken {
34 readonly token: string;
35 readonly expiresAt: number;
36 }
37
38 /** Epoch millis of a JWT's `exp` claim, if present. */
39 const jwtExpiry = (token: string): number | undefined => {
40 try {
41 const payload = token.split(".")[1];
42 if (payload === undefined) return undefined;
43 const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/"))) as {
44 exp?: unknown;
45 };
46 return typeof json.exp === "number" ? json.exp * 1000 : undefined;
47 } catch {
48 return undefined;
49 }
50 };
51
52 /** Mint a Google-signed ID token for `audience` from the metadata server. */
53 const fetchIdToken = (http: HttpClient.HttpClient, audience: string) =>
54 Effect.gen(function* () {
55 const response = yield* http.execute(
56 HttpClientRequest.get(IDENTITY_ENDPOINT).pipe(
57 HttpClientRequest.setUrlParams({ audience, format: "full" }),
58 HttpClientRequest.setHeader("Metadata-Flavor", "Google"),
59 ),
60 );
61 const body = yield* response.text;
62 if (response.status !== 200) {
63 return yield* new InvokeServiceError({
64 message: `GCE metadata identity endpoint returned HTTP ${response.status}: ${body}`,
65 });
66 }
67 const token = body.trim();
68 const now = yield* Clock.currentTimeMillis;
69 return {
70 token,
71 expiresAt: jwtExpiry(token) ?? now + DEFAULT_LIFETIME_MS,
72 } satisfies CachedToken;
73 }).pipe(
74 Effect.mapError((cause) =>
75 cause instanceof InvokeServiceError
76 ? cause
77 : new InvokeServiceError({
78 message: `GCE metadata identity endpoint is unreachable: ${String(cause)}`,
79 cause,
80 }),
81 ),
82 );
83
84 /** Single-flight, expiry-aware ID token cache for one audience. */
85 const makeIdTokenCache = (http: HttpClient.HttpClient) =>
86 Effect.gen(function* () {
87 const cache = yield* Ref.make<CachedToken | undefined>(undefined);
88 const lock = yield* Semaphore.make(1);
89 const fresh = (current: CachedToken | undefined, now: number) =>
90 current !== undefined && current.expiresAt - REFRESH_WINDOW_MS > now;
91 return (audience: string) =>
92 Effect.gen(function* () {
93 const current = yield* Ref.get(cache);
94 if (fresh(current, yield* Clock.currentTimeMillis)) {
95 return current!.token;
96 }
97 return yield* lock.withPermits(1)(
98 Effect.gen(function* () {
99 const latest = yield* Ref.get(cache);
100 if (fresh(latest, yield* Clock.currentTimeMillis)) {
101 return latest!.token;
102 }
103 const minted = yield* fetchIdToken(http, audience);
104 yield* Ref.set(cache, minted);
105 return minted.token;
106 }),
107 );
108 });
109 });
110
111 /**
112 * HTTP implementation of {@link InvokeService}: ID tokens from the Cloud
113 * Run metadata server, requests over the ambient `HttpClient`.
114 *
115 * @layer
116 * @provides GCP.Run.InvokeService
117 */
118 export const InvokeServiceHttp: Layer.Layer<InvokeService, never, HttpClient.HttpClient> =
119 Layer.effect(
120 InvokeService,
121 Effect.gen(function* () {
122 const bind = yield* GCPBindings.Bind;
123 const http = yield* HttpClient.HttpClient;
124 return Effect.fn(function* <T extends Service>(service: T, options?: InvokeServiceOptions) {
125 yield* GCPBindings.requireServiceAccountHost("GCP.Run.InvokeService");
126 if (!globalThis.__ALCHEMY_RUNTIME__) {
127 yield* bind`GCP.Run.InvokeService(${service})`({
128 iam: [grantFor({ role: "roles/run.invoker", on: "run.service" }, service.name)],
129 });
130 }
131 const uri = yield* service.uri;
132 const idToken = yield* makeIdTokenCache(http);
133
134 const fetch = Effect.fn(`GCP.Run.InvokeService(${service.LogicalId})`)(function* (
135 path: string,
136 init?: InvokeServiceRequestInit,
137 ) {
138 const base = yield* uri;
139 if (base === undefined) {
140 return yield* new InvokeServiceError({
141 message: `Cloud Run service ${service.LogicalId} has no URI`,
142 });
143 }
144 const audience = base.replace(/\/+$/, "");
145 const token = yield* idToken(audience);
146 const url = `${audience}/${path.replace(/^\/+/, "")}`;
147 let request = HttpClientRequest.make(
148 (init?.method?.toUpperCase() ?? "GET") as HttpMethod,
149 )(url).pipe(
150 HttpClientRequest.setHeaders(init?.headers ?? {}),
151 HttpClientRequest.bearerToken(token),
152 );
153 if (init?.body !== undefined) {
154 const contentType = init.headers?.["content-type"] ?? init.headers?.["Content-Type"];
155 request =
156 typeof init.body === "string"
157 ? HttpClientRequest.bodyText(request, init.body, contentType)
158 : HttpClientRequest.bodyUint8Array(request, init.body, contentType);
159 }
160 const response = yield* http.execute(request).pipe(
161 Effect.mapError(
162 (cause) =>
163 new InvokeServiceError({
164 message: `Request to ${url} failed: ${cause.message}`,
165 cause,
166 }),
167 ),
168 );
169 const text = yield* response.text.pipe(
170 Effect.mapError(
171 (cause) =>
172 new InvokeServiceError({
173 message: `Reading the response from ${url} failed: ${cause.message}`,
174 cause,
175 }),
176 ),
177 );
178 return {
179 status: response.status,
180 headers: { ...response.headers },
181 text: Effect.succeed(text),
182 json: Effect.try({
183 try: () => JSON.parse(text) as unknown,
184 catch: (cause) =>
185 new InvokeServiceError({
186 message: `Response from ${url} is not JSON`,
187 cause,
188 }),
189 }),
190 } satisfies InvokeServiceResponse;
191 });
192 const signed = (request: HttpClientRequest.HttpClientRequest) =>
193 Effect.gen(function* () {
194 const base = yield* uri;
195 if (base === undefined) {
196 return yield* new InvokeServiceError({
197 message: `Cloud Run service ${service.LogicalId} has no URI`,
198 });
199 }
200 const audience = base.replace(/\/+$/, "");
201 const token = yield* idToken(audience);
202 const url = /^[a-z]+:\/\//i.test(request.url)
203 ? request.url
204 : `${audience}/${request.url.replace(/^\/+/, "")}`;
205 return request.pipe(
206 HttpClientRequest.setUrl(url),
207 HttpClientRequest.bearerToken(token),
208 );
209 });
210 const httpClient = HttpClient.mapRequestEffect(http, signed);
211 // RPC methods post to `/__rpc__/<name>` on the service with the
212 // same ID token; the service serves them only behind its IAM
213 // invoker check.
214 const transport = { fetch, httpClient };
215 if (options !== undefined && "schema" in options) {
216 return Object.assign(
217 makeRpcGroupClient(options.schema, httpClient as unknown as HttpClient.HttpClient),
218 transport,
219 ) as unknown as InvokeServiceClient;
220 }
221 if (options !== undefined && "api" in options) {
222 return Object.assign(
223 yield* makeHttpApiClient(options.api, httpClient),
224 transport,
225 ) as unknown as InvokeServiceClient;
226 }
227 return makeFetchRpcStub<InvokeServiceClient>({
228 baseUrl: "",
229 fetch: (request) =>
230 httpClient.execute(request) as Effect.Effect<
231 HttpClientResponse.HttpClientResponse,
232 unknown
233 >,
234 base: transport,
235 });
236 });
237 }),
238 );