@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, 04:45 UTC

main
ts 321 lines 11.3 KB
Raw
1 import * as integrations from "@distilled.cloud/gcp/integrations_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 Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 encodeOwnership,
14 hasOwnershipMarker,
15 lastSegment,
16 locationOf,
17 locationParent,
18 normalizeLocation,
19 ownedByAlchemy,
20 parseOwnership,
21 sameText,
22 toResourceId,
23 updateMaskOf,
24 } from "./ownership.ts";
25 import type { AuthConfigVisibility, CredentialType, DecryptedCredential } from "./shared.ts";
26 import { credentialBody } from "./shared.ts";
27
28 export type AuthConfigProps = {
29 /**
30 * Auth config id (the `{authConfig}` segment of
31 * `projects/{project}/locations/{location}/authConfigs/{authConfig}`).
32 * Server-assigned on create. Immutable — changing it replaces the
33 * config.
34 */
35 authConfigId?: string;
36 /**
37 * Location (`us-central1`, …). Immutable — changing it replaces the
38 * config. `US-CENTRAL1` is accepted and normalized to `us-central1`.
39 * @default the stack's GCP region (`GCP.Region`, else the profile
40 * region, else `us-central1`)
41 */
42 location?: string;
43 /**
44 * Unique display name within the client.
45 */
46 displayName?: string;
47 /**
48 * Human-readable description. Auth configs have no labels field, so
49 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
50 * from attributes.
51 */
52 description?: string;
53 /**
54 * Credential type applied to `decryptedCredential` when it omits one.
55 * @default "USERNAME_AND_PASSWORD"
56 */
57 credentialType?: CredentialType;
58 /**
59 * Decrypted credential payload. Write-only — never returned on
60 * attributes.
61 */
62 decryptedCredential?: DecryptedCredential;
63 /**
64 * Certificate id used for client-certificate auth.
65 */
66 certificateId?: string;
67 /**
68 * Visibility of the auth config.
69 * @default "PRIVATE"
70 */
71 visibility?: AuthConfigVisibility;
72 };
73
74 export type AuthConfig = Resource<
75 "GCP.Integrations.AuthConfig",
76 AuthConfigProps,
77 {
78 /** Full resource name `projects/{project}/locations/{location}/authConfigs/{authConfig}`. */
79 name: string;
80 /** Auth config id (last path segment). */
81 authConfigId: string;
82 /** Location id. */
83 location: string;
84 /** Project id. */
85 project: string;
86 /** Display name. */
87 displayName: string | undefined;
88 /** User description with the Alchemy ownership prefix stripped. */
89 description: string | undefined;
90 /** Credential type. */
91 credentialType: string | undefined;
92 /** Certificate id, if any. */
93 certificateId: string | undefined;
94 /** Visibility. */
95 visibility: string | undefined;
96 /** Server-reported state. */
97 state: string | undefined;
98 /** RFC3339 creation timestamp. */
99 createTime: string | undefined;
100 /** RFC3339 last-update timestamp. */
101 updateTime: string | undefined;
102 },
103 never,
104 Providers
105 >;
106
107 /**
108 * An Application Integration auth config (username/password, token, JWT,
109 * service account, …).
110 *
111 * Auth configs have no labels field — Alchemy stamps ownership into the
112 * description so `list` / nuke can find them. Location and id are
113 * immutable. Display name, description, visibility, and credentials
114 * update in place.
115 *
116 * ### Creating an Auth Config
117 * **Example:** Username and password
118 * ```typescript
119 * const auth = yield* GCP.Integrations.AuthConfig("Salesforce", {
120 * displayName: "salesforce-basic",
121 * credentialType: "USERNAME_AND_PASSWORD",
122 * decryptedCredential: {
123 * credentialType: "USERNAME_AND_PASSWORD",
124 * usernameAndPassword: { username: "user", password: "secret" },
125 * },
126 * });
127 * ```
128 *
129 * @resource
130 * @category Integrations
131 */
132 export const AuthConfig = Resource<AuthConfig>("GCP.Integrations.AuthConfig");
133
134 export class AuthConfigNotResolved extends Data.TaggedError(
135 "GCP.Integrations.AuthConfigNotResolved",
136 )<{
137 resourceName: string;
138 }> {}
139
140 const DEFAULT_CREDENTIAL_TYPE: CredentialType = "USERNAME_AND_PASSWORD";
141 const DEFAULT_VISIBILITY: AuthConfigVisibility = "PRIVATE";
142
143 const resourceName = (project: string, location: string, authConfigId: string) =>
144 `${locationParent(project, location)}/authConfigs/${authConfigId}`;
145
146 const toAttrs = (
147 config: integrations.GoogleCloudIntegrationsV1alphaAuthConfig,
148 project: string,
149 region: string,
150 ) => {
151 const name = config.name ?? "";
152 const parsed = parseOwnership(config.description);
153 return {
154 name,
155 authConfigId: lastSegment(name),
156 location: locationOf(name, region),
157 project,
158 displayName: config.displayName,
159 description: parsed.text,
160 credentialType: config.credentialType ?? config.decryptedCredential?.credentialType,
161 certificateId: config.certificateId,
162 visibility: config.visibility,
163 state: config.state,
164 createTime: config.createTime,
165 updateTime: config.updateTime,
166 };
167 };
168
169 const getByName = (name: string) =>
170 name.length === 0
171 ? Effect.undefined
172 : integrations
173 .getProjectsLocationsAuthConfigs({ name })
174 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
175
176 const listAt = (parent: string, project: string, region: string) =>
177 integrations.listProjectsLocationsAuthConfigs.pages({ parent, pageSize: 100 }).pipe(
178 Stream.flatMap((page) => Stream.fromIterable(page.authConfigs ?? [])),
179 Stream.filter((config) => hasOwnershipMarker(config.description)),
180 Stream.map((config) => toAttrs(config, project, region)),
181 Stream.runCollect,
182 Effect.map((chunk) => Array.from(chunk)),
183 Effect.catchTag("NotFound", () => Effect.succeed([])),
184 );
185
186 const findOwned = (parent: string, id: string) =>
187 integrations.listProjectsLocationsAuthConfigs.pages({ parent, pageSize: 100 }).pipe(
188 Stream.flatMap((page) => Stream.fromIterable(page.authConfigs ?? [])),
189 Stream.filterEffect((config) => ownedByAlchemy(id, config.description)),
190 Stream.runHead,
191 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
192 Effect.catchTag("NotFound", () => Effect.undefined),
193 );
194
195 export const AuthConfigProvider = () =>
196 Provider.succeed(AuthConfig, {
197 stables: ["name", "authConfigId", "location", "project", "createTime"],
198
199 diff: Effect.fn(function* ({ news, olds, output }) {
200 if (!isResolved(news)) return undefined;
201 const env = yield* GcpEnvironment.current;
202 const previousLocation = olds?.location ?? output?.location;
203 const nextLocation = normalizeLocation(news.location, previousLocation ?? env.region);
204 if (
205 previousLocation !== undefined &&
206 normalizeLocation(previousLocation, env.region) !== nextLocation
207 ) {
208 return { action: "replace" as const, deleteFirst: false };
209 }
210 const previousId = olds?.authConfigId ?? output?.authConfigId;
211 if (
212 previousId !== undefined &&
213 news.authConfigId !== undefined &&
214 news.authConfigId !== previousId
215 ) {
216 return { action: "replace" as const, deleteFirst: false };
217 }
218 return undefined;
219 }),
220
221 read: Effect.fn(function* ({ id, olds, output }) {
222 const env = yield* GcpEnvironment.current;
223 const authConfigId = yield* toResourceId(id, olds?.authConfigId, output?.authConfigId);
224 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
225 const name = output?.name ?? resourceName(env.project, location, authConfigId);
226 let existing = yield* getByName(name);
227 if (existing === undefined && output?.name === undefined) {
228 existing = yield* findOwned(locationParent(env.project, location), id);
229 }
230 if (existing === undefined) return undefined;
231 const attrs = toAttrs(existing, env.project, env.region);
232 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
233 }),
234
235 list: () =>
236 Effect.gen(function* () {
237 const env = yield* GcpEnvironment.current;
238 return yield* listAt(locationParent(env.project, env.region), env.project, env.region);
239 }),
240
241 reconcile: Effect.fn(function* ({ id, news, output }) {
242 const env = yield* GcpEnvironment.current;
243 const location = normalizeLocation(news.location ?? output?.location, env.region);
244 const parent = locationParent(env.project, location);
245 const authConfigId = yield* toResourceId(id, news.authConfigId, output?.authConfigId);
246 const name = output?.name ?? resourceName(env.project, location, authConfigId);
247 const ownership = yield* createInternalLabels(id);
248 const description = encodeOwnership(ownership, news.description);
249 const displayName = news.displayName ?? authConfigId;
250 const credentialType = news.credentialType ?? DEFAULT_CREDENTIAL_TYPE;
251 const visibility = news.visibility ?? DEFAULT_VISIBILITY;
252 const decryptedCredential = credentialBody(news.decryptedCredential, credentialType);
253
254 let current = yield* getByName(output?.name ?? name);
255 if (current === undefined) {
256 current = yield* findOwned(parent, id);
257 }
258
259 if (current === undefined) {
260 const created = yield* integrations
261 .createProjectsLocationsAuthConfigs({
262 parent,
263 body: {
264 displayName,
265 description,
266 decryptedCredential,
267 certificateId: news.certificateId,
268 visibility,
269 },
270 })
271 .pipe(Effect.catchTag("Conflict", () => findOwned(parent, id)));
272 current = created ?? (yield* findOwned(parent, id));
273 }
274
275 if (current === undefined) {
276 return yield* new AuthConfigNotResolved({ resourceName: name });
277 }
278
279 const currentName = current.name ?? name;
280 const displayChanged = !sameText(current.displayName, displayName);
281 const descriptionChanged = (current.description ?? "") !== description;
282 const visibilityChanged = !sameText(current.visibility, visibility);
283 const certificateChanged = !sameText(current.certificateId, news.certificateId);
284 const credentialChanged = news.decryptedCredential !== undefined;
285
286 if (
287 displayChanged ||
288 descriptionChanged ||
289 visibilityChanged ||
290 certificateChanged ||
291 credentialChanged
292 ) {
293 current = yield* integrations.patchProjectsLocationsAuthConfigs({
294 name: currentName,
295 updateMask: updateMaskOf(
296 displayChanged ? "display_name" : undefined,
297 descriptionChanged ? "description" : undefined,
298 visibilityChanged ? "visibility" : undefined,
299 certificateChanged ? "certificate_id" : undefined,
300 credentialChanged ? "decrypted_credential" : undefined,
301 ),
302 body: {
303 name: currentName,
304 displayName,
305 description,
306 decryptedCredential,
307 certificateId: news.certificateId,
308 visibility,
309 },
310 });
311 }
312
313 return toAttrs(current, env.project, env.region);
314 }),
315
316 delete: Effect.fn(function* ({ output }) {
317 yield* integrations
318 .deleteProjectsLocationsAuthConfigs({ name: output.name })
319 .pipe(Effect.catchTag("NotFound", () => Effect.void));
320 }),
321 });