@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 326 lines 11.2 KB
Raw
1 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
2 import type { GcpOpContext } from "@distilled.cloud/gcp/Protocol";
3 import * as securityposture from "@distilled.cloud/gcp/securityposture_v1";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import { tagRecord } from "alchemy/Tags";
6 import * as Config from "effect/Config";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Schedule from "effect/Schedule";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { stripInternalLabels } from "../Labels.ts";
13 import { waitForOperation as waitForLongRunningOperation } from "../Operation.ts";
14
15 export const DEFAULT_LOCATION = "global";
16 export const DEFAULT_STATE = "DRAFT";
17 export const MAX_ID_LENGTH = 63;
18
19 export class SecuritypostureNotResolved extends Data.TaggedError(
20 "GCP.SecurityPosture.NotResolved",
21 )<{
22 resourceName: string;
23 }> {}
24
25 export class SecuritypostureStillExists extends Data.TaggedError(
26 "GCP.SecurityPosture.StillExists",
27 )<{
28 resourceName: string;
29 }> {}
30
31 export class OrganizationNotResolved extends Data.TaggedError(
32 "GCP.SecurityPosture.OrganizationNotResolved",
33 )<{
34 project: string;
35 }> {}
36
37 export const lastSegment = (value: string) => {
38 const trimmed = value.replace(/\/+$/, "");
39 const parts = trimmed.split("/");
40 return parts[parts.length - 1] || trimmed;
41 };
42
43 export const sanitizeId = (name: string, fallback = "posture"): string => {
44 let next = name
45 .toLowerCase()
46 .replace(/[^a-z0-9_-]/g, "-")
47 .replace(/-+/g, "-")
48 .replace(/^-+|-+$/g, "");
49 if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "p"}${next}`;
50 next = next.slice(0, MAX_ID_LENGTH).replace(/-+$/g, "");
51 if (next.length === 0) next = fallback;
52 if (!/[a-z0-9]$/.test(next)) {
53 next = `${next.slice(0, MAX_ID_LENGTH - 1)}0`;
54 }
55 return next.slice(0, MAX_ID_LENGTH);
56 };
57
58 export const toPhysicalId = (
59 id: string,
60 explicit: string | undefined,
61 existing: string | undefined,
62 fallback = "posture",
63 ) =>
64 Effect.gen(function* () {
65 if (explicit !== undefined) return sanitizeId(explicit, fallback);
66 if (existing !== undefined) return existing;
67 return sanitizeId(
68 yield* createPhysicalName({
69 id,
70 maxLength: MAX_ID_LENGTH,
71 lowercase: true,
72 }),
73 fallback,
74 );
75 });
76
77 export const organizationParent = (value: string) =>
78 value.startsWith("organizations/") ? value : `organizations/${lastSegment(value)}`;
79
80 export const organizationIdOf = (value: string) => lastSegment(value);
81
82 export const locationParent = (organization: string, location: string) =>
83 `${organizationParent(organization)}/locations/${location}`;
84
85 export const parseName = (name: string, collection: string) => {
86 const parts = name.split("/").filter((part) => part.length > 0);
87 const collectionAt = parts.lastIndexOf(collection);
88 const locationsAt = parts.lastIndexOf("locations");
89 const orgsAt = parts.lastIndexOf("organizations");
90 return {
91 organization: orgsAt >= 0 && parts[orgsAt + 1] ? parts[orgsAt + 1]! : "",
92 location:
93 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
94 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
95 parent:
96 collectionAt > 0
97 ? parts.slice(0, collectionAt).join("/")
98 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
99 };
100 };
101
102 export const userAnnotations = (
103 annotations: Record<string, string | undefined> | null | undefined,
104 ): Record<string, string> => stripInternalLabels(tagRecord(annotations));
105
106 export const hasAlchemyAnnotationMap = (
107 annotations: Record<string, string | undefined> | null | undefined,
108 ) => Object.keys(annotations ?? {}).some((key) => key.startsWith("alchemy-"));
109
110 export const sameText = (left: string | undefined, right: string | undefined) =>
111 (left ?? "") === (right ?? "");
112
113 export const canonical = (value: unknown): unknown => {
114 if (value === undefined || value === null) return undefined;
115 if (typeof value === "boolean" || typeof value === "number") return value;
116 if (typeof value === "string") {
117 return value.length === 0 ? undefined : value;
118 }
119 if (Array.isArray(value)) {
120 const items = value.map(canonical).filter((item) => item !== undefined);
121 return items.length === 0 ? undefined : items;
122 }
123 if (typeof value === "object") {
124 const entries = Object.entries(value as Record<string, unknown>)
125 .map(([key, item]) => [key, canonical(item)] as const)
126 .filter(([, item]) => item !== undefined)
127 .sort(([left], [right]) => left.localeCompare(right));
128 if (entries.length === 0) return undefined;
129 return Object.fromEntries(entries);
130 }
131 return undefined;
132 };
133
134 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
135
136 export const fieldMask = (fields: Array<string | false | undefined>) =>
137 fields.filter((field): field is string => typeof field === "string").join(",");
138
139 export const defaultPolicySets = (): securityposture.PolicySetList => [
140 {
141 policySetId: "alchemy",
142 description: "alchemy default policy set",
143 policies: [
144 {
145 policyId: "alchemy-sha",
146 constraint: {
147 securityHealthAnalyticsModule: {
148 moduleName: "API_KEY_EXISTS",
149 moduleEnablementState: "DISABLED",
150 },
151 },
152 },
153 ],
154 },
155 ];
156
157 export const desiredPolicySets = (
158 policySets: securityposture.PolicySetList | undefined,
159 ): securityposture.PolicySetList =>
160 policySets && policySets.length > 0 ? policySets : defaultPolicySets();
161
162 /**
163 * Wait on a Security Posture long-running operation (control-plane, usually under a minute).
164 * `ALREADY_EXISTS` (a create race) counts as success; so does `NOT_FOUND`
165 * when `notFoundOk` (deletes). Returns the final operation.
166 */
167 export const waitForOperation = (
168 operation: securityposture.Operation,
169 options?: { notFoundOk?: boolean },
170 ) =>
171 Effect.suspend(() => {
172 let latest = operation;
173 return waitForLongRunningOperation(
174 operation,
175 (name) => {
176 const get = securityposture.getOrganizationsLocationsOperations({ name }).pipe(
177 Effect.tap((current) =>
178 Effect.sync(() => {
179 latest = current;
180 }),
181 ),
182 );
183 const observe: Effect.Effect<
184 securityposture.Operation,
185 securityposture.GetOrganizationsLocationsOperationsError,
186 GcpOpContext
187 > =
188 options?.notFoundOk === true
189 ? get.pipe(
190 Effect.catchTag("NotFound", () =>
191 Effect.succeed<securityposture.Operation>({
192 name,
193 done: true,
194 }),
195 ),
196 )
197 : get.pipe(
198 // A just-returned operation can briefly 404 on read.
199 Effect.retry({
200 while: (error) => error._tag === "NotFound",
201 times: 5,
202 schedule: Schedule.exponential("250 millis"),
203 }),
204 );
205 return observe;
206 },
207 { budget: "10 minutes" },
208 ).pipe(
209 Effect.map(() => latest),
210 // google.rpc.Code ALREADY_EXISTS = 6, NOT_FOUND = 5.
211 Effect.catchTag("GCP.OperationFailed", (error) =>
212 error.code === 6 || (options?.notFoundOk === true && error.code === 5)
213 ? Effect.succeed(latest)
214 : Effect.fail(error),
215 ),
216 );
217 });
218
219 export const waitUntilExists = <A, E, R>(
220 get: Effect.Effect<A | undefined, E, R>,
221 name: string,
222 ): Effect.Effect<NonNullable<A>, E | SecuritypostureNotResolved, R> =>
223 get.pipe(
224 Effect.filterOrFail(
225 (value): value is NonNullable<A> => value != null,
226 () => new SecuritypostureNotResolved({ resourceName: name }),
227 ),
228 Effect.retry({
229 while: (error) => error instanceof SecuritypostureNotResolved,
230 times: 8,
231 schedule: Schedule.spaced("1 second"),
232 }),
233 );
234
235 export const waitUntilGone = <A, E, R>(
236 get: Effect.Effect<A | undefined, E, R>,
237 name: string,
238 ): Effect.Effect<void, E | SecuritypostureStillExists, R> =>
239 get.pipe(
240 Effect.filterOrFail(
241 (value) => value === undefined,
242 () => new SecuritypostureStillExists({ resourceName: name }),
243 ),
244 Effect.retry({
245 while: (error) => error instanceof SecuritypostureStillExists,
246 times: 10,
247 schedule: Schedule.spaced("2 seconds"),
248 }),
249 Effect.asVoid,
250 );
251
252 const ancestryParent = (name: string) =>
253 name.startsWith("projects/")
254 ? resourcemanager.getProjects({ name }).pipe(
255 Effect.map((resource) => resource.parent),
256 Effect.catchTag("NotFound", () => Effect.undefined),
257 )
258 : name.startsWith("folders/")
259 ? resourcemanager.getFolders({ name }).pipe(
260 Effect.map((folder) => folder.parent),
261 Effect.catchTag("NotFound", () => Effect.undefined),
262 )
263 : Effect.undefined;
264
265 export const tryResolveOrganization = () =>
266 Effect.gen(function* () {
267 const configured = Option.getOrUndefined(
268 yield* Config.option(Config.String("GOOGLE_ORGANIZATION_ID")),
269 )?.trim();
270 if (configured) return organizationParent(configured);
271 const env = yield* GcpEnvironment.current;
272 let current: string | undefined = `projects/${env.project}`;
273 for (let i = 0; i < 8; i++) {
274 if (current === undefined) return undefined;
275 if (current.startsWith("organizations/")) return current;
276 current = yield* ancestryParent(current);
277 }
278 return undefined;
279 });
280
281 export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) =>
282 Effect.gen(function* () {
283 if (explicit !== undefined) return organizationParent(explicit);
284 if (existing !== undefined) return organizationParent(existing);
285 const resolved = yield* tryResolveOrganization();
286 if (resolved === undefined) {
287 const env = yield* GcpEnvironment.current;
288 return yield* new OrganizationNotResolved({ project: env.project });
289 }
290 return resolved;
291 });
292
293 export const projectNumberOf = (project: string) =>
294 resourcemanager.getProjects({ name: `projects/${lastSegment(project)}` }).pipe(
295 Effect.map((resource) => {
296 const number = lastSegment(resource.name ?? "");
297 return /^\d+$/.test(number) ? number : lastSegment(project);
298 }),
299 Effect.catchTag("NotFound", () => Effect.succeed(lastSegment(project))),
300 );
301
302 export const normalizeTargetResource = (value: string) =>
303 Effect.gen(function* () {
304 if (value.startsWith("organizations/") || value.startsWith("folders/")) {
305 return value;
306 }
307 if (value.startsWith("projects/")) {
308 const id = lastSegment(value);
309 if (/^\d+$/.test(id)) return value;
310 const number = yield* projectNumberOf(id);
311 return `projects/${number}`;
312 }
313 if (/^\d+$/.test(value)) return `projects/${value}`;
314 const number = yield* projectNumberOf(value);
315 return `projects/${number}`;
316 });
317
318 export const defaultTargetResource = () =>
319 Effect.gen(function* () {
320 const env = yield* GcpEnvironment.current;
321 const number = yield* projectNumberOf(env.project);
322 return `projects/${number}`;
323 });
324
325 export const replaceOnIdentity = (changed: boolean, deleteFirst: boolean) =>
326 changed ? ({ action: "replace" as const, deleteFirst } as const) : undefined;