@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 407 lines 13.9 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 collectPages,
15 createOwnership,
16 defaultOrgName,
17 desiredAttributes,
18 lastSegment,
19 listOrgNames,
20 orgIdOf,
21 orgNameOf,
22 ownedBy,
23 recordToAttributes,
24 sameRecord,
25 sameStringList,
26 userAttributes,
27 } from "./operations.ts";
28
29 export type AppgroupsAppsKeyProps = {
30 /**
31 * Apigee organization id or `organizations/{org}`. Defaults to the
32 * current GCP project id. Immutable — changing it replaces the key.
33 */
34 organization?: string;
35 /**
36 * Parent AppGroup name or `organizations/{org}/appgroups/{appgroup}`.
37 * Immutable — changing it replaces the key.
38 */
39 appGroup: string;
40 /**
41 * Parent AppGroup app name or full resource name. Immutable — changing
42 * it replaces the key.
43 */
44 app: string;
45 /**
46 * Consumer key. If omitted, a unique key is generated. Immutable —
47 * changing it replaces the key.
48 */
49 consumerKey?: string;
50 /**
51 * Consumer secret. If omitted, a unique secret is generated. Immutable —
52 * changing it 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 * UpdateAppGroupAppKey.
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 AppgroupsAppsKey = Resource<
82 "GCP.Apigee.AppgroupsAppsKey",
83 AppgroupsAppsKeyProps,
84 {
85 /** Full resource name `organizations/{org}/appgroups/{appgroup}/apps/{app}/keys/{key}`. */
86 name: string;
87 /** Consumer key. */
88 consumerKey: string;
89 /** Consumer secret. */
90 consumerSecret: string | undefined;
91 /** Parent AppGroup id. */
92 appGroup: 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: apigee.GoogleCloudApigeeV1APIProductAssociation[];
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 AppGroup 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 an AppGroup App Key
123 * **Example:** Generated key under an AppGroup app
124 * ```typescript
125 * const key = yield* GCP.Apigee.AppgroupsAppsKey("GroupKey", {
126 * appGroup: "partners",
127 * app: "partner-portal",
128 * });
129 * ```
130 *
131 * **Example:** Custom key and secret
132 * ```typescript
133 * const key = yield* GCP.Apigee.AppgroupsAppsKey("GroupKey", {
134 * appGroup: "partners",
135 * app: "partner-portal",
136 * consumerKey: "partner-key",
137 * consumerSecret: "partner-secret",
138 * });
139 * ```
140 *
141 * @resource
142 * @category Apigee
143 */
144 export const AppgroupsAppsKey = Resource<AppgroupsAppsKey>("GCP.Apigee.AppgroupsAppsKey");
145
146 export class AppgroupsAppsKeyNotResolved extends Data.TaggedError(
147 "GCP.Apigee.AppgroupsAppsKeyNotResolved",
148 )<{
149 resourceName: string;
150 }> {}
151
152 const appGroupIdOf = (appGroup: string) =>
153 appGroup.includes("/appgroups/") ? lastSegment(appGroup) : appGroup;
154
155 const appNameOf = (app: string) => (app.includes("/apps/") ? lastSegment(app) : app);
156
157 const appParentOf = (organization: string, appGroup: string, app: string) =>
158 `${childName(orgNameOf(organization), "appgroups", appGroupIdOf(appGroup))}/apps/${appNameOf(app)}`;
159
160 const resourceName = (organization: string, appGroup: string, app: string, consumerKey: string) =>
161 `${appParentOf(organization, appGroup, app)}/keys/${consumerKey}`;
162
163 const toKeyId = (id: string, explicit: string | undefined, existing?: string) =>
164 Effect.gen(function* () {
165 if (explicit !== undefined) return explicit;
166 if (existing !== undefined) return existing;
167 return yield* createPhysicalName({ id, maxLength: 64, lowercase: true });
168 });
169
170 const toSecret = (id: string, explicit: string | undefined) =>
171 Effect.gen(function* () {
172 if (explicit !== undefined) return explicit;
173 return yield* createPhysicalName({
174 id: `${id}-secret`,
175 maxLength: 64,
176 lowercase: true,
177 });
178 });
179
180 const toAttrs = (
181 key: apigee.GoogleCloudApigeeV1AppGroupAppKey,
182 organization: string,
183 appGroup: string,
184 app: string,
185 ) => {
186 const consumerKey = key.consumerKey ?? "";
187 return {
188 name: resourceName(organization, appGroup, app, consumerKey),
189 consumerKey,
190 consumerSecret: key.consumerSecret,
191 appGroup: appGroupIdOf(appGroup),
192 app: appNameOf(app),
193 organization: orgIdOf(organization),
194 scopes: key.scopes ?? [],
195 apiProducts: key.apiProducts ?? [],
196 status: key.status,
197 attributes: userAttributes(attributesToRecord(key.attributes)),
198 issuedAt: key.issuedAt,
199 expiresAt: key.expiresAt,
200 };
201 };
202
203 const getByName = (name: string) =>
204 apigee
205 .getOrganizationsAppgroupsAppsKeys({ name })
206 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
207
208 const listAppGroups = (organization: string) =>
209 collectPages(
210 apigee.listOrganizationsAppgroups.pages({
211 parent: organization,
212 pageSize: 1000,
213 }),
214 (page) => page.appGroups,
215 ).pipe(
216 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
217 Effect.succeed([] as apigee.GoogleCloudApigeeV1AppGroup[]),
218 ),
219 );
220
221 const listApps = (parent: string) =>
222 collectPages(
223 apigee.listOrganizationsAppgroupsApps.pages({
224 parent,
225 pageSize: 1000,
226 }),
227 (page) => page.appGroupApps,
228 ).pipe(
229 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
230 Effect.succeed([] as apigee.GoogleCloudApigeeV1AppGroupApp[]),
231 ),
232 );
233
234 export const AppgroupsAppsKeyProvider = () =>
235 Provider.succeed(AppgroupsAppsKey, {
236 stables: ["name", "consumerKey", "appGroup", "app", "organization", "issuedAt"],
237
238 diff: Effect.fn(function* ({ news, olds, output }) {
239 if (!isResolved(news)) return undefined;
240 const previousKey = olds?.consumerKey ?? output?.consumerKey;
241 const previousSecret = olds?.consumerSecret ?? output?.consumerSecret;
242 const previousGroup = olds?.appGroup ?? output?.appGroup;
243 const previousApp = olds?.app ?? output?.app;
244 const previousOrg = olds?.organization ?? output?.organization;
245 const keyChanged =
246 previousKey !== undefined &&
247 news.consumerKey !== undefined &&
248 news.consumerKey !== previousKey;
249 const secretChanged =
250 previousSecret !== undefined &&
251 news.consumerSecret !== undefined &&
252 news.consumerSecret !== previousSecret;
253 const groupChanged =
254 previousGroup !== undefined && appGroupIdOf(news.appGroup) !== appGroupIdOf(previousGroup);
255 const appChanged =
256 previousApp !== undefined && appNameOf(news.app) !== appNameOf(previousApp);
257 const orgChanged =
258 previousOrg !== undefined &&
259 news.organization !== undefined &&
260 orgIdOf(news.organization) !== orgIdOf(previousOrg);
261 if (keyChanged || secretChanged || groupChanged || appChanged || orgChanged) {
262 return {
263 action: "replace" as const,
264 deleteFirst: keyChanged && !groupChanged && !appChanged && !orgChanged,
265 };
266 }
267 return undefined;
268 }),
269
270 read: Effect.fn(function* ({ id, olds, output }) {
271 const env = yield* GcpEnvironment.current;
272 const organization = defaultOrgName(env.project, olds?.organization ?? output?.organization);
273 const appGroup = olds?.appGroup ?? output?.appGroup;
274 const app = olds?.app ?? output?.app;
275 if (appGroup === undefined || app === undefined) return undefined;
276 const consumerKey = yield* toKeyId(id, olds?.consumerKey, output?.consumerKey);
277 const name = output?.name ?? resourceName(organization, appGroup, app, consumerKey);
278 const existing = yield* getByName(name);
279 if (existing === undefined) return undefined;
280 const attrs = toAttrs(existing, organization, appGroup, app);
281 return (yield* ownedBy(id, attributesToRecord(existing.attributes))) ? attrs : Unowned(attrs);
282 }),
283
284 list: () =>
285 Effect.gen(function* () {
286 const orgs = yield* listOrgNames();
287 const rows: AppgroupsAppsKey["Attributes"][] = [];
288 for (const organization of orgs) {
289 const groups = yield* listAppGroups(organization);
290 for (const group of groups) {
291 const groupId = group.name ?? "";
292 if (groupId.length === 0) continue;
293 const parent = childName(organization, "appgroups", groupId);
294 const apps = yield* listApps(parent);
295 for (const app of apps) {
296 const appName = app.name ?? "";
297 const fetched =
298 (app.credentials?.length ?? 0) > 0
299 ? app
300 : yield* apigee
301 .getOrganizationsAppgroupsApps({
302 name: `${parent}/apps/${appName}`,
303 })
304 .pipe(
305 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
306 Effect.succeed(app),
307 ),
308 );
309 for (const credential of fetched.credentials ?? []) {
310 const labels = attributesToRecord(credential.attributes);
311 if (!Object.keys(labels).some((key) => key.startsWith("alchemy-"))) {
312 continue;
313 }
314 rows.push(
315 toAttrs(
316 {
317 consumerKey: credential.consumerKey,
318 consumerSecret: credential.consumerSecret,
319 scopes: credential.scopes,
320 status: credential.status,
321 attributes: credential.attributes,
322 issuedAt: credential.issuedAt,
323 expiresAt: credential.expiresAt,
324 apiProducts: (credential.apiProducts ?? []).map((product) => ({
325 apiproduct: product.apiproduct,
326 status: product.status,
327 })),
328 },
329 organization,
330 groupId,
331 appName,
332 ),
333 );
334 }
335 }
336 }
337 }
338 return rows;
339 }),
340
341 reconcile: Effect.fn(function* ({ id, news, output }) {
342 const env = yield* GcpEnvironment.current;
343 const organization = defaultOrgName(env.project, news.organization);
344 const appGroup = appGroupIdOf(news.appGroup);
345 const app = appNameOf(news.app);
346 const consumerKey = yield* toKeyId(id, news.consumerKey, output?.consumerKey);
347 const consumerSecret = yield* toSecret(id, news.consumerSecret ?? output?.consumerSecret);
348 const parent = appParentOf(organization, appGroup, app);
349 const name = `${parent}/keys/${consumerKey}`;
350 const ownership = yield* createOwnership(id);
351 const attributes = desiredAttributes(news.attributes, ownership);
352 const status = news.status ?? "approved";
353
354 let current = yield* getByName(output?.name ?? name);
355
356 if (current === undefined) {
357 const created = yield* apigee
358 .createOrganizationsAppgroupsAppsKeys({
359 parent,
360 body: {
361 consumerKey,
362 consumerSecret,
363 expiresInSeconds: news.expiresInSeconds,
364 attributes: recordToAttributes(attributes),
365 },
366 })
367 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
368 current = created ?? undefined;
369 }
370
371 if (current === undefined) {
372 return yield* new AppgroupsAppsKeyNotResolved({ resourceName: name });
373 }
374
375 const observedAttributes = attributesToRecord(current.attributes);
376 const scopesChanged = !sameStringList(current.scopes, news.scopes);
377 const productsChanged = !sameStringList(
378 (current.apiProducts ?? []).map((product) => product.apiproduct ?? ""),
379 news.apiProducts ?? [],
380 );
381 const statusChanged = (current.status ?? "") !== status;
382 const attributesChanged = !sameRecord(observedAttributes, attributes);
383
384 if (scopesChanged || productsChanged || statusChanged || attributesChanged) {
385 current = yield* apigee.updateAppGroupAppKeyOrganizationsAppgroupsAppsKeys({
386 name,
387 body: {
388 action: statusChanged ? status : undefined,
389 apiProducts: news.apiProducts,
390 appGroupAppKey: {
391 consumerKey,
392 scopes: news.scopes,
393 attributes: recordToAttributes(attributes),
394 },
395 },
396 });
397 }
398
399 return toAttrs(current, organization, appGroup, app);
400 }),
401
402 delete: Effect.fn(function* ({ output }) {
403 yield* apigee
404 .deleteOrganizationsAppgroupsAppsKeys({ name: output.name })
405 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
406 }),
407 });