@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 277 lines 10.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 * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import type { Providers } from "../Providers.ts";
9
10 export interface UserProps {
11 /**
12 * The ID of the user pool the user belongs to. Changing this triggers a
13 * replacement.
14 */
15 userPoolId: string;
16 /**
17 * The username. If omitted, a deterministic physical name is generated
18 * from the app, stage, and logical ID. Changing this triggers a
19 * replacement. For pools with `usernameAttributes` this must be a value
20 * of one of those attributes (e.g. an email address).
21 */
22 username?: string;
23 /**
24 * User attributes as name → value pairs (e.g.
25 * `{ email: "a@b.com", email_verified: "true" }`). Attributes declared
26 * here are kept in sync; removing a previously declared attribute deletes
27 * it from the user.
28 */
29 attributes?: Record<string, string>;
30 /**
31 * A permanent password for the user, set via `AdminSetUserPassword`
32 * (`Permanent: true`), which moves the user to `CONFIRMED`. Without it
33 * the user is created in `FORCE_CHANGE_PASSWORD` state. Must satisfy the
34 * pool's password policy. Wrap with `Redacted.make(...)` so the value
35 * never leaks into logs or state output.
36 */
37 password?: Redacted.Redacted<string>;
38 /**
39 * Whether the user account is enabled.
40 * @default true
41 */
42 enabled?: boolean;
43 }
44
45 export interface User extends Resource<
46 "AWS.Cognito.User",
47 UserProps,
48 {
49 /** The username. */
50 username: string;
51 /** The ID of the user pool the user belongs to. */
52 userPoolId: string;
53 /** The user's stable unique identifier (the `sub` attribute). */
54 sub: string;
55 /** The user's status, e.g. `CONFIRMED` or `FORCE_CHANGE_PASSWORD`. */
56 userStatus: string;
57 },
58 never,
59 Providers
60 > {}
61
62 /**
63 * A user within an Amazon Cognito user pool, created administratively via
64 * `AdminCreateUser`. The invitation message is always suppressed
65 * (`MessageAction: SUPPRESS`) — declaratively managed users never trigger
66 * invite emails/SMS; set a permanent `password` to make the account usable
67 * immediately.
68 * ### Creating Users
69 * **Example:** Basic User
70 * ```typescript
71 * import * as Cognito from "@alchemy.run/aws/Cognito";
72 *
73 * const pool = yield* Cognito.UserPool("Users", {});
74 * const user = yield* Cognito.User("Admin", {
75 * userPoolId: pool.userPoolId,
76 * attributes: { email: "admin@example.com", email_verified: "true" },
77 * });
78 * ```
79 *
80 * **Example:** Confirmed User with a Permanent Password
81 * ```typescript
82 * import * as Redacted from "effect/Redacted";
83 *
84 * const user = yield* Cognito.User("ServiceAccount", {
85 * userPoolId: pool.userPoolId,
86 * username: "service-account",
87 * password: Redacted.make("A-Str0ng-Passw0rd!"),
88 * attributes: { email: "svc@example.com", email_verified: "true" },
89 * });
90 * // user.userStatus === "CONFIRMED"
91 * ```
92 *
93 * @resource
94 */
95 export const User = Resource<User>("AWS.Cognito.User");
96
97 const plain = (value: string | Redacted.Redacted<string> | undefined): string | undefined =>
98 value === undefined ? undefined : typeof value === "string" ? value : Redacted.value(value);
99
100 /** Observed user attributes as a plain name → value record. */
101 const attributeRecordOf = (attributes: cip.AttributeType[] | undefined): Record<string, string> =>
102 Object.fromEntries(
103 (attributes ?? []).flatMap((attribute) => {
104 const value = plain(attribute.Value);
105 return value === undefined ? [] : [[attribute.Name, value] as const];
106 }),
107 );
108
109 export const UserProvider = () =>
110 Provider.effect(
111 User,
112 Effect.gen(function* () {
113 const createName = Effect.fn(function* (id: string, props: Pick<UserProps, "username">) {
114 return props.username ?? (yield* createPhysicalName({ id, maxLength: 128 }));
115 });
116
117 const getUser = Effect.fn(function* (userPoolId: string, username: string) {
118 return yield* cip
119 .adminGetUser({ UserPoolId: userPoolId, Username: username })
120 .pipe(
121 Effect.catchTag(
122 ["UserNotFoundException", "ResourceNotFoundException"],
123 () => Effect.undefined,
124 ),
125 );
126 });
127
128 const attributesOf = (
129 username: string,
130 userPoolId: string,
131 observed: cip.AdminGetUserResponse,
132 ) => ({
133 username,
134 userPoolId,
135 sub: attributeRecordOf(observed.UserAttributes).sub ?? "",
136 userStatus: observed.UserStatus ?? "UNKNOWN",
137 });
138
139 return User.Provider.of({
140 stables: ["username", "userPoolId", "sub"],
141
142 // Sub-resource keyed entirely by its user pool (userPoolId) with no
143 // global enumeration API of its own — nuke reaches it through the
144 // parent's deletion, so enumeration returns empty per the
145 // ProviderService doctrine.
146 list: () => Effect.succeed([]),
147
148 read: Effect.fn(function* ({ id, olds, output }) {
149 const userPoolId = output?.userPoolId ?? olds?.userPoolId;
150 if (userPoolId === undefined) return undefined;
151 const username = output?.username ?? (yield* createName(id, olds ?? {}));
152 const observed = yield* getUser(userPoolId, username);
153 return observed === undefined ? undefined : attributesOf(username, userPoolId, observed);
154 }),
155
156 diff: Effect.fn(function* ({ id, news, olds }) {
157 if (!isResolved(news)) return undefined;
158 const oldName = yield* createName(id, olds ?? {});
159 const newName = yield* createName(id, news ?? {});
160 if (oldName !== newName || olds?.userPoolId !== news?.userPoolId) {
161 return { action: "replace" } as const;
162 }
163 }),
164
165 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
166 const username = output?.username ?? (yield* createName(id, news));
167 const userPoolId = news.userPoolId;
168 const desiredAttributes = news.attributes ?? {};
169
170 // 1. OBSERVE — cloud state is authoritative.
171 let observed = yield* getUser(userPoolId, username);
172
173 // 2. ENSURE — create when missing (invitation always suppressed);
174 // tolerate the create race.
175 if (observed === undefined) {
176 yield* cip
177 .adminCreateUser({
178 UserPoolId: userPoolId,
179 Username: username,
180 MessageAction: "SUPPRESS",
181 UserAttributes: Object.entries(desiredAttributes).map(([Name, Value]) => ({
182 Name,
183 Value,
184 })),
185 })
186 .pipe(Effect.catchTag("UsernameExistsException", () => Effect.void));
187 observed = yield* getUser(userPoolId, username);
188 } else {
189 // 3. SYNC ATTRIBUTES — upsert declared attributes that drifted
190 // from the OBSERVED values; delete attributes that were
191 // previously declared but no longer are (`olds` is only the
192 // hint for which attributes we manage — never for values).
193 const observedAttributes = attributeRecordOf(observed.UserAttributes);
194 const upsert = Object.entries(desiredAttributes).filter(
195 ([name, value]) => observedAttributes[name] !== value,
196 );
197 if (upsert.length > 0) {
198 yield* cip.adminUpdateUserAttributes({
199 UserPoolId: userPoolId,
200 Username: username,
201 UserAttributes: upsert.map(([Name, Value]) => ({
202 Name,
203 Value,
204 })),
205 });
206 }
207 const removed = Object.keys(olds?.attributes ?? {}).filter(
208 (name) =>
209 desiredAttributes[name] === undefined && observedAttributes[name] !== undefined,
210 );
211 if (removed.length > 0) {
212 yield* cip.adminDeleteUserAttributes({
213 UserPoolId: userPoolId,
214 Username: username,
215 UserAttributeNames: removed,
216 });
217 }
218 }
219
220 if (observed === undefined) {
221 return yield* Effect.die(`Cognito user ${username} not observable after create`);
222 }
223
224 // 3b. SYNC PASSWORD — a permanent password confirms the account.
225 // Passwords are write-only, so `olds` is the only drift signal;
226 // fresh creates and adoptions always apply it.
227 if (
228 news.password !== undefined &&
229 (output === undefined ||
230 olds === undefined ||
231 plain(olds.password) !== plain(news.password))
232 ) {
233 yield* cip.adminSetUserPassword({
234 UserPoolId: userPoolId,
235 Username: username,
236 Password: news.password,
237 Permanent: true,
238 });
239 }
240
241 // 3c. SYNC ENABLED — diff against the OBSERVED flag.
242 const desiredEnabled = news.enabled ?? true;
243 if ((observed.Enabled ?? true) !== desiredEnabled) {
244 yield* desiredEnabled
245 ? cip.adminEnableUser({
246 UserPoolId: userPoolId,
247 Username: username,
248 })
249 : cip.adminDisableUser({
250 UserPoolId: userPoolId,
251 Username: username,
252 });
253 }
254
255 // 4. RETURN fresh attributes (status/attributes may have changed
256 // during sync).
257 const final = (yield* getUser(userPoolId, username)) ?? observed;
258 yield* session.note(username);
259 return attributesOf(username, userPoolId, final);
260 }),
261
262 delete: Effect.fn(function* ({ output }) {
263 yield* cip
264 .adminDeleteUser({
265 UserPoolId: output.userPoolId,
266 Username: output.username,
267 })
268 .pipe(
269 Effect.catchTag(
270 ["UserNotFoundException", "ResourceNotFoundException"],
271 () => Effect.void,
272 ),
273 );
274 }),
275 });
276 }),
277 );