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

main
ts 414 lines 14 KB
Raw
1 import * as iap from "@distilled.cloud/gcp/iap_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6 import * as Stream from "effect/Stream";
7 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
8
9 export const MAX_DEST_GROUP_ID_LENGTH = 63;
10 export const MIN_DEST_GROUP_ID_LENGTH = 4;
11 export const MAX_DISPLAY_NAME_LENGTH = 255;
12 export const OWNER_ZONE = "alc.invalid";
13
14 const DIGIT_TO_LETTER = "abcdefghij";
15
16 const emptyList = <A>() => Effect.succeed([] as A[]);
17
18 export const lastSegment = (value: string) => {
19 const trimmed = value.replace(/\/+$/, "");
20 const parts = trimmed.split("/");
21 return parts[parts.length - 1] || trimmed;
22 };
23
24 export const parentOf = (name: string) => {
25 const parts = name.split("/").filter((part) => part.length > 0);
26 return parts.slice(0, -2).join("/");
27 };
28
29 export const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
30 lastSegment(location ?? defaultLocation).toLowerCase();
31
32 export const sameText = (left: string | undefined, right: string | undefined) =>
33 (left ?? "") === (right ?? "");
34
35 export const sameStringList = (
36 left: readonly string[] | undefined,
37 right: readonly string[] | undefined,
38 ) => {
39 const a = [...(left ?? [])].map((value) => value.toLowerCase()).sort();
40 const b = [...(right ?? [])].map((value) => value.toLowerCase()).sort();
41 return JSON.stringify(a) === JSON.stringify(b);
42 };
43
44 export const uniqueStrings = (values: readonly string[] | undefined) => {
45 const seen = new Set<string>();
46 const next: string[] = [];
47 for (const value of values ?? []) {
48 const trimmed = value.trim();
49 if (trimmed.length === 0) continue;
50 const key = trimmed.toLowerCase();
51 if (seen.has(key)) continue;
52 seen.add(key);
53 next.push(trimmed);
54 }
55 return next;
56 };
57
58 export const updateMaskOf = (...fields: Array<string | undefined>) =>
59 fields.filter((field): field is string => field !== undefined).join(",");
60
61 export const projectParent = (project: string) => `projects/${project}`;
62
63 export const destGroupParent = (project: string, location: string) =>
64 `projects/${project}/iap_tunnel/locations/${location}`;
65
66 export const destGroupNameOf = (project: string, location: string, destGroupId: string) => {
67 if (destGroupId.includes("/destGroups/")) {
68 return destGroupId.replace(/\/+$/, "");
69 }
70 return `${destGroupParent(project, location)}/destGroups/${lastSegment(destGroupId)}`;
71 };
72
73 export const parseDestGroupName = (
74 name: string,
75 fallbackProject: string,
76 fallbackLocation: string,
77 ) => {
78 const parts = name.split("/").filter((part) => part.length > 0);
79 const destAt = parts.lastIndexOf("destGroups");
80 const locationsAt = parts.lastIndexOf("locations");
81 const projectsAt = parts.lastIndexOf("projects");
82 return {
83 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : fallbackProject,
84 location:
85 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
86 destGroupId: destAt >= 0 && parts[destAt + 1] ? parts[destAt + 1]! : lastSegment(name),
87 };
88 };
89
90 export const parseClientName = (name: string, fallbackProject: string) => {
91 const parts = name.split("/").filter((part) => part.length > 0);
92 const clientsAt = parts.lastIndexOf("identityAwareProxyClients");
93 const brandsAt = parts.lastIndexOf("brands");
94 const projectsAt = parts.lastIndexOf("projects");
95 const project =
96 projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : fallbackProject;
97 const brandId = brandsAt >= 0 && parts[brandsAt + 1] ? parts[brandsAt + 1]! : "";
98 return {
99 project,
100 brandId,
101 brand: brandId.length > 0 ? `projects/${project}/brands/${brandId}` : "",
102 identityAwareProxyClientId:
103 clientsAt >= 0 && parts[clientsAt + 1] ? parts[clientsAt + 1]! : lastSegment(name),
104 };
105 };
106
107 export const brandNameOf = (project: string, brand: string) => {
108 const trimmed = brand.replace(/\/+$/, "");
109 if (trimmed.includes("/brands/")) return trimmed;
110 if (trimmed.startsWith("projects/")) return trimmed;
111 return `projects/${project}/brands/${lastSegment(trimmed)}`;
112 };
113
114 const lettersOnly = (value: string) =>
115 value
116 .toLowerCase()
117 .replace(/[0-9]/g, (digit) => DIGIT_TO_LETTER[Number(digit)] ?? "a")
118 .replace(/[^a-z-]/g, "-")
119 .replace(/-+/g, "-")
120 .replace(/^-|-$/g, "");
121
122 export const toDestGroupId = (
123 id: string,
124 explicit: string | undefined,
125 existing: string | undefined,
126 ) =>
127 Effect.gen(function* () {
128 if (explicit !== undefined && explicit.length > 0) {
129 return lastSegment(explicit).slice(0, MAX_DEST_GROUP_ID_LENGTH);
130 }
131 if (existing !== undefined && existing.length > 0) {
132 return lastSegment(existing).slice(0, MAX_DEST_GROUP_ID_LENGTH);
133 }
134 const generated = yield* createPhysicalName({
135 id,
136 maxLength: MAX_DEST_GROUP_ID_LENGTH,
137 lowercase: true,
138 });
139 let next = lettersOnly(generated);
140 if (!/^[a-z]/.test(next)) next = `d${next}`;
141 next = next.slice(0, MAX_DEST_GROUP_ID_LENGTH).replace(/-$/g, "");
142 if (next.length < MIN_DEST_GROUP_ID_LENGTH) {
143 next = `${next}dest`.slice(0, MAX_DEST_GROUP_ID_LENGTH);
144 }
145 return next;
146 });
147
148 const markerOf = (stack: string, stage: string, id: string) =>
149 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
150
151 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
152 let stack = labels[alchemyLabelKeys.stack] ?? "x";
153 let stage = labels[alchemyLabelKeys.stage] ?? "x";
154 let id = labels[alchemyLabelKeys.id] ?? "x";
155 let marker = markerOf(stack, stage, id);
156 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
157 if (stack.length >= stage.length && stack.length >= id.length) {
158 stack = stack.slice(0, -1);
159 } else if (stage.length >= id.length) {
160 stage = stage.slice(0, -1);
161 } else {
162 id = id.slice(0, -1);
163 }
164 marker = markerOf(stack, stage, id);
165 }
166 return marker.slice(0, maxLength);
167 };
168
169 export const encodeOwnershipLine = (
170 labels: Record<string, string>,
171 text: string | undefined,
172 maxLength = MAX_DISPLAY_NAME_LENGTH,
173 ): string => {
174 const trimmed = text?.replace(/[\r\n]+/g, " ").trim();
175 if (!trimmed) return fitMarker(labels, maxLength);
176 const minMarker = 24;
177 const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker));
178 const marker = fitMarker(labels, maxLength - reserved);
179 return `${marker} ${trimmed}`.slice(0, maxLength);
180 };
181
182 export const parseOwnership = (
183 text: string | undefined,
184 ): {
185 labels: Record<string, string>;
186 text: string | undefined;
187 } => {
188 if (!text?.startsWith("[alchemy ")) {
189 return { labels: {}, text };
190 }
191 const end = text.indexOf("]");
192 if (end < 0) return { labels: {}, text };
193 const labels: Record<string, string> = {};
194 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
195 const eq = part.indexOf("=");
196 if (eq > 0) {
197 labels[part.slice(0, eq)] = part.slice(eq + 1);
198 }
199 }
200 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
201 return { labels, text: rest.length > 0 ? rest : undefined };
202 };
203
204 export const hasOwnershipMarker = (text: string | undefined) =>
205 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
206
207 const prefixMatch = (expected: string, observed: string) =>
208 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
209
210 export const ownedByAlchemy = (id: string, text: string | undefined) =>
211 Effect.gen(function* () {
212 const expected = yield* createInternalLabels(id);
213 const { labels } = parseOwnership(text);
214 if (!hasOwnershipMarker(text)) return false;
215 const exact = yield* hasAlchemyLabels(id, labels);
216 if (exact) return true;
217 return (
218 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
219 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
220 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
221 );
222 });
223
224 export const ownershipLabels = (id: string) => createInternalLabels(id);
225
226 export const ownershipFqdn = (labels: Record<string, string>) => {
227 const raw = (labels[alchemyLabelKeys.id] ?? "x")
228 .toLowerCase()
229 .replace(/_/g, "-")
230 .replace(/[^a-z0-9-]/g, "")
231 .replace(/-+/g, "-")
232 .replace(/^-|-$/g, "")
233 .slice(0, 40);
234 return `alc-${raw.length > 0 ? raw : "x"}.${OWNER_ZONE}`;
235 };
236
237 export const isOwnershipFqdn = (fqdn: string) => fqdn.toLowerCase().endsWith(`.${OWNER_ZONE}`);
238
239 export const userFqdns = (fqdns: readonly string[] | undefined) =>
240 uniqueStrings(fqdns).filter((fqdn) => !isOwnershipFqdn(fqdn));
241
242 export const hasOwnershipFqdn = (fqdns: readonly string[] | undefined) =>
243 (fqdns ?? []).some((fqdn) => isOwnershipFqdn(fqdn));
244
245 export const ownedDestGroup = (id: string, fqdns: readonly string[] | undefined) =>
246 Effect.gen(function* () {
247 if (!hasOwnershipFqdn(fqdns)) return false;
248 const expected = ownershipFqdn(yield* createInternalLabels(id));
249 return (fqdns ?? []).some((fqdn) => {
250 const lower = fqdn.toLowerCase();
251 return lower === expected || prefixMatch(expected, lower);
252 });
253 });
254
255 export const desiredFqdns = (
256 labels: Record<string, string>,
257 fqdns: readonly string[] | undefined,
258 ) => uniqueStrings([...userFqdns(fqdns), ownershipFqdn(labels)]);
259
260 export const toGeneratedDisplayName = (
261 id: string,
262 requested: string | undefined,
263 existing: string | undefined,
264 ) =>
265 Effect.gen(function* () {
266 if (requested !== undefined) return requested;
267 if (existing !== undefined) return existing;
268 const generated = yield* createPhysicalName({
269 id,
270 maxLength: 80,
271 lowercase: true,
272 });
273 return generated;
274 });
275
276 export const replaceOnIdentity = (input: {
277 previousId?: string;
278 nextId?: string;
279 previousParent?: string;
280 nextParent?: string;
281 extra?: boolean;
282 }) => {
283 if (input.extra === true) {
284 return { action: "replace" as const, deleteFirst: false };
285 }
286 if (
287 input.previousId !== undefined &&
288 input.nextId !== undefined &&
289 input.previousId !== input.nextId
290 ) {
291 return { action: "replace" as const, deleteFirst: false };
292 }
293 if (
294 input.previousParent !== undefined &&
295 input.nextParent !== undefined &&
296 input.previousParent !== input.nextParent
297 ) {
298 return { action: "replace" as const, deleteFirst: false };
299 }
300 return undefined;
301 };
302
303 export const catchMissing = <A, E extends { readonly _tag: string }, R>(
304 effect: Effect.Effect<A, E, R>,
305 ) =>
306 effect.pipe(
307 Effect.catchIf(
308 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
309 () => Effect.undefined,
310 ),
311 );
312
313 const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
314 pages: Stream.Stream<Page, E, R>,
315 items: (page: Page) => readonly Item[] | null | undefined,
316 ) =>
317 pages.pipe(
318 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
319 Stream.runCollect,
320 Effect.map((chunk) => Array.from(chunk)),
321 Effect.catchIf(
322 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
323 () => emptyList<Item>(),
324 ),
325 );
326
327 export const getDestGroup = (name: string) =>
328 name.length === 0
329 ? Effect.undefined
330 : catchMissing(iap.getProjectsIap_tunnelLocationsDestGroups({ name }));
331
332 export const getClient = (name: string) =>
333 name.length === 0
334 ? Effect.undefined
335 : catchMissing(iap.getProjectsBrandsIdentityAwareProxyClients({ name }));
336
337 export const listDestGroups = (project: string) =>
338 collectPages(
339 iap.listProjectsIap_tunnelLocationsDestGroups.pages({
340 parent: destGroupParent(project, "-"),
341 pageSize: 1000,
342 }),
343 (page) => page.tunnelDestGroups,
344 );
345
346 export const listOwnedDestGroups = (project: string) =>
347 listDestGroups(project).pipe(
348 Effect.map((groups) => groups.filter((group) => hasOwnershipFqdn(group.fqdns))),
349 );
350
351 export const listBrands = (project: string) =>
352 iap.listProjectsBrands({ parent: projectParent(project) }).pipe(
353 Effect.map((page) => page.brands ?? []),
354 Effect.catchTag("NotFound", () => emptyList<iap.Brand>()),
355 );
356
357 export const listClients = (brand: string) =>
358 brand.length === 0
359 ? emptyList<iap.IdentityAwareProxyClient>()
360 : collectPages(
361 iap.listProjectsBrandsIdentityAwareProxyClients.pages({
362 parent: brand,
363 pageSize: 100,
364 }),
365 (page) => page.identityAwareProxyClients,
366 );
367
368 export const listOwnedClients = (project: string) =>
369 Effect.gen(function* () {
370 const brands = yield* listBrands(project);
371 const pages = yield* Effect.forEach(
372 brands,
373 (brand) => (brand.name ? listClients(brand.name) : emptyList<iap.IdentityAwareProxyClient>()),
374 { concurrency: 4 },
375 );
376 return pages.flat().filter((client) => hasOwnershipMarker(client.displayName));
377 });
378
379 export const findOwnedClient = (
380 project: string,
381 id: string,
382 brand: string | undefined,
383 displayName: string | undefined,
384 ) =>
385 Effect.gen(function* () {
386 const clients =
387 brand !== undefined && brand.length > 0
388 ? yield* listClients(brand)
389 : yield* listOwnedClients(project);
390 for (const client of clients) {
391 if (!(yield* ownedByAlchemy(id, client.displayName))) continue;
392 const parsed = parseOwnership(client.displayName);
393 if (displayName !== undefined && parsed.text !== undefined && parsed.text !== displayName) {
394 continue;
395 }
396 return client;
397 }
398 return undefined;
399 });
400
401 export class DeleteNotConfirmed extends Data.TaggedError("GCP.IAP.DeleteNotConfirmed")<{}> {}
402
403 /** Poll until the resource is gone; fails if it is still readable after ~60s. */
404 export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>) =>
405 get.pipe(
406 Effect.repeat({
407 schedule: Schedule.spaced("2 seconds"),
408 until: (value) => value === undefined,
409 times: 30,
410 }),
411 Effect.flatMap((value): Effect.Effect<void, DeleteNotConfirmed> =>
412 value === undefined ? Effect.void : Effect.fail(new DeleteNotConfirmed()),
413 ),
414 );