@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 423 lines 15.1 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 { toWireMinutes } from "alchemy/Util/Duration";
7 import type * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 /**
14 * The authentication flows an app client is allowed to use.
15 */
16 export type ExplicitAuthFlow =
17 | "ALLOW_USER_PASSWORD_AUTH"
18 | "ALLOW_ADMIN_USER_PASSWORD_AUTH"
19 | "ALLOW_USER_SRP_AUTH"
20 | "ALLOW_USER_AUTH"
21 | "ALLOW_CUSTOM_AUTH"
22 | "ALLOW_REFRESH_TOKEN_AUTH";
23
24 /** Units for the token validity durations. */
25 export type TokenValidityUnit = "seconds" | "minutes" | "hours" | "days";
26
27 export interface UserPoolClientProps {
28 /**
29 * The ID of the user pool the client belongs to. Changing this triggers a
30 * replacement.
31 */
32 userPoolId: string;
33 /**
34 * Name of the app client. If omitted, a deterministic physical name is
35 * generated from the app, stage, and logical ID.
36 */
37 clientName?: string;
38 /**
39 * Whether to generate a client secret. Confidential (server-side) clients
40 * should use a secret; public (browser/mobile) clients must not.
41 * Changing this triggers a replacement.
42 * @default false
43 */
44 generateSecret?: boolean;
45 /**
46 * The authentication flows this client may use, e.g.
47 * `ALLOW_USER_PASSWORD_AUTH` for direct username/password sign-in or
48 * `ALLOW_USER_SRP_AUTH` for the SRP protocol.
49 * @default ALLOW_USER_SRP_AUTH, ALLOW_CUSTOM_AUTH, ALLOW_REFRESH_TOKEN_AUTH
50 */
51 explicitAuthFlows?: ExplicitAuthFlow[];
52 /**
53 * Refresh token validity (in `tokenValidityUnits.refreshToken`, default days).
54 * @default 30 days
55 */
56 refreshTokenValidity?: number;
57 /**
58 * Access token validity (in `tokenValidityUnits.accessToken`, default hours).
59 * @default 1 hour
60 */
61 accessTokenValidity?: number;
62 /**
63 * ID token validity (in `tokenValidityUnits.idToken`, default hours).
64 * @default 1 hour
65 */
66 idTokenValidity?: number;
67 /**
68 * Units for the three token validity numbers.
69 */
70 tokenValidityUnits?: {
71 accessToken?: TokenValidityUnit;
72 idToken?: TokenValidityUnit;
73 refreshToken?: TokenValidityUnit;
74 };
75 /**
76 * User attributes this client may read.
77 */
78 readAttributes?: string[];
79 /**
80 * User attributes this client may write.
81 */
82 writeAttributes?: string[];
83 /**
84 * Identity providers this client supports, e.g. `COGNITO` or the names of
85 * configured `IdentityProvider`s.
86 */
87 supportedIdentityProviders?: string[];
88 /**
89 * Allowed OAuth callback (redirect) URLs.
90 */
91 callbackUrls?: string[];
92 /**
93 * Allowed OAuth sign-out URLs.
94 */
95 logoutUrls?: string[];
96 /**
97 * Default redirect URI; must be listed in `callbackUrls`.
98 */
99 defaultRedirectUri?: string;
100 /**
101 * Allowed OAuth flows (`code`, `implicit`, `client_credentials`).
102 */
103 allowedOAuthFlows?: ("code" | "implicit" | "client_credentials")[];
104 /**
105 * Allowed OAuth scopes, e.g. `openid`, `email`, or resource-server scopes.
106 */
107 allowedOAuthScopes?: string[];
108 /**
109 * Must be `true` for the OAuth settings above to take effect.
110 * @default false
111 */
112 allowedOAuthFlowsUserPoolClient?: boolean;
113 /**
114 * `ENABLED` returns a generic error for sign-in attempts against
115 * non-existent users (prevents user enumeration); `LEGACY` returns the
116 * original errors.
117 * @default "ENABLED"
118 */
119 preventUserExistenceErrors?: "ENABLED" | "LEGACY";
120 /**
121 * Whether issued tokens can be revoked with `RevokeToken`.
122 * @default true
123 */
124 enableTokenRevocation?: boolean;
125 /**
126 * Duration of the session token in auth challenge flows, e.g.
127 * `"5 minutes"` (3-15 minutes). Rounded to whole minutes on the wire.
128 * @default 3 minutes
129 */
130 authSessionValidity?: Duration.Input;
131 }
132
133 export interface UserPoolClient extends Resource<
134 "AWS.Cognito.UserPoolClient",
135 UserPoolClientProps,
136 {
137 /** The generated app client ID. */
138 clientId: string;
139 /** The client secret; defined only when `generateSecret` is true. */
140 clientSecret: Redacted.Redacted<string> | undefined;
141 /** The name of the app client. */
142 clientName: string;
143 /** The ID of the user pool the client belongs to. */
144 userPoolId: string;
145 },
146 never,
147 Providers
148 > {}
149
150 /**
151 * An app client of an Amazon Cognito user pool. Applications authenticate
152 * against the pool through a client, which controls the allowed auth flows,
153 * token lifetimes, and OAuth settings.
154 * ### Creating an App Client
155 * **Example:** Public Client with Password Auth
156 * ```typescript
157 * import * as Cognito from "@alchemy.run/aws/Cognito";
158 *
159 * const pool = yield* Cognito.UserPool("Users", {});
160 * const client = yield* Cognito.UserPoolClient("Web", {
161 * userPoolId: pool.userPoolId,
162 * explicitAuthFlows: ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
163 * });
164 * ```
165 *
166 * **Example:** Confidential Client with a Secret
167 * ```typescript
168 * const server = yield* Cognito.UserPoolClient("Server", {
169 * userPoolId: pool.userPoolId,
170 * generateSecret: true,
171 * explicitAuthFlows: ["ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
172 * });
173 * ```
174 *
175 * ### Token Configuration
176 * **Example:** Short-Lived Access Tokens
177 * ```typescript
178 * const client = yield* Cognito.UserPoolClient("Web", {
179 * userPoolId: pool.userPoolId,
180 * accessTokenValidity: 30,
181 * idTokenValidity: 30,
182 * refreshTokenValidity: 7,
183 * tokenValidityUnits: {
184 * accessToken: "minutes",
185 * idToken: "minutes",
186 * refreshToken: "days",
187 * },
188 * });
189 * ```
190 *
191 * ### OAuth
192 * **Example:** Authorization Code Flow
193 * ```typescript
194 * const client = yield* Cognito.UserPoolClient("Web", {
195 * userPoolId: pool.userPoolId,
196 * allowedOAuthFlowsUserPoolClient: true,
197 * allowedOAuthFlows: ["code"],
198 * allowedOAuthScopes: ["openid", "email"],
199 * callbackUrls: ["https://example.com/callback"],
200 * supportedIdentityProviders: ["COGNITO"],
201 * });
202 * ```
203 *
204 * @resource
205 */
206 export const UserPoolClient = Resource<UserPoolClient>("AWS.Cognito.UserPoolClient");
207
208 const plain = (value: string | Redacted.Redacted<string> | undefined): string | undefined =>
209 value === undefined ? undefined : typeof value === "string" ? value : Redacted.value(value);
210
211 /** The mutable desired state, in wire shape — used both as the update body
212 * and (against the observed client) for drift detection. */
213 const desiredConfig = (news: UserPoolClientProps) => ({
214 ExplicitAuthFlows: news.explicitAuthFlows,
215 RefreshTokenValidity: news.refreshTokenValidity,
216 AccessTokenValidity: news.accessTokenValidity,
217 IdTokenValidity: news.idTokenValidity,
218 TokenValidityUnits:
219 news.tokenValidityUnits === undefined
220 ? undefined
221 : {
222 AccessToken: news.tokenValidityUnits.accessToken,
223 IdToken: news.tokenValidityUnits.idToken,
224 RefreshToken: news.tokenValidityUnits.refreshToken,
225 },
226 ReadAttributes: news.readAttributes,
227 WriteAttributes: news.writeAttributes,
228 SupportedIdentityProviders: news.supportedIdentityProviders,
229 CallbackURLs: news.callbackUrls,
230 LogoutURLs: news.logoutUrls,
231 DefaultRedirectURI: news.defaultRedirectUri,
232 AllowedOAuthFlows: news.allowedOAuthFlows,
233 AllowedOAuthScopes: news.allowedOAuthScopes,
234 AllowedOAuthFlowsUserPoolClient: news.allowedOAuthFlowsUserPoolClient,
235 PreventUserExistenceErrors: news.preventUserExistenceErrors,
236 EnableTokenRevocation: news.enableTokenRevocation,
237 // The Cognito wire unit for AuthSessionValidity is whole minutes.
238 AuthSessionValidity: toWireMinutes(news.authSessionValidity),
239 });
240
241 /** True when any prop the user specified differs from the observed client.
242 * Unspecified props are "don't care". */
243 const hasDrift = (
244 news: UserPoolClientProps,
245 clientName: string,
246 observed: cip.UserPoolClientType,
247 ) => {
248 if (observed.ClientName !== clientName) return true;
249 const desired = desiredConfig(news);
250 const observedSubset: Record<string, unknown> = {
251 ExplicitAuthFlows: [...(observed.ExplicitAuthFlows ?? [])].sort(),
252 RefreshTokenValidity: observed.RefreshTokenValidity,
253 AccessTokenValidity: observed.AccessTokenValidity,
254 IdTokenValidity: observed.IdTokenValidity,
255 TokenValidityUnits: {
256 AccessToken: observed.TokenValidityUnits?.AccessToken,
257 IdToken: observed.TokenValidityUnits?.IdToken,
258 RefreshToken: observed.TokenValidityUnits?.RefreshToken,
259 },
260 ReadAttributes: [...(observed.ReadAttributes ?? [])].sort(),
261 WriteAttributes: [...(observed.WriteAttributes ?? [])].sort(),
262 SupportedIdentityProviders: [...(observed.SupportedIdentityProviders ?? [])].sort(),
263 CallbackURLs: [...(observed.CallbackURLs ?? [])].sort(),
264 LogoutURLs: [...(observed.LogoutURLs ?? [])].sort(),
265 DefaultRedirectURI: observed.DefaultRedirectURI,
266 AllowedOAuthFlows: [...(observed.AllowedOAuthFlows ?? [])].sort(),
267 AllowedOAuthScopes: [...(observed.AllowedOAuthScopes ?? [])].sort(),
268 AllowedOAuthFlowsUserPoolClient: observed.AllowedOAuthFlowsUserPoolClient,
269 PreventUserExistenceErrors: observed.PreventUserExistenceErrors,
270 EnableTokenRevocation: observed.EnableTokenRevocation,
271 AuthSessionValidity: observed.AuthSessionValidity,
272 };
273 for (const [key, desiredValue] of Object.entries(desired)) {
274 if (desiredValue === undefined) continue;
275 const observedValue = observedSubset[key];
276 const normalizedDesired = Array.isArray(desiredValue) ? [...desiredValue].sort() : desiredValue;
277 if (JSON.stringify(normalizedDesired) !== JSON.stringify(observedValue)) {
278 return true;
279 }
280 }
281 return false;
282 };
283
284 export const UserPoolClientProvider = () =>
285 Provider.effect(
286 UserPoolClient,
287 Effect.gen(function* () {
288 const createName = Effect.fn(function* (
289 id: string,
290 props: Pick<UserPoolClientProps, "clientName">,
291 ) {
292 return props.clientName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
293 });
294
295 const describeClient = Effect.fn(function* (userPoolId: string, clientId: string) {
296 return yield* cip
297 .describeUserPoolClient({
298 UserPoolId: userPoolId,
299 ClientId: clientId,
300 })
301 .pipe(
302 Effect.map((r) => r.UserPoolClient),
303 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
304 );
305 });
306
307 /** Find a client of the pool by exact name (used when state was lost).
308 * The physical name embeds app/stage/id, so a match is ours. */
309 const findClientByName = Effect.fn(function* (userPoolId: string, clientName: string) {
310 const pages = yield* cip.listUserPoolClients
311 .pages({ UserPoolId: userPoolId, MaxResults: 60 })
312 .pipe(
313 Stream.runCollect,
314 Effect.catchTag("ResourceNotFoundException", () =>
315 Effect.succeed([] as cip.ListUserPoolClientsResponse[]),
316 ),
317 );
318 const match = Array.from(pages)
319 .flatMap((page) => page.UserPoolClients ?? [])
320 .find((client) => client.ClientName === clientName);
321 if (match?.ClientId === undefined) return undefined;
322 return yield* describeClient(userPoolId, plain(match.ClientId)!);
323 });
324
325 const attributesOf = (client: cip.UserPoolClientType) => {
326 const secret = plain(client.ClientSecret);
327 return {
328 clientId: plain(client.ClientId)!,
329 clientSecret: secret === undefined ? undefined : Redacted.make(secret),
330 clientName: client.ClientName!,
331 userPoolId: client.UserPoolId!,
332 };
333 };
334
335 return UserPoolClient.Provider.of({
336 stables: ["clientId", "userPoolId"],
337
338 // Sub-resource keyed entirely by its user pool (userPoolId) with no
339 // global enumeration API of its own — nuke reaches it through the
340 // parent pool's deletion, so enumeration returns empty per the
341 // ProviderService doctrine.
342 list: () => Effect.succeed([]),
343
344 read: Effect.fn(function* ({ id, olds, output }) {
345 const userPoolId = output?.userPoolId ?? olds?.userPoolId;
346 if (userPoolId === undefined) return undefined;
347 const observed =
348 output?.clientId !== undefined
349 ? yield* describeClient(userPoolId, output.clientId)
350 : yield* findClientByName(userPoolId, yield* createName(id, olds ?? {}));
351 return observed === undefined ? undefined : attributesOf(observed);
352 }),
353
354 diff: Effect.fn(function* ({ id, news, olds }) {
355 if (!isResolved(news)) return undefined;
356 if ((olds?.generateSecret ?? false) !== (news?.generateSecret ?? false)) {
357 return { action: "replace" } as const;
358 }
359 if (olds?.userPoolId !== news?.userPoolId) {
360 return { action: "replace" } as const;
361 }
362 const oldName = yield* createName(id, olds ?? {});
363 const newName = yield* createName(id, news ?? {});
364 if (oldName !== newName) {
365 // ClientName is mutable via UpdateUserPoolClient — fall through
366 // to the default update path.
367 return undefined;
368 }
369 }),
370
371 reconcile: Effect.fn(function* ({ id, news, output, session }) {
372 const clientName = output?.clientName ?? (yield* createName(id, news));
373 const userPoolId = news.userPoolId;
374
375 // 1. OBSERVE — output.clientId is only a cache.
376 let observed =
377 output?.clientId !== undefined
378 ? yield* describeClient(userPoolId, output.clientId)
379 : undefined;
380 if (observed === undefined) {
381 observed = yield* findClientByName(userPoolId, clientName);
382 }
383
384 // 2. ENSURE — create when missing.
385 if (observed === undefined) {
386 observed = yield* cip
387 .createUserPoolClient({
388 UserPoolId: userPoolId,
389 ClientName: clientName,
390 GenerateSecret: news.generateSecret,
391 ...desiredConfig(news),
392 })
393 .pipe(Effect.map((r) => r.UserPoolClient!));
394 } else if (hasDrift(news, clientName, observed)) {
395 // 3. SYNC — UpdateUserPoolClient resets omitted fields to
396 // defaults, so the body is the full desired state; skip the
397 // call when nothing drifted.
398 observed = yield* cip
399 .updateUserPoolClient({
400 UserPoolId: userPoolId,
401 ClientId: plain(observed.ClientId)!,
402 ClientName: clientName,
403 ...desiredConfig(news),
404 })
405 .pipe(Effect.map((r) => r.UserPoolClient!));
406 }
407
408 const attrs = attributesOf(observed);
409 yield* session.note(attrs.clientId);
410 return attrs;
411 }),
412
413 delete: Effect.fn(function* ({ output }) {
414 yield* cip
415 .deleteUserPoolClient({
416 UserPoolId: output.userPoolId,
417 ClientId: output.clientId,
418 })
419 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
420 }),
421 });
422 }),
423 );