@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 161 lines 6.11 KB
Raw
1 import { ConfigError } from "@distilled.cloud/core/errors";
2 import { Credentials, type Config as CredentialsConfig } from "@distilled.cloud/gcp/Credentials";
3 import { cacheUntilExpiry } from "alchemy/Auth/CredentialsCache";
4 import * as Clock from "effect/Clock";
5 import * as Config from "effect/Config";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 import * as Redacted from "effect/Redacted";
12 import * as Ref from "effect/Ref";
13
14 /**
15 * Credentials sourced from the GCE / Cloud Run metadata server — the
16 * runtime identity of a deployed Cloud Run Service, Job, or WorkerPool.
17 *
18 * Kept dependency-light: the generated container bootstraps import this
19 * module, so it must not pull in the deploy-time AuthProvider machinery.
20 */
21
22 /** A resolved token plus the wall-clock time it stops being valid. */
23 export interface ExpiringCredentials {
24 readonly config: CredentialsConfig;
25 /** Epoch millis; `undefined` never expires (e.g. a static env token). */
26 readonly expiresAt: number | undefined;
27 }
28
29 /**
30 * Expiry-aware cache over a credential resolver: callers reuse the cached
31 * token until it nears expiry, and concurrent callers share one refresh.
32 */
33 export const cacheCredentials = <E>(resolve: Effect.Effect<ExpiringCredentials, E>) =>
34 cacheUntilExpiry(resolve, (resolved) => resolved.expiresAt).pipe(
35 Effect.map((cached) => Effect.map(cached, (resolved) => resolved.config)),
36 );
37
38 const METADATA_ROOT = "http://metadata.google.internal/computeMetadata/v1";
39
40 const metadataGet = (http: HttpClient.HttpClient, path: string) =>
41 http
42 .execute(
43 HttpClientRequest.get(`${METADATA_ROOT}${path}`).pipe(
44 HttpClientRequest.setHeader("Metadata-Flavor", "Google"),
45 ),
46 )
47 .pipe(
48 Effect.filterOrFail(
49 (response) => response.status === 200,
50 (response) =>
51 ConfigError.make({
52 message: `GCE metadata ${path} returned HTTP ${response.status}`,
53 }),
54 ),
55 Effect.mapError((cause) =>
56 ConfigError.is(cause)
57 ? cause
58 : ConfigError.make({
59 message: `GCE metadata ${path} is unreachable: ${String(cause)}`,
60 }),
61 ),
62 );
63
64 /** Mint an access token for the instance's attached service account. */
65 export const fetchMetadataToken = (http: HttpClient.HttpClient) =>
66 Effect.gen(function* () {
67 const response = yield* metadataGet(http, "/instance/service-accounts/default/token");
68 const body = yield* response.json.pipe(
69 Effect.mapError(() =>
70 ConfigError.make({
71 message: "GCE metadata token endpoint returned invalid JSON",
72 }),
73 ),
74 );
75 const record =
76 typeof body === "object" && body !== null
77 ? (body as { access_token?: unknown; expires_in?: unknown })
78 : {};
79 if (typeof record.access_token !== "string") {
80 return yield* ConfigError.make({
81 message: "GCE metadata token endpoint returned no access_token",
82 });
83 }
84 const expiresIn = typeof record.expires_in === "number" ? record.expires_in : 300;
85 const now = yield* Clock.currentTimeMillis;
86 return {
87 accessToken: Redacted.make(record.access_token),
88 expiresAt: now + expiresIn * 1000,
89 };
90 });
91
92 /** Project id of the instance, from the metadata server. */
93 export const fetchMetadataProject = (http: HttpClient.HttpClient) =>
94 metadataGet(http, "/project/project-id").pipe(
95 Effect.flatMap((response) => response.text),
96 Effect.map((text) => text.trim()),
97 Effect.mapError(() =>
98 ConfigError.make({
99 message: "GCE metadata project-id endpoint returned no project",
100 }),
101 ),
102 );
103
104 /**
105 * Region of the instance (`projects/{n}/regions/{region}` on Cloud Run and
106 * Cloud Functions), from the metadata server.
107 */
108 export const fetchMetadataRegion = (http: HttpClient.HttpClient) =>
109 metadataGet(http, "/instance/region").pipe(
110 Effect.flatMap((response) => response.text),
111 Effect.map((text) => text.trim().split("/").pop() || undefined),
112 Effect.orElseSucceed(() => undefined),
113 );
114
115 /**
116 * `Credentials` for code running on Cloud Run (or any GCE-backed runtime):
117 * the attached service account's token from the metadata server, cached
118 * until shortly before expiry. The project comes from
119 * `GOOGLE_CLOUD_PROJECT` when set, else from the metadata server once.
120 */
121 export const fromMetadataServer = (): Layer.Layer<Credentials, never, HttpClient.HttpClient> =>
122 Layer.effect(
123 Credentials,
124 Effect.gen(function* () {
125 const http = yield* HttpClient.HttpClient;
126 const projectCache = yield* Ref.make<string | undefined>(undefined);
127 const project = Effect.gen(function* () {
128 const cached = yield* Ref.get(projectCache);
129 if (cached !== undefined) return cached;
130 const fromEnv = yield* Config.option(Config.String("GOOGLE_CLOUD_PROJECT"));
131 const resolved = Option.isSome(fromEnv) ? fromEnv.value : yield* fetchMetadataProject(http);
132 yield* Ref.set(projectCache, resolved);
133 return resolved;
134 });
135 // The runtime's default region is the region it runs in.
136 const regionCache = yield* Ref.make<string | undefined>(undefined);
137 const region = Effect.gen(function* () {
138 const cached = yield* Ref.get(regionCache);
139 if (cached !== undefined) return cached;
140 const resolved = yield* fetchMetadataRegion(http);
141 if (resolved !== undefined) yield* Ref.set(regionCache, resolved);
142 return resolved;
143 });
144 const cached = yield* cacheCredentials(
145 Effect.gen(function* () {
146 const token = yield* fetchMetadataToken(http);
147 return {
148 config: {
149 accessToken: token.accessToken,
150 project: yield* project,
151 region: yield* region,
152 },
153 expiresAt: token.expiresAt,
154 };
155 }),
156 );
157 // Distilled `Credentials` is `Effect<Config>` (error `never`): a
158 // runtime without a metadata server cannot call GCP at all.
159 return cached.pipe(Effect.orDie);
160 }),
161 );