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

main
ts 324 lines 11.3 KB
Raw
1 import * as cip from "@distilled.cloud/aws/cognito-identity-provider";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import type { Providers } from "../Providers.ts";
8
9 /**
10 * An image asset (logo, favicon, background, …) attached to a managed login
11 * branding style, per color mode.
12 */
13 export interface ManagedLoginBrandingAsset {
14 /** Which slot of the managed login pages the asset fills. */
15 category:
16 | "FAVICON_ICO"
17 | "FAVICON_SVG"
18 | "EMAIL_GRAPHIC"
19 | "SMS_GRAPHIC"
20 | "AUTH_APP_GRAPHIC"
21 | "PASSWORD_GRAPHIC"
22 | "PASSKEY_GRAPHIC"
23 | "PAGE_HEADER_LOGO"
24 | "PAGE_HEADER_BACKGROUND"
25 | "PAGE_FOOTER_LOGO"
26 | "PAGE_FOOTER_BACKGROUND"
27 | "PAGE_BACKGROUND"
28 | "FORM_BACKGROUND"
29 | "FORM_LOGO"
30 | "IDP_BUTTON_ICON";
31 /** The color scheme the asset applies to. */
32 colorMode: "LIGHT" | "DARK" | "DYNAMIC";
33 /** The file type of the asset. */
34 extension: "ICO" | "JPEG" | "PNG" | "SVG" | "WEBP";
35 /** The image file, as bytes (max 2 MB). */
36 bytes?: Uint8Array;
37 /** For `IDP_BUTTON_ICON` assets, the identity provider the icon is for. */
38 resourceId?: string;
39 }
40
41 export interface ManagedLoginBrandingProps {
42 /**
43 * The ID of the user pool the branding style belongs to. Changing this
44 * triggers a replacement.
45 */
46 userPoolId: string;
47 /**
48 * The ID of the app client the branding style is assigned to. Each app
49 * client can have exactly one style. Changing this triggers a
50 * replacement.
51 */
52 clientId: string;
53 /**
54 * Apply Cognito's default branding instead of custom `settings` /
55 * `assets`. This is what makes a fresh pool's managed login pages render
56 * without a one-time console step.
57 * @default true when neither `settings` nor `assets` is provided
58 */
59 useCognitoProvidedValues?: boolean;
60 /**
61 * The branding settings JSON document (colors, component styles, …) in
62 * the shape produced by the managed login branding designer / returned by
63 * `DescribeManagedLoginBranding`.
64 */
65 settings?: Record<string, unknown>;
66 /**
67 * Image assets for the branding style (logos, favicons, backgrounds),
68 * one per category + color mode.
69 */
70 assets?: ManagedLoginBrandingAsset[];
71 }
72
73 export interface ManagedLoginBranding extends Resource<
74 "AWS.Cognito.ManagedLoginBranding",
75 ManagedLoginBrandingProps,
76 {
77 /** The generated ID of the branding style. */
78 managedLoginBrandingId: string;
79 /** The ID of the user pool the style belongs to. */
80 userPoolId: string;
81 /** The ID of the app client the style is assigned to. */
82 clientId: string;
83 },
84 never,
85 Providers
86 > {}
87
88 /**
89 * A managed login branding style for an Amazon Cognito user pool app
90 * client. Assigning a style (even just Cognito's provided defaults) is what
91 * activates the hosted managed login pages — a `UserPoolDomain` with
92 * `managedLoginVersion: 2` serves them end-to-end without any console step.
93 * ### Activating Managed Login
94 * **Example:** Default Branding for a Hosted Login Domain
95 * ```typescript
96 * import * as Cognito from "@alchemy.run/aws/Cognito";
97 *
98 * const pool = yield* Cognito.UserPool("Users", {});
99 * const client = yield* Cognito.UserPoolClient("Web", {
100 * userPoolId: pool.userPoolId,
101 * callbackUrls: ["https://example.com/callback"],
102 * allowedOAuthFlowsUserPoolClient: true,
103 * allowedOAuthFlows: ["code"],
104 * allowedOAuthScopes: ["openid", "email"],
105 * });
106 * const domain = yield* Cognito.UserPoolDomain("AuthDomain", {
107 * userPoolId: pool.userPoolId,
108 * managedLoginVersion: 2,
109 * });
110 * yield* Cognito.ManagedLoginBranding("Branding", {
111 * userPoolId: pool.userPoolId,
112 * clientId: client.clientId,
113 * });
114 * ```
115 *
116 * ### Custom Branding
117 * **Example:** Custom Settings and a Logo Asset
118 * ```typescript
119 * yield* Cognito.ManagedLoginBranding("Branding", {
120 * userPoolId: pool.userPoolId,
121 * clientId: client.clientId,
122 * settings: brandingSettings, // designer-exported JSON document
123 * assets: [{
124 * category: "FORM_LOGO",
125 * colorMode: "LIGHT",
126 * extension: "PNG",
127 * bytes: logoBytes,
128 * }],
129 * });
130 * ```
131 *
132 * @resource
133 */
134 export const ManagedLoginBranding = Resource<ManagedLoginBranding>(
135 "AWS.Cognito.ManagedLoginBranding",
136 );
137
138 const toWireAssets = (
139 assets: ManagedLoginBrandingAsset[] | undefined,
140 ): cip.AssetType[] | undefined =>
141 assets?.map((asset) => ({
142 Category: asset.category,
143 ColorMode: asset.colorMode,
144 Extension: asset.extension,
145 Bytes: asset.bytes,
146 ResourceId: asset.resourceId,
147 }));
148
149 /** Canonicalize an asset list for order-insensitive comparison; bytes are
150 * folded to base64. */
151 const canonicalAssets = (assets: cip.AssetType[] | undefined) =>
152 (assets ?? [])
153 .map((asset) =>
154 [
155 asset.Category,
156 asset.ColorMode,
157 asset.Extension,
158 asset.ResourceId ?? "",
159 asset.Bytes === undefined ? "" : Buffer.from(asset.Bytes).toString("base64"),
160 ].join(":"),
161 )
162 .sort()
163 .join(",");
164
165 /**
166 * Whether the style should carry Cognito's provided default values: an
167 * explicit prop wins, otherwise defaults to `true` exactly when no custom
168 * settings/assets are declared.
169 */
170 const desiredUseProvidedValues = (news: ManagedLoginBrandingProps) =>
171 news.useCognitoProvidedValues ?? (news.settings === undefined && news.assets === undefined);
172
173 /**
174 * Bounded retry over the concurrent-modification window (branding updates
175 * can race domain/pool operations). Explicitly typed so the conditional
176 * `Retry.Return` type never leaks into declaration emit.
177 */
178 const retryWhileConcurrent = <A, E extends { _tag: string }, R>(
179 self: Effect.Effect<A, E, R>,
180 ): Effect.Effect<A, E, R> =>
181 Effect.retry(self, {
182 while: (e) => e._tag === "ConcurrentModificationException",
183 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
184 });
185
186 export const ManagedLoginBrandingProvider = () =>
187 Provider.effect(
188 ManagedLoginBranding,
189 Effect.gen(function* () {
190 const describeById = Effect.fn(function* (
191 userPoolId: string,
192 managedLoginBrandingId: string,
193 ) {
194 return yield* cip
195 .describeManagedLoginBranding({
196 UserPoolId: userPoolId,
197 ManagedLoginBrandingId: managedLoginBrandingId,
198 })
199 .pipe(
200 Effect.map((r) => r.ManagedLoginBranding),
201 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
202 );
203 });
204
205 const describeByClient = Effect.fn(function* (userPoolId: string, clientId: string) {
206 return yield* cip
207 .describeManagedLoginBrandingByClient({
208 UserPoolId: userPoolId,
209 ClientId: clientId,
210 })
211 .pipe(
212 Effect.map((r) => r.ManagedLoginBranding),
213 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
214 );
215 });
216
217 return ManagedLoginBranding.Provider.of({
218 stables: ["managedLoginBrandingId", "userPoolId", "clientId"],
219
220 // Sub-resource keyed entirely by its user pool (userPoolId) with no
221 // global enumeration API of its own — nuke reaches it through the
222 // parent's deletion, so enumeration returns empty per the
223 // ProviderService doctrine.
224 list: () => Effect.succeed([]),
225
226 read: Effect.fn(function* ({ olds, output }) {
227 const userPoolId = output?.userPoolId ?? olds?.userPoolId;
228 const clientId = output?.clientId ?? olds?.clientId;
229 if (userPoolId === undefined) return undefined;
230 const observed =
231 output?.managedLoginBrandingId !== undefined
232 ? yield* describeById(userPoolId, output.managedLoginBrandingId)
233 : clientId !== undefined
234 ? yield* describeByClient(userPoolId, clientId)
235 : undefined;
236 if (observed?.ManagedLoginBrandingId === undefined) return undefined;
237 return {
238 managedLoginBrandingId: observed.ManagedLoginBrandingId,
239 userPoolId,
240 clientId: clientId!,
241 };
242 }),
243
244 diff: Effect.fn(function* ({ news, olds }) {
245 if (!isResolved(news)) return undefined;
246 if (olds?.userPoolId !== news?.userPoolId || olds?.clientId !== news?.clientId) {
247 return { action: "replace" } as const;
248 }
249 }),
250
251 reconcile: Effect.fn(function* ({ news, output, session }) {
252 const { userPoolId, clientId } = news;
253 const useProvided = desiredUseProvidedValues(news);
254
255 // 1. OBSERVE — output.managedLoginBrandingId is only a cache;
256 // fall back to the by-client lookup so state loss converges.
257 let observed =
258 output?.managedLoginBrandingId !== undefined
259 ? yield* describeById(userPoolId, output.managedLoginBrandingId)
260 : undefined;
261 if (observed === undefined) {
262 observed = yield* describeByClient(userPoolId, clientId);
263 }
264
265 // 2. ENSURE — create when missing; a branding created out-of-band
266 // (or by a concurrent run) for the same client surfaces as
267 // ManagedLoginBrandingExistsException and is taken over.
268 if (observed === undefined) {
269 observed = yield* cip
270 .createManagedLoginBranding({
271 UserPoolId: userPoolId,
272 ClientId: clientId,
273 UseCognitoProvidedValues: useProvided,
274 Settings: news.settings,
275 Assets: toWireAssets(news.assets),
276 })
277 .pipe(
278 Effect.map((r) => r.ManagedLoginBranding),
279 Effect.catchTag("ManagedLoginBrandingExistsException", () =>
280 describeByClient(userPoolId, clientId),
281 ),
282 );
283 }
284
285 const managedLoginBrandingId = observed?.ManagedLoginBrandingId!;
286
287 // 3. SYNC — diff observed style against desired; skip the update
288 // entirely on no-op.
289 const drift =
290 (observed?.UseCognitoProvidedValues ?? false) !== useProvided ||
291 (news.settings !== undefined &&
292 JSON.stringify(news.settings) !== JSON.stringify(observed?.Settings)) ||
293 (news.assets !== undefined &&
294 canonicalAssets(toWireAssets(news.assets)) !== canonicalAssets(observed?.Assets));
295 if (drift) {
296 yield* cip
297 .updateManagedLoginBranding({
298 UserPoolId: userPoolId,
299 ManagedLoginBrandingId: managedLoginBrandingId,
300 UseCognitoProvidedValues: useProvided,
301 Settings: news.settings,
302 Assets: toWireAssets(news.assets),
303 })
304 .pipe(retryWhileConcurrent);
305 }
306
307 yield* session.note(managedLoginBrandingId);
308 return { managedLoginBrandingId, userPoolId, clientId };
309 }),
310
311 delete: Effect.fn(function* ({ output }) {
312 yield* cip
313 .deleteManagedLoginBranding({
314 UserPoolId: output.userPoolId,
315 ManagedLoginBrandingId: output.managedLoginBrandingId,
316 })
317 .pipe(
318 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
319 retryWhileConcurrent,
320 );
321 }),
322 });
323 }),
324 );