@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 134 lines 4.81 KB
Raw
1 import * as Cognito from "@alchemy.run/aws/Cognito";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Redacted from "effect/Redacted";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "trigger-handler.ts");
12
13 const plain = (value: string | Redacted.Redacted<string> | undefined): string | undefined =>
14 value === undefined ? undefined : typeof value === "string" ? value : Redacted.value(value);
15
16 const PASSWORD = "Alchemy-Trigger-Passw0rd!";
17
18 export class CognitoTriggerFunction extends Lambda.Function<Lambda.Function>()(
19 "CognitoTriggerFunction",
20 ) {}
21
22 /**
23 * Fixture for the user pool trigger e2e test: ONE Lambda that both hosts
24 * the pool's PreSignUp / PreTokenGeneration triggers (the circular case the
25 * binding-contract pattern exists for — the pool's LambdaConfig points back
26 * at this function) and drives the auth flows over its function URL.
27 */
28 export default CognitoTriggerFunction.make(
29 {
30 main,
31 functionUrl: true,
32 timeout: Duration.seconds(30),
33 },
34 Effect.gen(function* () {
35 const pool = yield* Cognito.UserPool("TriggerUserPool", {
36 passwordPolicy: {
37 minimumLength: 12,
38 requireSymbols: false,
39 },
40 accountRecovery: [{ name: "admin_only", priority: 1 }],
41 tags: { Purpose: "cognito-trigger-fixture" },
42 });
43 const client = yield* Cognito.UserPoolClient("TriggerUserPoolClient", {
44 userPoolId: pool.userPoolId,
45 explicitAuthFlows: ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
46 });
47
48 // PreSignUp: auto-confirm every sign-up (and mark the email verified)
49 // so users arrive CONFIRMED without ever receiving a confirmation code.
50 yield* Cognito.onPreSignUp(pool, (event) =>
51 Effect.sync(() => Cognito.autoConfirmUser(event, { verifyEmail: true })),
52 );
53
54 // PreTokenGeneration: stamp a custom claim into every issued ID token.
55 yield* Cognito.onPreTokenGeneration(pool, (event) =>
56 Effect.sync(() => {
57 event.response.claimsOverrideDetails = {
58 claimsToAddOrOverride: { alchemyTrigger: "pre-token-generation" },
59 };
60 return event;
61 }),
62 );
63
64 const auth = yield* Cognito.UserPoolAuth(client);
65 const admin = yield* Cognito.UserPoolAdmin(pool);
66 const UserPoolId = yield* pool.userPoolId;
67 const ClientId = yield* client.clientId;
68
69 return {
70 fetch: Effect.gen(function* () {
71 const request = yield* HttpServerRequest;
72 const url = new URL(request.originalUrl);
73 const pathname = url.pathname;
74 const username = url.searchParams.get("username") ?? "missing-user";
75
76 // Sign up (PreSignUp auto-confirms) → adminGetUser (assert state)
77 // → password auth (PreTokenGeneration stamps a claim) → delete.
78 if (request.method === "POST" && pathname === "/sign-up-flow") {
79 // rerun tolerance: an earlier partial run may have left the user
80 yield* admin
81 .adminDeleteUser({ Username: username })
82 .pipe(Effect.catchTag("UserNotFoundException", () => Effect.void));
83
84 const signedUp = yield* auth.signUp({
85 Username: username,
86 Password: PASSWORD,
87 UserAttributes: [{ Name: "email", Value: `${username}@example.com` }],
88 });
89
90 const user = yield* admin.adminGetUser({ Username: username });
91 const emailVerified = plain(
92 (user.UserAttributes ?? []).find((attribute) => attribute.Name === "email_verified")
93 ?.Value,
94 );
95
96 const signIn = yield* auth.initiateAuth({
97 AuthFlow: "USER_PASSWORD_AUTH",
98 AuthParameters: { USERNAME: username, PASSWORD },
99 });
100
101 yield* admin.adminDeleteUser({ Username: username });
102
103 return yield* HttpServerResponse.json({
104 userConfirmed: signedUp.UserConfirmed,
105 userStatus: user.UserStatus,
106 emailVerified,
107 idToken: plain(signIn.AuthenticationResult?.IdToken),
108 });
109 }
110
111 if (request.method === "GET" && pathname === "/config") {
112 return yield* HttpServerResponse.json({
113 ok: true,
114 userPoolId: yield* UserPoolId,
115 clientId: yield* ClientId,
116 });
117 }
118
119 return yield* HttpServerResponse.json(
120 { error: "Not found", method: request.method, pathname },
121 { status: 404 },
122 );
123 }).pipe(Effect.orDie),
124 };
125 }).pipe(
126 Effect.provide(
127 Layer.mergeAll(
128 Lambda.UserPoolTriggerEventSource,
129 Cognito.UserPoolAuthHttp,
130 Cognito.UserPoolAdminHttp,
131 ),
132 ),
133 ),
134 );