@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 452 lines 15.2 KB
Raw
1 import * as beyondcorp from "@distilled.cloud/gcp/beyondcorp_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 DEFAULT_GLOBAL,
13 ResourceNotResolved,
14 collectPages,
15 encodeOwnershipLine,
16 fieldMask,
17 fingerprint,
18 hasOwnershipMarker,
19 listAtLocation,
20 normalizeLocation,
21 ownedByAlchemy,
22 parentOf,
23 parseName,
24 parseOwnership,
25 replaceOnIdentity,
26 rfc1035,
27 toPhysicalId,
28 waitForDeleteOperation,
29 waitForOperation,
30 waitUntilExists,
31 waitUntilGone,
32 waitUntilReady,
33 } from "./internal.ts";
34
35 const COLLECTION = "securityGateways";
36
37 export type SecurityGatewayInternetGateway = {
38 /** IP addresses assigned to Cloud NAT. Output only. */
39 assignedIps?: string[];
40 };
41
42 export type SecurityGatewayHub = {
43 /** Internet gateway configuration for the hub. */
44 internetGateway?: SecurityGatewayInternetGateway;
45 };
46
47 export type SecurityGatewayServiceDiscovery = {
48 /** External API-gateway discovery settings. */
49 apiGateway?: {
50 /** Path used to fetch resource-model updates. */
51 resourceOverride?: { path?: string };
52 };
53 };
54
55 export type SecurityGatewayContextualHeaders = {
56 /** Delegated device-info output type. */
57 deviceInfo?: { outputType?: string };
58 /** Delegated user-info output type. */
59 userInfo?: { outputType?: string };
60 /** Delegated group-info output type. */
61 groupInfo?: { outputType?: string };
62 /** Default output type for enabled headers. */
63 outputType?: string;
64 };
65
66 export type SecurityGatewayProxyProtocolConfig = {
67 /** Allowed client header names. */
68 allowedClientHeaders?: string[];
69 /** Custom metadata headers. */
70 metadataHeaders?: Record<string, string>;
71 /** Gateway identity included in the proxy protocol. */
72 gatewayIdentity?: string;
73 /** Contextual header configuration. */
74 contextualHeaders?: SecurityGatewayContextualHeaders;
75 /** Include the client IP when true. */
76 clientIp?: boolean;
77 };
78
79 export type SecurityGatewayProps = {
80 /**
81 * SecurityGateway id (the `{securityGateway}` segment of
82 * `projects/{project}/locations/{location}/securityGateways/{securityGateway}`).
83 * If omitted, a unique RFC1035 name is generated. Must be 4-63
84 * characters matching `[a-z]([a-z0-9-]{0,61}[a-z0-9])?`. Immutable —
85 * changing it replaces the gateway.
86 */
87 securityGatewayId?: string;
88 /**
89 * Location. Security gateways live in `global`. Immutable — changing
90 * it replaces the gateway.
91 * @default "global"
92 */
93 location?: string;
94 /**
95 * Human-readable name. Cannot exceed 64 characters. SecurityGateway
96 * has no labels field, so Alchemy stamps ownership into this value
97 * and strips it from attributes.
98 */
99 displayName?: string;
100 /**
101 * Regional hubs keyed by GCP region. Defaults to an internet-gateway
102 * hub in the stack's GCP region (`GCP.Region`, else the profile region,
103 * else `us-central1`); once created, an unset value keeps the current hubs.
104 */
105 hubs?: Record<string, SecurityGatewayHub>;
106 /**
107 * Service discovery settings.
108 */
109 serviceDiscovery?: SecurityGatewayServiceDiscovery;
110 /**
111 * Shared proxy-protocol configuration for applications.
112 */
113 proxyProtocolConfig?: SecurityGatewayProxyProtocolConfig;
114 };
115
116 export type SecurityGateway = Resource<
117 "GCP.BeyondCorp.SecurityGateway",
118 SecurityGatewayProps,
119 {
120 /** Full resource name `projects/{project}/locations/{location}/securityGateways/{securityGateway}`. */
121 name: string;
122 /** SecurityGateway id (last path segment). */
123 securityGatewayId: string;
124 /** Project id. */
125 project: string;
126 /** Location id (`global`). */
127 location: string;
128 /** User display name with the Alchemy ownership prefix stripped. */
129 displayName: string | undefined;
130 /** Regional hubs. */
131 hubs: Record<string, SecurityGatewayHub> | undefined;
132 /** Service discovery settings. */
133 serviceDiscovery: SecurityGatewayServiceDiscovery | undefined;
134 /** Shared proxy-protocol configuration. */
135 proxyProtocolConfig: SecurityGatewayProxyProtocolConfig | undefined;
136 /** Server-reported state (`RUNNING`, `CREATING`, …). */
137 state: string | undefined;
138 /** Service account used for consumer-project operations. */
139 delegatingServiceAccount: string | undefined;
140 /** External IPs used to reach endpoints. */
141 externalIps: string[];
142 /** RFC3339 creation timestamp. */
143 createTime: string | undefined;
144 /** RFC3339 last-update timestamp. */
145 updateTime: string | undefined;
146 },
147 never,
148 Providers
149 >;
150
151 /**
152 * A BeyondCorp Security Gateway that fronts Chrome Enterprise Premium
153 * applications.
154 *
155 * The API has no labels field, so Alchemy stamps ownership into
156 * `displayName` for `list` / nuke. Changing `securityGatewayId` or
157 * `location` replaces the gateway. Display name and hubs update in
158 * place.
159 *
160 * ### Creating a SecurityGateway
161 * **Example:** Generated name with a us-central1 hub
162 * ```typescript
163 * const gateway = yield* GCP.BeyondCorp.SecurityGateway("Pep", {});
164 * ```
165 *
166 * **Example:** Explicit id and display name
167 * ```typescript
168 * const gateway = yield* GCP.BeyondCorp.SecurityGateway("Pep", {
169 * securityGatewayId: "app-pep",
170 * displayName: "prod gateway",
171 * hubs: {
172 * "us-central1": { internetGateway: {} },
173 * },
174 * });
175 * ```
176 *
177 * @resource
178 * @category BeyondCorp
179 */
180 export const SecurityGateway = Resource<SecurityGateway>("GCP.BeyondCorp.SecurityGateway");
181
182 const resourceName = (project: string, location: string, securityGatewayId: string) =>
183 `projects/${project}/locations/${location}/securityGateways/${securityGatewayId}`;
184
185 const hubKeys = (hubs: Record<string, SecurityGatewayHub> | undefined) =>
186 Object.keys(hubs ?? {}).sort();
187
188 const toHubs = (
189 hubs: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1HubMap | undefined,
190 ): Record<string, SecurityGatewayHub> | undefined => {
191 if (hubs === undefined) return undefined;
192 return Object.fromEntries(
193 Object.entries(hubs).map(([region, hub]) => [
194 region,
195 {
196 internetGateway: hub?.internetGateway
197 ? {
198 assignedIps: hub.internetGateway.assignedIps
199 ? [...hub.internetGateway.assignedIps]
200 : undefined,
201 }
202 : undefined,
203 },
204 ]),
205 );
206 };
207
208 const toServiceDiscovery = (
209 value: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1ServiceDiscovery | undefined,
210 ): SecurityGatewayServiceDiscovery | undefined => {
211 if (value === undefined) return undefined;
212 return {
213 apiGateway: value.apiGateway
214 ? {
215 resourceOverride: value.apiGateway.resourceOverride
216 ? { path: value.apiGateway.resourceOverride.path }
217 : undefined,
218 }
219 : undefined,
220 };
221 };
222
223 const toContextualHeaders = (
224 value: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1ContextualHeaders | undefined,
225 ): SecurityGatewayContextualHeaders | undefined => {
226 if (value === undefined) return undefined;
227 return {
228 deviceInfo: value.deviceInfo
229 ? {
230 outputType:
231 value.deviceInfo.outputType === undefined
232 ? undefined
233 : `${value.deviceInfo.outputType}`,
234 }
235 : undefined,
236 userInfo: value.userInfo
237 ? {
238 outputType:
239 value.userInfo.outputType === undefined ? undefined : `${value.userInfo.outputType}`,
240 }
241 : undefined,
242 groupInfo: value.groupInfo
243 ? {
244 outputType:
245 value.groupInfo.outputType === undefined ? undefined : `${value.groupInfo.outputType}`,
246 }
247 : undefined,
248 outputType: value.outputType === undefined ? undefined : `${value.outputType}`,
249 };
250 };
251
252 const toProxyProtocolConfig = (
253 value: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1ProxyProtocolConfig | undefined,
254 ): SecurityGatewayProxyProtocolConfig | undefined => {
255 if (value === undefined) return undefined;
256 const metadataHeaders = value.metadataHeaders;
257 return {
258 allowedClientHeaders: value.allowedClientHeaders ? [...value.allowedClientHeaders] : undefined,
259 metadataHeaders:
260 metadataHeaders === undefined
261 ? undefined
262 : Object.fromEntries(
263 Object.entries(metadataHeaders).flatMap(([key, header]) =>
264 header === undefined ? [] : [[key, header]],
265 ),
266 ),
267 gatewayIdentity: value.gatewayIdentity === undefined ? undefined : `${value.gatewayIdentity}`,
268 contextualHeaders: toContextualHeaders(value.contextualHeaders),
269 clientIp: value.clientIp,
270 };
271 };
272
273 const toAttrs = (
274 item: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1SecurityGateway,
275 project: string,
276 ) => {
277 const name = item.name ?? "";
278 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
279 const ownership = parseOwnership(item.displayName);
280 return {
281 name,
282 securityGatewayId: parsed.id,
283 project: parsed.project || project,
284 location: parsed.location,
285 displayName: ownership.text,
286 hubs: toHubs(item.hubs),
287 serviceDiscovery: toServiceDiscovery(item.serviceDiscovery),
288 proxyProtocolConfig: toProxyProtocolConfig(item.proxyProtocolConfig),
289 state: item.state === undefined ? undefined : `${item.state}`,
290 delegatingServiceAccount: item.delegatingServiceAccount,
291 externalIps: item.externalIps ? [...item.externalIps] : [],
292 createTime: item.createTime,
293 updateTime: item.updateTime,
294 };
295 };
296
297 const getByName = (name: string) =>
298 beyondcorp
299 .getProjectsLocationsSecurityGateways({ name })
300 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
301
302 const listOwned = (project: string) =>
303 listAtLocation(project, (parent) =>
304 collectPages(
305 beyondcorp.listProjectsLocationsSecurityGateways.pages({
306 parent,
307 pageSize: 1000,
308 }),
309 (
310 page,
311 ): readonly beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1SecurityGateway[] | undefined =>
312 page.securityGateways,
313 ),
314 ).pipe(Effect.map((items) => items.filter((item) => hasOwnershipMarker(item.displayName))));
315
316 const desiredHubs = (
317 hubs: Record<string, SecurityGatewayHub>,
318 ): beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1HubMap =>
319 Object.fromEntries(
320 Object.entries(hubs).map(([region, hub]) => [
321 region,
322 { internetGateway: hub.internetGateway ? {} : undefined },
323 ]),
324 );
325
326 export const SecurityGatewayProvider = () =>
327 Provider.succeed(SecurityGateway, {
328 stables: ["name", "securityGatewayId", "project", "location", "createTime"],
329
330 diff: Effect.fn(function* ({ news, olds, output }) {
331 if (!isResolved(news)) return undefined;
332 return replaceOnIdentity({
333 previousId: olds?.securityGatewayId ?? output?.securityGatewayId,
334 nextId: news.securityGatewayId
335 ? rfc1035(news.securityGatewayId, "securitygateway")
336 : (olds?.securityGatewayId ?? output?.securityGatewayId),
337 previousLocation: normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL),
338 nextLocation: normalizeLocation(
339 news.location ?? olds?.location ?? output?.location,
340 DEFAULT_GLOBAL,
341 ),
342 });
343 }),
344
345 read: Effect.fn(function* ({ id, olds, output }) {
346 const env = yield* GcpEnvironment.current;
347 const securityGatewayId = yield* toPhysicalId(
348 id,
349 olds?.securityGatewayId,
350 output?.securityGatewayId,
351 "securitygateway",
352 );
353 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
354 const name = output?.name ?? resourceName(env.project, location, securityGatewayId);
355 const existing = yield* getByName(name);
356 if (existing === undefined) return undefined;
357 const attrs = toAttrs(existing, env.project);
358 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
359 }),
360
361 list: () =>
362 Effect.gen(function* () {
363 const env = yield* GcpEnvironment.current;
364 const items = yield* listOwned(env.project);
365 return items.map((item) => toAttrs(item, env.project));
366 }),
367
368 reconcile: Effect.fn(function* ({ id, news, olds, output }) {
369 const env = yield* GcpEnvironment.current;
370 const securityGatewayId = yield* toPhysicalId(
371 id,
372 news.securityGatewayId,
373 output?.securityGatewayId,
374 "securitygateway",
375 );
376 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
377 const name = resourceName(env.project, location, securityGatewayId);
378 const ownership = yield* createInternalLabels(id);
379 const desiredDisplayName = encodeOwnershipLine(ownership, news.displayName);
380 // An unset `hubs` keeps the existing hubs (a previous default or an
381 // adopted gateway's) so a changed stack region never moves them.
382 const hubSpec: Record<string, SecurityGatewayHub> = news.hubs ??
383 (olds?.hubs === undefined ? output?.hubs : undefined) ?? {
384 [env.region]: { internetGateway: {} },
385 };
386 const hubs = desiredHubs(hubSpec);
387
388 let current = yield* getByName(output?.name ?? name);
389
390 if (current === undefined) {
391 const created = yield* beyondcorp
392 .createProjectsLocationsSecurityGateways({
393 parent: parentOf(env.project, location),
394 securityGatewayId,
395 body: {
396 displayName: desiredDisplayName,
397 hubs,
398 serviceDiscovery: news.serviceDiscovery,
399 proxyProtocolConfig: news.proxyProtocolConfig,
400 },
401 })
402 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
403 if (created !== undefined) {
404 yield* waitForOperation(created);
405 }
406 current = yield* waitUntilReady(getByName(name), name, (item) =>
407 item.state === undefined ? undefined : `${item.state}`,
408 );
409 }
410
411 if (current === undefined) {
412 return yield* new ResourceNotResolved({ resourceName: name });
413 }
414
415 const mask = fieldMask([
416 (current.displayName ?? "") !== desiredDisplayName && "display_name",
417 fingerprint(hubKeys(toHubs(current.hubs))) !== fingerprint(hubKeys(hubSpec)) && "hubs",
418 ]);
419
420 if (mask.length > 0) {
421 const operation = yield* beyondcorp.patchProjectsLocationsSecurityGateways({
422 name: current.name ?? name,
423 updateMask: mask,
424 body: {
425 displayName: desiredDisplayName,
426 hubs,
427 },
428 });
429 yield* waitForOperation(operation);
430 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
431 }
432
433 return toAttrs(current, env.project);
434 }),
435
436 delete: Effect.fn(function* ({ output }) {
437 const operation = yield* beyondcorp
438 .deleteProjectsLocationsSecurityGateways({ name: output.name })
439 .pipe(
440 Effect.retry({
441 while: (error) => error._tag === "Conflict",
442 times: 8,
443 schedule: Schedule.spaced("2 seconds"),
444 }),
445 Effect.catchTag("NotFound", () => Effect.undefined),
446 );
447 if (operation !== undefined) {
448 yield* waitForDeleteOperation(operation);
449 }
450 yield* waitUntilGone(getByName(output.name), output.name);
451 }),
452 });