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

main
ts 1,127 lines 42.6 KB
Raw
1 import * as cip from "@distilled.cloud/aws/cognito-identity-provider";
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 { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import { toWireDays } from "alchemy/Util/Duration";
9 import * as Data from "effect/Data";
10 import type * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14
15 /**
16 * Password complexity requirements enforced by the user pool at sign-up and
17 * password change.
18 */
19 export interface UserPoolPasswordPolicy {
20 /**
21 * Minimum password length (6-99).
22 * @default 8
23 */
24 minimumLength?: number;
25 /**
26 * Require at least one uppercase letter.
27 * @default true
28 */
29 requireUppercase?: boolean;
30 /**
31 * Require at least one lowercase letter.
32 * @default true
33 */
34 requireLowercase?: boolean;
35 /**
36 * Require at least one number.
37 * @default true
38 */
39 requireNumbers?: boolean;
40 /**
41 * Require at least one symbol.
42 * @default true
43 */
44 requireSymbols?: boolean;
45 /**
46 * Number of previous passwords a user cannot reuse. Requires the
47 * `ESSENTIALS` or `PLUS` feature tier.
48 */
49 passwordHistorySize?: number;
50 /**
51 * How long an admin-set temporary password stays valid, e.g.
52 * `"7 days"` (0-365 days). Rounded to whole days on the wire
53 * (`TemporaryPasswordValidityDays`).
54 * @default 7 days
55 */
56 temporaryPasswordValidity?: Duration.Input;
57 }
58
59 /**
60 * A custom schema attribute added to the user pool. Custom attributes are
61 * automatically prefixed with `custom:` by Cognito. Attributes can be added
62 * to an existing pool but never removed or changed — removing or modifying a
63 * declared attribute triggers a replacement.
64 */
65 export interface UserPoolSchemaAttribute {
66 /**
67 * Attribute name (without the `custom:` prefix; Cognito adds it).
68 * 1-20 characters.
69 */
70 name: string;
71 /**
72 * The data type of the attribute.
73 * @default "String"
74 */
75 attributeDataType?: "String" | "Number" | "DateTime" | "Boolean";
76 /**
77 * Whether users can change the value after it is set.
78 * @default true
79 */
80 mutable?: boolean;
81 /**
82 * Whether the attribute is required at sign-up. Custom attributes cannot
83 * be required.
84 * @default false
85 */
86 required?: boolean;
87 /**
88 * Min/max length constraints for `String` attributes (stringified numbers,
89 * matching the Cognito wire format).
90 */
91 stringConstraints?: { minLength?: string; maxLength?: string };
92 /**
93 * Min/max value constraints for `Number` attributes (stringified numbers,
94 * matching the Cognito wire format).
95 */
96 numberConstraints?: { minValue?: string; maxValue?: string };
97 /**
98 * Developer-only attributes can only be modified with IAM credentials
99 * (prefixed `dev:` in addition to `custom:`).
100 * @default false
101 */
102 developerOnlyAttribute?: boolean;
103 }
104
105 /**
106 * The user pool Lambda trigger slots that take a plain function ARN — the
107 * string-valued keys of the pool's `LambdaConfig`. The versioned custom
108 * sender slots are configured separately: `CustomEmailSender` through
109 * {@link UserPoolProps.customEmailSender} (+ `kmsKeyId`); `CustomSMSSender`
110 * is not modelled yet (an observed one is preserved, never cleared).
111 */
112 export type UserPoolTriggerName =
113 | "PreSignUp"
114 | "PostConfirmation"
115 | "PreAuthentication"
116 | "PostAuthentication"
117 | "CustomMessage"
118 | "DefineAuthChallenge"
119 | "CreateAuthChallenge"
120 | "VerifyAuthChallengeResponse"
121 | "PreTokenGeneration"
122 | "UserMigration";
123
124 const USER_POOL_TRIGGER_NAMES: readonly UserPoolTriggerName[] = [
125 "PreSignUp",
126 "PostConfirmation",
127 "PreAuthentication",
128 "PostAuthentication",
129 "CustomMessage",
130 "DefineAuthChallenge",
131 "CreateAuthChallenge",
132 "VerifyAuthChallengeResponse",
133 "PreTokenGeneration",
134 "UserMigration",
135 ];
136
137 /**
138 * Lambda trigger configuration for the pool: each key is a trigger slot,
139 * each value the ARN of the Lambda function Cognito invokes for it.
140 * Usually populated through the trigger event source
141 * (`Cognito.onPreSignUp(pool, ...)` etc.) rather than declared directly.
142 */
143 export interface UserPoolLambdaConfig extends Partial<Record<UserPoolTriggerName, string>> {}
144
145 /**
146 * The binding contract of a user pool: event sources contribute
147 * `LambdaConfig` trigger entries (trigger slot → function ARN) that the
148 * provider merges with `props.lambdaConfig` and syncs onto the pool.
149 */
150 export interface UserPoolBinding {
151 /** Trigger entries injected by `Cognito.onUserPoolTrigger` and friends. */
152 lambdaConfig?: UserPoolLambdaConfig;
153 }
154
155 /**
156 * Two different Lambda functions were registered for the same user pool
157 * trigger slot — Cognito supports exactly one function per trigger.
158 */
159 export class ConflictingUserPoolTrigger extends Data.TaggedError("ConflictingUserPoolTrigger")<{
160 readonly trigger: string;
161 readonly functionArns: readonly string[];
162 }> {}
163
164 /**
165 * The user pool's configuration is internally inconsistent (e.g. a custom
166 * email sender without the KMS key Cognito needs to encrypt the codes it
167 * hands to the function). Raised before any API call is made.
168 */
169 export class InvalidUserPoolConfiguration extends Data.TaggedError("InvalidUserPoolConfiguration")<{
170 readonly reason: string;
171 }> {}
172
173 /**
174 * A first-factor sign-in method for choice-based authentication.
175 */
176 export type UserPoolAuthFactor = "PASSWORD" | "EMAIL_OTP" | "SMS_OTP" | "WEB_AUTHN";
177
178 /**
179 * The sign-in policy of the pool — which first-factor authentication
180 * methods users may start with (choice-based authentication). Requires the
181 * `ESSENTIALS` or `PLUS` feature tier.
182 */
183 export interface UserPoolSignInPolicy {
184 /**
185 * First-factor sign-in methods the pool allows. `PASSWORD` is the
186 * classic username + password flow; `EMAIL_OTP` / `SMS_OTP` send a
187 * one-time code (email OTP is delivered through `customEmailSender` when
188 * one is configured); `WEB_AUTHN` is passkey sign-in.
189 * Passwordless factors require the `ESSENTIALS` or `PLUS` tier.
190 */
191 allowedFirstAuthFactors?: UserPoolAuthFactor[];
192 }
193
194 /**
195 * The `CustomEmailSender` Lambda trigger: Cognito invokes this function
196 * instead of sending email itself, passing the verification / OTP code
197 * encrypted with `kmsKeyId` (decrypt it with the AWS Encryption SDK).
198 * Requires {@link UserPoolProps.kmsKeyId}. The function must also grant
199 * `cognito-idp.amazonaws.com` invoke access (`AWS.Lambda.Permission`).
200 */
201 export interface UserPoolCustomEmailSender {
202 /** ARN of the Lambda function that delivers the pool's email messages. */
203 lambdaArn: string;
204 /**
205 * The custom sender event version the function understands.
206 * @default "V1_0"
207 */
208 lambdaVersion?: "V1_0";
209 }
210
211 /**
212 * How the user pool delivers its email messages (verification codes, OTPs,
213 * invitations): either Cognito's built-in, rate-limited delivery
214 * (`COGNITO_DEFAULT`) or your own verified Amazon SES identity
215 * (`DEVELOPER`). With `DEVELOPER`, the SES identity's policy must grant
216 * `cognito-idp.amazonaws.com` permission to send
217 * (`SES.EmailIdentityPolicy`).
218 */
219 export interface UserPoolEmailConfiguration {
220 /**
221 * Which sending account delivers the pool's email. `COGNITO_DEFAULT`
222 * uses Cognito's built-in delivery (limited daily volume);
223 * `DEVELOPER` sends through your own SES identity (`sourceArn`
224 * required) at your SES quota.
225 * @default "COGNITO_DEFAULT"
226 */
227 emailSendingAccount?: "COGNITO_DEFAULT" | "DEVELOPER";
228 /**
229 * ARN of a verified SES email identity (address or domain) in a
230 * supported region. Required when `emailSendingAccount` is `DEVELOPER`;
231 * with `COGNITO_DEFAULT` it customizes the FROM address while Cognito
232 * still handles delivery.
233 */
234 sourceArn?: string;
235 /**
236 * The FROM address, either bare (`no-reply@example.com`) or with a
237 * friendly display name (`"My App <no-reply@example.com>"`). Must be
238 * covered by the `sourceArn` identity.
239 */
240 from?: string;
241 /**
242 * The destination for replies to the pool's messages.
243 */
244 replyToEmailAddress?: string;
245 /**
246 * Name of an SES configuration set applied to email sent by the pool
247 * (event publishing, IP pool selection). `DEVELOPER` only.
248 */
249 configurationSet?: string;
250 }
251
252 /**
253 * An account recovery mechanism with its priority (1 is highest).
254 */
255 export interface UserPoolRecoveryMechanism {
256 /** Recovery channel. */
257 name: "verified_email" | "verified_phone_number" | "admin_only";
258 /** Priority of this mechanism; 1 is tried first. */
259 priority: number;
260 }
261
262 export interface UserPoolProps {
263 /**
264 * Name of the user pool. If omitted, a deterministic physical name is
265 * generated from the app, stage, and logical ID.
266 */
267 poolName?: string;
268 /**
269 * Password complexity policy for the pool.
270 */
271 passwordPolicy?: UserPoolPasswordPolicy;
272 /**
273 * Attributes users may sign in with *instead of* a username
274 * (`email` and/or `phone_number`). When set, Cognito generates an
275 * immutable UUID username and the listed attributes become sign-in
276 * identifiers. Mutually exclusive with `aliasAttributes`.
277 * Changing this triggers a replacement.
278 */
279 usernameAttributes?: ("email" | "phone_number")[];
280 /**
281 * Attributes that may be used as sign-in aliases *in addition to* the
282 * username (`email`, `phone_number`, `preferred_username`). Mutually
283 * exclusive with `usernameAttributes`. Changing this triggers a
284 * replacement.
285 */
286 aliasAttributes?: ("email" | "phone_number" | "preferred_username")[];
287 /**
288 * Attributes Cognito verifies automatically by sending a code
289 * (`email` and/or `phone_number`). `phone_number` requires SMS (SNS)
290 * configuration.
291 */
292 autoVerifiedAttributes?: ("email" | "phone_number")[];
293 /**
294 * Custom schema attributes. Attributes may be added to an existing pool;
295 * removing or changing a declared attribute triggers a replacement.
296 */
297 schema?: UserPoolSchemaAttribute[];
298 /**
299 * Choice-based authentication: the first-factor sign-in methods users may
300 * start with (`PASSWORD`, `EMAIL_OTP`, `SMS_OTP`, `WEB_AUTHN`). Requires
301 * the `ESSENTIALS` or `PLUS` tier when any passwordless factor is listed.
302 * When omitted the observed policy is left untouched.
303 */
304 signInPolicy?: UserPoolSignInPolicy;
305 /**
306 * Multi-factor authentication mode. `ON` requires SMS or TOTP setup for
307 * every user; avoid SMS-based MFA unless the account has SNS spend
308 * entitlements.
309 * @default "OFF"
310 */
311 mfaConfiguration?: "OFF" | "OPTIONAL" | "ON";
312 /**
313 * Account recovery mechanisms in priority order.
314 * @default verified_email then verified_phone_number
315 */
316 accountRecovery?: UserPoolRecoveryMechanism[];
317 /**
318 * When true the pool cannot be deleted until protection is disabled.
319 * @default false
320 */
321 deletionProtection?: boolean;
322 /**
323 * When true, only administrators (via `AdminCreateUser`) can create
324 * users — public `SignUp` is disabled.
325 * @default false
326 */
327 adminCreateUserOnly?: boolean;
328 /**
329 * Whether usernames are case sensitive. Changing this triggers a
330 * replacement.
331 * @default true (the API default)
332 */
333 usernameCaseSensitive?: boolean;
334 /**
335 * The feature tier of the user pool.
336 * @default "ESSENTIALS"
337 */
338 tier?: "LITE" | "ESSENTIALS" | "PLUS";
339 /**
340 * Lambda trigger configuration (trigger slot → function ARN). Merged with
341 * trigger entries injected through the binding contract by
342 * `Cognito.onUserPoolTrigger` / `onPreSignUp` / etc. — prefer those over
343 * declaring ARNs here, since the event source also creates the invoke
344 * Permission and registers the runtime handler.
345 */
346 lambdaConfig?: UserPoolLambdaConfig;
347 /**
348 * Route the pool's email messages (sign-up / OTP / recovery codes,
349 * temporary passwords) through your own Lambda function instead of
350 * Cognito's built-in delivery. Requires `kmsKeyId`. Omitting this on an
351 * existing pool clears the custom sender (Cognito falls back to its own
352 * email delivery); ordinary triggers and the other pool settings are
353 * never affected by adding or removing it.
354 */
355 customEmailSender?: UserPoolCustomEmailSender;
356 /**
357 * How the pool delivers its email messages: Cognito's built-in delivery
358 * (`COGNITO_DEFAULT`, the service default) or a verified SES identity
359 * (`DEVELOPER`) — no custom sender Lambda required. When omitted, an
360 * observed email configuration is preserved rather than reset to the
361 * service default.
362 */
363 emailConfiguration?: UserPoolEmailConfiguration;
364 /**
365 * ARN of the symmetric KMS key Cognito uses to encrypt the codes it
366 * passes to the custom sender function(s) (`LambdaConfig.KMSKeyID`).
367 * The principal running the deploy must hold `kms:CreateGrant` on the
368 * key — Cognito creates a grant against it when the pool is configured —
369 * and the sender function's role needs `kms:Decrypt`.
370 */
371 kmsKeyId?: string;
372 /**
373 * Tags to apply to the user pool. Merged with internal Alchemy tags.
374 */
375 tags?: Record<string, string>;
376 }
377
378 export interface UserPool extends Resource<
379 "AWS.Cognito.UserPool",
380 UserPoolProps,
381 {
382 /** The generated ID of the user pool, e.g. `us-west-2_AbCdEfGhI`. */
383 userPoolId: string;
384 /** The ARN of the user pool. */
385 userPoolArn: string;
386 /** The name of the user pool. */
387 userPoolName: string;
388 },
389 UserPoolBinding,
390 Providers
391 > {}
392
393 /**
394 * An Amazon Cognito user pool — a managed user directory that handles
395 * sign-up, sign-in, and token issuance (OIDC-compliant JWTs) for your
396 * application.
397 * ### Creating a User Pool
398 * **Example:** Basic User Pool
399 * ```typescript
400 * import * as Cognito from "@alchemy.run/aws/Cognito";
401 *
402 * const pool = yield* Cognito.UserPool("Users", {});
403 * ```
404 *
405 * **Example:** Email Sign-In with Password Policy
406 * ```typescript
407 * const pool = yield* Cognito.UserPool("Users", {
408 * usernameAttributes: ["email"],
409 * autoVerifiedAttributes: ["email"],
410 * passwordPolicy: {
411 * minimumLength: 12,
412 * requireSymbols: false,
413 * },
414 * });
415 * ```
416 *
417 * **Example:** Admin-Only User Creation
418 * ```typescript
419 * const pool = yield* Cognito.UserPool("Users", {
420 * adminCreateUserOnly: true,
421 * accountRecovery: [{ name: "admin_only", priority: 1 }],
422 * });
423 * ```
424 *
425 * ### Custom Attributes
426 * **Example:** Pool with Custom Schema Attributes
427 * ```typescript
428 * const pool = yield* Cognito.UserPool("Users", {
429 * schema: [
430 * { name: "tenantId", mutable: false },
431 * { name: "plan", attributeDataType: "String" },
432 * ],
433 * });
434 * ```
435 *
436 * ### Sending Email Through SES
437 * **Example:** OTP and Verification Email from a Verified SES Identity
438 * ```typescript
439 * const identity = yield* SES.EmailIdentity("Sender", {
440 * emailIdentity: "mail.example.com",
441 * });
442 * // allow Cognito to send through the identity
443 * yield* SES.EmailIdentityPolicy("CognitoSend", {
444 * emailIdentity: identity.emailIdentity,
445 * policyName: "cognito",
446 * policy: {
447 * Version: "2012-10-17",
448 * Statement: [{
449 * Effect: "Allow",
450 * Principal: { Service: "cognito-idp.amazonaws.com" },
451 * Action: ["ses:SendEmail", "ses:SendRawEmail"],
452 * Resource: identity.identityArn,
453 * }],
454 * },
455 * });
456 * const pool = yield* Cognito.UserPool("Users", {
457 * usernameAttributes: ["email"],
458 * autoVerifiedAttributes: ["email"],
459 * emailConfiguration: {
460 * emailSendingAccount: "DEVELOPER",
461 * sourceArn: identity.identityArn,
462 * from: "My App <no-reply@mail.example.com>",
463 * replyToEmailAddress: "support@example.com",
464 * },
465 * });
466 * ```
467 *
468 * ### Email OTP with a Custom Email Sender
469 * **Example:** Passwordless Email OTP Delivered by Your Own Lambda
470 * ```typescript
471 * const key = yield* KMS.Key("CodeKey", {});
472 * const sender = yield* Lambda.Function("EmailSender", {
473 * main: import.meta.url,
474 * });
475 * yield* Lambda.Permission("CognitoInvoke", {
476 * functionName: sender.functionName,
477 * action: "lambda:InvokeFunction",
478 * principal: "cognito-idp.amazonaws.com",
479 * });
480 * const pool = yield* Cognito.UserPool("Auth", {
481 * tier: "ESSENTIALS",
482 * usernameAttributes: ["email"],
483 * signInPolicy: { allowedFirstAuthFactors: ["PASSWORD", "EMAIL_OTP"] },
484 * customEmailSender: { lambdaArn: sender.functionArn },
485 * kmsKeyId: key.keyArn,
486 * });
487 * ```
488 *
489 * ### App Clients and Auth
490 * **Example:** Pool with an App Client
491 * ```typescript
492 * const pool = yield* Cognito.UserPool("Users", {});
493 * const client = yield* Cognito.UserPoolClient("Web", {
494 * userPoolId: pool.userPoolId,
495 * explicitAuthFlows: ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
496 * });
497 * ```
498 *
499 * @resource
500 */
501 export const UserPool = Resource<UserPool>("AWS.Cognito.UserPool");
502
503 /** Map camelCase password policy props to the Cognito wire shape (the wire
504 * unit for `TemporaryPasswordValidityDays` is whole days). */
505 const toWirePasswordPolicy = (policy: UserPoolPasswordPolicy | undefined) =>
506 policy === undefined
507 ? undefined
508 : {
509 MinimumLength: policy.minimumLength,
510 RequireUppercase: policy.requireUppercase,
511 RequireLowercase: policy.requireLowercase,
512 RequireNumbers: policy.requireNumbers,
513 RequireSymbols: policy.requireSymbols,
514 PasswordHistorySize: policy.passwordHistorySize,
515 TemporaryPasswordValidityDays: toWireDays(policy.temporaryPasswordValidity),
516 };
517
518 const toWireSchemaAttribute = (attribute: UserPoolSchemaAttribute) => ({
519 Name: attribute.name,
520 AttributeDataType: attribute.attributeDataType ?? "String",
521 Mutable: attribute.mutable ?? true,
522 Required: attribute.required ?? false,
523 DeveloperOnlyAttribute: attribute.developerOnlyAttribute,
524 StringAttributeConstraints:
525 attribute.stringConstraints === undefined
526 ? undefined
527 : {
528 MinLength: attribute.stringConstraints.minLength,
529 MaxLength: attribute.stringConstraints.maxLength,
530 },
531 NumberAttributeConstraints:
532 attribute.numberConstraints === undefined
533 ? undefined
534 : {
535 MinValue: attribute.numberConstraints.minValue,
536 MaxValue: attribute.numberConstraints.maxValue,
537 },
538 });
539
540 const toWireAccountRecovery = (mechanisms: UserPoolRecoveryMechanism[] | undefined) =>
541 mechanisms === undefined
542 ? undefined
543 : {
544 RecoveryMechanisms: mechanisms.map((m) => ({
545 Name: m.name,
546 Priority: m.priority,
547 })),
548 };
549
550 const toWireSignInPolicy = (policy: UserPoolSignInPolicy | undefined) =>
551 policy === undefined ? undefined : { AllowedFirstAuthFactors: policy.allowedFirstAuthFactors };
552
553 const toWireEmailConfiguration = (
554 config: UserPoolEmailConfiguration | undefined,
555 ): cip.EmailConfigurationType | undefined =>
556 config === undefined
557 ? undefined
558 : {
559 EmailSendingAccount: config.emailSendingAccount ?? "COGNITO_DEFAULT",
560 SourceArn: config.sourceArn,
561 From: config.from,
562 ReplyToEmailAddress: config.replyToEmailAddress,
563 ConfigurationSet: config.configurationSet,
564 };
565
566 /** Observed/desired email configuration with the service default filled in,
567 * for order- and absence-insensitive comparison (`JSON.stringify` drops the
568 * `undefined` members on both sides). */
569 const normalizedEmailConfiguration = (config: cip.EmailConfigurationType | undefined) => ({
570 emailSendingAccount: config?.EmailSendingAccount ?? "COGNITO_DEFAULT",
571 sourceArn: config?.SourceArn,
572 from: config?.From,
573 replyToEmailAddress: config?.ReplyToEmailAddress,
574 configurationSet: config?.ConfigurationSet,
575 });
576
577 const toWireCustomEmailSender = (
578 sender: UserPoolCustomEmailSender | undefined,
579 ): cip.CustomEmailLambdaVersionConfigType | undefined =>
580 sender === undefined
581 ? undefined
582 : {
583 LambdaArn: sender.lambdaArn,
584 LambdaVersion: sender.lambdaVersion ?? "V1_0",
585 };
586
587 const PASSWORDLESS_AUTH_FACTORS: readonly UserPoolAuthFactor[] = [
588 "EMAIL_OTP",
589 "SMS_OTP",
590 "WEB_AUTHN",
591 ];
592
593 /**
594 * Reject configurations Cognito would refuse (or silently mangle) before
595 * any API call is made.
596 */
597 const validateProps = (props: UserPoolProps) =>
598 props.customEmailSender !== undefined && props.kmsKeyId === undefined
599 ? Effect.fail(
600 new InvalidUserPoolConfiguration({
601 reason:
602 "customEmailSender requires kmsKeyId — Cognito encrypts the codes it passes to the custom sender with that KMS key",
603 }),
604 )
605 : props.emailConfiguration?.emailSendingAccount === "DEVELOPER" &&
606 props.emailConfiguration.sourceArn === undefined
607 ? Effect.fail(
608 new InvalidUserPoolConfiguration({
609 reason:
610 "emailConfiguration with emailSendingAccount DEVELOPER requires sourceArn — the ARN of the verified SES identity Cognito sends from",
611 }),
612 )
613 : props.tier === "LITE" &&
614 (props.signInPolicy?.allowedFirstAuthFactors ?? []).some((factor) =>
615 PASSWORDLESS_AUTH_FACTORS.includes(factor),
616 )
617 ? Effect.fail(
618 new InvalidUserPoolConfiguration({
619 reason:
620 "passwordless first-auth factors (EMAIL_OTP / SMS_OTP / WEB_AUTHN) require the ESSENTIALS or PLUS tier, not LITE",
621 }),
622 )
623 : Effect.void;
624
625 const tagRecordOf = (
626 tags: { [key: string]: string | undefined } | undefined,
627 ): Record<string, string> =>
628 Object.fromEntries(
629 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
630 );
631
632 /**
633 * The wire name an observed pool attribute would have for a declared custom
634 * schema attribute (Cognito prefixes `custom:`, or `dev:custom:` for
635 * developer-only attributes).
636 */
637 const customAttributeWireName = (attribute: UserPoolSchemaAttribute) =>
638 attribute.developerOnlyAttribute ? `dev:custom:${attribute.name}` : `custom:${attribute.name}`;
639
640 const schemaAttributeChanged = (before: UserPoolSchemaAttribute, after: UserPoolSchemaAttribute) =>
641 JSON.stringify(toWireSchemaAttribute(before)) !== JSON.stringify(toWireSchemaAttribute(after));
642
643 export const UserPoolProvider = () =>
644 Provider.effect(
645 UserPool,
646 Effect.gen(function* () {
647 const createName = Effect.fn(function* (id: string, props: Pick<UserPoolProps, "poolName">) {
648 return props.poolName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
649 });
650
651 const describePool = Effect.fn(function* (userPoolId: string) {
652 return yield* cip.describeUserPool({ UserPoolId: userPoolId }).pipe(
653 Effect.map((r) => r.UserPool),
654 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
655 );
656 });
657
658 /**
659 * Find a pool by exact name. Pool names are not unique, so return every
660 * candidate — callers disambiguate by ownership tags.
661 */
662 const findPoolsByName = Effect.fn(function* (name: string) {
663 const pages = yield* cip.listUserPools.pages({ MaxResults: 60 }).pipe(Stream.runCollect);
664 const candidates = Array.from(pages)
665 .flatMap((page) => page.UserPools ?? [])
666 .filter((pool) => pool.Name === name && pool.Id !== undefined);
667 return yield* Effect.forEach(candidates, (candidate) => describePool(candidate.Id!), {
668 concurrency: 3,
669 }).pipe(Effect.map((pools) => pools.filter((pool) => pool !== undefined)));
670 });
671
672 const attributesOf = (pool: cip.UserPoolType) => ({
673 userPoolId: pool.Id!,
674 userPoolArn: pool.Arn!,
675 userPoolName: pool.Name!,
676 });
677
678 /**
679 * The pool's desired trigger slots: `props.lambdaConfig` merged with
680 * the trigger entries contributed through the binding contract
681 * (`Cognito.onUserPoolTrigger` and friends). Fails when two different
682 * function ARNs target the same trigger slot.
683 */
684 const resolveTriggers = Effect.fn(function* (
685 news: UserPoolProps,
686 bindings: ReadonlyArray<UserPoolBinding | { data?: UserPoolBinding }>,
687 ) {
688 const merged: Partial<Record<UserPoolTriggerName, string>> = {};
689 const contributions = [
690 news.lambdaConfig,
691 ...bindings.map(
692 (binding) =>
693 (binding as { data?: UserPoolBinding }).data?.lambdaConfig ??
694 (binding as UserPoolBinding).lambdaConfig,
695 ),
696 ];
697 for (const config of contributions) {
698 if (config === undefined) continue;
699 for (const trigger of USER_POOL_TRIGGER_NAMES) {
700 const arn = config[trigger];
701 if (arn === undefined) continue;
702 const existing = merged[trigger];
703 if (existing !== undefined && existing !== arn) {
704 return yield* new ConflictingUserPoolTrigger({
705 trigger,
706 functionArns: [existing, arn],
707 });
708 }
709 merged[trigger] = arn;
710 }
711 }
712 return merged as UserPoolLambdaConfig;
713 });
714
715 /**
716 * The full desired `LambdaConfig` wire shape: the string trigger slots
717 * plus the versioned `CustomEmailSender` + `KMSKeyID` from props. The
718 * provider owns `LambdaConfig` outright, so a trigger or custom sender
719 * removed from the program is cleared on the pool. The one exception
720 * is `CustomSMSSender`, which the props cannot express yet: an
721 * observed one (and the KMS key it needs) is carried over rather than
722 * wiped by an unrelated update. Returns `undefined` when nothing is
723 * desired (omitting `LambdaConfig` clears it on both create and
724 * update).
725 */
726 const desiredLambdaConfig = (
727 news: UserPoolProps,
728 triggers: UserPoolLambdaConfig,
729 observed: cip.LambdaConfigType | undefined,
730 ): cip.LambdaConfigType | undefined => {
731 const customSMSSender = observed?.CustomSMSSender;
732 const config: cip.LambdaConfigType = {
733 ...triggers,
734 CustomEmailSender: toWireCustomEmailSender(news.customEmailSender),
735 CustomSMSSender: customSMSSender,
736 KMSKeyID:
737 news.kmsKeyId ?? (customSMSSender !== undefined ? observed?.KMSKeyID : undefined),
738 };
739 const present = Object.fromEntries(
740 Object.entries(config).filter(([, value]) => value !== undefined),
741 ) as cip.LambdaConfigType;
742 return Object.keys(present).length > 0 ? present : undefined;
743 };
744
745 /** True when the managed parts of the observed `LambdaConfig` differ
746 * from the desired one. */
747 const lambdaConfigDrifted = (
748 desired: cip.LambdaConfigType | undefined,
749 observed: cip.LambdaConfigType | undefined,
750 ) => {
751 for (const trigger of USER_POOL_TRIGGER_NAMES) {
752 if (desired?.[trigger] !== observed?.[trigger]) return true;
753 }
754 if (
755 desired?.CustomEmailSender?.LambdaArn !== observed?.CustomEmailSender?.LambdaArn ||
756 desired?.CustomEmailSender?.LambdaVersion !== observed?.CustomEmailSender?.LambdaVersion
757 ) {
758 return true;
759 }
760 return desired?.KMSKeyID !== observed?.KMSKeyID;
761 };
762
763 /** The update body sent to `updateUserPool` — always the full desired
764 * state, because Cognito resets any omitted field to its default.
765 * Props the user left undefined are "don't care" (see `hasDrift`), so
766 * their OBSERVED value is echoed back rather than dropped — an update
767 * to one setting must not reset another to its default. */
768 const desiredUpdate = (
769 news: UserPoolProps,
770 observed: cip.UserPoolType,
771 lambdaConfig: cip.LambdaConfigType | undefined,
772 ): Omit<cip.UpdateUserPoolRequest, "UserPoolId"> => {
773 const PasswordPolicy =
774 news.passwordPolicy === undefined
775 ? observed.Policies?.PasswordPolicy
776 : toWirePasswordPolicy(news.passwordPolicy);
777 const SignInPolicy =
778 news.signInPolicy === undefined
779 ? observed.Policies?.SignInPolicy
780 : toWireSignInPolicy(news.signInPolicy);
781 return {
782 LambdaConfig: lambdaConfig,
783 // updateUserPool resets an omitted EmailConfiguration to the
784 // service default — echo the OBSERVED configuration back when the
785 // prop is undefined so unrelated updates never clear it.
786 EmailConfiguration:
787 news.emailConfiguration === undefined
788 ? observed.EmailConfiguration
789 : toWireEmailConfiguration(news.emailConfiguration),
790 Policies:
791 PasswordPolicy === undefined && SignInPolicy === undefined
792 ? undefined
793 : { PasswordPolicy, SignInPolicy },
794 DeletionProtection: news.deletionProtection ? "ACTIVE" : "INACTIVE",
795 AutoVerifiedAttributes: news.autoVerifiedAttributes ?? observed.AutoVerifiedAttributes,
796 MfaConfiguration: news.mfaConfiguration ?? "OFF",
797 AdminCreateUserConfig:
798 news.adminCreateUserOnly === undefined
799 ? observed.AdminCreateUserConfig === undefined
800 ? undefined
801 : {
802 // never echo the deprecated UnusedAccountValidityDays —
803 // Cognito rejects it next to TemporaryPasswordValidityDays
804 AllowAdminCreateUserOnly:
805 observed.AdminCreateUserConfig.AllowAdminCreateUserOnly,
806 InviteMessageTemplate: observed.AdminCreateUserConfig.InviteMessageTemplate,
807 }
808 : { AllowAdminCreateUserOnly: news.adminCreateUserOnly },
809 AccountRecoverySetting:
810 news.accountRecovery === undefined
811 ? observed.AccountRecoverySetting
812 : toWireAccountRecovery(news.accountRecovery),
813 UserPoolTier: news.tier ?? observed.UserPoolTier,
814 };
815 };
816
817 /** Canonicalize a recovery-mechanism list for order-insensitive
818 * comparison. */
819 const canonicalRecovery = (
820 mechanisms: {
821 priority: number | undefined;
822 name: string | undefined;
823 }[],
824 ) =>
825 mechanisms
826 .map((m) => `${m.priority}:${m.name}`)
827 .sort()
828 .join(",");
829
830 /** Full password policy with the Cognito API defaults filled in, so a
831 * partial desired policy compares fairly against the observed one.
832 * Operates on the wire shape — `temporaryPasswordValidityDays` is a
833 * whole number of days (desired durations are converted first). */
834 const normalizedPasswordPolicy = (
835 policy: Omit<UserPoolPasswordPolicy, "temporaryPasswordValidity"> & {
836 temporaryPasswordValidityDays?: number;
837 },
838 ): Required<
839 Omit<UserPoolPasswordPolicy, "passwordHistorySize" | "temporaryPasswordValidity">
840 > & {
841 passwordHistorySize: number | undefined;
842 temporaryPasswordValidityDays: number;
843 } => ({
844 minimumLength: policy.minimumLength ?? 8,
845 requireUppercase: policy.requireUppercase ?? true,
846 requireLowercase: policy.requireLowercase ?? true,
847 requireNumbers: policy.requireNumbers ?? true,
848 requireSymbols: policy.requireSymbols ?? true,
849 passwordHistorySize: policy.passwordHistorySize,
850 temporaryPasswordValidityDays: policy.temporaryPasswordValidityDays ?? 7,
851 });
852
853 /** True when the observed pool differs from the desired mutable state.
854 * Props the user left undefined are "don't care" and never drift —
855 * except `LambdaConfig`, which the provider owns outright (bindings
856 * contribute to it), so a trigger or custom sender removed from the
857 * program is drift that clears the observed entry. */
858 const hasDrift = (
859 news: UserPoolProps,
860 observed: cip.UserPoolType,
861 lambdaConfig: cip.LambdaConfigType | undefined,
862 ) => {
863 if (lambdaConfigDrifted(lambdaConfig, observed.LambdaConfig)) {
864 return true;
865 }
866 if (
867 news.signInPolicy?.allowedFirstAuthFactors !== undefined &&
868 [...news.signInPolicy.allowedFirstAuthFactors].sort().join(",") !==
869 [...(observed.Policies?.SignInPolicy?.AllowedFirstAuthFactors ?? [])].sort().join(",")
870 ) {
871 return true;
872 }
873 if (news.passwordPolicy !== undefined) {
874 const desired = normalizedPasswordPolicy({
875 ...news.passwordPolicy,
876 temporaryPasswordValidityDays: toWireDays(
877 news.passwordPolicy.temporaryPasswordValidity,
878 ),
879 });
880 const actual = normalizedPasswordPolicy({
881 minimumLength: observed.Policies?.PasswordPolicy?.MinimumLength,
882 requireUppercase: observed.Policies?.PasswordPolicy?.RequireUppercase,
883 requireLowercase: observed.Policies?.PasswordPolicy?.RequireLowercase,
884 requireNumbers: observed.Policies?.PasswordPolicy?.RequireNumbers,
885 requireSymbols: observed.Policies?.PasswordPolicy?.RequireSymbols,
886 passwordHistorySize: observed.Policies?.PasswordPolicy?.PasswordHistorySize,
887 temporaryPasswordValidityDays:
888 observed.Policies?.PasswordPolicy?.TemporaryPasswordValidityDays,
889 });
890 if (JSON.stringify(desired) !== JSON.stringify(actual)) return true;
891 }
892 if (
893 (news.deletionProtection ? "ACTIVE" : "INACTIVE") !==
894 (observed.DeletionProtection ?? "INACTIVE")
895 ) {
896 return true;
897 }
898 if (
899 news.autoVerifiedAttributes !== undefined &&
900 [...news.autoVerifiedAttributes].sort().join(",") !==
901 [...(observed.AutoVerifiedAttributes ?? [])].sort().join(",")
902 ) {
903 return true;
904 }
905 if ((news.mfaConfiguration ?? "OFF") !== (observed.MfaConfiguration ?? "OFF")) {
906 return true;
907 }
908 if (
909 news.emailConfiguration !== undefined &&
910 JSON.stringify(
911 normalizedEmailConfiguration(toWireEmailConfiguration(news.emailConfiguration)),
912 ) !== JSON.stringify(normalizedEmailConfiguration(observed.EmailConfiguration))
913 ) {
914 return true;
915 }
916 if (
917 news.adminCreateUserOnly !== undefined &&
918 news.adminCreateUserOnly !==
919 (observed.AdminCreateUserConfig?.AllowAdminCreateUserOnly ?? false)
920 ) {
921 return true;
922 }
923 if (
924 news.accountRecovery !== undefined &&
925 canonicalRecovery(news.accountRecovery) !==
926 canonicalRecovery(
927 (observed.AccountRecoverySetting?.RecoveryMechanisms ?? []).map((m) => ({
928 priority: m.Priority,
929 name: m.Name,
930 })),
931 )
932 ) {
933 return true;
934 }
935 if (news.tier !== undefined && news.tier !== observed.UserPoolTier) {
936 return true;
937 }
938 return false;
939 };
940
941 return UserPool.Provider.of({
942 stables: ["userPoolId", "userPoolArn"],
943
944 list: () =>
945 Effect.gen(function* () {
946 const pages = yield* cip.listUserPools
947 .pages({ MaxResults: 60 })
948 .pipe(Stream.runCollect);
949 const descriptions = Array.from(pages).flatMap((page) => page.UserPools ?? []);
950 const pools = yield* Effect.forEach(
951 descriptions.filter((d) => d.Id !== undefined),
952 (d) => describePool(d.Id!),
953 { concurrency: 5 },
954 );
955 return pools.filter((pool) => pool !== undefined).map((pool) => attributesOf(pool));
956 }),
957
958 read: Effect.fn(function* ({ id, olds, output }) {
959 if (output?.userPoolId !== undefined) {
960 const pool = yield* describePool(output.userPoolId);
961 if (pool === undefined) return undefined;
962 const attrs = attributesOf(pool);
963 const tags = tagRecordOf(pool.UserPoolTags);
964 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
965 }
966 const name = yield* createName(id, olds ?? {});
967 const pools = yield* findPoolsByName(name);
968 if (pools.length === 0) return undefined;
969 for (const pool of pools) {
970 if (yield* hasAlchemyTags(id, tagRecordOf(pool.UserPoolTags))) {
971 return attributesOf(pool);
972 }
973 }
974 return Unowned(attributesOf(pools[0]!));
975 }),
976
977 diff: Effect.fn(function* ({ id, news, olds }) {
978 if (!isResolved(news)) return undefined;
979 const oldName = yield* createName(id, olds ?? {});
980 const newName = yield* createName(id, news ?? {});
981 if (oldName !== newName) return { action: "replace" } as const;
982 // sign-in configuration is immutable
983 if (
984 JSON.stringify(olds?.usernameAttributes ?? []) !==
985 JSON.stringify(news?.usernameAttributes ?? []) ||
986 JSON.stringify(olds?.aliasAttributes ?? []) !==
987 JSON.stringify(news?.aliasAttributes ?? []) ||
988 (olds?.usernameCaseSensitive ?? true) !== (news?.usernameCaseSensitive ?? true)
989 ) {
990 return { action: "replace" } as const;
991 }
992 // schema attributes are add-only: removal or mutation ⇒ replace
993 const oldSchema = olds?.schema ?? [];
994 const newSchema = news?.schema ?? [];
995 for (const before of oldSchema) {
996 const after = newSchema.find((a) => a.name === before.name);
997 if (after === undefined || schemaAttributeChanged(before, after)) {
998 return { action: "replace" } as const;
999 }
1000 }
1001 }),
1002
1003 reconcile: Effect.fn(function* ({ id, news = {}, output, session, bindings }) {
1004 yield* validateProps(news);
1005 const name = output?.userPoolName ?? (yield* createName(id, news));
1006 const internalTags = yield* createInternalTags(id);
1007 const desiredTags = { ...news.tags, ...internalTags };
1008 const triggers = yield* resolveTriggers(news, bindings);
1009
1010 // 1. OBSERVE — output.userPoolId is only a cache; fall back to a
1011 // name search so out-of-band deletes and adoption converge.
1012 let observed =
1013 output?.userPoolId !== undefined ? yield* describePool(output.userPoolId) : undefined;
1014 if (observed === undefined) {
1015 // Recover from state loss by name — only take over a pool that
1016 // carries our ownership tags (adoption flows arrive with output
1017 // set, not through this path).
1018 const candidates = yield* findPoolsByName(name);
1019 for (const candidate of candidates) {
1020 if (yield* hasAlchemyTags(id, tagRecordOf(candidate.UserPoolTags))) {
1021 observed = candidate;
1022 break;
1023 }
1024 }
1025 }
1026
1027 // 2. ENSURE — create when missing.
1028 if (observed === undefined) {
1029 observed = yield* cip
1030 .createUserPool({
1031 PoolName: name,
1032 LambdaConfig: desiredLambdaConfig(news, triggers, undefined),
1033 Policies:
1034 news.passwordPolicy === undefined && news.signInPolicy === undefined
1035 ? undefined
1036 : {
1037 PasswordPolicy: toWirePasswordPolicy(news.passwordPolicy),
1038 SignInPolicy: toWireSignInPolicy(news.signInPolicy),
1039 },
1040 DeletionProtection: news.deletionProtection ? "ACTIVE" : "INACTIVE",
1041 EmailConfiguration: toWireEmailConfiguration(news.emailConfiguration),
1042 UsernameAttributes: news.usernameAttributes,
1043 AliasAttributes: news.aliasAttributes,
1044 AutoVerifiedAttributes: news.autoVerifiedAttributes,
1045 Schema: news.schema?.map(toWireSchemaAttribute),
1046 MfaConfiguration: news.mfaConfiguration ?? "OFF",
1047 AdminCreateUserConfig:
1048 news.adminCreateUserOnly === undefined
1049 ? undefined
1050 : { AllowAdminCreateUserOnly: news.adminCreateUserOnly },
1051 AccountRecoverySetting: toWireAccountRecovery(news.accountRecovery),
1052 UsernameConfiguration:
1053 news.usernameCaseSensitive === undefined
1054 ? undefined
1055 : { CaseSensitive: news.usernameCaseSensitive },
1056 UserPoolTier: news.tier,
1057 UserPoolTags: desiredTags,
1058 })
1059 .pipe(Effect.map((r) => r.UserPool!));
1060 } else {
1061 // 3. SYNC — updateUserPool resets omitted fields to defaults, so
1062 // the body is always the full desired mutable state; skip the
1063 // call entirely when nothing drifted.
1064 const lambdaConfig = desiredLambdaConfig(news, triggers, observed.LambdaConfig);
1065 if (hasDrift(news, observed, lambdaConfig)) {
1066 yield* cip.updateUserPool({
1067 UserPoolId: observed.Id!,
1068 ...desiredUpdate(news, observed, lambdaConfig),
1069 });
1070 }
1071
1072 // 3b. SYNC SCHEMA — custom attributes are add-only.
1073 const observedNames = new Set(
1074 (observed.SchemaAttributes ?? [])
1075 .map((attribute) => attribute.Name)
1076 .filter((n): n is string => n !== undefined),
1077 );
1078 const missing = (news.schema ?? []).filter(
1079 (attribute) =>
1080 !observedNames.has(customAttributeWireName(attribute)) &&
1081 !observedNames.has(attribute.name),
1082 );
1083 if (missing.length > 0) {
1084 yield* cip.addCustomAttributes({
1085 UserPoolId: observed.Id!,
1086 CustomAttributes: missing.map(toWireSchemaAttribute),
1087 });
1088 }
1089 }
1090
1091 const userPoolId = observed.Id!;
1092 const userPoolArn = observed.Arn!;
1093
1094 // 3c. SYNC TAGS — diff against OBSERVED cloud tags so adoption
1095 // converges (never olds/output).
1096 const observedTags = yield* cip.listTagsForResource({ ResourceArn: userPoolArn }).pipe(
1097 Effect.map((r) => tagRecordOf(r.Tags)),
1098 Effect.catchTag("ResourceNotFoundException", () =>
1099 Effect.succeed({} as Record<string, string>),
1100 ),
1101 );
1102 const { upsert, removed } = diffTags(observedTags, desiredTags);
1103 if (upsert.length > 0) {
1104 yield* cip.tagResource({
1105 ResourceArn: userPoolArn,
1106 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
1107 });
1108 }
1109 if (removed.length > 0) {
1110 yield* cip.untagResource({
1111 ResourceArn: userPoolArn,
1112 TagKeys: removed,
1113 });
1114 }
1115
1116 yield* session.note(userPoolId);
1117 return { userPoolId, userPoolArn, userPoolName: name };
1118 }),
1119
1120 delete: Effect.fn(function* ({ output }) {
1121 yield* cip
1122 .deleteUserPool({ UserPoolId: output.userPoolId })
1123 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
1124 }),
1125 });
1126 }),
1127 );