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

main
ts 168 lines 6.01 KB
Raw
1 import { createHash } from "node:crypto";
2 import * as iamcredentials from "@distilled.cloud/gcp/iamcredentials_v1";
3 import * as Clock from "effect/Clock";
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 * as Layer from "effect/Layer";
8 import * as GCPBindings from "../GCPBindings.ts";
9 import { HOST_SERVICE_ACCOUNT } from "../Host.ts";
10 import { grantFor } from "../HttpBinding.ts";
11 import type { Bucket } from "./Bucket.ts";
12 import {
13 SignedUrlFailed,
14 SignGetObjectUrl,
15 type SignGetObjectUrlRequest,
16 } from "./SignGetObjectUrl.ts";
17
18 const EMAIL_ENDPOINT =
19 "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email";
20 const STORAGE_HOST = "storage.googleapis.com";
21 const DEFAULT_EXPIRES_IN = 900;
22 const MAX_EXPIRES_IN = 604_800;
23
24 /** RFC 3986 encoding, as V4 signing requires. */
25 const encode = (value: string) =>
26 encodeURIComponent(value).replace(
27 /[!'()*]/g,
28 (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
29 );
30
31 const sha256Hex = (value: string) => createHash("sha256").update(value, "utf8").digest("hex");
32
33 /** `20260102T030405Z` and `20260102` for a Unix time in millis. */
34 const timestamps = (millis: number) => {
35 const iso = new Date(millis).toISOString().replace(/[-:]/g, "");
36 const datetime = `${iso.slice(0, 15)}Z`;
37 return { datetime, date: datetime.slice(0, 8) };
38 };
39
40 /**
41 * HTTP implementation of {@link SignGetObjectUrl}: V4 signing where the
42 * signature comes from IAM Credentials `signBlob` as the runtime's own
43 * service account (read from the metadata server).
44 *
45 * @layer
46 * @provides GCP.Storage.SignGetObjectUrl
47 * @category Storage
48 */
49 export const SignGetObjectUrlHttp = Layer.effect(
50 SignGetObjectUrl,
51 Effect.gen(function* () {
52 const bind = yield* GCPBindings.Bind;
53 const http = yield* HttpClient.HttpClient;
54 const signBlob = yield* GCPBindings.withCredentials(
55 iamcredentials.signBlobProjectsServiceAccounts,
56 );
57 let ownEmail: string | undefined;
58
59 const serviceAccountEmail = Effect.gen(function* () {
60 if (ownEmail !== undefined) return ownEmail;
61 const response = yield* http.execute(
62 HttpClientRequest.get(EMAIL_ENDPOINT).pipe(
63 HttpClientRequest.setHeader("Metadata-Flavor", "Google"),
64 ),
65 );
66 const text = (yield* response.text).trim();
67 if (response.status !== 200 || !text.includes("@")) {
68 return yield* new SignedUrlFailed({
69 message: `GCE metadata email endpoint returned HTTP ${response.status}`,
70 });
71 }
72 ownEmail = text;
73 return text;
74 }).pipe(
75 Effect.mapError((cause) =>
76 cause instanceof SignedUrlFailed
77 ? cause
78 : new SignedUrlFailed({
79 message: `GCE metadata email endpoint is unreachable: ${String(cause)}`,
80 cause,
81 }),
82 ),
83 );
84
85 return Effect.fn(function* (bucket: Bucket) {
86 yield* GCPBindings.requireServiceAccountHost("GCP.Storage.SignGetObjectUrl");
87 if (!globalThis.__ALCHEMY_RUNTIME__) {
88 yield* bind`GCP.Storage.SignGetObjectUrl(${bucket})`({
89 iam: [
90 // A signed URL carries the signer's own object permissions.
91 grantFor(
92 { role: "roles/storage.objectViewer", on: "storage.bucket" },
93 bucket.bucketName,
94 ),
95 // signBlob as itself, and on no other account.
96 {
97 role: "roles/iam.serviceAccountTokenCreator",
98 resource: {
99 kind: "iam.serviceAccount",
100 name: HOST_SERVICE_ACCOUNT,
101 },
102 },
103 ],
104 });
105 }
106 const bucketName = yield* bucket.bucketName;
107 return Effect.fn(`GCP.Storage.SignGetObjectUrl(${bucket.LogicalId})`)(function* (
108 request: SignGetObjectUrlRequest,
109 ) {
110 const email = yield* serviceAccountEmail;
111 const name = yield* bucketName;
112 const now = yield* Clock.currentTimeMillis;
113 const { datetime, date } = timestamps(now);
114 const scope = `${date}/auto/storage/goog4_request`;
115 const expiresIn = Math.min(
116 Math.max(Math.floor(request.expiresIn ?? DEFAULT_EXPIRES_IN), 1),
117 MAX_EXPIRES_IN,
118 );
119 const params: Record<string, string> = {
120 "X-Goog-Algorithm": "GOOG4-RSA-SHA256",
121 "X-Goog-Credential": `${email}/${scope}`,
122 "X-Goog-Date": datetime,
123 "X-Goog-Expires": String(expiresIn),
124 "X-Goog-SignedHeaders": "host",
125 ...(request.generation !== undefined ? { generation: request.generation } : {}),
126 ...(request.contentType !== undefined
127 ? { "response-content-type": request.contentType }
128 : {}),
129 };
130 const query = Object.keys(params)
131 .sort()
132 .map((key) => `${encode(key)}=${encode(params[key]!)}`)
133 .join("&");
134 const path = `/${name}/${request.object.split("/").map(encode).join("/")}`;
135 const canonicalRequest = [
136 "GET",
137 path,
138 query,
139 `host:${STORAGE_HOST}`,
140 "",
141 "host",
142 "UNSIGNED-PAYLOAD",
143 ].join("\n");
144 const stringToSign = [
145 "GOOG4-RSA-SHA256",
146 datetime,
147 scope,
148 yield* Effect.sync(() => sha256Hex(canonicalRequest)),
149 ].join("\n");
150 const signed = yield* signBlob({
151 name: `projects/-/serviceAccounts/${email}`,
152 body: {
153 payload: yield* Effect.sync(() => Buffer.from(stringToSign, "utf8").toString("base64")),
154 },
155 });
156 if (signed.signedBlob === undefined) {
157 return yield* new SignedUrlFailed({
158 message: "IAM Credentials signBlob returned no signature",
159 });
160 }
161 const signature = yield* Effect.sync(() =>
162 Buffer.from(signed.signedBlob!, "base64").toString("hex"),
163 );
164 return `https://${STORAGE_HOST}${path}?${query}&X-Goog-Signature=${signature}`;
165 });
166 });
167 }),
168 );