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

main
ts 208 lines 7.8 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import type * as lambda from "aws-lambda";
3 import type * as Effect from "effect/Effect";
4 import type { UserPool, UserPoolTriggerName } from "./UserPool.ts";
5
6 /**
7 * The typed event each trigger slot receives (the Cognito
8 * `version`/`triggerSource`/`request`/`response` envelope from
9 * `aws-lambda`).
10 */
11 export interface UserPoolTriggerEventMap {
12 PreSignUp: lambda.PreSignUpTriggerEvent;
13 PostConfirmation: lambda.PostConfirmationTriggerEvent;
14 PreAuthentication: lambda.PreAuthenticationTriggerEvent;
15 PostAuthentication: lambda.PostAuthenticationTriggerEvent;
16 CustomMessage: lambda.CustomMessageTriggerEvent;
17 DefineAuthChallenge: lambda.DefineAuthChallengeTriggerEvent;
18 CreateAuthChallenge: lambda.CreateAuthChallengeTriggerEvent;
19 VerifyAuthChallengeResponse: lambda.VerifyAuthChallengeResponseTriggerEvent;
20 PreTokenGeneration: lambda.PreTokenGenerationTriggerEvent;
21 UserMigration: lambda.UserMigrationTriggerEvent;
22 }
23
24 export type UserPoolTriggerEvent<T extends UserPoolTriggerName> = UserPoolTriggerEventMap[T];
25
26 /**
27 * The `triggerSource` prefix Cognito stamps on invocations of each trigger
28 * slot (e.g. `PreSignUp` fires with `PreSignUp_SignUp`,
29 * `PreSignUp_AdminCreateUser`, …; `PreTokenGeneration` fires with
30 * `TokenGeneration_*`). Used by the runtime dispatcher to route events to
31 * the registered handler.
32 */
33 export const userPoolTriggerSourcePrefixes: Record<UserPoolTriggerName, string> = {
34 PreSignUp: "PreSignUp_",
35 PostConfirmation: "PostConfirmation_",
36 PreAuthentication: "PreAuthentication_",
37 PostAuthentication: "PostAuthentication_",
38 CustomMessage: "CustomMessage_",
39 DefineAuthChallenge: "DefineAuthChallenge_",
40 CreateAuthChallenge: "CreateAuthChallenge_",
41 VerifyAuthChallengeResponse: "VerifyAuthChallengeResponse_",
42 PreTokenGeneration: "TokenGeneration_",
43 UserMigration: "UserMigration_",
44 };
45
46 export interface UserPoolTriggerProps<T extends UserPoolTriggerName = UserPoolTriggerName> {
47 /** The trigger slot to handle, e.g. `PreSignUp` or `CustomMessage`. */
48 trigger: T;
49 }
50
51 /**
52 * A user pool trigger handler receives the typed trigger event and returns
53 * the (usually mutated) event, which becomes the Lambda's response back to
54 * Cognito. Returning `void` responds with the event as-is.
55 */
56 export type UserPoolTriggerHandler<T extends UserPoolTriggerName, Req = never> = (
57 event: UserPoolTriggerEvent<T>,
58 ) => Effect.Effect<UserPoolTriggerEvent<T> | void, never, Req>;
59
60 export type UserPoolTriggerEventSourceService = <T extends UserPoolTriggerName, Req = never>(
61 userPool: UserPool,
62 props: UserPoolTriggerProps<T>,
63 handler: UserPoolTriggerHandler<T, Req>,
64 ) => Effect.Effect<void, never, never>;
65
66 /**
67 * Event source connecting a Cognito {@link UserPool} Lambda trigger to the
68 * hosting Lambda function.
69 *
70 * At deploy time the Lambda implementation
71 * (`Lambda.UserPoolTriggerEventSource`) injects the function ARN into the
72 * pool's `LambdaConfig` (via the pool's binding contract) and creates the
73 * `lambda:InvokeFunction` Permission for `cognito-idp.amazonaws.com`; at
74 * runtime it dispatches matching trigger events to the handler and returns
75 * the handler's (mutated) event to Cognito.
76 *
77 * Use the {@link onUserPoolTrigger} helper (or the per-slot shorthands
78 * {@link onPreSignUp}, {@link onPostConfirmation},
79 * {@link onPreTokenGeneration}, {@link onCustomMessage}) rather than the
80 * service directly, and provide `Lambda.UserPoolTriggerEventSource` on the
81 * hosting function.
82 * ### Handling User Pool Triggers
83 * **Example:** Auto-confirm Sign-ups from a Lambda Function
84 * ```typescript
85 * export default AuthFunction.make(
86 * { main: import.meta.url },
87 * Effect.gen(function* () {
88 * const pool = yield* Cognito.UserPool("Users", {});
89 *
90 * // deploy: wires PreSignUp in the pool's LambdaConfig + invoke Permission
91 * // runtime: dispatches PreSignUp_* events to this handler
92 * yield* Cognito.onPreSignUp(pool, (event) =>
93 * Effect.sync(() => Cognito.autoConfirmUser(event, { verifyEmail: true })),
94 * );
95 *
96 * return {};
97 * }).pipe(Effect.provide(Lambda.UserPoolTriggerEventSource)),
98 * );
99 * ```
100 *
101 * @binding
102 */
103 export interface UserPoolTriggerEventSource extends Binding.Service<
104 UserPoolTriggerEventSource,
105 "AWS.Cognito.UserPoolTriggerEventSource",
106 UserPoolTriggerEventSourceService
107 > {}
108
109 export const UserPoolTriggerEventSource = Binding.Service<UserPoolTriggerEventSource>(
110 "AWS.Cognito.UserPoolTriggerEventSource",
111 );
112
113 /**
114 * Handle a Cognito user pool Lambda trigger with the current Lambda
115 * function.
116 *
117 * Provide `Lambda.UserPoolTriggerEventSource` on the hosting function to
118 * satisfy the requirement.
119 *
120 * @param userPool The user pool whose trigger to handle.
121 * @param props The trigger slot to handle.
122 * @param handler Invoked once per trigger event; the returned event is the
123 * response Cognito receives.
124 *
125 * @example Auto-confirm every sign-up
126 * ```typescript
127 * yield* Cognito.onUserPoolTrigger(pool, { trigger: "PreSignUp" }, (event) =>
128 * Effect.sync(() => Cognito.autoConfirmUser(event, { verifyEmail: true })),
129 * );
130 * ```
131 */
132 export function onUserPoolTrigger<T extends UserPoolTriggerName, Req = never>(
133 userPool: UserPool,
134 props: UserPoolTriggerProps<T>,
135 handler: UserPoolTriggerHandler<T, Req>,
136 ): Effect.Effect<void, never, UserPoolTriggerEventSource> {
137 return UserPoolTriggerEventSource.use((source) => source(userPool, props, handler));
138 }
139
140 /**
141 * Handle the `PreSignUp` trigger — runs before Cognito registers a new
142 * user; the handler can auto-confirm the user (see
143 * {@link autoConfirmUser}) or reject the sign-up.
144 */
145 export const onPreSignUp = <Req = never>(
146 userPool: UserPool,
147 handler: UserPoolTriggerHandler<"PreSignUp", Req>,
148 ) => onUserPoolTrigger(userPool, { trigger: "PreSignUp" }, handler);
149
150 /**
151 * Handle the `PostConfirmation` trigger — runs after a user confirms their
152 * account (welcome emails, provisioning rows, analytics).
153 */
154 export const onPostConfirmation = <Req = never>(
155 userPool: UserPool,
156 handler: UserPoolTriggerHandler<"PostConfirmation", Req>,
157 ) => onUserPoolTrigger(userPool, { trigger: "PostConfirmation" }, handler);
158
159 /**
160 * Handle the `PreTokenGeneration` trigger — runs before Cognito issues
161 * tokens; the handler can add, override, or suppress claims via
162 * `event.response.claimsOverrideDetails`.
163 */
164 export const onPreTokenGeneration = <Req = never>(
165 userPool: UserPool,
166 handler: UserPoolTriggerHandler<"PreTokenGeneration", Req>,
167 ) => onUserPoolTrigger(userPool, { trigger: "PreTokenGeneration" }, handler);
168
169 /**
170 * Handle the `CustomMessage` trigger — customizes the verification /
171 * invitation messages Cognito sends by mutating
172 * `event.response.emailSubject` / `emailMessage` / `smsMessage`.
173 */
174 export const onCustomMessage = <Req = never>(
175 userPool: UserPool,
176 handler: UserPoolTriggerHandler<"CustomMessage", Req>,
177 ) => onUserPoolTrigger(userPool, { trigger: "CustomMessage" }, handler);
178
179 /**
180 * Mutate a `PreSignUp` trigger event's response to auto-confirm the user
181 * (and optionally auto-verify their email / phone number), then return the
182 * event so it can be handed straight back to Cognito.
183 *
184 * @example Sign-ups arrive CONFIRMED, no confirmation code required
185 * ```typescript
186 * yield* Cognito.onPreSignUp(pool, (event) =>
187 * Effect.sync(() => Cognito.autoConfirmUser(event, { verifyEmail: true })),
188 * );
189 * ```
190 */
191 export const autoConfirmUser = <E extends lambda.PreSignUpTriggerEvent>(
192 event: E,
193 options?: {
194 /** Also mark the user's email as verified. @default false */
195 verifyEmail?: boolean;
196 /** Also mark the user's phone number as verified. @default false */
197 verifyPhone?: boolean;
198 },
199 ): E => {
200 event.response.autoConfirmUser = true;
201 if (options?.verifyEmail === true) {
202 event.response.autoVerifyEmail = true;
203 }
204 if (options?.verifyPhone === true) {
205 event.response.autoVerifyPhone = true;
206 }
207 return event;
208 };