@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 392 lines 13.5 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_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 { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 attributesToRecord,
13 childName,
14 createOwnership,
15 defaultOrgName,
16 desiredAttributes,
17 lastSegment,
18 listOrgNames,
19 orgIdOf,
20 orgNameOf,
21 ownedBy,
22 recordToAttributes,
23 sameRecord,
24 sameStringList,
25 userAttributes,
26 } from "./operations.ts";
27
28 export type DevelopersAppsKeyProps = {
29 /**
30 * Apigee organization id or `organizations/{org}`. Defaults to the
31 * current GCP project id. Immutable — changing it replaces the key.
32 */
33 organization?: string;
34 /**
35 * Parent developer email or `organizations/{org}/developers/{email}`.
36 * Immutable — changing it replaces the key.
37 */
38 developer: string;
39 /**
40 * Parent developer app name or full resource name. Immutable — changing
41 * it replaces the key.
42 */
43 app: string;
44 /**
45 * Consumer key. If omitted, a unique key is generated. Immutable —
46 * changing it replaces the key.
47 */
48 consumerKey?: string;
49 /**
50 * Consumer secret. Required on create when supplying a custom key; if
51 * omitted, a unique secret is generated. Immutable — changing it
52 * replaces the key.
53 */
54 consumerSecret?: string;
55 /**
56 * Scopes to apply to the key.
57 */
58 scopes?: string[];
59 /**
60 * API products associated with the key. Applied after create via
61 * UpdateDeveloperAppKey.
62 */
63 apiProducts?: string[];
64 /**
65 * Credential status (`approved` or `revoked`).
66 * @default "approved"
67 */
68 status?: string;
69 /**
70 * Expiration time in seconds. `-1` (default) never expires. Immutable
71 * after create.
72 */
73 expiresInSeconds?: string;
74 /**
75 * Custom attributes. Alchemy ownership attributes are merged in
76 * automatically.
77 */
78 attributes?: Record<string, string>;
79 };
80
81 export type DevelopersAppsKey = Resource<
82 "GCP.Apigee.DevelopersAppsKey",
83 DevelopersAppsKeyProps,
84 {
85 /** Full resource name `organizations/{org}/developers/{email}/apps/{app}/keys/{key}`. */
86 name: string;
87 /** Consumer key. */
88 consumerKey: string;
89 /** Consumer secret. */
90 consumerSecret: string | undefined;
91 /** Parent developer email. */
92 developer: string;
93 /** Parent app name. */
94 app: string;
95 /** Apigee organization id. */
96 organization: string;
97 /** Scopes. */
98 scopes: string[];
99 /** Associated API products. */
100 apiProducts: unknown[];
101 /** Credential status. */
102 status: string | undefined;
103 /** User attributes (Alchemy ownership attributes stripped). */
104 attributes: Record<string, string>;
105 /** Issued-at time in milliseconds since epoch. */
106 issuedAt: string | undefined;
107 /** Expiration time in milliseconds since epoch. */
108 expiresAt: string | undefined;
109 },
110 never,
111 Providers
112 >;
113
114 /**
115 * A custom consumer key and secret for an Apigee developer app.
116 *
117 * Apigee keys have no labels field, so Alchemy stamps ownership into
118 * custom attributes for `list` / nuke. The consumer key is identity —
119 * changing it replaces the key. Scopes, API products, status, and
120 * attributes update in place.
121 *
122 * ### Creating a Developer App Key
123 * **Example:** Generated key under a developer app
124 * ```typescript
125 * const key = yield* GCP.Apigee.DevelopersAppsKey("PortalKey", {
126 * developer: developer.email,
127 * app: app.appName,
128 * });
129 * ```
130 *
131 * **Example:** Custom key and secret
132 * ```typescript
133 * const key = yield* GCP.Apigee.DevelopersAppsKey("PortalKey", {
134 * developer: "ada@example.com",
135 * app: "portal-app",
136 * consumerKey: "portal-key",
137 * consumerSecret: "portal-secret",
138 * status: "approved",
139 * });
140 * ```
141 *
142 * @resource
143 * @category Apigee
144 */
145 export const DevelopersAppsKey = Resource<DevelopersAppsKey>("GCP.Apigee.DevelopersAppsKey");
146
147 export class DevelopersAppsKeyNotResolved extends Data.TaggedError(
148 "GCP.Apigee.DevelopersAppsKeyNotResolved",
149 )<{
150 resourceName: string;
151 }> {}
152
153 const developerEmailOf = (developer: string) =>
154 developer.includes("/developers/") ? lastSegment(developer) : developer;
155
156 const appNameOf = (app: string) => (app.includes("/apps/") ? lastSegment(app) : app);
157
158 const appParentOf = (organization: string, developer: string, app: string) =>
159 `${childName(orgNameOf(organization), "developers", developerEmailOf(developer))}/apps/${appNameOf(app)}`;
160
161 const resourceName = (organization: string, developer: string, app: string, consumerKey: string) =>
162 `${appParentOf(organization, developer, app)}/keys/${consumerKey}`;
163
164 const toKeyId = (id: string, explicit: string | undefined, existing?: string) =>
165 Effect.gen(function* () {
166 if (explicit !== undefined) return explicit;
167 if (existing !== undefined) return existing;
168 return yield* createPhysicalName({ id, maxLength: 64, lowercase: true });
169 });
170
171 const toSecret = (id: string, explicit: string | undefined) =>
172 Effect.gen(function* () {
173 if (explicit !== undefined) return explicit;
174 return yield* createPhysicalName({
175 id: `${id}-secret`,
176 maxLength: 64,
177 lowercase: true,
178 });
179 });
180
181 const productsOf = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
182
183 const toAttrs = (
184 key: apigee.GoogleCloudApigeeV1DeveloperAppKey,
185 organization: string,
186 developer: string,
187 app: string,
188 ) => {
189 const consumerKey = key.consumerKey ?? "";
190 return {
191 name: resourceName(organization, developer, app, consumerKey),
192 consumerKey,
193 consumerSecret: key.consumerSecret,
194 developer: developerEmailOf(developer),
195 app: appNameOf(app),
196 organization: orgIdOf(organization),
197 scopes: key.scopes ?? [],
198 apiProducts: productsOf(key.apiProducts),
199 status: key.status,
200 attributes: userAttributes(attributesToRecord(key.attributes)),
201 issuedAt: key.issuedAt,
202 expiresAt: key.expiresAt,
203 };
204 };
205
206 const getByName = (name: string) =>
207 apigee
208 .getOrganizationsDevelopersAppsKeys({ name })
209 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
210
211 const listDeveloperEmails = (organization: string) =>
212 apigee
213 .listOrganizationsDevelopers({
214 parent: organization,
215 expand: true,
216 count: "1000",
217 })
218 .pipe(
219 Effect.map((page) =>
220 (page.developer ?? [])
221 .map((developer) => developer.email ?? "")
222 .filter((email) => email.length > 0),
223 ),
224 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.succeed([] as string[])),
225 );
226
227 export const DevelopersAppsKeyProvider = () =>
228 Provider.succeed(DevelopersAppsKey, {
229 stables: ["name", "consumerKey", "developer", "app", "organization", "issuedAt"],
230
231 diff: Effect.fn(function* ({ news, olds, output }) {
232 if (!isResolved(news)) return undefined;
233 const previousKey = olds?.consumerKey ?? output?.consumerKey;
234 const previousSecret = olds?.consumerSecret ?? output?.consumerSecret;
235 const previousDeveloper = olds?.developer ?? output?.developer;
236 const previousApp = olds?.app ?? output?.app;
237 const previousOrg = olds?.organization ?? output?.organization;
238 const keyChanged =
239 previousKey !== undefined &&
240 news.consumerKey !== undefined &&
241 news.consumerKey !== previousKey;
242 const secretChanged =
243 previousSecret !== undefined &&
244 news.consumerSecret !== undefined &&
245 news.consumerSecret !== previousSecret;
246 const developerChanged =
247 previousDeveloper !== undefined &&
248 developerEmailOf(news.developer) !== developerEmailOf(previousDeveloper);
249 const appChanged =
250 previousApp !== undefined && appNameOf(news.app) !== appNameOf(previousApp);
251 const orgChanged =
252 previousOrg !== undefined &&
253 news.organization !== undefined &&
254 orgIdOf(news.organization) !== orgIdOf(previousOrg);
255 if (keyChanged || secretChanged || developerChanged || appChanged || orgChanged) {
256 return {
257 action: "replace" as const,
258 deleteFirst: keyChanged && !developerChanged && !appChanged && !orgChanged,
259 };
260 }
261 return undefined;
262 }),
263
264 read: Effect.fn(function* ({ id, olds, output }) {
265 const env = yield* GcpEnvironment.current;
266 const organization = defaultOrgName(env.project, olds?.organization ?? output?.organization);
267 const developer = olds?.developer ?? output?.developer;
268 const app = olds?.app ?? output?.app;
269 if (developer === undefined || app === undefined) return undefined;
270 const consumerKey = yield* toKeyId(id, olds?.consumerKey, output?.consumerKey);
271 const name = output?.name ?? resourceName(organization, developer, app, consumerKey);
272 const existing = yield* getByName(name);
273 if (existing === undefined) return undefined;
274 const attrs = toAttrs(existing, organization, developer, app);
275 return (yield* ownedBy(id, attributesToRecord(existing.attributes))) ? attrs : Unowned(attrs);
276 }),
277
278 list: () =>
279 Effect.gen(function* () {
280 const orgs = yield* listOrgNames();
281 const rows: DevelopersAppsKey["Attributes"][] = [];
282 for (const organization of orgs) {
283 const emails = yield* listDeveloperEmails(organization);
284 for (const email of emails) {
285 const page = yield* apigee
286 .listOrganizationsDevelopersApps({
287 parent: childName(organization, "developers", email),
288 expand: true,
289 count: "1000",
290 })
291 .pipe(
292 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
293 Effect.succeed({
294 app: [] as apigee.GoogleCloudApigeeV1DeveloperApp[],
295 }),
296 ),
297 );
298 for (const app of page.app ?? []) {
299 for (const credential of app.credentials ?? []) {
300 const labels = attributesToRecord(credential.attributes);
301 if (!Object.keys(labels).some((key) => key.startsWith("alchemy-"))) {
302 continue;
303 }
304 rows.push(
305 toAttrs(
306 {
307 consumerKey: credential.consumerKey,
308 consumerSecret: credential.consumerSecret,
309 scopes: credential.scopes,
310 apiProducts: credential.apiProducts,
311 status: credential.status,
312 attributes: credential.attributes,
313 issuedAt: credential.issuedAt,
314 expiresAt: credential.expiresAt,
315 },
316 organization,
317 email,
318 app.name ?? "",
319 ),
320 );
321 }
322 }
323 }
324 }
325 return rows;
326 }),
327
328 reconcile: Effect.fn(function* ({ id, news, output }) {
329 const env = yield* GcpEnvironment.current;
330 const organization = defaultOrgName(env.project, news.organization);
331 const developer = developerEmailOf(news.developer);
332 const app = appNameOf(news.app);
333 const consumerKey = yield* toKeyId(id, news.consumerKey, output?.consumerKey);
334 const consumerSecret = yield* toSecret(id, news.consumerSecret ?? output?.consumerSecret);
335 const parent = appParentOf(organization, developer, app);
336 const name = `${parent}/keys/${consumerKey}`;
337 const ownership = yield* createOwnership(id);
338 const attributes = desiredAttributes(news.attributes, ownership);
339 const status = news.status ?? "approved";
340
341 let current = yield* getByName(output?.name ?? name);
342
343 if (current === undefined) {
344 const created = yield* apigee
345 .createOrganizationsDevelopersAppsKeys({
346 parent,
347 body: {
348 consumerKey,
349 consumerSecret,
350 expiresInSeconds: news.expiresInSeconds,
351 attributes: recordToAttributes(attributes),
352 },
353 })
354 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
355 current = created ?? undefined;
356 }
357
358 if (current === undefined) {
359 return yield* new DevelopersAppsKeyNotResolved({ resourceName: name });
360 }
361
362 const observedAttributes = attributesToRecord(current.attributes);
363 const scopesChanged = !sameStringList(current.scopes, news.scopes);
364 const productsChanged = !sameStringList(
365 productsOf(current.apiProducts).map(String),
366 (news.apiProducts ?? []).map(String),
367 );
368 const statusChanged = (current.status ?? "") !== status;
369 const attributesChanged = !sameRecord(observedAttributes, attributes);
370
371 if (scopesChanged || productsChanged || statusChanged || attributesChanged) {
372 current = yield* apigee.updateDeveloperAppKeyOrganizationsDevelopersAppsKeys({
373 name,
374 action: statusChanged ? status : undefined,
375 body: {
376 consumerKey,
377 scopes: news.scopes,
378 apiProducts: news.apiProducts,
379 attributes: recordToAttributes(attributes),
380 },
381 });
382 }
383
384 return toAttrs(current, organization, developer, app);
385 }),
386
387 delete: Effect.fn(function* ({ output }) {
388 yield* apigee
389 .deleteOrganizationsDevelopersAppsKeys({ name: output.name })
390 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
391 }),
392 });