@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 294 lines 9.77 KB
Raw
1 import * as binaryauthorization from "@distilled.cloud/gcp/binaryauthorization_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 { isTransientGcpError } from "../Errors.ts";
8 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
9
10 export const MAX_ID_LENGTH = 63;
11 export const DEFAULT_PLATFORM = "gke";
12 export const LIST_PLATFORMS = ["gke", "cloudRun"] as const;
13
14 export class ResourceNotResolved extends Data.TaggedError(
15 "GCP.BinaryAuthorization.ResourceNotResolved",
16 )<{
17 resourceName: string;
18 }> {}
19
20 export const lastSegment = (value: string) => {
21 const trimmed = value.replace(/\/+$/, "");
22 const parts = trimmed.split("/");
23 return parts[parts.length - 1] || trimmed;
24 };
25
26 export const rfc1035 = (name: string, fallback = "binauthz"): string => {
27 let next = name
28 .toLowerCase()
29 .replace(/[^a-z0-9-]/g, "-")
30 .replace(/-+/g, "-")
31 .replace(/^-+|-+$/g, "");
32 if (!/^[a-z]/.test(next)) next = `a${next}`;
33 next = next.slice(0, MAX_ID_LENGTH).replace(/-+$/g, "");
34 if (next.length === 0) return fallback;
35 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_ID_LENGTH - 1)}0`;
36 return next.slice(0, MAX_ID_LENGTH);
37 };
38
39 export const toPhysicalId = (
40 id: string,
41 explicit: string | undefined,
42 existing: string | undefined,
43 fallback = "binauthz",
44 ) =>
45 Effect.gen(function* () {
46 if (explicit !== undefined) return rfc1035(explicit, fallback);
47 if (existing !== undefined) return existing;
48 return rfc1035(
49 yield* createPhysicalName({
50 id,
51 maxLength: MAX_ID_LENGTH,
52 lowercase: true,
53 }),
54 fallback,
55 );
56 });
57
58 export const projectParent = (project: string) => `projects/${project}`;
59
60 export const attestorName = (project: string, attestorId: string) =>
61 `${projectParent(project)}/attestors/${attestorId}`;
62
63 export const platformParent = (project: string, platform: string) =>
64 `${projectParent(project)}/platforms/${platform}`;
65
66 export const policyName = (project: string, platform: string, policyId: string) =>
67 `${platformParent(project, platform)}/policies/${policyId}`;
68
69 export const parseAttestorName = (name: string) => {
70 const parts = name.split("/").filter((part) => part.length > 0);
71 const attestorsAt = parts.lastIndexOf("attestors");
72 const projectsAt = parts.lastIndexOf("projects");
73 return {
74 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
75 attestorId:
76 attestorsAt >= 0 && parts[attestorsAt + 1] ? parts[attestorsAt + 1]! : lastSegment(name),
77 };
78 };
79
80 export const parsePolicyName = (name: string) => {
81 const parts = name.split("/").filter((part) => part.length > 0);
82 const policiesAt = parts.lastIndexOf("policies");
83 const platformsAt = parts.lastIndexOf("platforms");
84 const projectsAt = parts.lastIndexOf("projects");
85 return {
86 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
87 platform:
88 platformsAt >= 0 && parts[platformsAt + 1] ? parts[platformsAt + 1]! : DEFAULT_PLATFORM,
89 policyId: policiesAt >= 0 && parts[policiesAt + 1] ? parts[policiesAt + 1]! : lastSegment(name),
90 };
91 };
92
93 export const expandNoteReference = (value: string, project: string) => {
94 const trimmed = value.replace(/\/+$/, "");
95 if (trimmed.includes("/")) return trimmed;
96 return `${projectParent(project)}/notes/${trimmed}`;
97 };
98
99 export const encodeDescription = (
100 labels: Record<string, string>,
101 description: string | undefined,
102 ): string => {
103 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
104 return description ? `${marker}\n${description}` : marker;
105 };
106
107 export const parseDescription = (
108 description: string | undefined,
109 ): {
110 labels: Record<string, string>;
111 description: string | undefined;
112 } => {
113 if (!description?.startsWith("[alchemy ")) {
114 return { labels: {}, description };
115 }
116 const end = description.indexOf("]");
117 if (end < 0) return { labels: {}, description };
118 const labels: Record<string, string> = {};
119 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
120 const eq = part.indexOf("=");
121 if (eq > 0) {
122 labels[part.slice(0, eq)] = part.slice(eq + 1);
123 }
124 }
125 const rest = description.slice(end + 1).replace(/^\n/, "");
126 return { labels, description: rest.length > 0 ? rest : undefined };
127 };
128
129 export const hasOwnershipMarker = (description: string | undefined) =>
130 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
131
132 export const ownedBy = (id: string, labels: Record<string, string>) => hasAlchemyLabels(id, labels);
133
134 export const createOwnership = (id: string) => createInternalLabels(id);
135
136 export const sameText = (left: string | undefined, right: string | undefined) =>
137 (left ?? "") === (right ?? "");
138
139 export const sameJson = (left: unknown, right: unknown) =>
140 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
141
142 export const replaceOnIdentity = (input: {
143 previousId?: string;
144 nextId?: string;
145 previousParent?: string;
146 nextParent?: string;
147 extra?: boolean;
148 deleteFirst?: boolean;
149 }) => {
150 if (input.extra === true) {
151 return {
152 action: "replace" as const,
153 deleteFirst: input.deleteFirst === true,
154 };
155 }
156 const idChanged =
157 input.previousId !== undefined &&
158 input.nextId !== undefined &&
159 input.previousId !== input.nextId;
160 const parentChanged =
161 (input.previousParent ?? "") !== "" &&
162 (input.nextParent ?? "") !== "" &&
163 (input.previousParent ?? "") !== input.nextParent;
164 if (!idChanged && !parentChanged) return undefined;
165 return { action: "replace" as const, deleteFirst: false };
166 };
167
168 export const retryTransient = <A, E extends { readonly _tag: string }, R>(
169 effect: Effect.Effect<A, E, R>,
170 ) =>
171 effect.pipe(
172 Effect.retry({
173 while: isTransientGcpError,
174 times: 8,
175 schedule: Schedule.exponential("250 millis"),
176 }),
177 );
178
179 const isNotFound = <E extends { readonly _tag: string }>(
180 error: E,
181 ): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound";
182
183 export const ignoreGone = <A, E extends { readonly _tag: string }, R>(
184 effect: Effect.Effect<A, E, R>,
185 ) => effect.pipe(Effect.catchIf(isNotFound, () => Effect.void));
186
187 export const missingGet =
188 <A, E extends { readonly _tag: string }, R>(
189 effect: (input: { name: string }) => Effect.Effect<A, E, R>,
190 ) =>
191 (name: string) =>
192 name.length === 0
193 ? Effect.undefined
194 : effect({ name }).pipe(Effect.catchIf(isNotFound, () => Effect.undefined));
195
196 const emptyList = <A>() => Effect.succeed<A[]>([]);
197
198 export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
199 pages: Stream.Stream<Page, E, R>,
200 items: (page: Page) => readonly Item[] | null | undefined,
201 ) =>
202 pages.pipe(
203 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
204 Stream.runCollect,
205 Effect.map((chunk): Item[] => Array.from(chunk)),
206 Effect.catchIf(isNotFound, () => emptyList<Item>()),
207 );
208
209 export const listAttestors = (project: string) =>
210 collectPages(
211 binaryauthorization.listProjectsAttestors.pages({
212 parent: projectParent(project),
213 pageSize: 1000,
214 }),
215 (page) => page.attestors,
216 );
217
218 export const listPlatformPolicies = (project: string) =>
219 Effect.gen(function* () {
220 const pages = yield* Effect.forEach(
221 LIST_PLATFORMS,
222 (platform) =>
223 collectPages(
224 binaryauthorization.listProjectsPlatformsPolicies.pages({
225 parent: platformParent(project, platform),
226 pageSize: 1000,
227 }),
228 (page) => page.platformPolicies,
229 ),
230 { concurrency: "unbounded" },
231 );
232 return pages.flat();
233 });
234
235 const normalizePem = (value: string | undefined) =>
236 (value ?? "")
237 .replace(/-----BEGIN PUBLIC KEY-----/g, "")
238 .replace(/-----END PUBLIC KEY-----/g, "")
239 .replace(/\s+/g, "");
240
241 const normalizeAlgorithm = (value: string | undefined) => {
242 const next = (value ?? "").toUpperCase();
243 if (next === "ECDSA_P256_SHA256") return "EC_SIGN_P256_SHA256";
244 if (next === "ECDSA_P384_SHA384") return "EC_SIGN_P384_SHA384";
245 if (next === "ECDSA_P521_SHA512") return "EC_SIGN_P521_SHA512";
246 return next;
247 };
248
249 export const publicKeysOf = (
250 keys: readonly binaryauthorization.AttestorPublicKey[] | undefined,
251 ): binaryauthorization.AttestorPublicKey[] => [...(keys ?? [])];
252
253 export const samePublicKeys = (
254 observed: readonly binaryauthorization.AttestorPublicKey[] | undefined,
255 desired: readonly binaryauthorization.AttestorPublicKey[] | undefined,
256 ) => {
257 const left = observed ?? [];
258 const right = desired ?? [];
259 if (left.length !== right.length) return false;
260 return left.every((obs, index) => {
261 const want = right[index];
262 if (want === undefined) return false;
263 if ((obs.comment ?? "") !== (want.comment ?? "")) return false;
264 if (
265 normalizePem(obs.asciiArmoredPgpPublicKey) !== normalizePem(want.asciiArmoredPgpPublicKey)
266 ) {
267 return false;
268 }
269 if (
270 normalizePem(obs.pkixPublicKey?.publicKeyPem) !==
271 normalizePem(want.pkixPublicKey?.publicKeyPem)
272 ) {
273 return false;
274 }
275 if (
276 normalizeAlgorithm(obs.pkixPublicKey?.signatureAlgorithm) !==
277 normalizeAlgorithm(want.pkixPublicKey?.signatureAlgorithm)
278 ) {
279 return false;
280 }
281 if (want.id !== undefined && obs.id !== want.id) return false;
282 if (
283 want.pkixPublicKey?.keyId !== undefined &&
284 obs.pkixPublicKey?.keyId !== want.pkixPublicKey.keyId
285 ) {
286 return false;
287 }
288 return true;
289 });
290 };
291
292 export const gkePolicyOf = (
293 policy: binaryauthorization.GkePolicy | undefined,
294 ): binaryauthorization.GkePolicy => policy ?? {};