@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, 04:45 UTC

main
ts 281 lines 9.87 KB
Raw
1 import * as cip from "@distilled.cloud/aws/cognito-identity-provider";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import type { Providers } from "../Providers.ts";
10
11 export interface UserPoolDomainProps {
12 /**
13 * The ID of the user pool the domain serves. Changing this triggers a
14 * replacement.
15 */
16 userPoolId: string;
17 /**
18 * The domain prefix (for `<prefix>.auth.<region>.amazoncognito.com`) or
19 * the full custom domain name when `certificateArn` is set. Prefixes must
20 * be lowercase alphanumeric/hyphens and globally unique per region. If
21 * omitted, a deterministic prefix is generated from the app, stage, and
22 * logical ID. Changing this triggers a replacement.
23 */
24 domain?: string;
25 /**
26 * ARN of an ACM certificate in us-east-1 for a custom domain. Custom
27 * domains can take 15-60 minutes to distribute.
28 */
29 certificateArn?: string;
30 /**
31 * The branding version served by the domain: `1` for hosted UI (classic),
32 * `2` for managed login.
33 * @default 2
34 */
35 managedLoginVersion?: number;
36 }
37
38 export interface UserPoolDomain extends Resource<
39 "AWS.Cognito.UserPoolDomain",
40 UserPoolDomainProps,
41 {
42 /** The domain prefix or full custom domain name. */
43 domain: string;
44 /** The ID of the user pool the domain serves. */
45 userPoolId: string;
46 /**
47 * The CloudFront distribution domain fronting the hosted endpoint —
48 * for custom domains, point a DNS alias record here.
49 */
50 cloudFrontDomain: string | undefined;
51 },
52 never,
53 Providers
54 > {}
55
56 /**
57 * A domain for an Amazon Cognito user pool's managed login and OAuth 2.0
58 * authorization server. Cognito-prefix domains
59 * (`<prefix>.auth.<region>.amazoncognito.com`) provision in seconds; custom
60 * domains require an ACM certificate in us-east-1 and can take 15-60 minutes.
61 * ### Creating a Domain
62 * **Example:** Cognito-Prefix Domain
63 * ```typescript
64 * import * as Cognito from "@alchemy.run/aws/Cognito";
65 *
66 * const pool = yield* Cognito.UserPool("Users", {});
67 * const domain = yield* Cognito.UserPoolDomain("AuthDomain", {
68 * userPoolId: pool.userPoolId,
69 * });
70 * ```
71 *
72 * **Example:** Explicit Prefix
73 * ```typescript
74 * const domain = yield* Cognito.UserPoolDomain("AuthDomain", {
75 * userPoolId: pool.userPoolId,
76 * domain: "my-app-auth",
77 * });
78 * ```
79 *
80 * ### Custom Domains
81 * **Example:** Custom Domain with an ACM Certificate
82 * ```typescript
83 * const domain = yield* Cognito.UserPoolDomain("AuthDomain", {
84 * userPoolId: pool.userPoolId,
85 * domain: "auth.example.com",
86 * certificateArn: certificate.certificateArn, // must be us-east-1
87 * });
88 * ```
89 *
90 * @resource
91 */
92 export const UserPoolDomain = Resource<UserPoolDomain>("AWS.Cognito.UserPoolDomain");
93
94 class DomainNotActive extends Data.TaggedError("DomainNotActive")<{
95 readonly domain: string;
96 readonly status: string | undefined;
97 }> {}
98
99 /**
100 * Cognito rejects domain prefixes containing the reserved words below, and
101 * requires lowercase alphanumerics/hyphens. Deterministically sanitize the
102 * generated physical name.
103 */
104 const sanitizeDomainPrefix = (name: string) => {
105 let sanitized = name.toLowerCase().replaceAll(/[^a-z0-9-]/g, "-");
106 for (const [reserved, replacement] of [
107 ["amazon", "amzn"],
108 ["cognito", "cgnto"],
109 ["aws", "ws"],
110 ] as const) {
111 while (sanitized.includes(reserved)) {
112 sanitized = sanitized.replaceAll(reserved, replacement);
113 }
114 }
115 return sanitized.replaceAll(/^-+|-+$/g, "").slice(0, 63);
116 };
117
118 /**
119 * Bounded retry while the domain has not yet reached ACTIVE. Explicitly
120 * typed so the conditional `Retry.Return` type never leaks into declaration
121 * emit (which would widen the provider layer to an `unknown` R).
122 */
123 const retryWhileNotActive = <A, E extends { _tag: string }, R>(
124 self: Effect.Effect<A, E, R>,
125 ): Effect.Effect<A, E, R> =>
126 Effect.retry(self, {
127 while: (e) => e._tag === "DomainNotActive",
128 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]),
129 });
130
131 /** Bounded wait for the domain to reach ACTIVE (up to ~60s). */
132 const waitUntilActive = (domain: string) =>
133 retryWhileNotActive(
134 cip.describeUserPoolDomain({ Domain: domain }).pipe(
135 Effect.flatMap((r) => {
136 const description = r.DomainDescription;
137 if (
138 description?.UserPoolId !== undefined &&
139 (description.Status === "ACTIVE" || description.Status === undefined)
140 ) {
141 return Effect.succeed(description);
142 }
143 return Effect.fail(new DomainNotActive({ domain, status: description?.Status }));
144 }),
145 ),
146 );
147
148 export const UserPoolDomainProvider = () =>
149 Provider.effect(
150 UserPoolDomain,
151 Effect.gen(function* () {
152 const createDomain = Effect.fn(function* (
153 id: string,
154 props: Pick<UserPoolDomainProps, "domain">,
155 ) {
156 if (props.domain) return props.domain;
157 const generated = yield* createPhysicalName({
158 id,
159 maxLength: 63,
160 lowercase: true,
161 });
162 return sanitizeDomainPrefix(generated);
163 });
164
165 const describeDomain = Effect.fn(function* (domain: string) {
166 const result = yield* cip
167 .describeUserPoolDomain({ Domain: domain })
168 .pipe(
169 Effect.catchTag("ResourceNotFoundException", () =>
170 Effect.succeed({} as cip.DescribeUserPoolDomainResponse),
171 ),
172 );
173 const description = result.DomainDescription;
174 // Cognito returns an empty description (no UserPoolId) for a
175 // non-existent domain rather than a NotFound error.
176 return description?.UserPoolId === undefined ? undefined : description;
177 });
178
179 const attributesOf = (description: cip.DomainDescriptionType) => ({
180 domain: description.Domain!,
181 userPoolId: description.UserPoolId!,
182 cloudFrontDomain: description.CloudFrontDistribution,
183 });
184
185 return UserPoolDomain.Provider.of({
186 stables: ["domain", "userPoolId"],
187
188 // Sub-resource keyed entirely by its user pool (userPoolId) with no global
189 // enumeration API of its own — nuke reaches it through the parent's
190 // deletion, so enumeration returns empty per the ProviderService
191 // doctrine.
192 list: () => Effect.succeed([]),
193
194 read: Effect.fn(function* ({ id, olds, output }) {
195 const domain = output?.domain ?? (yield* createDomain(id, olds ?? {}));
196 const observed = yield* describeDomain(domain);
197 return observed === undefined ? undefined : attributesOf(observed);
198 }),
199
200 diff: Effect.fn(function* ({ id, news, olds }) {
201 if (!isResolved(news)) return undefined;
202 const oldDomain = yield* createDomain(id, olds ?? {});
203 const newDomain = yield* createDomain(id, news ?? {});
204 if (oldDomain !== newDomain) return { action: "replace" } as const;
205 if (olds?.userPoolId !== news?.userPoolId) {
206 return { action: "replace" } as const;
207 }
208 }),
209
210 reconcile: Effect.fn(function* ({ id, news, output, session }) {
211 const domain = output?.domain ?? (yield* createDomain(id, news));
212
213 // 1. OBSERVE
214 let observed = yield* describeDomain(domain);
215
216 // 2. ENSURE
217 if (observed === undefined) {
218 yield* cip.createUserPoolDomain({
219 Domain: domain,
220 UserPoolId: news.userPoolId,
221 ManagedLoginVersion: news.managedLoginVersion,
222 CustomDomainConfig:
223 news.certificateArn === undefined
224 ? undefined
225 : { CertificateArn: news.certificateArn },
226 });
227 observed = yield* waitUntilActive(domain);
228 } else {
229 // 3. SYNC — branding version / certificate are mutable in place.
230 const drift =
231 (news.managedLoginVersion !== undefined &&
232 observed.ManagedLoginVersion !== news.managedLoginVersion) ||
233 (news.certificateArn !== undefined &&
234 observed.CustomDomainConfig?.CertificateArn !== news.certificateArn);
235 if (drift) {
236 yield* cip.updateUserPoolDomain({
237 Domain: domain,
238 UserPoolId: news.userPoolId,
239 ManagedLoginVersion: news.managedLoginVersion,
240 CustomDomainConfig:
241 news.certificateArn === undefined
242 ? undefined
243 : { CertificateArn: news.certificateArn },
244 });
245 observed = yield* waitUntilActive(domain);
246 }
247 }
248
249 yield* session.note(domain);
250 return attributesOf({ ...observed, Domain: domain });
251 }),
252
253 delete: Effect.fn(function* ({ output }) {
254 yield* cip
255 .deleteUserPoolDomain({
256 Domain: output.domain,
257 UserPoolId: output.userPoolId,
258 })
259 .pipe(
260 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
261 // The domain briefly rejects deletion while still provisioning
262 // or updating; InvalidParameterException surfaces that window.
263 (self) => retryWhileTransitioning(self),
264 );
265 }),
266 });
267 }),
268 );
269
270 /**
271 * Bounded retry over the delete-while-transitioning window. Explicitly typed
272 * (see {@link retryWhileNotActive}) to keep declaration emit clean.
273 */
274 const retryWhileTransitioning = <A, E extends { _tag: string }, R>(
275 self: Effect.Effect<A, E, R>,
276 ): Effect.Effect<A, E, R> =>
277 Effect.retry(self, {
278 while: (e) =>
279 e._tag === "InvalidParameterException" || e._tag === "ConcurrentModificationException",
280 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
281 });