@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, 06:00 UTC

main
ts 363 lines 13.1 KB
Raw
1 import * as ci from "@distilled.cloud/aws/cognito-identity";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { AWSEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 /** A Cognito user pool provider entry for an identity pool. */
13 export interface IdentityPoolCognitoProvider {
14 /**
15 * The user pool provider name:
16 * `cognito-idp.<region>.amazonaws.com/<userPoolId>`.
17 */
18 providerName: string;
19 /** The app client ID allowed to exchange tokens. */
20 clientId: string;
21 /**
22 * Whether Cognito checks with the user pool that the token was not
23 * globally signed out.
24 * @default false
25 */
26 serverSideTokenCheck?: boolean;
27 }
28
29 export interface IdentityPoolProps {
30 /**
31 * Name of the identity pool. If omitted, a deterministic physical name is
32 * generated from the app, stage, and logical ID. Mutable in place.
33 */
34 identityPoolName?: string;
35 /**
36 * Whether the pool vends credentials to unauthenticated (guest)
37 * identities.
38 * @default false
39 */
40 allowUnauthenticatedIdentities?: boolean;
41 /**
42 * Enables the legacy basic (classic) credentials flow.
43 * @default false
44 */
45 allowClassicFlow?: boolean;
46 /**
47 * Social login providers keyed by their domain, e.g.
48 * `{ "accounts.google.com": "<client-id>" }`.
49 */
50 supportedLoginProviders?: Record<string, string>;
51 /**
52 * Domain for developer-authenticated identities. Letters, digits, periods,
53 * underscores, and dashes.
54 */
55 developerProviderName?: string;
56 /**
57 * ARNs of IAM OpenID Connect providers this pool trusts.
58 */
59 openIdConnectProviderArns?: string[];
60 /**
61 * Cognito user pools this identity pool federates.
62 */
63 cognitoIdentityProviders?: IdentityPoolCognitoProvider[];
64 /**
65 * ARNs of IAM SAML providers this pool trusts.
66 */
67 samlProviderArns?: string[];
68 /**
69 * Tags to apply to the identity pool. Merged with internal Alchemy tags.
70 */
71 tags?: Record<string, string>;
72 }
73
74 export interface IdentityPool extends Resource<
75 "AWS.Cognito.IdentityPool",
76 IdentityPoolProps,
77 {
78 /** The generated identity pool ID, e.g. `us-west-2:xxxx-...`. */
79 identityPoolId: string;
80 /** The ARN of the identity pool. */
81 identityPoolArn: string;
82 /** The name of the identity pool. */
83 identityPoolName: string;
84 },
85 never,
86 Providers
87 > {}
88
89 /**
90 * An Amazon Cognito identity pool (federated identities) — exchanges tokens
91 * from user pools, social providers, OIDC/SAML IdPs, or developer backends
92 * for temporary AWS credentials.
93 * ### Creating an Identity Pool
94 * **Example:** Identity Pool Federating a User Pool
95 * ```typescript
96 * import * as Cognito from "@alchemy.run/aws/Cognito";
97 * import * as Output from "alchemy/Output";
98 *
99 * const pool = yield* Cognito.UserPool("Users", {});
100 * const client = yield* Cognito.UserPoolClient("Web", {
101 * userPoolId: pool.userPoolId,
102 * });
103 * const identities = yield* Cognito.IdentityPool("Identities", {
104 * cognitoIdentityProviders: [
105 * {
106 * providerName: Output.interpolate`cognito-idp.us-west-2.amazonaws.com/${pool.userPoolId}`,
107 * clientId: client.clientId,
108 * },
109 * ],
110 * });
111 * ```
112 *
113 * **Example:** Guest (Unauthenticated) Access
114 * ```typescript
115 * const identities = yield* Cognito.IdentityPool("Identities", {
116 * allowUnauthenticatedIdentities: true,
117 * });
118 * ```
119 *
120 * ### Roles
121 * **Example:** Attach Authenticated/Unauthenticated Roles
122 * ```typescript
123 * yield* Cognito.IdentityPoolRoleAttachment("Roles", {
124 * identityPoolId: identities.identityPoolId,
125 * roles: { authenticated: role.roleArn },
126 * });
127 * ```
128 *
129 * @resource
130 */
131 export const IdentityPool = Resource<IdentityPool>("AWS.Cognito.IdentityPool");
132
133 const tagRecordOf = (
134 tags: { [key: string]: string | undefined } | undefined,
135 ): Record<string, string> =>
136 Object.fromEntries(
137 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
138 );
139
140 const identityPoolArnOf = (region: string, accountId: string, id: string) =>
141 `arn:aws:cognito-identity:${region}:${accountId}:identitypool/${id}`;
142
143 /** The full desired wire configuration (update resets omitted fields). */
144 const desiredConfig = (name: string, news: IdentityPoolProps) => ({
145 IdentityPoolName: name,
146 AllowUnauthenticatedIdentities: news.allowUnauthenticatedIdentities ?? false,
147 AllowClassicFlow: news.allowClassicFlow,
148 SupportedLoginProviders: news.supportedLoginProviders,
149 DeveloperProviderName: news.developerProviderName,
150 OpenIdConnectProviderARNs: news.openIdConnectProviderArns,
151 CognitoIdentityProviders: news.cognitoIdentityProviders?.map((p) => ({
152 ProviderName: p.providerName,
153 ClientId: p.clientId,
154 ServerSideTokenCheck: p.serverSideTokenCheck,
155 })),
156 SamlProviderARNs: news.samlProviderArns,
157 });
158
159 const canonical = (value: unknown) =>
160 JSON.stringify(value, (_, v) =>
161 v !== null && typeof v === "object" && !Array.isArray(v)
162 ? Object.fromEntries(
163 Object.entries(v as Record<string, unknown>)
164 .filter(([, x]) => x !== undefined)
165 .sort(([a], [b]) => a.localeCompare(b)),
166 )
167 : v,
168 );
169
170 const hasDrift = (name: string, news: IdentityPoolProps, observed: ci.IdentityPool) => {
171 const desired = desiredConfig(name, news);
172 const observedSubset = {
173 IdentityPoolName: observed.IdentityPoolName,
174 AllowUnauthenticatedIdentities: observed.AllowUnauthenticatedIdentities,
175 AllowClassicFlow:
176 desired.AllowClassicFlow === undefined ? undefined : (observed.AllowClassicFlow ?? false),
177 SupportedLoginProviders:
178 desired.SupportedLoginProviders === undefined
179 ? undefined
180 : tagRecordOf(observed.SupportedLoginProviders),
181 DeveloperProviderName:
182 desired.DeveloperProviderName === undefined ? undefined : observed.DeveloperProviderName,
183 OpenIdConnectProviderARNs:
184 desired.OpenIdConnectProviderARNs === undefined
185 ? undefined
186 : (observed.OpenIdConnectProviderARNs ?? []),
187 CognitoIdentityProviders:
188 desired.CognitoIdentityProviders === undefined
189 ? undefined
190 : (observed.CognitoIdentityProviders ?? []).map((p) => ({
191 ProviderName: p.ProviderName,
192 ClientId: p.ClientId,
193 ServerSideTokenCheck: p.ServerSideTokenCheck ?? undefined,
194 })),
195 SamlProviderARNs:
196 desired.SamlProviderARNs === undefined ? undefined : (observed.SamlProviderARNs ?? []),
197 };
198 const normalizedDesired = {
199 ...desired,
200 CognitoIdentityProviders: desired.CognitoIdentityProviders?.map((p) => ({
201 ...p,
202 ServerSideTokenCheck: p.ServerSideTokenCheck ?? false,
203 })),
204 };
205 const normalizedObserved = {
206 ...observedSubset,
207 CognitoIdentityProviders: observedSubset.CognitoIdentityProviders?.map((p) => ({
208 ...p,
209 ServerSideTokenCheck: p.ServerSideTokenCheck ?? false,
210 })),
211 };
212 return canonical(normalizedDesired) !== canonical(normalizedObserved);
213 };
214
215 export const IdentityPoolProvider = () =>
216 Provider.effect(
217 IdentityPool,
218 Effect.gen(function* () {
219 const createName = Effect.fn(function* (
220 id: string,
221 props: Pick<IdentityPoolProps, "identityPoolName">,
222 ) {
223 return props.identityPoolName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
224 });
225
226 const describePool = Effect.fn(function* (identityPoolId: string) {
227 return yield* ci
228 .describeIdentityPool({ IdentityPoolId: identityPoolId })
229 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
230 });
231
232 const findPoolsByName = Effect.fn(function* (name: string) {
233 const pages = yield* ci.listIdentityPools.pages({ MaxResults: 60 }).pipe(Stream.runCollect);
234 const candidates = Array.from(pages)
235 .flatMap((page) => page.IdentityPools ?? [])
236 .filter((pool) => pool.IdentityPoolName === name && pool.IdentityPoolId !== undefined);
237 return yield* Effect.forEach(
238 candidates,
239 (candidate) => describePool(candidate.IdentityPoolId!),
240 { concurrency: 3 },
241 ).pipe(Effect.map((pools) => pools.filter((p) => p !== undefined)));
242 });
243
244 return IdentityPool.Provider.of({
245 stables: ["identityPoolId", "identityPoolArn"],
246
247 list: () =>
248 Effect.gen(function* () {
249 const { accountId, region } = yield* AWSEnvironment.current;
250 const pages = yield* ci.listIdentityPools
251 .pages({ MaxResults: 60 })
252 .pipe(Stream.runCollect);
253 return Array.from(pages)
254 .flatMap((page) => page.IdentityPools ?? [])
255 .filter((pool) => pool.IdentityPoolId !== undefined)
256 .map((pool) => ({
257 identityPoolId: pool.IdentityPoolId!,
258 identityPoolArn: identityPoolArnOf(region, accountId, pool.IdentityPoolId!),
259 identityPoolName: pool.IdentityPoolName ?? "",
260 }));
261 }),
262
263 read: Effect.fn(function* ({ id, olds, output }) {
264 const { accountId, region } = yield* AWSEnvironment.current;
265 const attributesOf = (pool: ci.IdentityPool) => ({
266 identityPoolId: pool.IdentityPoolId,
267 identityPoolArn: identityPoolArnOf(region, accountId, pool.IdentityPoolId),
268 identityPoolName: pool.IdentityPoolName,
269 });
270 if (output?.identityPoolId !== undefined) {
271 const pool = yield* describePool(output.identityPoolId);
272 if (pool === undefined) return undefined;
273 const attrs = attributesOf(pool);
274 const tags = tagRecordOf(pool.IdentityPoolTags);
275 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
276 }
277 const name = yield* createName(id, olds ?? {});
278 const pools = yield* findPoolsByName(name);
279 if (pools.length === 0) return undefined;
280 for (const pool of pools) {
281 if (yield* hasAlchemyTags(id, tagRecordOf(pool.IdentityPoolTags))) {
282 return attributesOf(pool);
283 }
284 }
285 return Unowned(attributesOf(pools[0]!));
286 }),
287
288 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
289 const { accountId, region } = yield* AWSEnvironment.current;
290 const name = yield* createName(id, news);
291 const internalTags = yield* createInternalTags(id);
292 const desiredTags = { ...news.tags, ...internalTags };
293
294 // 1. OBSERVE — the id in output is only a cache.
295 let observed =
296 output?.identityPoolId !== undefined
297 ? yield* describePool(output.identityPoolId)
298 : undefined;
299 if (observed === undefined) {
300 const candidates = yield* findPoolsByName(name);
301 for (const candidate of candidates) {
302 if (yield* hasAlchemyTags(id, tagRecordOf(candidate.IdentityPoolTags))) {
303 observed = candidate;
304 break;
305 }
306 }
307 }
308
309 // 2. ENSURE
310 if (observed === undefined) {
311 observed = yield* ci.createIdentityPool({
312 ...desiredConfig(name, news),
313 IdentityPoolTags: desiredTags,
314 });
315 } else if (hasDrift(name, news, observed)) {
316 // 3. SYNC — UpdateIdentityPool resets omitted fields to their
317 // defaults, so send the full desired configuration.
318 observed = yield* ci.updateIdentityPool({
319 IdentityPoolId: observed.IdentityPoolId,
320 ...desiredConfig(name, news),
321 });
322 }
323
324 const identityPoolId = observed.IdentityPoolId;
325 const identityPoolArn = identityPoolArnOf(region, accountId, identityPoolId);
326
327 // 3b. SYNC TAGS against OBSERVED cloud tags.
328 const observedTags = yield* ci.listTagsForResource({ ResourceArn: identityPoolArn }).pipe(
329 Effect.map((r) => tagRecordOf(r.Tags)),
330 Effect.catchTag("ResourceNotFoundException", () =>
331 Effect.succeed({} as Record<string, string>),
332 ),
333 );
334 const { upsert, removed } = diffTags(observedTags, desiredTags);
335 if (upsert.length > 0) {
336 yield* ci.tagResource({
337 ResourceArn: identityPoolArn,
338 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
339 });
340 }
341 if (removed.length > 0) {
342 yield* ci.untagResource({
343 ResourceArn: identityPoolArn,
344 TagKeys: removed,
345 });
346 }
347
348 yield* session.note(identityPoolId);
349 return {
350 identityPoolId,
351 identityPoolArn,
352 identityPoolName: name,
353 };
354 }),
355
356 delete: Effect.fn(function* ({ output }) {
357 yield* ci
358 .deleteIdentityPool({ IdentityPoolId: output.identityPoolId })
359 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
360 }),
361 });
362 }),
363 );