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

main
ts 128 lines 5.13 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Schedule from "effect/Schedule";
10 import CognitoTriggerFunctionLive, { CognitoTriggerFunction } from "./trigger-handler";
11
12 const testOptions = { providers: AWS.providers() };
13 const { test, beforeAll, afterAll } = Test.make(testOptions);
14 const sharedStack = Core.scratchStack(testOptions, "CognitoTriggers");
15
16 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
17 // over 60s on a fresh deploy under parallel-suite load.
18 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
19
20 let baseUrl: string;
21
22 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
23 readonly status: number;
24 readonly body: string;
25 }> {}
26
27 // Retry transient 5xx only (cold re-init, IAM / trigger-permission
28 // propagation); 4xx and assertion failures surface immediately.
29 const send = (request: HttpClientRequest.HttpClientRequest) =>
30 HttpClient.execute(request).pipe(
31 Effect.flatMap((response) =>
32 response.status >= 500
33 ? response.text.pipe(
34 Effect.flatMap((body) =>
35 Effect.fail(new TransientUpstream({ status: response.status, body })),
36 ),
37 )
38 : Effect.succeed(response),
39 ),
40 Effect.retry({
41 while: (e) => e._tag === "TransientUpstream",
42 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
43 }),
44 );
45
46 const decodeJwtPayload = (token: string): Record<string, unknown> =>
47 JSON.parse(Buffer.from(token.split(".")[1]!, "base64url").toString("utf8"));
48
49 describe(
50 "Cognito UserPool Triggers",
51 { tags: ["provider:aws", "provider:aws:cognito", "provider:aws:lambda", "live"] },
52 () => {
53 beforeAll(
54 Effect.gen(function* () {
55 yield* Effect.logInfo("Cognito triggers setup: destroying previous stack");
56 yield* sharedStack.destroy();
57
58 yield* Effect.logInfo("Cognito triggers setup: deploying fixture");
59 const { functionUrl } = yield* sharedStack.deploy(
60 Effect.gen(function* () {
61 return yield* CognitoTriggerFunction;
62 }).pipe(Effect.provide(CognitoTriggerFunctionLive)),
63 );
64
65 expect(functionUrl).toBeTruthy();
66 baseUrl = functionUrl!.replace(/\/+$/, "");
67 const readinessUrl = `${baseUrl}/config`;
68
69 yield* Effect.logInfo(`Cognito triggers setup: probing readiness at ${readinessUrl}`);
70 yield* HttpClient.get(readinessUrl).pipe(
71 Effect.flatMap((response) =>
72 response.status === 200
73 ? Effect.succeed(response)
74 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
75 ),
76 Effect.tapError((error) =>
77 Effect.logWarning(`Cognito triggers setup: fixture not ready yet (${String(error)})`),
78 ),
79 Effect.retry({ schedule: readinessPolicy }),
80 );
81 }),
82 { timeout: 240_000 },
83 );
84
85 afterAll(sharedStack.destroy(), { timeout: 120_000 });
86
87 describe("UserPoolTriggerEventSource", () => {
88 test.provider(
89 "preSignUp auto-confirms sign-up; preTokenGeneration stamps a claim",
90 (_stack) =>
91 Effect.gen(function* () {
92 const config = (yield* send(HttpClientRequest.get(`${baseUrl}/config`)).pipe(
93 Effect.flatMap((r) => r.json),
94 )) as { userPoolId: string; clientId: string };
95
96 const response = (yield* send(
97 HttpClientRequest.post(`${baseUrl}/sign-up-flow?username=trigger-user`),
98 ).pipe(Effect.flatMap((r) => r.json))) as {
99 userConfirmed: boolean | undefined;
100 userStatus: string | undefined;
101 emailVerified: string | undefined;
102 idToken: string | undefined;
103 };
104
105 // PreSignUp auto-confirm: the sign-up response itself reports the
106 // user as confirmed, and the pool shows CONFIRMED — no
107 // confirmation code was ever entered.
108 expect(response.userConfirmed).toBe(true);
109 expect(response.userStatus).toBe("CONFIRMED");
110 expect(response.emailVerified).toBe("true");
111
112 // Password auth succeeded immediately after sign-up, proving the
113 // account was usable without confirmation.
114 expect(response.idToken).toBeTruthy();
115
116 // PreTokenGeneration: the ID token carries the claim the trigger
117 // handler stamped in, and is a real JWT issued by our pool.
118 const payload = decodeJwtPayload(response.idToken!);
119 expect(payload.alchemyTrigger).toBe("pre-token-generation");
120 expect(payload.iss).toContain(`/${config.userPoolId}`);
121 expect(payload["cognito:username"]).toBe("trigger-user");
122 expect(payload.aud).toBe(config.clientId);
123 }),
124 { timeout: 120_000 },
125 );
126 });
127 },
128 );