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

main
ts 606 lines 19.3 KB
Raw
1 import * as apikeys from "@distilled.cloud/gcp/apikeys_v2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import { waitForOperation as waitForLongRunning, type LongRunningOperation } from "../Operation.ts";
21 import type { Providers } from "../Providers.ts";
22
23 const LOCATION = "global";
24 const MAX_NAME_LENGTH = 63;
25
26 export type ApiTarget = {
27 /**
28 * Canonical service name, e.g. `translate.googleapis.com`.
29 */
30 service?: string;
31 /**
32 * Allowed methods. Empty means all methods for `service`. A trailing
33 * `*` wildcard is allowed (`Get*`).
34 */
35 methods?: string[];
36 };
37
38 export type BrowserKeyRestrictions = {
39 /**
40 * Referrer URL regular expressions allowed to call with this key.
41 */
42 allowedReferrers?: string[];
43 };
44
45 export type AndroidApplication = {
46 /**
47 * SHA-1 fingerprint of the app signing cert. Colon-separated and
48 * compact hex are both accepted; the API stores the compact form.
49 */
50 sha1Fingerprint?: string;
51 /**
52 * Android application package name.
53 */
54 packageName?: string;
55 };
56
57 export type AndroidKeyRestrictions = {
58 /**
59 * Android apps allowed to call with this key.
60 */
61 allowedApplications?: AndroidApplication[];
62 };
63
64 export type ServerKeyRestrictions = {
65 /**
66 * Caller IP addresses (or CIDRs) allowed to call with this key.
67 */
68 allowedIps?: string[];
69 };
70
71 export type IosKeyRestrictions = {
72 /**
73 * iOS bundle IDs allowed to call with this key.
74 */
75 allowedBundleIds?: string[];
76 };
77
78 export type KeyRestrictions = {
79 /**
80 * Allowed API targets. Empty / omitted allows every enabled service.
81 */
82 apiTargets?: ApiTarget[];
83 /**
84 * HTTP referrer restrictions. Mutually exclusive with android, iOS,
85 * and server restrictions.
86 */
87 browserKeyRestrictions?: BrowserKeyRestrictions;
88 /**
89 * Android app restrictions. Mutually exclusive with browser, iOS, and
90 * server restrictions.
91 */
92 androidKeyRestrictions?: AndroidKeyRestrictions;
93 /**
94 * Caller IP restrictions. Mutually exclusive with browser, Android,
95 * and iOS restrictions.
96 */
97 serverKeyRestrictions?: ServerKeyRestrictions;
98 /**
99 * iOS bundle-id restrictions. Mutually exclusive with browser,
100 * Android, and server restrictions.
101 */
102 iosKeyRestrictions?: IosKeyRestrictions;
103 };
104
105 export type KeyProps = {
106 /**
107 * Key id (the `{key}` segment of
108 * `projects/{project}/locations/global/keys/{key}`). If omitted, a
109 * unique name is generated from the stack, stage, and logical id.
110 * Must match `[a-z]([a-z0-9-]{0,61}[a-z0-9])?`, must not be UUID-like,
111 * and is immutable — changing it replaces the key.
112 */
113 keyId?: string;
114 /**
115 * Human-readable display name. Max 63 characters.
116 */
117 displayName?: string;
118 /**
119 * User annotations. API keys have no labels field — Alchemy ownership
120 * (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) is stored here
121 * so `list` / `pnpm nuke:gcp` can find owned keys. User keys are
122 * preserved; Alchemy keys win on conflict.
123 */
124 annotations?: Record<string, string>;
125 /**
126 * Key restrictions (API targets and client-type limits).
127 */
128 restrictions?: KeyRestrictions;
129 /**
130 * Service account the key is bound to. Immutable — changing it
131 * replaces the key. Binding enables service-account auth on the key.
132 */
133 serviceAccountEmail?: string;
134 };
135
136 export type Key = Resource<
137 "GCP.ApiKeys.Key",
138 KeyProps,
139 {
140 /** Full resource name `projects/{project}/locations/global/keys/{key}`. */
141 name: string;
142 /** Key id (last path segment). */
143 keyId: string;
144 /** Project id. */
145 project: string;
146 /** Always `global` — API keys are a global resource. */
147 location: string;
148 /** Human-readable display name. */
149 displayName: string | undefined;
150 /** User annotations (Alchemy ownership keys stripped). */
151 annotations: Record<string, string>;
152 /** Key restrictions currently configured. */
153 restrictions: KeyRestrictions | undefined;
154 /** Bound service account email, if any. */
155 serviceAccountEmail: string | undefined;
156 /**
157 * Encrypted key string. Empty on `list` (nuke does not need it).
158 * Fetch at runtime with {@link GetKeyString}.
159 */
160 keyString: string | undefined;
161 /** Server-assigned UUID4, stable until delete. */
162 uid: string | undefined;
163 /** Server checksum of the resource. */
164 etag: string | undefined;
165 /** RFC3339 creation timestamp. */
166 createTime: string | undefined;
167 /** RFC3339 last-update timestamp. */
168 updateTime: string | undefined;
169 },
170 never,
171 Providers
172 >;
173
174 /**
175 * A Google Cloud API key (the API Keys API, `apikeys.googleapis.com`).
176 *
177 * Keys are global (`locations/global`). They have no labels — Alchemy
178 * stamps ownership into `annotations` so `read`, `list`, and
179 * `pnpm nuke:gcp` can find them. `keyId` and `serviceAccountEmail` are
180 * immutable; changing either replaces the key. Deletes are soft: the key
181 * can be undeleted for 30 days, then it is purged.
182 *
183 * ### Creating a Key
184 * **Example:** Generated name
185 * ```typescript
186 * const maps = yield* GCP.ApiKeys.Key("Maps", {
187 * displayName: "maps browser key",
188 * });
189 * ```
190 *
191 * **Example:** Named key with annotations and API-target restrictions
192 * ```typescript
193 * const maps = yield* GCP.ApiKeys.Key("Maps", {
194 * keyId: "maps-browser",
195 * displayName: "maps browser key",
196 * annotations: { env: "prod" },
197 * restrictions: {
198 * apiTargets: [{ service: "geocoding-backend.googleapis.com" }],
199 * browserKeyRestrictions: {
200 * allowedReferrers: ["https://example.com/*"],
201 * },
202 * },
203 * });
204 * ```
205 *
206 * ### Reading the Key String
207 * **Example:** Get the encrypted key string at runtime
208 * ```typescript
209 * const getKeyString = yield* GCP.ApiKeys.GetKeyString(maps);
210 * const { keyString } = yield* getKeyString();
211 * ```
212 *
213 * @resource
214 * @category ApiKeys
215 */
216 export const Key = Resource<Key>("GCP.ApiKeys.Key");
217
218 export class KeyNotResolved extends Data.TaggedError("GCP.ApiKeys.KeyNotResolved")<{
219 resourceName: string;
220 }> {}
221
222 export class KeyStillExists extends Data.TaggedError("GCP.ApiKeys.KeyStillExists")<{
223 resourceName: string;
224 }> {}
225
226 const lastSegment = (value: string) => {
227 const trimmed = value.replace(/\/+$/, "");
228 const parts = trimmed.split("/");
229 return parts[parts.length - 1] || trimmed;
230 };
231
232 const rfc1035 = (name: string): string => {
233 let next = name
234 .toLowerCase()
235 .replace(/[^a-z0-9-]/g, "-")
236 .replace(/-+/g, "-")
237 .replace(/^-+/, "")
238 .replace(/-+$/, "");
239 if (!/^[a-z]/.test(next)) {
240 next = `k${next}`;
241 }
242 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
243 return next.length > 0 ? next : "apikey";
244 };
245
246 const resourceName = (project: string, keyId: string) =>
247 `projects/${project}/locations/${LOCATION}/keys/${keyId}`;
248
249 const parentOf = (project: string) => `projects/${project}/locations/${LOCATION}`;
250
251 const parseName = (name: string) => {
252 const parts = name.split("/").filter((part) => part.length > 0);
253 const keysAt = parts.lastIndexOf("keys");
254 const projectsAt = parts.lastIndexOf("projects");
255 return {
256 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
257 keyId: keysAt >= 0 && parts[keysAt + 1] ? parts[keysAt + 1]! : lastSegment(name),
258 };
259 };
260
261 const userAnnotations = (
262 annotations: Record<string, string | undefined> | null | undefined,
263 ): Record<string, string> => stripInternalLabels(tagRecord(annotations));
264
265 const toId = (id: string, keyId: string | undefined, existing?: string) =>
266 Effect.gen(function* () {
267 if (keyId !== undefined) return keyId;
268 if (existing !== undefined) return existing;
269 return rfc1035(
270 yield* createPhysicalName({
271 id,
272 maxLength: MAX_NAME_LENGTH,
273 lowercase: true,
274 }),
275 );
276 });
277
278 const isDeleted = (key: apikeys.V2Key | undefined) => (key?.deleteTime ?? "") !== "";
279
280 const toRestrictions = (
281 restrictions: apikeys.V2Restrictions | undefined,
282 ): KeyRestrictions | undefined => {
283 if (restrictions === undefined) return undefined;
284 if (
285 (restrictions.apiTargets?.length ?? 0) === 0 &&
286 restrictions.browserKeyRestrictions === undefined &&
287 restrictions.androidKeyRestrictions === undefined &&
288 restrictions.serverKeyRestrictions === undefined &&
289 restrictions.iosKeyRestrictions === undefined
290 ) {
291 return undefined;
292 }
293 return {
294 apiTargets: restrictions.apiTargets,
295 browserKeyRestrictions: restrictions.browserKeyRestrictions,
296 androidKeyRestrictions: restrictions.androidKeyRestrictions,
297 serverKeyRestrictions: restrictions.serverKeyRestrictions,
298 iosKeyRestrictions: restrictions.iosKeyRestrictions,
299 };
300 };
301
302 const sorted = (values: readonly string[] | undefined) =>
303 [...(values ?? [])].slice().sort((a, b) => a.localeCompare(b));
304
305 const fingerprintSha1 = (value: string | undefined) =>
306 (value ?? "").replace(/:/g, "").toUpperCase();
307
308 const restrictionsFingerprint = (restrictions: KeyRestrictions | undefined): string => {
309 if (restrictions === undefined) return "";
310 const apiTargets = [...(restrictions.apiTargets ?? [])]
311 .map((target) => ({
312 service: target.service ?? "",
313 methods: sorted(target.methods),
314 }))
315 .sort((a, b) => a.service.localeCompare(b.service));
316 const android = [...(restrictions.androidKeyRestrictions?.allowedApplications ?? [])]
317 .map((app) => ({
318 packageName: app.packageName ?? "",
319 sha1Fingerprint: fingerprintSha1(app.sha1Fingerprint),
320 }))
321 .sort((a, b) => a.packageName.localeCompare(b.packageName));
322 return JSON.stringify({
323 apiTargets,
324 browser: restrictions.browserKeyRestrictions
325 ? {
326 allowedReferrers: sorted(restrictions.browserKeyRestrictions.allowedReferrers),
327 }
328 : undefined,
329 android: restrictions.androidKeyRestrictions ? { allowedApplications: android } : undefined,
330 server: restrictions.serverKeyRestrictions
331 ? {
332 allowedIps: sorted(restrictions.serverKeyRestrictions.allowedIps),
333 }
334 : undefined,
335 ios: restrictions.iosKeyRestrictions
336 ? {
337 allowedBundleIds: sorted(restrictions.iosKeyRestrictions.allowedBundleIds),
338 }
339 : undefined,
340 });
341 };
342
343 const toAttrs = (key: apikeys.V2Key, project: string, keyString?: string): Key["Attributes"] => {
344 const name = key.name ?? "";
345 const parsed = parseName(name);
346 return {
347 name,
348 keyId: parsed.keyId,
349 project: parsed.project || project,
350 location: LOCATION,
351 displayName: key.displayName,
352 annotations: userAnnotations(key.annotations),
353 restrictions: toRestrictions(key.restrictions),
354 serviceAccountEmail: key.serviceAccountEmail,
355 keyString,
356 uid: key.uid,
357 etag: key.etag,
358 createTime: key.createTime,
359 updateTime: key.updateTime,
360 };
361 };
362
363 const getByName = (name: string) =>
364 apikeys
365 .getProjectsLocationsKeys({ name })
366 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
367
368 const getKeyStringValue = (name: string) =>
369 apikeys.getKeyStringProjectsLocationsKeys({ name }).pipe(
370 Effect.map((response) => response.keyString),
371 Effect.catchTag("NotFound", () => Effect.undefined),
372 );
373
374 const toAttrsLive = (key: apikeys.V2Key, project: string) =>
375 Effect.gen(function* () {
376 const name = key.name ?? "";
377 const keyString = name.length > 0 ? yield* getKeyStringValue(name) : undefined;
378 return toAttrs(key, project, keyString);
379 });
380
381 const waitUntilActive = (name: string) =>
382 getByName(name).pipe(
383 Effect.flatMap((key) =>
384 key && !isDeleted(key)
385 ? Effect.succeed(key)
386 : Effect.fail(new KeyNotResolved({ resourceName: name })),
387 ),
388 Effect.retry({
389 while: (error) => error._tag === "GCP.ApiKeys.KeyNotResolved",
390 times: 8,
391 schedule: Schedule.spaced("1 second"),
392 }),
393 );
394
395 const waitUntilGone = (name: string) =>
396 getByName(name).pipe(
397 Effect.flatMap((key) =>
398 key === undefined || isDeleted(key)
399 ? Effect.void
400 : Effect.fail(new KeyStillExists({ resourceName: name })),
401 ),
402 Effect.retry({
403 while: (error) => error._tag === "GCP.ApiKeys.KeyStillExists",
404 times: 8,
405 schedule: Schedule.spaced("1 second"),
406 }),
407 );
408
409 const reviveDeleted = (name: string) =>
410 Effect.gen(function* () {
411 const operation = yield* apikeys
412 .undeleteProjectsLocationsKeys({ name, body: {} })
413 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
414 if (operation !== undefined) {
415 yield* waitForOperation(operation);
416 }
417 return yield* getByName(name);
418 });
419
420 const listOwnedKeys = (project: string) =>
421 apikeys.listProjectsLocationsKeys
422 .pages({
423 parent: parentOf(project),
424 pageSize: 1000,
425 })
426 .pipe(
427 Stream.flatMap((page) => Stream.fromIterable(page.keys ?? [])),
428 Stream.filter(
429 (key) =>
430 !isDeleted(key) &&
431 Object.keys(key.annotations ?? {}).some((item) => item.startsWith("alchemy-")),
432 ),
433 Stream.map((key) => toAttrs(key, project)),
434 Stream.runCollect,
435 Effect.map((chunk) => Array.from(chunk)),
436 Effect.catchTag("NotFound", () => Effect.succeed([])),
437 );
438
439 const toCreateBody = (news: KeyProps, annotations: Record<string, string>): apikeys.V2Key => ({
440 displayName: news.displayName,
441 annotations,
442 restrictions: news.restrictions,
443 serviceAccountEmail: news.serviceAccountEmail,
444 });
445
446 export const KeyProvider = () =>
447 Provider.succeed(Key, {
448 stables: ["name", "keyId", "project", "location", "uid", "createTime"],
449
450 diff: Effect.fn(function* ({ news, olds, output }) {
451 if (!isResolved(news)) return undefined;
452 const previousId = olds?.keyId ?? output?.keyId;
453 const nextId = news.keyId ?? previousId;
454 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
455 const previousSa = olds?.serviceAccountEmail ?? output?.serviceAccountEmail ?? "";
456 const nextSa = news.serviceAccountEmail ?? previousSa;
457 const saChanged = previousSa !== nextSa;
458
459 if (!idChanged && !saChanged) return undefined;
460 return {
461 action: "replace" as const,
462 deleteFirst: !idChanged && previousId !== undefined && nextId === previousId,
463 };
464 }),
465
466 read: Effect.fn(function* ({ id, olds, output }) {
467 const env = yield* GcpEnvironment.current;
468 const keyId = yield* toId(id, olds?.keyId, output?.keyId);
469 const name = output?.name ?? resourceName(env.project, keyId);
470 const existing = yield* getByName(name);
471 if (existing === undefined || isDeleted(existing)) return undefined;
472 const attrs = yield* toAttrsLive(existing, env.project);
473 return (yield* hasAlchemyLabels(id, tagRecord(existing.annotations)))
474 ? attrs
475 : Unowned(attrs);
476 }),
477
478 list: () =>
479 Effect.gen(function* () {
480 const env = yield* GcpEnvironment.current;
481 return yield* listOwnedKeys(env.project);
482 }),
483
484 reconcile: Effect.fn(function* ({ id, news, output }) {
485 const env = yield* GcpEnvironment.current;
486 const keyId = yield* toId(id, news.keyId, output?.keyId);
487 const name = resourceName(env.project, keyId);
488 const parent = parentOf(env.project);
489 const desiredAnnotations = {
490 ...toLabels(news.annotations),
491 ...(yield* createInternalLabels(id)),
492 };
493
494 let current = yield* getByName(name);
495
496 if (current !== undefined && isDeleted(current)) {
497 current = yield* reviveDeleted(name);
498 }
499
500 if (current === undefined || isDeleted(current)) {
501 const created = yield* apikeys
502 .createProjectsLocationsKeys({
503 parent,
504 keyId,
505 body: toCreateBody(news, desiredAnnotations),
506 })
507 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
508 if (created !== undefined) {
509 yield* waitForOperation(created);
510 }
511 current = yield* getByName(name);
512 if (current !== undefined && isDeleted(current)) {
513 current = yield* reviveDeleted(name);
514 }
515 if (current === undefined || isDeleted(current)) {
516 current = yield* waitUntilActive(name);
517 }
518 }
519
520 if (current === undefined || isDeleted(current)) {
521 return yield* new KeyNotResolved({ resourceName: name });
522 }
523
524 const observedAnnotations = tagRecord(current.annotations);
525 const { upsert, removed } = diffLabels(observedAnnotations, desiredAnnotations);
526 const annotationsChanged = upsert.length > 0 || removed.length > 0;
527 const displayNameChanged = (current.displayName ?? "") !== (news.displayName ?? "");
528 const restrictionsChanged =
529 restrictionsFingerprint(toRestrictions(current.restrictions)) !==
530 restrictionsFingerprint(news.restrictions);
531
532 if (annotationsChanged || displayNameChanged || restrictionsChanged) {
533 const updateMask = [
534 annotationsChanged ? "annotations" : undefined,
535 displayNameChanged ? "display_name" : undefined,
536 restrictionsChanged ? "restrictions" : undefined,
537 ].filter((field): field is string => field !== undefined);
538
539 const operation = yield* apikeys.patchProjectsLocationsKeys({
540 name,
541 updateMask: updateMask.join(","),
542 body: {
543 name,
544 etag: current.etag,
545 annotations: desiredAnnotations,
546 displayName: news.displayName,
547 restrictions: news.restrictions ?? {},
548 },
549 });
550 yield* waitForOperation(operation);
551 current = yield* waitUntilActive(name);
552 }
553
554 return yield* toAttrsLive(current, env.project);
555 }),
556
557 delete: Effect.fn(function* ({ output }) {
558 const operation = yield* apikeys
559 .deleteProjectsLocationsKeys({
560 name: output.name,
561 etag: output.etag,
562 })
563 .pipe(
564 Effect.retry({
565 while: (error) => error._tag === "Conflict",
566 times: 8,
567 schedule: Schedule.spaced("1 second"),
568 }),
569 Effect.catchTag("NotFound", () => Effect.undefined),
570 );
571 if (operation !== undefined) {
572 yield* waitForDeleteOperation(operation);
573 }
574 yield* waitUntilGone(output.name);
575 }),
576 });
577
578 /** API key operations finish within seconds. */
579 const OPERATION_BUDGET = "5 minutes";
580
581 /**
582 * Wait for a long-running operation. ALREADY_EXISTS (code 6) means a
583 * concurrent create won the race; reconcile observes the resource next.
584 */
585 const waitForOperation = (operation: LongRunningOperation) =>
586 waitForLongRunning(operation, (name) => apikeys.getOperations({ name }), {
587 budget: OPERATION_BUDGET,
588 }).pipe(
589 Effect.catchIf(
590 (error) => error._tag === "GCP.OperationFailed" && error.code === 6,
591 () => Effect.succeed(operation),
592 ),
593 );
594
595 /**
596 * Wait for a delete operation. A vanished operation or NOT_FOUND (code 5)
597 * means the resource is already gone.
598 */
599 const waitForDeleteOperation = (operation: LongRunningOperation) =>
600 waitForOperation(operation).pipe(
601 Effect.catchIf(
602 (error) =>
603 error._tag === "NotFound" || (error._tag === "GCP.OperationFailed" && error.code === 5),
604 () => Effect.succeed(operation),
605 ),
606 );