@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 654 lines 20.4 KB
Raw
1 import * as recaptchaenterprise from "@distilled.cloud/gcp/recaptchaenterprise_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 Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import { GcpEnvironment } from "../Environment.ts";
10 import {
11 createInternalLabels,
12 diffLabels,
13 hasAlchemyLabels,
14 stripInternalLabels,
15 toLabels,
16 } from "../Labels.ts";
17 import type { Providers } from "../Providers.ts";
18 import {
19 findOwnedKey,
20 keyNameOf,
21 lastSegment,
22 listKeys,
23 sameText,
24 stringList,
25 toDisplayName,
26 updateMaskOf,
27 } from "./internal.ts";
28
29 export type TestingOptions = {
30 /**
31 * Score returned for every assessment of this key. Must be between 0
32 * and 1 inclusive.
33 */
34 testingScore?: number;
35 /**
36 * Challenge outcome for CHECKBOX / INVISIBLE keys: `NOCAPTCHA` or
37 * `UNSOLVABLE_CHALLENGE`.
38 */
39 testingChallenge?: string;
40 };
41
42 export type AppleDeveloperId = {
43 /**
44 * Input-only Apple DeviceCheck private key (`.p8` contents).
45 */
46 privateKey?: string;
47 /**
48 * Apple team id (10 characters).
49 */
50 teamId?: string;
51 /**
52 * Apple developer key id (10 characters).
53 */
54 keyId?: string;
55 };
56
57 export type IOSKeySettings = {
58 /**
59 * iOS bundle ids allowed to use the key.
60 */
61 allowedBundleIds?: string[];
62 /**
63 * When true, `allowedBundleIds` are not enforced.
64 */
65 allowAllBundleIds?: boolean;
66 /**
67 * Apple Developer account used for App Attest / DeviceCheck.
68 */
69 appleDeveloperId?: AppleDeveloperId;
70 };
71
72 export type AndroidKeySettings = {
73 /**
74 * Android package names allowed to use the key.
75 */
76 allowedPackageNames?: string[];
77 /**
78 * When true, the key may be used by apps distributed outside Play.
79 */
80 supportNonGoogleAppStoreDistribution?: boolean;
81 /**
82 * When true, `allowedPackageNames` are not enforced.
83 */
84 allowAllPackageNames?: boolean;
85 };
86
87 export type WebActionSettings = {
88 /**
89 * Challenge is triggered when the score is below this threshold (0–1).
90 */
91 scoreThreshold?: number;
92 };
93
94 export type WebChallengeSettings = {
95 /**
96 * Default action threshold.
97 */
98 defaultSettings?: WebActionSettings;
99 /**
100 * Per-action score thresholds. Action names match `data-action`.
101 */
102 actionSettings?: Record<string, WebActionSettings | undefined>;
103 };
104
105 export type WebKeySettings = {
106 /**
107 * Hostnames allowed to use the key (no path, port, or fragment).
108 */
109 allowedDomains?: string[];
110 /**
111 * How the key is integrated with the site. Immutable — changing it
112 * replaces the key.
113 * @default "SCORE"
114 */
115 integrationType?: string;
116 /**
117 * Challenge frequency / difficulty for CHECKBOX, INVISIBLE, and
118 * POLICY_BASED_CHALLENGE keys.
119 */
120 challengeSecurityPreference?: string;
121 /**
122 * When true, `allowedDomains` are not enforced.
123 * @default true
124 */
125 allowAllDomains?: boolean;
126 /**
127 * Allow AMP pages. SCORE keys only. Immutable — changing it replaces
128 * the key.
129 */
130 allowAmpTraffic?: boolean;
131 /**
132 * POLICY_BASED_CHALLENGE thresholds.
133 */
134 challengeSettings?: WebChallengeSettings;
135 };
136
137 export type WafSettings = {
138 /**
139 * WAF service that uses this key (`CA`, `FASTLY`, `CLOUDFLARE`,
140 * `AKAMAI`). Immutable — changing it replaces the key.
141 */
142 wafService?: string;
143 /**
144 * WAF feature (`CHALLENGE_PAGE`, `SESSION_TOKEN`, `ACTION_TOKEN`,
145 * `EXPRESS`). Immutable — changing it replaces the key.
146 */
147 wafFeature?: string;
148 };
149
150 export type KeyProps = {
151 /**
152 * Server-assigned key id (the `{key}` segment of
153 * `projects/{project}/keys/{key}`). This is also the site key used by
154 * client libraries. Immutable — changing it replaces the key.
155 */
156 keyId?: string;
157 /**
158 * Human-readable display name. If omitted, a unique name is generated
159 * from the stack, stage, and logical id.
160 */
161 displayName?: string;
162 /**
163 * User labels. Alchemy ownership labels are merged in automatically.
164 */
165 labels?: Record<string, string>;
166 /**
167 * User-acceptance testing overrides (fixed score / challenge).
168 */
169 testingOptions?: TestingOptions;
170 /**
171 * Website key settings. Default when no Android, iOS, or Express
172 * settings are set: SCORE integration with `allowAllDomains`.
173 */
174 webSettings?: WebKeySettings;
175 /**
176 * Android app key settings. Mutually exclusive with web, iOS, and
177 * Express. Changing the platform kind replaces the key.
178 */
179 androidSettings?: AndroidKeySettings;
180 /**
181 * iOS app key settings. Mutually exclusive with web, Android, and
182 * Express. Changing the platform kind replaces the key.
183 */
184 iosSettings?: IOSKeySettings;
185 /**
186 * reCAPTCHA Express settings. Mutually exclusive with web, Android,
187 * and iOS. Changing the platform kind replaces the key.
188 */
189 expressSettings?: Record<string, never> | {};
190 /**
191 * Web Application Firewall settings. Immutable — changing them
192 * replaces the key.
193 */
194 wafSettings?: WafSettings;
195 };
196
197 export type Key = Resource<
198 "GCP.RecaptchaEnterprise.Key",
199 KeyProps,
200 {
201 /** Full resource name `projects/{project}/keys/{key}`. */
202 name: string;
203 /** Server-assigned key id (site key). */
204 keyId: string;
205 /** Project id used when the key was reconciled. */
206 project: string;
207 /** Human-readable display name. */
208 displayName: string | undefined;
209 /** User labels (Alchemy ownership labels stripped). */
210 labels: Record<string, string>;
211 /** Testing overrides, if set. */
212 testingOptions: TestingOptions | undefined;
213 /** Website settings, if this is a web key. */
214 webSettings: WebKeySettings | undefined;
215 /** Android settings, if this is an Android key. */
216 androidSettings: AndroidKeySettings | undefined;
217 /** iOS settings, if this is an iOS key. */
218 iosSettings: IOSKeySettings | undefined;
219 /** Whether Express settings are configured. */
220 expressSettings: Record<string, never> | {} | undefined;
221 /** WAF settings, if set. */
222 wafSettings: WafSettings | undefined;
223 /** RFC3339 creation timestamp. */
224 createTime: string | undefined;
225 },
226 never,
227 Providers
228 >;
229
230 /**
231 * A reCAPTCHA Enterprise key.
232 *
233 * Key ids are assigned by Google and are the site key used by client
234 * libraries. Alchemy stamps ownership into labels so `list` / nuke can
235 * find them. Display name, labels, and allowed domains update in place.
236 * Changing `keyId`, platform kind (web / Android / iOS / Express),
237 * `webSettings.integrationType`, AMP traffic, WAF settings, or testing
238 * options replaces the key.
239 *
240 * ### Creating a Key
241 * **Example:** Generated SCORE web key
242 * ```typescript
243 * const key = yield* GCP.RecaptchaEnterprise.Key("Signup", {});
244 * ```
245 *
246 * **Example:** Named SCORE key with labels and a test score
247 * ```typescript
248 * const key = yield* GCP.RecaptchaEnterprise.Key("Signup", {
249 * displayName: "signup form",
250 * labels: { env: "prod" },
251 * testingOptions: { testingScore: 0.9 },
252 * webSettings: {
253 * integrationType: "SCORE",
254 * allowAllDomains: true,
255 * },
256 * });
257 * ```
258 *
259 * ### Assessments
260 * **Example:** Create an assessment for the key
261 * ```typescript
262 * const createAssessment = yield* GCP.RecaptchaEnterprise.CreateAssessment(
263 * key,
264 * );
265 * const assessment = yield* createAssessment({
266 * body: {
267 * event: { token: recaptchaToken, expectedAction: "login" },
268 * },
269 * });
270 * ```
271 *
272 * @resource
273 * @category RecaptchaEnterprise
274 */
275 export const Key = Resource<Key>("GCP.RecaptchaEnterprise.Key");
276
277 export class KeyNotResolved extends Data.TaggedError("GCP.RecaptchaEnterprise.KeyNotResolved")<{
278 resourceName: string;
279 }> {}
280
281 type KeyKind = "web" | "android" | "ios" | "express";
282
283 const userLabels = (
284 labels: Record<string, string | undefined> | null | undefined,
285 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
286
287 const kindOf = (
288 props: {
289 webSettings?: unknown;
290 androidSettings?: unknown;
291 iosSettings?: unknown;
292 expressSettings?: unknown;
293 },
294 fallback?: KeyKind,
295 ): KeyKind => {
296 if (props.androidSettings !== undefined) return "android";
297 if (props.iosSettings !== undefined) return "ios";
298 if (props.expressSettings !== undefined) return "express";
299 if (props.webSettings !== undefined) return "web";
300 return fallback ?? "web";
301 };
302
303 const toTestingOptions = (
304 options:
305 | recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1TestingOptions
306 | TestingOptions
307 | undefined,
308 ): TestingOptions | undefined => {
309 if (options === undefined) return undefined;
310 if (options.testingScore === undefined && options.testingChallenge === undefined) {
311 return undefined;
312 }
313 return {
314 testingScore: options.testingScore,
315 testingChallenge: options.testingChallenge,
316 };
317 };
318
319 const toWebSettings = (
320 settings:
321 | recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1WebKeySettings
322 | WebKeySettings
323 | undefined,
324 ): WebKeySettings | undefined => {
325 if (settings === undefined) return undefined;
326 return {
327 allowedDomains: stringList(settings.allowedDomains),
328 integrationType: settings.integrationType,
329 challengeSecurityPreference: settings.challengeSecurityPreference,
330 allowAllDomains: settings.allowAllDomains,
331 allowAmpTraffic: settings.allowAmpTraffic,
332 challengeSettings: settings.challengeSettings,
333 };
334 };
335
336 const toAndroidSettings = (
337 settings:
338 | recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1AndroidKeySettings
339 | AndroidKeySettings
340 | undefined,
341 ): AndroidKeySettings | undefined => {
342 if (settings === undefined) return undefined;
343 return {
344 allowedPackageNames: stringList(settings.allowedPackageNames),
345 supportNonGoogleAppStoreDistribution: settings.supportNonGoogleAppStoreDistribution,
346 allowAllPackageNames: settings.allowAllPackageNames,
347 };
348 };
349
350 const toIosSettings = (
351 settings:
352 | recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1IOSKeySettings
353 | IOSKeySettings
354 | undefined,
355 ): IOSKeySettings | undefined => {
356 if (settings === undefined) return undefined;
357 const apple = settings.appleDeveloperId;
358 return {
359 allowedBundleIds: stringList(settings.allowedBundleIds),
360 allowAllBundleIds: settings.allowAllBundleIds,
361 appleDeveloperId:
362 apple === undefined
363 ? undefined
364 : {
365 teamId: apple.teamId,
366 keyId: apple.keyId,
367 },
368 };
369 };
370
371 const toWafSettings = (
372 settings:
373 | recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1WafSettings
374 | WafSettings
375 | undefined,
376 ): WafSettings | undefined => {
377 if (settings === undefined) return undefined;
378 if (settings.wafService === undefined && settings.wafFeature === undefined) {
379 return undefined;
380 }
381 return {
382 wafService: settings.wafService,
383 wafFeature: settings.wafFeature,
384 };
385 };
386
387 const toExpressSettings = (
388 settings:
389 | recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1FirewallActionBlockAction
390 | Record<string, never>
391 | {}
392 | undefined,
393 ): Record<string, never> | {} | undefined => (settings === undefined ? undefined : {});
394
395 const desiredWebSettings = (news: KeyProps): WebKeySettings => ({
396 allowAllDomains: true,
397 integrationType: "SCORE",
398 ...news.webSettings,
399 });
400
401 const platformBody = (news: KeyProps, kind: KeyKind) => {
402 if (kind === "android") {
403 return { androidSettings: news.androidSettings ?? {} };
404 }
405 if (kind === "ios") {
406 return { iosSettings: news.iosSettings ?? {} };
407 }
408 if (kind === "express") {
409 return { expressSettings: {} };
410 }
411 return { webSettings: desiredWebSettings(news) };
412 };
413
414 const toKeyBody = (
415 news: KeyProps,
416 displayName: string,
417 labels: Record<string, string>,
418 kind: KeyKind,
419 ): recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1Key => ({
420 displayName,
421 labels,
422 testingOptions: news.testingOptions,
423 wafSettings: news.wafSettings,
424 ...platformBody(news, kind),
425 });
426
427 const unspecified = (value: string | undefined) =>
428 value === undefined || value.length === 0 || value.endsWith("_UNSPECIFIED") ? "" : value;
429
430 const testingFingerprint = (options: TestingOptions | undefined) =>
431 JSON.stringify({
432 testingScore: options?.testingScore ?? null,
433 testingChallenge: unspecified(options?.testingChallenge),
434 });
435
436 const webFingerprint = (settings: WebKeySettings | undefined) =>
437 JSON.stringify({
438 allowedDomains: settings?.allowedDomains ? [...settings.allowedDomains].slice().sort() : [],
439 integrationType: unspecified(settings?.integrationType),
440 challengeSecurityPreference: unspecified(settings?.challengeSecurityPreference),
441 allowAllDomains: settings?.allowAllDomains === true,
442 allowAmpTraffic: settings?.allowAmpTraffic === true,
443 challengeSettings: settings?.challengeSettings ?? null,
444 });
445
446 const androidFingerprint = (settings: AndroidKeySettings | undefined) =>
447 JSON.stringify({
448 allowedPackageNames: settings?.allowedPackageNames
449 ? [...settings.allowedPackageNames].slice().sort()
450 : [],
451 supportNonGoogleAppStoreDistribution: settings?.supportNonGoogleAppStoreDistribution === true,
452 allowAllPackageNames: settings?.allowAllPackageNames === true,
453 });
454
455 const iosFingerprint = (settings: IOSKeySettings | undefined) =>
456 JSON.stringify({
457 allowedBundleIds: settings?.allowedBundleIds
458 ? [...settings.allowedBundleIds].slice().sort()
459 : [],
460 allowAllBundleIds: settings?.allowAllBundleIds === true,
461 teamId: settings?.appleDeveloperId?.teamId ?? "",
462 keyId: settings?.appleDeveloperId?.keyId ?? "",
463 });
464
465 const wafFingerprint = (settings: WafSettings | undefined) =>
466 JSON.stringify({
467 wafService: settings?.wafService ?? "",
468 wafFeature: settings?.wafFeature ?? "",
469 });
470
471 const toAttrs = (key: recaptchaenterprise.GoogleCloudRecaptchaenterpriseV1Key, project: string) => {
472 const name = key.name ?? "";
473 return {
474 name,
475 keyId: lastSegment(name),
476 project,
477 displayName: key.displayName,
478 labels: userLabels(key.labels),
479 testingOptions: toTestingOptions(key.testingOptions),
480 webSettings: toWebSettings(key.webSettings),
481 androidSettings: toAndroidSettings(key.androidSettings),
482 iosSettings: toIosSettings(key.iosSettings),
483 expressSettings: toExpressSettings(key.expressSettings),
484 wafSettings: toWafSettings(key.wafSettings),
485 createTime: key.createTime,
486 };
487 };
488
489 export const KeyProvider = () =>
490 Provider.succeed(Key, {
491 stables: ["name", "keyId", "project", "createTime"],
492
493 diff: Effect.fn(function* ({ news, olds, output }) {
494 if (!isResolved(news)) return undefined;
495 const previousId = olds?.keyId ?? output?.keyId;
496 if (news.keyId !== undefined && previousId !== undefined && news.keyId !== previousId) {
497 return { action: "replace" as const, deleteFirst: false };
498 }
499 const previousKind = kindOf(olds ?? output ?? {});
500 const nextKind = kindOf(news, previousKind);
501 if (previousKind !== nextKind) {
502 return { action: "replace" as const, deleteFirst: false };
503 }
504 const previousType =
505 olds?.webSettings?.integrationType ?? output?.webSettings?.integrationType;
506 const nextType = news.webSettings?.integrationType;
507 if (previousType !== undefined && nextType !== undefined && previousType !== nextType) {
508 return { action: "replace" as const, deleteFirst: false };
509 }
510 const previousAmp =
511 olds?.webSettings?.allowAmpTraffic ?? output?.webSettings?.allowAmpTraffic;
512 if (
513 news.webSettings?.allowAmpTraffic !== undefined &&
514 previousAmp !== undefined &&
515 news.webSettings.allowAmpTraffic !== previousAmp
516 ) {
517 return { action: "replace" as const, deleteFirst: false };
518 }
519 if (
520 (news.wafSettings !== undefined ||
521 olds?.wafSettings !== undefined ||
522 output?.wafSettings !== undefined) &&
523 wafFingerprint(news.wafSettings) !==
524 wafFingerprint(olds?.wafSettings ?? output?.wafSettings)
525 ) {
526 return { action: "replace" as const, deleteFirst: false };
527 }
528 const previousTesting = olds?.testingOptions ?? output?.testingOptions;
529 if (
530 (olds !== undefined || output !== undefined) &&
531 testingFingerprint(toTestingOptions(news.testingOptions)) !==
532 testingFingerprint(toTestingOptions(previousTesting))
533 ) {
534 return { action: "replace" as const, deleteFirst: false };
535 }
536 return undefined;
537 }),
538
539 read: Effect.fn(function* ({ id, olds, output }) {
540 const env = yield* GcpEnvironment.current;
541 const name =
542 output?.name ??
543 (olds?.keyId !== undefined
544 ? keyNameOf(env.project, olds.keyId)
545 : output?.keyId !== undefined
546 ? keyNameOf(env.project, output.keyId)
547 : "");
548 const existing = yield* findOwnedKey(env.project, id, name);
549 if (existing === undefined) return undefined;
550 const attrs = toAttrs(existing, env.project);
551 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
552 }),
553
554 list: () =>
555 Effect.gen(function* () {
556 const env = yield* GcpEnvironment.current;
557 const keys = yield* listKeys(env.project);
558 return keys
559 .filter((key) =>
560 Object.keys(key.labels ?? {}).some((label) => label.startsWith("alchemy-")),
561 )
562 .map((key) => toAttrs(key, env.project));
563 }),
564
565 reconcile: Effect.fn(function* ({ id, news, output }) {
566 const env = yield* GcpEnvironment.current;
567 const desiredLabels = {
568 ...toLabels(news.labels),
569 ...(yield* createInternalLabels(id)),
570 };
571 const lookupName =
572 output?.name ??
573 (news.keyId !== undefined
574 ? keyNameOf(env.project, news.keyId)
575 : output?.keyId !== undefined
576 ? keyNameOf(env.project, output.keyId)
577 : "");
578
579 let current = yield* findOwnedKey(env.project, id, lookupName);
580 const kind = kindOf(news, kindOf(current ?? {}, "web"));
581 const displayName = yield* toDisplayName(
582 id,
583 news.displayName,
584 current?.displayName ?? output?.displayName,
585 );
586 const desired = toKeyBody(news, displayName, desiredLabels, kind);
587
588 if (current === undefined) {
589 const created = yield* recaptchaenterprise
590 .createProjectsKeys({
591 parent: `projects/${env.project}`,
592 body: desired,
593 })
594 .pipe(Effect.catchTag("Conflict", () => findOwnedKey(env.project, id, lookupName)));
595 current = created ?? undefined;
596 }
597
598 if (current === undefined) {
599 return yield* new KeyNotResolved({
600 resourceName: lookupName.length > 0 ? lookupName : displayName,
601 });
602 }
603
604 const name = current.name ?? lookupName;
605 const labelsChanged = (() => {
606 const { upsert, removed } = diffLabels(tagRecord(current.labels), desiredLabels);
607 return upsert.length > 0 || removed.length > 0;
608 })();
609 const displayChanged = !sameText(current.displayName, displayName);
610 const webChanged =
611 kind === "web" &&
612 webFingerprint(toWebSettings(current.webSettings)) !==
613 webFingerprint(desiredWebSettings(news));
614 const androidChanged =
615 kind === "android" &&
616 androidFingerprint(toAndroidSettings(current.androidSettings)) !==
617 androidFingerprint(toAndroidSettings(news.androidSettings ?? {}));
618 const iosChanged =
619 kind === "ios" &&
620 iosFingerprint(toIosSettings(current.iosSettings)) !==
621 iosFingerprint(toIosSettings(news.iosSettings ?? {}));
622 const expressChanged = kind === "express" && current.expressSettings === undefined;
623 const wafChanged =
624 wafFingerprint(toWafSettings(current.wafSettings)) !==
625 wafFingerprint(toWafSettings(news.wafSettings));
626
627 const updateMask = updateMaskOf(
628 displayChanged ? "displayName" : undefined,
629 labelsChanged ? "labels" : undefined,
630 webChanged ? "webSettings" : undefined,
631 androidChanged ? "androidSettings" : undefined,
632 iosChanged ? "iosSettings" : undefined,
633 expressChanged ? "expressSettings" : undefined,
634 wafChanged ? "wafSettings" : undefined,
635 );
636
637 if (updateMask.length > 0) {
638 current = yield* recaptchaenterprise.patchProjectsKeys({
639 name,
640 updateMask,
641 body: { ...desired, name },
642 });
643 }
644
645 return toAttrs(current, env.project);
646 }),
647
648 delete: Effect.fn(function* ({ output }) {
649 if (output.name.length === 0) return;
650 yield* recaptchaenterprise
651 .deleteProjectsKeys({ name: output.name })
652 .pipe(Effect.catchTag("NotFound", () => Effect.void));
653 }),
654 });