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

main
ts 528 lines 17.3 KB
Raw
1 import * as developerconnect from "@distilled.cloud/gcp/developerconnect_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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import type { ServiceDirectoryConfig } from "./Connection.ts";
13 import {
14 compact,
15 fieldMask,
16 fingerprint,
17 listAtLocation,
18 listLabeledPages,
19 normalizeLocation,
20 parentOf,
21 parseName,
22 replaceOnIdentity,
23 ResourceNotResolved,
24 sameBool,
25 toPhysicalId,
26 userAnnotations,
27 userLabels,
28 waitForOperation,
29 waitUntilExists,
30 waitUntilGone,
31 } from "./internal.ts";
32
33 export type CustomOAuthConfig = {
34 /**
35 * Client secret of the OAuth application. Input only — not returned
36 * on read.
37 */
38 clientSecret?: string;
39 /**
40 * Service Directory config for a private OAuth host.
41 */
42 serviceDirectoryConfig?: ServiceDirectoryConfig;
43 /**
44 * SCM provider (`GITHUB_ENTERPRISE`, `GITLAB_ENTERPRISE`,
45 * `BITBUCKET_DATA_CENTER`). Immutable — changing it replaces the
46 * connector.
47 */
48 scmProvider?: developerconnect.CustomOAuthConfigScmProviderEnum | (string & {});
49 /**
50 * Host URI of the OAuth application. Immutable — changing it
51 * replaces the connector.
52 */
53 hostUri?: string;
54 /**
55 * OAuth client id.
56 */
57 clientId?: string;
58 /**
59 * SSL certificate used for requests to a private host.
60 */
61 sslCaCertificate?: string;
62 /**
63 * OAuth2 token request URL. Immutable — changing it replaces the
64 * connector.
65 */
66 tokenUri?: string;
67 /**
68 * Disable PKCE for this OAuth config. PKCE is enabled by default.
69 */
70 pkceDisabled?: boolean;
71 /**
72 * OAuth2 authorization server URL. Immutable — changing it replaces
73 * the connector.
74 */
75 authUri?: string;
76 /**
77 * Scopes requested during OAuth.
78 */
79 scopes?: string[];
80 };
81
82 export type ProviderOAuthConfig = {
83 /**
84 * Developer Connect provided OAuth system
85 * (`GITHUB`, `GITLAB`, `GOOGLE`, `SENTRY`, `ROVO`, `NEW_RELIC`,
86 * `DATASTAX`, `DYNATRACE`). Immutable — changing it replaces the
87 * connector.
88 */
89 systemProviderId?: developerconnect.ProviderOAuthConfigSystemProviderIdEnum | (string & {});
90 /**
91 * User-selected OAuth scopes. Changing scopes deletes existing user
92 * records under the connector so users re-auth.
93 */
94 scopes?: string[];
95 };
96
97 export type ProxyConfig = {
98 /**
99 * Allow the git and HTTP proxies to act on behalf of users configured
100 * under this connector.
101 * @default false
102 */
103 enabled?: boolean;
104 };
105
106 export type AccountConnectorProps = {
107 /**
108 * Account connector id (the `{accountConnector}` segment of
109 * `projects/{project}/locations/{location}/accountConnectors/{accountConnector}`).
110 * If omitted, a unique RFC1035 name is generated from the stack,
111 * stage, and logical id. Immutable — changing it replaces the
112 * connector.
113 */
114 accountConnectorId?: string;
115 /**
116 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
117 * replaces the connector. `US-CENTRAL1` is accepted and normalized
118 * to `us-central1`.
119 * @default the stack's GCP region (`GCP.Region`, else the profile
120 * region, else `us-central1`)
121 */
122 location?: string;
123 /**
124 * Developer Connect provided OAuth. Mutually exclusive with
125 * `customOauthConfig`.
126 */
127 providerOauthConfig?: ProviderOAuthConfig;
128 /**
129 * Custom OAuth application. Mutually exclusive with
130 * `providerOauthConfig`. Changing immutable host fields replaces the
131 * connector.
132 */
133 customOauthConfig?: CustomOAuthConfig;
134 /**
135 * Git and HTTP proxy configuration.
136 */
137 proxyConfig?: ProxyConfig;
138 /**
139 * User labels. Alchemy ownership labels are merged in automatically.
140 */
141 labels?: Record<string, string>;
142 /**
143 * User annotations (AIP-148).
144 */
145 annotations?: Record<string, string>;
146 };
147
148 export type AccountConnector = Resource<
149 "GCP.DeveloperConnect.AccountConnector",
150 AccountConnectorProps,
151 {
152 /** Full resource name. */
153 name: string;
154 /** Account connector id (last path segment). */
155 accountConnectorId: string;
156 /** Project id. */
157 project: string;
158 /** Location id. */
159 location: string;
160 /** Developer Connect provided OAuth config, if any. */
161 providerOauthConfig: ProviderOAuthConfig | undefined;
162 /** Custom OAuth config, if any (secrets stripped). */
163 customOauthConfig: CustomOAuthConfig | undefined;
164 /** Proxy configuration. */
165 proxyConfig: ProxyConfig | undefined;
166 /** User labels (Alchemy ownership labels stripped). */
167 labels: Record<string, string>;
168 /** User annotations. */
169 annotations: Record<string, string>;
170 /** URL that starts the OAuth flow. */
171 oauthStartUri: string | undefined;
172 /** Server checksum of the resource. */
173 etag: string | undefined;
174 /** Server-generated resource uid. */
175 uid: string | undefined;
176 /** RFC3339 creation timestamp. */
177 createTime: string | undefined;
178 /** RFC3339 last-update timestamp. */
179 updateTime: string | undefined;
180 },
181 never,
182 Providers
183 >;
184
185 /**
186 * A Developer Connect account connector — the OAuth configuration that
187 * lets users connect their SCM accounts (GitHub, GitLab, Google, …) to
188 * Google Cloud.
189 *
190 * Changing `accountConnectorId`, `location`, `systemProviderId`, or
191 * immutable custom-OAuth host fields (`hostUri`, `tokenUri`, `authUri`,
192 * `scmProvider`) replaces the connector. Labels, annotations, scopes,
193 * and `proxyConfig` update in place.
194 *
195 * ### Creating an Account Connector
196 * **Example:** GitHub system provider
197 * ```typescript
198 * const github = yield* GCP.DeveloperConnect.AccountConnector("Github", {
199 * providerOauthConfig: {
200 * systemProviderId: "GITHUB",
201 * scopes: ["repo"],
202 * },
203 * });
204 * ```
205 *
206 * **Example:** Explicit id, labels, and proxy
207 * ```typescript
208 * const github = yield* GCP.DeveloperConnect.AccountConnector("Github", {
209 * accountConnectorId: "app-github",
210 * location: "us-central1",
211 * providerOauthConfig: {
212 * systemProviderId: "GITHUB",
213 * scopes: ["repo", "read:user"],
214 * },
215 * proxyConfig: { enabled: true },
216 * labels: { env: "prod" },
217 * });
218 * ```
219 *
220 * ### Updating an Account Connector
221 * **Example:** Labels and proxy
222 * ```typescript
223 * // Same logical id as before; only the changed props differ.
224 * const github = yield* GCP.DeveloperConnect.AccountConnector("Github", {
225 * accountConnectorId: "app-github",
226 * providerOauthConfig: {
227 * systemProviderId: "GITHUB",
228 * scopes: ["repo"],
229 * },
230 * labels: { env: "prod", team: "platform" },
231 * proxyConfig: { enabled: true },
232 * });
233 * ```
234 *
235 * @resource
236 * @category DeveloperConnect
237 */
238 export const AccountConnector = Resource<AccountConnector>("GCP.DeveloperConnect.AccountConnector");
239
240 const resourceName = (project: string, location: string, accountConnectorId: string) =>
241 `projects/${project}/locations/${location}/accountConnectors/${accountConnectorId}`;
242
243 const toServiceDirectory = (
244 config: ServiceDirectoryConfig | undefined,
245 ): developerconnect.ServiceDirectoryConfig | undefined => {
246 if (config === undefined) return undefined;
247 return compact({ service: config.service });
248 };
249
250 const toCustomOauth = (
251 config: CustomOAuthConfig | undefined,
252 ): developerconnect.CustomOAuthConfig | undefined => {
253 if (config === undefined) return undefined;
254 return compact({
255 clientSecret: config.clientSecret,
256 serviceDirectoryConfig: toServiceDirectory(config.serviceDirectoryConfig),
257 scmProvider: config.scmProvider,
258 hostUri: config.hostUri,
259 clientId: config.clientId,
260 sslCaCertificate: config.sslCaCertificate,
261 tokenUri: config.tokenUri,
262 pkceDisabled: config.pkceDisabled,
263 authUri: config.authUri,
264 scopes: config.scopes,
265 });
266 };
267
268 const toProviderOauth = (
269 config: ProviderOAuthConfig | undefined,
270 ): developerconnect.ProviderOAuthConfig | undefined => {
271 if (config === undefined) return undefined;
272 return compact({
273 systemProviderId: config.systemProviderId,
274 scopes: config.scopes,
275 });
276 };
277
278 const toProxy = (config: ProxyConfig | undefined): developerconnect.ProxyConfig | undefined => {
279 if (config === undefined) return undefined;
280 return compact({ enabled: config.enabled });
281 };
282
283 const fromCustomOauth = (
284 config: developerconnect.CustomOAuthConfig | undefined,
285 ): CustomOAuthConfig | undefined => {
286 if (config === undefined) return undefined;
287 return compact({
288 serviceDirectoryConfig: config.serviceDirectoryConfig
289 ? compact({ service: config.serviceDirectoryConfig.service })
290 : undefined,
291 scmProvider: config.scmProvider,
292 hostUri: config.hostUri,
293 clientId: config.clientId,
294 sslCaCertificate: config.sslCaCertificate,
295 tokenUri: config.tokenUri,
296 pkceDisabled: config.pkceDisabled,
297 authUri: config.authUri,
298 scopes: config.scopes,
299 });
300 };
301
302 const fromProviderOauth = (
303 config: developerconnect.ProviderOAuthConfig | undefined,
304 ): ProviderOAuthConfig | undefined => {
305 if (config === undefined) return undefined;
306 return compact({
307 systemProviderId: config.systemProviderId,
308 scopes: config.scopes,
309 });
310 };
311
312 const fromProxy = (config: developerconnect.ProxyConfig | undefined): ProxyConfig | undefined => {
313 if (config === undefined) return undefined;
314 return compact({ enabled: config.enabled === true });
315 };
316
317 const toAttrs = (item: developerconnect.AccountConnector, project: string, region: string) => {
318 const name = item.name ?? "";
319 const parsed = parseName(name, "accountConnectors", region);
320 return {
321 name,
322 accountConnectorId: parsed.id,
323 project: parsed.project || project,
324 location: parsed.location,
325 providerOauthConfig: fromProviderOauth(item.providerOauthConfig),
326 customOauthConfig: fromCustomOauth(item.customOauthConfig),
327 proxyConfig: fromProxy(item.proxyConfig),
328 labels: userLabels(item.labels),
329 annotations: userAnnotations(item.annotations),
330 oauthStartUri: item.oauthStartUri,
331 etag: item.etag,
332 uid: item.uid,
333 createTime: item.createTime,
334 updateTime: item.updateTime,
335 };
336 };
337
338 const getByName = (name: string) =>
339 developerconnect
340 .getProjectsLocationsAccountConnectors({ name })
341 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
342
343 const listOwned = (project: string, region: string) =>
344 listAtLocation(project, region, (parent) =>
345 listLabeledPages(
346 developerconnect.listProjectsLocationsAccountConnectors.pages({
347 parent,
348 pageSize: 1000,
349 }),
350 (page) => page.accountConnectors,
351 (item) => item.labels,
352 ),
353 );
354
355 const immutableCustomKey = (config: CustomOAuthConfig | undefined) =>
356 fingerprint({
357 scmProvider: config?.scmProvider,
358 hostUri: config?.hostUri,
359 tokenUri: config?.tokenUri,
360 authUri: config?.authUri,
361 });
362
363 export const AccountConnectorProvider = () =>
364 Provider.succeed(AccountConnector, {
365 stables: ["name", "accountConnectorId", "project", "location", "uid", "createTime"],
366
367 diff: Effect.fn(function* ({ news, olds, output }) {
368 if (!isResolved(news)) return undefined;
369 const env = yield* GcpEnvironment.current;
370 const previousProvider =
371 olds?.providerOauthConfig?.systemProviderId ??
372 output?.providerOauthConfig?.systemProviderId;
373 const nextProvider = news.providerOauthConfig?.systemProviderId;
374 const previousCustom =
375 immutableCustomKey(olds?.customOauthConfig) ??
376 immutableCustomKey(output?.customOauthConfig);
377 const nextCustom = immutableCustomKey(news.customOauthConfig);
378 return replaceOnIdentity({
379 previousId: olds?.accountConnectorId ?? output?.accountConnectorId,
380 nextId: news.accountConnectorId ?? olds?.accountConnectorId ?? output?.accountConnectorId,
381 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
382 nextLocation: normalizeLocation(
383 news.location ?? olds?.location ?? output?.location,
384 env.region,
385 ),
386 extra:
387 (previousProvider !== undefined &&
388 nextProvider !== undefined &&
389 previousProvider !== nextProvider) ||
390 (previousCustom !== fingerprint(undefined) &&
391 nextCustom !== fingerprint(undefined) &&
392 previousCustom !== nextCustom),
393 });
394 }),
395
396 read: Effect.fn(function* ({ id, olds, output }) {
397 const env = yield* GcpEnvironment.current;
398 const accountConnectorId = yield* toPhysicalId(
399 id,
400 olds?.accountConnectorId,
401 output?.accountConnectorId,
402 "accountconnector",
403 );
404 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
405 const name = output?.name ?? resourceName(env.project, location, accountConnectorId);
406 const existing = yield* getByName(name);
407 if (existing === undefined) return undefined;
408 const attrs = toAttrs(existing, env.project, env.region);
409 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
410 }),
411
412 list: () =>
413 Effect.gen(function* () {
414 const env = yield* GcpEnvironment.current;
415 const items = yield* listOwned(env.project, env.region);
416 return items.map((item) => toAttrs(item, env.project, env.region));
417 }),
418
419 reconcile: Effect.fn(function* ({ id, news, output }) {
420 const env = yield* GcpEnvironment.current;
421 const accountConnectorId = yield* toPhysicalId(
422 id,
423 news.accountConnectorId,
424 output?.accountConnectorId,
425 "accountconnector",
426 );
427 const location = normalizeLocation(news.location ?? output?.location, env.region);
428 const name = resourceName(env.project, location, accountConnectorId);
429 const desiredLabels = {
430 ...toLabels(news.labels),
431 ...(yield* createInternalLabels(id)),
432 };
433 const annotations = news.annotations;
434 const body = compact({
435 providerOauthConfig: toProviderOauth(news.providerOauthConfig),
436 customOauthConfig: toCustomOauth(news.customOauthConfig),
437 proxyConfig: toProxy(news.proxyConfig),
438 labels: desiredLabels,
439 annotations,
440 });
441
442 let current = yield* getByName(output?.name ?? name);
443
444 if (current === undefined) {
445 const created = yield* developerconnect
446 .createProjectsLocationsAccountConnectors({
447 parent: parentOf(env.project, location),
448 accountConnectorId,
449 body,
450 })
451 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
452 if (created !== undefined) {
453 yield* waitForOperation(created);
454 }
455 current = yield* waitUntilExists(getByName(name), name);
456 }
457
458 if (current === undefined) {
459 return yield* new ResourceNotResolved({ resourceName: name });
460 }
461
462 const observedLabels = tagRecord(current.labels);
463 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
464 const mask = fieldMask([
465 (upsert.length > 0 || removed.length > 0) && "labels",
466 fingerprint(userAnnotations(current.annotations)) !==
467 fingerprint(userAnnotations(annotations)) && "annotations",
468 fingerprint(fromProviderOauth(current.providerOauthConfig)) !==
469 fingerprint(news.providerOauthConfig) && "providerOauthConfig",
470 fingerprint(fromCustomOauth(current.customOauthConfig)) !==
471 fingerprint({
472 ...news.customOauthConfig,
473 clientSecret: undefined,
474 }) && "customOauthConfig",
475 !sameBool(current.proxyConfig?.enabled, news.proxyConfig?.enabled) && "proxyConfig",
476 ]);
477
478 if (mask.length > 0) {
479 const operation = yield* developerconnect
480 .patchProjectsLocationsAccountConnectors({
481 name: current.name ?? name,
482 updateMask: mask,
483 body: compact({
484 etag: current.etag,
485 ...body,
486 }),
487 })
488 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
489 if (operation === undefined) {
490 const created = yield* developerconnect
491 .createProjectsLocationsAccountConnectors({
492 parent: parentOf(env.project, location),
493 accountConnectorId,
494 body,
495 })
496 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
497 if (created !== undefined) {
498 yield* waitForOperation(created);
499 }
500 } else {
501 yield* waitForOperation(operation);
502 }
503 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
504 }
505
506 return toAttrs(current, env.project, env.region);
507 }),
508
509 delete: Effect.fn(function* ({ output }) {
510 const operation = yield* developerconnect
511 .deleteProjectsLocationsAccountConnectors({
512 name: output.name,
513 force: true,
514 })
515 .pipe(
516 Effect.retry({
517 while: (error) => error._tag === "Conflict",
518 times: 8,
519 schedule: Schedule.spaced("2 seconds"),
520 }),
521 Effect.catchTag("NotFound", () => Effect.undefined),
522 );
523 if (operation !== undefined) {
524 yield* waitForOperation(operation, { notFoundOk: true });
525 }
526 yield* waitUntilGone(getByName(output.name), output.name);
527 }),
528 });