@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 445 lines 15 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_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 * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { waitRegionOperation } from "./operations.ts";
15 import type {
16 SslPolicyMinTlsVersion,
17 SslPolicyPostQuantumKeyExchange,
18 SslPolicyProfile,
19 } from "./SslPolicy.ts";
20
21 const DEFAULT_PROFILE: SslPolicyProfile = "COMPATIBLE";
22 const DEFAULT_MIN_TLS: SslPolicyMinTlsVersion = "TLS_1_0";
23
24 export type RegionSslPolicyProps = {
25 /**
26 * SSL policy name (RFC1035, 1-63 chars). If omitted, a unique name is
27 * generated from the stack, stage, and logical id. Changing it replaces
28 * the resource.
29 */
30 sslPolicyName?: string;
31 /**
32 * Region the policy lives in (e.g. `us-central1`). Immutable — changing
33 * it replaces the resource. `US-CENTRAL1` is accepted and normalized to
34 * `us-central1`.
35 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
36 */
37 region?: string;
38 /**
39 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
40 * prefix so `list` / nuke can find resources (Compute SslPolicy has no
41 * labels field).
42 */
43 description?: string;
44 /**
45 * Minimum TLS version clients may use (`TLS_1_0`, `TLS_1_1`, `TLS_1_2`,
46 * `TLS_1_3`). `TLS_1_3` requires `profile: "RESTRICTED"`.
47 * @default "TLS_1_0"
48 */
49 minTlsVersion?: SslPolicyMinTlsVersion;
50 /**
51 * Cipher-suite profile (`COMPATIBLE`, `MODERN`, `RESTRICTED`,
52 * `FIPS_202205`, `CUSTOM`). `CUSTOM` requires `customFeatures`.
53 * `FIPS_202205` requires `minTlsVersion: "TLS_1_2"`.
54 * @default "COMPATIBLE"
55 */
56 profile?: SslPolicyProfile;
57 /**
58 * Features enabled when `profile` is `CUSTOM`. Must be empty for every
59 * other profile.
60 */
61 customFeatures?: string[];
62 /**
63 * Whether the load balancer negotiates X25519MLKEM768 (`DEFAULT`,
64 * `ENABLED`, `DEFERRED`).
65 */
66 postQuantumKeyExchange?: SslPolicyPostQuantumKeyExchange;
67 };
68
69 export type RegionSslPolicy = Resource<
70 "GCP.Compute.RegionSslPolicy",
71 RegionSslPolicyProps,
72 {
73 /** SSL policy name. */
74 sslPolicyName: string;
75 /** Project id. */
76 project: string;
77 /** Region short name (`us-central1`). */
78 region: string;
79 /** User description with the Alchemy ownership prefix stripped. */
80 description: string | undefined;
81 /** Minimum TLS version. */
82 minTlsVersion: SslPolicyMinTlsVersion;
83 /** Cipher-suite profile. */
84 profile: SslPolicyProfile;
85 /** Custom features (only when `profile` is `CUSTOM`). */
86 customFeatures: string[];
87 /** Features currently enabled by the selected profile. */
88 enabledFeatures: string[];
89 /** Post-quantum key exchange mode, if set. */
90 postQuantumKeyExchange: string | undefined;
91 /** Server-defined URL. */
92 selfLink: string | undefined;
93 /** Server-assigned numeric id. */
94 sslPolicyId: string | undefined;
95 /** Optimistic-locking fingerprint. */
96 fingerprint: string | undefined;
97 /** RFC3339 creation timestamp. */
98 creationTimestamp: string | undefined;
99 /** Resource kind. */
100 kind: string | undefined;
101 },
102 never,
103 Providers
104 >;
105
106 /**
107 * A regional Compute Engine SSL policy for HTTPS and SSL load balancing.
108 *
109 * SSL policies control the TLS versions and cipher suites offered by
110 * regional Application Load Balancers and proxy Network Load Balancers.
111 * This resource maps to the `regionSslPolicies` collection (the global
112 * `sslPolicies` collection is `GCP.Compute.SslPolicy`). Compute SslPolicy
113 * has no labels field — Alchemy ownership is stored in the description
114 * so nuke can find leaked policies.
115 *
116 * ### Creating a Regional SSL Policy
117 * **Example:** Generated name (COMPATIBLE, TLS 1.0)
118 * ```typescript
119 * const policy = yield* GCP.Compute.RegionSslPolicy("Frontend", {
120 * region: "us-central1",
121 * });
122 * ```
123 *
124 * **Example:** Modern profile and TLS 1.2
125 * ```typescript
126 * const policy = yield* GCP.Compute.RegionSslPolicy("Frontend", {
127 * region: "us-central1",
128 * description: "prod frontend",
129 * profile: "MODERN",
130 * minTlsVersion: "TLS_1_2",
131 * });
132 * ```
133 *
134 * @resource
135 * @category Compute
136 */
137 export const RegionSslPolicy = Resource<RegionSslPolicy>("GCP.Compute.RegionSslPolicy");
138
139 export class RegionSslPolicyNotResolved extends Data.TaggedError(
140 "GCP.Compute.RegionSslPolicyNotResolved",
141 )<{
142 sslPolicyName: string;
143 region: string;
144 }> {}
145
146 const lastSegment = (value: string | undefined) => {
147 if (value === undefined || value.length === 0) return "";
148 const trimmed = value.replace(/\/+$/, "");
149 const parts = trimmed.split("/");
150 return parts[parts.length - 1] || trimmed;
151 };
152
153 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
154 lastSegment(region ?? defaultRegion).toLowerCase();
155
156 const rfc1035 = (name: string): string => {
157 let next = name
158 .toLowerCase()
159 .replace(/[^a-z0-9-]/g, "-")
160 .replace(/-+/g, "-")
161 .replace(/^-+/, "")
162 .replace(/-+$/, "");
163 if (!/^[a-z]/.test(next)) {
164 next = `s${next}`;
165 }
166 next = next.slice(0, 63).replace(/-+$/, "");
167 return next.length > 0 ? next : "sslpolicy";
168 };
169
170 const toName = (id: string, name: string | undefined, existing?: string) =>
171 Effect.gen(function* () {
172 if (name !== undefined) return name;
173 if (existing !== undefined) return existing;
174 return rfc1035(
175 yield* createPhysicalName({
176 id,
177 maxLength: 63,
178 lowercase: true,
179 }),
180 );
181 });
182
183 const encodeDescription = (
184 labels: Record<string, string>,
185 description: string | undefined,
186 ): string => {
187 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
188 return description ? `${marker}\n${description}` : marker;
189 };
190
191 const parseDescription = (
192 description: string | undefined,
193 ): {
194 labels: Record<string, string>;
195 description: string | undefined;
196 } => {
197 if (!description?.startsWith("[alchemy ")) {
198 return { labels: {}, description };
199 }
200 const end = description.indexOf("]");
201 if (end < 0) return { labels: {}, description };
202 const labels: Record<string, string> = {};
203 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
204 const eq = part.indexOf("=");
205 if (eq > 0) {
206 labels[part.slice(0, eq)] = part.slice(eq + 1);
207 }
208 }
209 const rest = description.slice(end + 1).replace(/^\n/, "");
210 return { labels, description: rest.length > 0 ? rest : undefined };
211 };
212
213 const asProfile = (value: string | undefined): SslPolicyProfile => {
214 switch (value) {
215 case "COMPATIBLE":
216 case "MODERN":
217 case "RESTRICTED":
218 case "FIPS_202205":
219 case "CUSTOM":
220 return value;
221 default:
222 return DEFAULT_PROFILE;
223 }
224 };
225
226 const asMinTlsVersion = (value: string | undefined): SslPolicyMinTlsVersion => {
227 switch (value) {
228 case "TLS_1_0":
229 case "TLS_1_1":
230 case "TLS_1_2":
231 case "TLS_1_3":
232 return value;
233 default:
234 return DEFAULT_MIN_TLS;
235 }
236 };
237
238 const featuresOf = (features: readonly string[] | undefined): string[] => [...(features ?? [])];
239
240 const sameFeatures = (observed?: readonly string[], desired?: readonly string[]) =>
241 [...(observed ?? [])].sort().join("\0") === [...(desired ?? [])].sort().join("\0");
242
243 const toBody = (
244 sslPolicyName: string,
245 props: RegionSslPolicyProps,
246 ownership: Record<string, string>,
247 fingerprint?: string,
248 ): compute.SslPolicy => {
249 const profile = props.profile ?? DEFAULT_PROFILE;
250 return {
251 name: sslPolicyName,
252 fingerprint,
253 description: encodeDescription(ownership, props.description),
254 profile,
255 minTlsVersion: props.minTlsVersion ?? DEFAULT_MIN_TLS,
256 customFeatures: profile === "CUSTOM" ? featuresOf(props.customFeatures) : [],
257 postQuantumKeyExchange: props.postQuantumKeyExchange,
258 };
259 };
260
261 const toAttrs = (policy: compute.SslPolicy, project: string): RegionSslPolicy["Attributes"] => {
262 const parsed = parseDescription(policy.description);
263 return {
264 sslPolicyName: policy.name ?? policy.id ?? "",
265 project,
266 region: lastSegment(policy.region).toLowerCase(),
267 description: parsed.description,
268 minTlsVersion: asMinTlsVersion(policy.minTlsVersion),
269 profile: asProfile(policy.profile),
270 customFeatures: featuresOf(policy.customFeatures),
271 enabledFeatures: featuresOf(policy.enabledFeatures),
272 postQuantumKeyExchange: policy.postQuantumKeyExchange,
273 selfLink: policy.selfLink,
274 sslPolicyId: policy.id,
275 fingerprint: policy.fingerprint,
276 creationTimestamp: policy.creationTimestamp,
277 kind: policy.kind,
278 };
279 };
280
281 const needsUpdate = (current: compute.SslPolicy, desired: compute.SslPolicy) => {
282 if ((current.description ?? "") !== (desired.description ?? "")) return true;
283 if (asProfile(current.profile) !== asProfile(desired.profile)) return true;
284 if (asMinTlsVersion(current.minTlsVersion) !== asMinTlsVersion(desired.minTlsVersion)) {
285 return true;
286 }
287 if (!sameFeatures(current.customFeatures, desired.customFeatures)) {
288 return true;
289 }
290 if (
291 desired.postQuantumKeyExchange !== undefined &&
292 (current.postQuantumKeyExchange ?? "DEFAULT") !== desired.postQuantumKeyExchange
293 ) {
294 return true;
295 }
296 return false;
297 };
298
299 const getByName = (project: string, region: string, sslPolicy: string) =>
300 compute
301 .getRegionSslPolicies({ project, region, sslPolicy })
302 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
303
304 const awaitResource = (project: string, region: string, sslPolicyName: string) =>
305 getByName(project, region, sslPolicyName).pipe(
306 Effect.repeat({
307 schedule: Schedule.spaced("1 second"),
308 until: (policy) => policy !== undefined,
309 times: 8,
310 }),
311 );
312
313 export const RegionSslPolicyProvider = () =>
314 Provider.succeed(RegionSslPolicy, {
315 stables: ["sslPolicyName", "project", "region", "sslPolicyId", "selfLink", "creationTimestamp"],
316
317 diff: Effect.fn(function* ({ news, olds, output }) {
318 if (!isResolved(news)) return undefined;
319 const env = yield* GcpEnvironment.current;
320 const previousName = olds?.sslPolicyName ?? output?.sslPolicyName;
321 const nextName = news.sslPolicyName;
322 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
323 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
324 if (previousRegion !== nextRegion) {
325 return { action: "replace" as const, deleteFirst: false };
326 }
327 if (previousName !== undefined && nextName !== undefined && previousName !== nextName) {
328 return { action: "replace" as const };
329 }
330 return undefined;
331 }),
332
333 read: Effect.fn(function* ({ id, olds, output }) {
334 const env = yield* GcpEnvironment.current;
335 const sslPolicyName = yield* toName(id, olds?.sslPolicyName, output?.sslPolicyName);
336 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
337 const existing = yield* getByName(env.project, region, sslPolicyName);
338 if (existing === undefined) return undefined;
339 const attrs = toAttrs(existing, env.project);
340 const { labels } = parseDescription(existing.description);
341 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
342 }),
343
344 list: () =>
345 Effect.gen(function* () {
346 const env = yield* GcpEnvironment.current;
347 const pages = yield* compute.aggregatedListSslPolicies
348 .pages({
349 project: env.project,
350 returnPartialSuccess: true,
351 maxResults: 500,
352 })
353 .pipe(Stream.runCollect);
354 return Array.from(pages).flatMap((page) =>
355 Object.values(page.items ?? {}).flatMap((scoped) =>
356 (scoped?.sslPolicies ?? [])
357 .filter((policy) => (policy.region ?? "").length > 0)
358 .filter((policy) => {
359 const { labels } = parseDescription(policy.description);
360 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
361 })
362 .map((policy) => toAttrs(policy, env.project)),
363 ),
364 );
365 }),
366
367 reconcile: Effect.fn(function* ({ id, news, output }) {
368 const env = yield* GcpEnvironment.current;
369 const sslPolicyName = yield* toName(id, news.sslPolicyName, output?.sslPolicyName);
370 const region = normalizeRegion(news.region ?? output?.region, env.region);
371 const ownership = yield* createInternalLabels(id);
372 const desired = toBody(sslPolicyName, news, ownership);
373
374 let current = yield* getByName(env.project, region, sslPolicyName);
375
376 if (current === undefined) {
377 yield* compute
378 .insertRegionSslPolicies({
379 project: env.project,
380 region,
381 body: desired,
382 })
383 .pipe(
384 Effect.flatMap((operation) =>
385 waitRegionOperation(env.project, region, operation, {
386 ignore: ["RESOURCE_ALREADY_EXISTS"],
387 }),
388 ),
389 Effect.catchTag("Conflict", () => Effect.undefined),
390 );
391 current = yield* awaitResource(env.project, region, sslPolicyName);
392 }
393
394 if (current === undefined) {
395 return yield* new RegionSslPolicyNotResolved({
396 sslPolicyName,
397 region,
398 });
399 }
400
401 if (needsUpdate(current, desired)) {
402 yield* compute
403 .patchRegionSslPolicies({
404 project: env.project,
405 region,
406 sslPolicy: sslPolicyName,
407 body: toBody(sslPolicyName, news, ownership, current.fingerprint),
408 })
409 .pipe(Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)));
410 current = yield* getByName(env.project, region, sslPolicyName);
411 if (current === undefined) {
412 return yield* new RegionSslPolicyNotResolved({
413 sslPolicyName,
414 region,
415 });
416 }
417 }
418
419 return toAttrs(current, env.project);
420 }),
421
422 delete: Effect.fn(function* ({ output }) {
423 const env = yield* GcpEnvironment.current;
424 const region = normalizeRegion(output.region, env.region);
425 const operation = yield* compute
426 .deleteRegionSslPolicies({
427 project: env.project,
428 region,
429 sslPolicy: output.sslPolicyName,
430 })
431 .pipe(
432 Effect.retry({
433 while: (error) => error._tag === "Conflict",
434 schedule: Schedule.spaced("2 seconds"),
435 times: 8,
436 }),
437 Effect.catchTag("NotFound", () => Effect.undefined),
438 );
439 if (operation !== undefined) {
440 yield* waitRegionOperation(env.project, region, operation).pipe(
441 Effect.catchTag("NotFound", () => Effect.void),
442 );
443 }
444 }),
445 });