@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, 06:00 UTC

main
ts 463 lines 16.9 KB
Raw
1 import * as secretmanager from "@distilled.cloud/gcp/secretmanager_v1";
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 Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import {
13 ALCHEMY_LABEL_PREFIX,
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import type { CustomerManagedEncryption, Rotation, SecretTopic } from "./Secret.ts";
22
23 export type LocationsSecretProps = {
24 /**
25 * Secret id (the `{secret}` segment of
26 * `projects/{project}/locations/{location}/secrets/{secret}`). If omitted,
27 * a unique name is generated from the stack, stage, and logical id. Max
28 * 255 characters; letters, numbers, hyphens, and underscores. Changing it
29 * replaces the secret.
30 */
31 secretId?: string;
32 /**
33 * Secret Manager location (`us-central1`, `us-east1`, …). Immutable —
34 * changing it replaces the secret. `US-CENTRAL1` is accepted and
35 * normalized to `us-central1`. Regional secrets live only in this
36 * location (use {@link Secret} for automatic/user-managed replication).
37 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
38 */
39 location?: string;
40 /**
41 * User labels. Alchemy ownership labels are merged in automatically.
42 */
43 labels?: Record<string, string>;
44 /**
45 * Custom metadata. Distinct from labels; not used for ownership.
46 */
47 annotations?: Record<string, string>;
48 /**
49 * Cloud KMS CryptoKey used to encrypt versions
50 * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`).
51 * Must live in the same location as the secret. Empty or omitted uses
52 * Google-managed encryption. Updates apply to versions added afterwards.
53 */
54 customerManagedEncryption?: CustomerManagedEncryption;
55 /**
56 * Timestamp in UTC when the secret expires.
57 */
58 expireTime?: string;
59 /**
60 * Input-only TTL used to compute `expireTime` (e.g. `"86400s"`). Ignored
61 * when `expireTime` is set.
62 */
63 ttl?: string;
64 /**
65 * Pub/Sub topics notified on control-plane events. Required when
66 * `rotation` is set.
67 */
68 topics?: SecretTopic[];
69 /**
70 * Rotation policy. Requires `topics`.
71 */
72 rotation?: Rotation;
73 /**
74 * Mapping from version alias to version id.
75 */
76 versionAliases?: Record<string, string>;
77 /**
78 * Delay before a destroyed version is permanently deleted (e.g.
79 * `"86400s"`).
80 */
81 versionDestroyTtl?: string;
82 };
83
84 export type LocationsSecret = Resource<
85 "GCP.SecretManager.LocationsSecret",
86 LocationsSecretProps,
87 {
88 /** Full resource name `projects/{project}/locations/{location}/secrets/{secret}`. */
89 name: string;
90 /** Secret id (last path segment). */
91 secretId: string;
92 /** Project id. */
93 project: string;
94 /** Location id (`us-central1`, …). */
95 location: string;
96 /** User labels (Alchemy ownership labels stripped). */
97 labels: Record<string, string>;
98 /** Custom annotations. */
99 annotations: Record<string, string>;
100 /** CMEK used for new versions, if set. */
101 customerManagedEncryption: CustomerManagedEncryption | undefined;
102 /** Expiration timestamp, if set. */
103 expireTime: string | undefined;
104 /** RFC3339 creation timestamp. */
105 createTime: string | undefined;
106 /** Server etag. */
107 etag: string | undefined;
108 /** Pub/Sub notification topics. */
109 topics: SecretTopic[];
110 /** Rotation policy, if set. */
111 rotation: Rotation | undefined;
112 /** Version alias map. */
113 versionAliases: Record<string, string>;
114 /** Delayed-destroy TTL, if set. */
115 versionDestroyTtl: string | undefined;
116 },
117 never,
118 Providers
119 >;
120
121 /**
122 * A regional Google Cloud Secret Manager secret. Payloads stay in one
123 * location (`projects/{project}/locations/{location}/secrets/{secret}`).
124 * For automatically replicated secrets, use {@link Secret}.
125 *
126 * Changing `secretId` or `location` replaces the secret.
127 *
128 * ### Creating a LocationsSecret
129 * **Example:** Generated name in us-central1
130 * ```typescript
131 * const secret = yield* GCP.SecretManager.LocationsSecret("ApiKey", {});
132 * ```
133 *
134 * **Example:** Explicit id, location, labels, and annotations
135 * ```typescript
136 * const secret = yield* GCP.SecretManager.LocationsSecret("ApiKey", {
137 * secretId: "order-api-key",
138 * location: "us-central1",
139 * labels: { env: "prod" },
140 * annotations: { owner: "payments" },
141 * });
142 * ```
143 *
144 * ### Secret Versions
145 * **Example:** Add and access a version
146 * ```typescript
147 * const addVersion = yield* GCP.SecretManager.AddSecretVersion(secret);
148 * yield* addVersion({ payload: { data: btoa("hello") } });
149 * const access = yield* GCP.SecretManager.AccessSecretVersion(secret);
150 * const { payload } = yield* access();
151 * ```
152 *
153 * @resource
154 * @category SecretManager
155 */
156 export const LocationsSecret = Resource<LocationsSecret>("GCP.SecretManager.LocationsSecret");
157
158 export class LocationsSecretNotResolved extends Data.TaggedError(
159 "GCP.SecretManager.LocationsSecretNotResolved",
160 )<{
161 resourceName: string;
162 }> {}
163
164 const lastSegment = (value: string) => {
165 const trimmed = value.replace(/\/+$/, "");
166 const parts = trimmed.split("/");
167 return parts[parts.length - 1] || trimmed;
168 };
169
170 const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
171 lastSegment(location ?? defaultLocation).toLowerCase();
172
173 const resourceName = (project: string, location: string, secretId: string) =>
174 `projects/${project}/locations/${location}/secrets/${secretId}`;
175
176 const parseName = (name: string, defaultLocation: string) => {
177 const parts = name.split("/").filter((part) => part.length > 0);
178 const secretsAt = parts.lastIndexOf("secrets");
179 const locationsAt = parts.lastIndexOf("locations");
180 const projectsAt = parts.lastIndexOf("projects");
181 return {
182 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
183 location:
184 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
185 secretId: secretsAt >= 0 && parts[secretsAt + 1] ? parts[secretsAt + 1]! : lastSegment(name),
186 };
187 };
188
189 const userLabels = (
190 labels: Record<string, string | undefined> | null | undefined,
191 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
192
193 const userAnnotations = (
194 annotations: Record<string, string | undefined> | null | undefined,
195 ): Record<string, string> => tagRecord(annotations);
196
197 const userAliases = (
198 aliases: Record<string, string | undefined> | null | undefined,
199 ): Record<string, string> => tagRecord(aliases);
200
201 const toId = (id: string, secretId: string | undefined, existing?: string) =>
202 Effect.gen(function* () {
203 return (
204 secretId ?? existing ?? (yield* createPhysicalName({ id, maxLength: 255, lowercase: true }))
205 );
206 });
207
208 const toTopics = (topics: secretmanager.TopicList | null | undefined) =>
209 (topics ?? [])
210 .filter((topic): topic is { name: string } => typeof topic.name === "string")
211 .map((topic) => ({ name: topic.name }));
212
213 const toRotation = (rotation: secretmanager.Rotation | undefined): Rotation | undefined => {
214 if (rotation === undefined) return undefined;
215 if (rotation.nextRotationTime === undefined && rotation.rotationPeriod === undefined) {
216 return undefined;
217 }
218 return {
219 nextRotationTime: rotation.nextRotationTime,
220 rotationPeriod: rotation.rotationPeriod,
221 };
222 };
223
224 const toCmek = (
225 encryption: secretmanager.CustomerManagedEncryption | undefined,
226 ): CustomerManagedEncryption | undefined => {
227 if (encryption === undefined || encryption.kmsKeyName === undefined) {
228 return undefined;
229 }
230 return { kmsKeyName: encryption.kmsKeyName };
231 };
232
233 const recordsEqual = (left: Record<string, string>, right: Record<string, string>) => {
234 const leftKeys = Object.keys(left).sort();
235 const rightKeys = Object.keys(right).sort();
236 return (
237 leftKeys.length === rightKeys.length &&
238 leftKeys.every((key, index) => key === rightKeys[index] && left[key] === right[key])
239 );
240 };
241
242 const topicsEqual = (left: SecretTopic[], right: SecretTopic[]) => {
243 const a = left.map((topic) => topic.name ?? "").sort();
244 const b = right.map((topic) => topic.name ?? "").sort();
245 return a.length === b.length && a.every((name, index) => name === b[index]);
246 };
247
248 const rotationEqual = (left: Rotation | undefined, right: Rotation | undefined) =>
249 (left?.nextRotationTime ?? "") === (right?.nextRotationTime ?? "") &&
250 (left?.rotationPeriod ?? "") === (right?.rotationPeriod ?? "");
251
252 const cmekEqual = (
253 left: CustomerManagedEncryption | undefined,
254 right: CustomerManagedEncryption | undefined,
255 ) => (left?.kmsKeyName ?? "") === (right?.kmsKeyName ?? "");
256
257 const toAttrs = (secret: secretmanager.Secret, project: string, region: string) => {
258 const name = secret.name ?? "";
259 const parsed = parseName(name, region);
260 return {
261 name,
262 secretId: parsed.secretId,
263 project: parsed.project || project,
264 location: parsed.location,
265 labels: userLabels(secret.labels),
266 annotations: userAnnotations(secret.annotations),
267 customerManagedEncryption: toCmek(secret.customerManagedEncryption),
268 expireTime: secret.expireTime,
269 createTime: secret.createTime,
270 etag: secret.etag,
271 topics: toTopics(secret.topics),
272 rotation: toRotation(secret.rotation),
273 versionAliases: userAliases(secret.versionAliases),
274 versionDestroyTtl: secret.versionDestroyTtl,
275 };
276 };
277
278 const getByName = (name: string) =>
279 secretmanager
280 .getProjectsLocationsSecrets({ name })
281 .pipe(Effect.catchTag(["NotFound"], () => Effect.undefined));
282
283 const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
284 Object.keys(labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX));
285
286 const collectSecretPages = (parent: string) =>
287 secretmanager.listProjectsLocationsSecrets
288 .pages({
289 parent,
290 pageSize: 1000,
291 filter: "labels.alchemy-id:*",
292 })
293 .pipe(
294 Stream.runCollect,
295 Effect.map((pages) => Array.from(pages).flatMap((page) => page.secrets ?? [])),
296 Effect.catchTag("NotFound", () => Effect.succeed([])),
297 );
298
299 const toCreateBody = (
300 news: LocationsSecretProps,
301 labels: Record<string, string>,
302 ): secretmanager.Secret => ({
303 labels,
304 annotations: news.annotations,
305 customerManagedEncryption: news.customerManagedEncryption,
306 expireTime: news.expireTime,
307 ttl: news.expireTime === undefined ? news.ttl : undefined,
308 topics: news.topics,
309 rotation: news.rotation,
310 versionAliases: news.versionAliases,
311 versionDestroyTtl: news.versionDestroyTtl,
312 });
313
314 export const LocationsSecretProvider = () =>
315 Provider.succeed(LocationsSecret, {
316 stables: ["name", "secretId", "project", "location", "createTime"],
317
318 diff: Effect.fn(function* ({ news, olds, output }) {
319 if (!isResolved(news)) return undefined;
320 const env = yield* GcpEnvironment.current;
321 const previousId = olds?.secretId ?? output?.secretId;
322 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
323 const nextLocation = normalizeLocation(
324 news.location ?? olds?.location ?? output?.location,
325 env.region,
326 );
327 const idChanged =
328 previousId !== undefined && news.secretId !== undefined && previousId !== news.secretId;
329 const locationChanged = previousLocation !== nextLocation;
330 if (!idChanged && !locationChanged) return undefined;
331 return { action: "replace" as const };
332 }),
333
334 read: Effect.fn(function* ({ id, olds, output }) {
335 const env = yield* GcpEnvironment.current;
336 const secretId = yield* toId(id, olds?.secretId, output?.secretId);
337 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
338 const name = output?.name ?? resourceName(env.project, location, secretId);
339 const existing = yield* getByName(name);
340 if (existing === undefined) return undefined;
341 const attrs = toAttrs(existing, env.project, env.region);
342 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
343 }),
344
345 list: () =>
346 Effect.gen(function* () {
347 const env = yield* GcpEnvironment.current;
348 const aggregated = yield* collectSecretPages(`projects/${env.project}/locations/-`);
349 const secrets =
350 aggregated.length > 0
351 ? aggregated
352 : yield* collectSecretPages(`projects/${env.project}/locations/${env.region}`);
353 return secrets
354 .filter(
355 (secret) =>
356 (secret.name ?? "").includes("/locations/") && hasAlchemyLabelMap(secret.labels),
357 )
358 .map((secret) => toAttrs(secret, env.project, env.region));
359 }),
360
361 reconcile: Effect.fn(function* ({ id, news, output }) {
362 const env = yield* GcpEnvironment.current;
363 const secretId = yield* toId(id, news.secretId, output?.secretId);
364 const location = normalizeLocation(news.location ?? output?.location, env.region);
365 const name = resourceName(env.project, location, secretId);
366 const parent = `projects/${env.project}/locations/${location}`;
367 const desiredLabels = {
368 ...toLabels(news.labels),
369 ...(yield* createInternalLabels(id)),
370 };
371 const desiredAnnotations = news.annotations ?? {};
372 const desiredAliases = news.versionAliases ?? {};
373 const desiredTopics = news.topics ?? [];
374 const desiredRotation = news.rotation;
375 const desiredDestroyTtl = news.versionDestroyTtl;
376 const desiredCmek = news.customerManagedEncryption;
377
378 let current = yield* getByName(name);
379
380 if (current === undefined) {
381 const created = yield* secretmanager
382 .createProjectsLocationsSecrets({
383 parent,
384 secretId,
385 body: toCreateBody(news, desiredLabels),
386 })
387 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
388 current = created ?? undefined;
389 }
390
391 if (current === undefined) {
392 return yield* new LocationsSecretNotResolved({ resourceName: name });
393 }
394
395 const observedLabels = tagRecord(current.labels);
396 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
397 const labelsChanged = upsert.length > 0 || removed.length > 0;
398 const annotationsChanged = !recordsEqual(
399 userAnnotations(current.annotations),
400 desiredAnnotations,
401 );
402 const aliasesChanged = !recordsEqual(userAliases(current.versionAliases), desiredAliases);
403 const topicsChanged = !topicsEqual(toTopics(current.topics), desiredTopics);
404 const rotationChanged = !rotationEqual(toRotation(current.rotation), desiredRotation);
405 const destroyTtlChanged = (current.versionDestroyTtl ?? "") !== (desiredDestroyTtl ?? "");
406 const cmekChanged = !cmekEqual(toCmek(current.customerManagedEncryption), desiredCmek);
407 const expireTimeChanged =
408 news.expireTime !== undefined && (current.expireTime ?? "") !== news.expireTime;
409 const ttlChanged =
410 news.expireTime === undefined &&
411 news.ttl !== undefined &&
412 (current.expireTime === undefined || current.expireTime === "");
413
414 if (
415 labelsChanged ||
416 annotationsChanged ||
417 aliasesChanged ||
418 topicsChanged ||
419 rotationChanged ||
420 destroyTtlChanged ||
421 cmekChanged ||
422 expireTimeChanged ||
423 ttlChanged
424 ) {
425 current = yield* secretmanager.patchProjectsLocationsSecrets({
426 name,
427 updateMask: [
428 labelsChanged ? "labels" : undefined,
429 annotationsChanged ? "annotations" : undefined,
430 aliasesChanged ? "versionAliases" : undefined,
431 topicsChanged ? "topics" : undefined,
432 rotationChanged ? "rotation" : undefined,
433 destroyTtlChanged ? "versionDestroyTtl" : undefined,
434 cmekChanged ? "customerManagedEncryption" : undefined,
435 expireTimeChanged ? "expireTime" : undefined,
436 ttlChanged ? "ttl" : undefined,
437 ]
438 .filter((field): field is string => field !== undefined)
439 .join(","),
440 body: {
441 name,
442 labels: desiredLabels,
443 annotations: desiredAnnotations,
444 versionAliases: desiredAliases,
445 topics: desiredTopics,
446 rotation: desiredRotation,
447 versionDestroyTtl: desiredDestroyTtl,
448 customerManagedEncryption: desiredCmek,
449 expireTime: news.expireTime,
450 ttl: ttlChanged ? news.ttl : undefined,
451 },
452 });
453 }
454
455 return toAttrs(current, env.project, env.region);
456 }),
457
458 delete: Effect.fn(function* ({ output }) {
459 yield* secretmanager
460 .deleteProjectsLocationsSecrets({ name: output.name })
461 .pipe(Effect.catchTag(["NotFound"], () => Effect.void));
462 }),
463 });