@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 276 lines 9.95 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 Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import type { Providers } from "../Providers.ts";
9
10 /** The kind of third-party identity provider. */
11 export type IdentityProviderType =
12 | "SAML"
13 | "OIDC"
14 | "Facebook"
15 | "Google"
16 | "LoginWithAmazon"
17 | "SignInWithApple";
18
19 export interface IdentityProviderProps {
20 /**
21 * The ID of the user pool the IdP is attached to. Changing this triggers
22 * a replacement.
23 */
24 userPoolId: string;
25 /**
26 * The kind of identity provider. Changing this triggers a replacement.
27 */
28 providerType: IdentityProviderType;
29 /**
30 * Name of the identity provider (1-32 chars, no spaces). For social
31 * providers the name must match the provider type (e.g. `Google`). If
32 * omitted, a deterministic name is generated from the app, stage, and
33 * logical ID. Changing this triggers a replacement.
34 */
35 providerName?: string;
36 /**
37 * Provider configuration. For OIDC: `client_id`, `client_secret`,
38 * `authorize_scopes`, `oidc_issuer`, `attributes_request_method`. For
39 * SAML: `MetadataURL` or `MetadataFile`. For social providers:
40 * `client_id`, `client_secret`, `authorize_scopes`. Wrap secret values
41 * (e.g. `client_secret`) with `Redacted.make(...)` so they never leak
42 * into logs or state output.
43 */
44 providerDetails: Record<string, string | Redacted.Redacted<string>>;
45 /**
46 * Maps IdP claims to user pool attributes, e.g. `{ email: "email" }`.
47 */
48 attributeMapping?: Record<string, string>;
49 /**
50 * Identifiers (up to 50) that direct sign-in requests to this IdP.
51 */
52 idpIdentifiers?: string[];
53 }
54
55 export interface IdentityProvider extends Resource<
56 "AWS.Cognito.IdentityProvider",
57 IdentityProviderProps,
58 {
59 /** The name of the identity provider. */
60 providerName: string;
61 /** The ID of the user pool the IdP is attached to. */
62 userPoolId: string;
63 /** The kind of identity provider. */
64 providerType: IdentityProviderType;
65 },
66 never,
67 Providers
68 > {}
69
70 /**
71 * A third-party identity provider (SAML, OIDC, or social) attached to an
72 * Amazon Cognito user pool, enabling federated sign-in through managed
73 * login.
74 * ### Creating Identity Providers
75 * **Example:** OIDC Provider
76 * ```typescript
77 * import * as Cognito from "@alchemy.run/aws/Cognito";
78 *
79 * const pool = yield* Cognito.UserPool("Users", {});
80 * const oidc = yield* Cognito.IdentityProvider("Corporate", {
81 * userPoolId: pool.userPoolId,
82 * providerType: "OIDC",
83 * providerDetails: {
84 * client_id: "my-client-id",
85 * client_secret: Redacted.make("my-client-secret"),
86 * authorize_scopes: "openid email",
87 * oidc_issuer: "https://accounts.google.com",
88 * attributes_request_method: "GET",
89 * },
90 * attributeMapping: { email: "email", username: "sub" },
91 * });
92 * ```
93 *
94 * **Example:** Wire the IdP to an App Client
95 * ```typescript
96 * const client = yield* Cognito.UserPoolClient("Web", {
97 * userPoolId: pool.userPoolId,
98 * supportedIdentityProviders: ["COGNITO", oidc.providerName],
99 * });
100 * ```
101 *
102 * @resource
103 */
104 export const IdentityProvider = Resource<IdentityProvider>("AWS.Cognito.IdentityProvider");
105
106 /** Unwrap any `Redacted` values (e.g. `client_secret`) into the plain
107 * string record the Cognito wire API expects. */
108 const plainDetails = (
109 details: Record<string, string | Redacted.Redacted<string>>,
110 ): Record<string, string> =>
111 Object.fromEntries(
112 Object.entries(details).map(([key, value]) => [
113 key,
114 typeof value === "string" ? value : Redacted.value(value),
115 ]),
116 );
117
118 const definedRecord = (
119 record: { [key: string]: string | undefined } | undefined,
120 ): Record<string, string> =>
121 Object.fromEntries(
122 Object.entries(record ?? {}).filter(
123 (entry): entry is [string, string] => entry[1] !== undefined,
124 ),
125 );
126
127 const canonicalRecord = (record: Record<string, string>) =>
128 JSON.stringify(Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b))));
129
130 export const IdentityProviderProvider = () =>
131 Provider.effect(
132 IdentityProvider,
133 Effect.gen(function* () {
134 const createName = Effect.fn(function* (
135 id: string,
136 props: Pick<IdentityProviderProps, "providerName" | "providerType">,
137 ) {
138 if (props.providerName) return props.providerName;
139 // social providers require the name to equal the type
140 if (
141 props.providerType !== undefined &&
142 props.providerType !== "SAML" &&
143 props.providerType !== "OIDC"
144 ) {
145 return props.providerType;
146 }
147 return yield* createPhysicalName({ id, maxLength: 32 });
148 });
149
150 const describeProvider = Effect.fn(function* (userPoolId: string, providerName: string) {
151 return yield* cip
152 .describeIdentityProvider({
153 UserPoolId: userPoolId,
154 ProviderName: providerName,
155 })
156 .pipe(
157 Effect.map((r) => r.IdentityProvider),
158 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
159 );
160 });
161
162 const attributesOf = (
163 provider: cip.IdentityProviderType,
164 providerName: string,
165 userPoolId: string,
166 ) => ({
167 providerName,
168 userPoolId,
169 providerType: (provider.ProviderType ?? "OIDC") as IdentityProviderType,
170 });
171
172 return IdentityProvider.Provider.of({
173 stables: ["providerName", "userPoolId", "providerType"],
174
175 // Sub-resource keyed entirely by its user pool (userPoolId) with no global
176 // enumeration API of its own — nuke reaches it through the parent's
177 // deletion, so enumeration returns empty per the ProviderService
178 // doctrine.
179 list: () => Effect.succeed([]),
180
181 read: Effect.fn(function* ({ id, olds, output }) {
182 const userPoolId = output?.userPoolId ?? olds?.userPoolId;
183 if (userPoolId === undefined) return undefined;
184 const providerName =
185 output?.providerName ??
186 (yield* createName(id, olds ?? { providerType: "OIDC" as const, providerDetails: {} }));
187 const observed = yield* describeProvider(userPoolId, providerName);
188 return observed === undefined
189 ? undefined
190 : attributesOf(observed, providerName, userPoolId);
191 }),
192
193 diff: Effect.fn(function* ({ id, news, olds }) {
194 if (!isResolved(news)) return undefined;
195 const oldName = olds === undefined ? undefined : yield* createName(id, olds);
196 const newName = news === undefined ? undefined : yield* createName(id, news);
197 if (
198 oldName !== newName ||
199 olds?.providerType !== news?.providerType ||
200 olds?.userPoolId !== news?.userPoolId
201 ) {
202 return { action: "replace" } as const;
203 }
204 }),
205
206 reconcile: Effect.fn(function* ({ id, news, output, session }) {
207 const providerName = output?.providerName ?? (yield* createName(id, news));
208 const userPoolId = news.userPoolId;
209 const desiredDetails = plainDetails(news.providerDetails);
210
211 // 1. OBSERVE
212 let observed = yield* describeProvider(userPoolId, providerName);
213
214 // 2. ENSURE — tolerate the create race.
215 if (observed === undefined) {
216 observed = yield* cip
217 .createIdentityProvider({
218 UserPoolId: userPoolId,
219 ProviderName: providerName,
220 ProviderType: news.providerType,
221 ProviderDetails: desiredDetails,
222 AttributeMapping: news.attributeMapping,
223 IdpIdentifiers: news.idpIdentifiers,
224 })
225 .pipe(
226 Effect.map((r) => r.IdentityProvider),
227 Effect.catchTag("DuplicateProviderException", () =>
228 describeProvider(userPoolId, providerName).pipe(
229 Effect.map((provider) => provider!),
230 ),
231 ),
232 );
233 } else {
234 // 3. SYNC — details, mapping, and identifiers are mutable.
235 // Cognito augments ProviderDetails with derived keys (e.g.
236 // attributes_url), so compare desired keys only.
237 const observedDetails = definedRecord(observed.ProviderDetails);
238 const detailsDrift = Object.entries(desiredDetails).some(
239 ([key, value]) => observedDetails[key] !== value,
240 );
241 const mappingDrift =
242 news.attributeMapping !== undefined &&
243 canonicalRecord(definedRecord(observed.AttributeMapping)) !==
244 canonicalRecord(news.attributeMapping);
245 const identifiersDrift =
246 news.idpIdentifiers !== undefined &&
247 [...news.idpIdentifiers].sort().join(",") !==
248 [...(observed.IdpIdentifiers ?? [])].sort().join(",");
249 if (detailsDrift || mappingDrift || identifiersDrift) {
250 observed = yield* cip
251 .updateIdentityProvider({
252 UserPoolId: userPoolId,
253 ProviderName: providerName,
254 ProviderDetails: desiredDetails,
255 AttributeMapping: news.attributeMapping,
256 IdpIdentifiers: news.idpIdentifiers,
257 })
258 .pipe(Effect.map((r) => r.IdentityProvider));
259 }
260 }
261
262 yield* session.note(providerName);
263 return attributesOf(observed!, providerName, userPoolId);
264 }),
265
266 delete: Effect.fn(function* ({ output }) {
267 yield* cip
268 .deleteIdentityProvider({
269 UserPoolId: output.userPoolId,
270 ProviderName: output.providerName,
271 })
272 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
273 }),
274 });
275 }),
276 );