@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 314 lines 9.94 KB
Raw
1 import * as storage from "@distilled.cloud/gcp/storage_v1";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 export type HmacKeyState = "ACTIVE" | "INACTIVE";
14
15 const DEFAULT_STATE: HmacKeyState = "ACTIVE";
16
17 export type HmacKeyProps = {
18 /**
19 * Email of the service account this HMAC key authenticates. Immutable —
20 * changing it replaces the key. The service account must belong to the
21 * same project.
22 */
23 serviceAccountEmail: string;
24 /**
25 * Desired key state. Newly created keys are always `ACTIVE`; this value
26 * is applied after create. An HMAC key must be `INACTIVE` before it can
27 * be deleted.
28 * @default "ACTIVE"
29 */
30 state?: HmacKeyState;
31 };
32
33 export type HmacKey = Resource<
34 "GCP.Storage.HmacKey",
35 HmacKeyProps,
36 {
37 /** Access id assigned by Cloud Storage; the API id for get/update/delete. */
38 accessId: string;
39 /**
40 * Composite HMAC key id (`{projectId}/{accessId}`), when the API
41 * returns one.
42 */
43 id: string | undefined;
44 /** Project id that owns the service account. */
45 projectId: string;
46 /** Email of the service account this key authenticates. */
47 serviceAccountEmail: string;
48 /** Key state (`ACTIVE` or `INACTIVE`). */
49 state: HmacKeyState;
50 /** RFC3339 creation timestamp. */
51 timeCreated: string | undefined;
52 /** RFC3339 last-update timestamp. */
53 updated: string | undefined;
54 /** GCS self-link. */
55 selfLink: string | undefined;
56 /** HTTP etag used for concurrent updates. */
57 etag: string | undefined;
58 /**
59 * HMAC secret. Cloud Storage returns it only at create time; later
60 * reads preserve the originally stored redacted value. Never logged.
61 */
62 secret: Redacted.Redacted<string> | undefined;
63 },
64 never,
65 Providers
66 >;
67
68 /**
69 * A Cloud Storage HMAC key for a service account.
70 *
71 * HMAC keys authenticate S3-compatible interoperable requests. Cloud
72 * Storage returns the secret once at create time; Alchemy stores it
73 * redacted and never re-reads it. Keys have no labels field, so `list`
74 * enumerates every HMAC key in the project (excluding `DELETED`) for
75 * `pnpm nuke:gcp`. A service account may have at most ten keys in
76 * `ACTIVE` or `INACTIVE` state. Changing `serviceAccountEmail` replaces
77 * the key. Destroy deactivates the key, then deletes it.
78 *
79 * ### Creating an HMAC Key
80 * **Example:** Active key for a service account
81 * ```typescript
82 * const key = yield* GCP.Storage.HmacKey("interop", {
83 * serviceAccountEmail: "app@project.iam.gserviceaccount.com",
84 * });
85 * ```
86 *
87 * **Example:** Inactive key
88 * ```typescript
89 * const key = yield* GCP.Storage.HmacKey("interop", {
90 * serviceAccountEmail: "app@project.iam.gserviceaccount.com",
91 * state: "INACTIVE",
92 * });
93 * ```
94 *
95 * @resource
96 * @category Storage
97 */
98 export const HmacKey = Resource<HmacKey>("GCP.Storage.HmacKey");
99
100 export class HmacKeyNotResolved extends Data.TaggedError("GCP.Storage.HmacKeyNotResolved")<{
101 projectId: string;
102 serviceAccountEmail: string;
103 accessId?: string;
104 }> {}
105
106 export class HmacKeyStillExists extends Data.TaggedError("GCP.Storage.HmacKeyStillExists")<{
107 projectId: string;
108 accessId: string;
109 }> {}
110
111 const sameEmail = (left: string, right: string) =>
112 left.trim().toLowerCase() === right.trim().toLowerCase();
113
114 const normalizeState = (state: string | undefined): HmacKeyState =>
115 state?.toUpperCase() === "INACTIVE" ? "INACTIVE" : DEFAULT_STATE;
116
117 const toSecret = (
118 value: string | Redacted.Redacted<string> | undefined,
119 ): Redacted.Redacted<string> | undefined =>
120 value === undefined ? undefined : typeof value === "string" ? Redacted.make(value) : value;
121
122 const toAttrs = (
123 metadata: storage.HmacKeyMetadata,
124 projectId: string,
125 secret?: Redacted.Redacted<string>,
126 ): HmacKey["Attributes"] => ({
127 accessId: metadata.accessId ?? "",
128 id: metadata.id,
129 projectId: metadata.projectId ?? projectId,
130 serviceAccountEmail: metadata.serviceAccountEmail ?? "",
131 state: normalizeState(metadata.state),
132 timeCreated: metadata.timeCreated,
133 updated: metadata.updated,
134 selfLink: metadata.selfLink,
135 etag: metadata.etag,
136 secret,
137 });
138
139 const isDeleted = (metadata: storage.HmacKeyMetadata | undefined) =>
140 metadata === undefined || metadata.state?.toUpperCase() === "DELETED";
141
142 const getByAccessId = (projectId: string, accessId: string) =>
143 storage.getProjectsHmacKeys({ projectId, accessId }).pipe(
144 Effect.map((metadata) => (isDeleted(metadata) ? undefined : metadata)),
145 Effect.catchTag("NotFound", () => Effect.undefined),
146 );
147
148 const waitUntilGone = (projectId: string, accessId: string) =>
149 getByAccessId(projectId, accessId).pipe(
150 Effect.flatMap((existing) =>
151 existing === undefined
152 ? Effect.void
153 : Effect.fail(new HmacKeyStillExists({ projectId, accessId })),
154 ),
155 Effect.retry({
156 while: (error) => error._tag === "GCP.Storage.HmacKeyStillExists",
157 times: 10,
158 schedule: Schedule.spaced("1 second"),
159 }),
160 );
161
162 const deactivateThenDelete = (projectId: string, accessId: string) =>
163 Effect.gen(function* () {
164 const current = yield* getByAccessId(projectId, accessId);
165 if (current === undefined) return;
166 if (normalizeState(current.state) === "ACTIVE") {
167 yield* storage
168 .updateProjectsHmacKeys({
169 projectId,
170 accessId,
171 body: {
172 accessId,
173 state: "INACTIVE",
174 etag: current.etag,
175 },
176 })
177 .pipe(
178 Effect.catchTags({
179 NotFound: () => Effect.undefined,
180 Conflict: () => Effect.undefined,
181 }),
182 );
183 }
184 yield* storage
185 .deleteProjectsHmacKeys({ projectId, accessId })
186 .pipe(Effect.catchTag("NotFound", () => Effect.void));
187 }).pipe(
188 Effect.retry({
189 while: (error) => error._tag === "BadRequest" || error._tag === "Conflict",
190 times: 8,
191 schedule: Schedule.spaced("1 second"),
192 }),
193 );
194
195 export const HmacKeyProvider = () =>
196 Provider.succeed(HmacKey, {
197 stables: [
198 "accessId",
199 "id",
200 "projectId",
201 "serviceAccountEmail",
202 "timeCreated",
203 "selfLink",
204 "secret",
205 ],
206
207 diff: Effect.fn(function* ({ news, olds, output }) {
208 if (!isResolved(news)) return undefined;
209 const previous = olds?.serviceAccountEmail ?? output?.serviceAccountEmail;
210 if (previous !== undefined && !sameEmail(previous, news.serviceAccountEmail)) {
211 return { action: "replace" as const, deleteFirst: false };
212 }
213 return undefined;
214 }),
215
216 read: Effect.fn(function* ({ output }) {
217 if (output?.accessId === undefined || output.accessId.length === 0) {
218 return undefined;
219 }
220 const env = yield* GcpEnvironment.current;
221 const projectId = output.projectId || env.project;
222 const existing = yield* getByAccessId(projectId, output.accessId);
223 if (existing === undefined) return undefined;
224 return toAttrs(existing, projectId, output.secret);
225 }),
226
227 list: () =>
228 Effect.gen(function* () {
229 const env = yield* GcpEnvironment.current;
230 return yield* storage.listProjectsHmacKeys
231 .items({
232 projectId: env.project,
233 maxResults: 250,
234 })
235 .pipe(
236 Stream.filter((item) => !!item.accessId && item.state?.toUpperCase() !== "DELETED"),
237 Stream.map((item) => toAttrs(item, env.project)),
238 Stream.runCollect,
239 Effect.map((chunk) => Array.from(chunk)),
240 );
241 }),
242
243 reconcile: Effect.fn(function* ({ news, output }) {
244 const env = yield* GcpEnvironment.current;
245 const projectId = env.project;
246 const serviceAccountEmail = news.serviceAccountEmail;
247 const desiredState = news.state ?? DEFAULT_STATE;
248
249 let current =
250 output?.accessId !== undefined && output.accessId.length > 0
251 ? yield* getByAccessId(projectId, output.accessId)
252 : undefined;
253 let secret = output?.secret;
254
255 if (current === undefined) {
256 const created = yield* storage.createProjectsHmacKeys({
257 projectId,
258 serviceAccountEmail,
259 });
260 current = created.metadata;
261 secret = toSecret(created.secret) ?? secret;
262 }
263
264 if (current === undefined || !current.accessId) {
265 return yield* new HmacKeyNotResolved({
266 projectId,
267 serviceAccountEmail,
268 accessId: output?.accessId,
269 });
270 }
271
272 if (normalizeState(current.state) !== desiredState) {
273 const accessId = current.accessId;
274 current = yield* Effect.gen(function* () {
275 const latest = yield* getByAccessId(projectId, accessId);
276 if (latest === undefined) {
277 return yield* new HmacKeyNotResolved({
278 projectId,
279 serviceAccountEmail,
280 accessId,
281 });
282 }
283 if (normalizeState(latest.state) === desiredState) {
284 return latest;
285 }
286 return yield* storage.updateProjectsHmacKeys({
287 projectId,
288 accessId,
289 body: {
290 accessId,
291 state: desiredState,
292 etag: latest.etag,
293 },
294 });
295 }).pipe(
296 Effect.retry({
297 while: (error) => error._tag === "Conflict",
298 times: 8,
299 schedule: Schedule.spaced("1 second"),
300 }),
301 );
302 }
303
304 return toAttrs(current, projectId, secret);
305 }),
306
307 delete: Effect.fn(function* ({ output }) {
308 const projectId = output.projectId;
309 const accessId = output.accessId;
310 if (!projectId || !accessId) return;
311 yield* deactivateThenDelete(projectId, accessId);
312 yield* waitUntilGone(projectId, accessId);
313 }),
314 });