The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cognito from "@alchemy.run/aws/Cognito"; |
| 2 | import * as IAM from "@alchemy.run/aws/IAM"; |
| 3 | import * as Lambda from "@alchemy.run/aws/Lambda"; |
| 4 | import * as Duration from "effect/Duration"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 7 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import * as Redacted from "effect/Redacted"; |
| 10 | import path from "pathe"; |
| 11 | |
| 12 | const main = path.resolve(import.meta.dirname, "handler.ts"); |
| 13 | |
| 14 | const plain = (value: string | Redacted.Redacted<string> | undefined): string | undefined => |
| 15 | value === undefined ? undefined : typeof value === "string" ? value : Redacted.value(value); |
| 16 | |
| 17 | const PASSWORD = "Alchemy-Test-Passw0rd!"; |
| 18 | const NEW_PASSWORD = "Alchemy-Test-Passw0rd!2"; |
| 19 | |
| 20 | export class CognitoTestFunction extends Lambda.Function<Lambda.Function>()( |
| 21 | "CognitoTestFunction", |
| 22 | ) {} |
| 23 | |
| 24 | export default CognitoTestFunction.make( |
| 25 | { |
| 26 | main, |
| 27 | functionUrl: true, |
| 28 | timeout: Duration.seconds(30), |
| 29 | }, |
| 30 | Effect.gen(function* () { |
| 31 | const pool = yield* Cognito.UserPool("BindingsUserPool", { |
| 32 | passwordPolicy: { |
| 33 | minimumLength: 12, |
| 34 | requireSymbols: false, |
| 35 | }, |
| 36 | accountRecovery: [{ name: "admin_only", priority: 1 }], |
| 37 | tags: { Purpose: "cognito-bindings-fixture" }, |
| 38 | }); |
| 39 | const client = yield* Cognito.UserPoolClient("BindingsUserPoolClient", { |
| 40 | userPoolId: pool.userPoolId, |
| 41 | explicitAuthFlows: [ |
| 42 | "ALLOW_USER_PASSWORD_AUTH", |
| 43 | "ALLOW_ADMIN_USER_PASSWORD_AUTH", |
| 44 | "ALLOW_REFRESH_TOKEN_AUTH", |
| 45 | ], |
| 46 | }); |
| 47 | const group = yield* Cognito.Group("BindingsGroup", { |
| 48 | userPoolId: pool.userPoolId, |
| 49 | description: "cognito bindings fixture group", |
| 50 | }); |
| 51 | |
| 52 | const identities = yield* Cognito.IdentityPool("BindingsIdentityPool", { |
| 53 | allowUnauthenticatedIdentities: true, |
| 54 | allowClassicFlow: true, |
| 55 | tags: { Purpose: "cognito-bindings-fixture" }, |
| 56 | }); |
| 57 | const guestRole = yield* IAM.Role("BindingsGuestRole", { |
| 58 | assumeRolePolicyDocument: { |
| 59 | Version: "2012-10-17", |
| 60 | Statement: [ |
| 61 | { |
| 62 | Effect: "Allow", |
| 63 | Principal: { Federated: "cognito-identity.amazonaws.com" }, |
| 64 | Action: ["sts:AssumeRoleWithWebIdentity"], |
| 65 | Condition: { |
| 66 | StringEquals: { |
| 67 | "cognito-identity.amazonaws.com:aud": identities.identityPoolId, |
| 68 | }, |
| 69 | "ForAnyValue:StringLike": { |
| 70 | "cognito-identity.amazonaws.com:amr": "unauthenticated", |
| 71 | }, |
| 72 | }, |
| 73 | }, |
| 74 | ], |
| 75 | }, |
| 76 | }); |
| 77 | yield* Cognito.IdentityPoolRoleAttachment("BindingsIdentityRoles", { |
| 78 | identityPoolId: identities.identityPoolId, |
| 79 | roles: { unauthenticated: guestRole.roleArn }, |
| 80 | }); |
| 81 | |
| 82 | const admin = yield* Cognito.UserPoolAdmin(pool); |
| 83 | const auth = yield* Cognito.UserPoolAuth(client); |
| 84 | const identityAuth = yield* Cognito.IdentityPoolAuth(identities); |
| 85 | const identityAdmin = yield* Cognito.IdentityPoolAdmin(identities); |
| 86 | // Output → deferred effect; resolved per-request inside the handler. |
| 87 | const GroupName = yield* group.groupName; |
| 88 | const UserPoolId = yield* pool.userPoolId; |
| 89 | const ClientId = yield* client.clientId; |
| 90 | |
| 91 | return { |
| 92 | fetch: Effect.gen(function* () { |
| 93 | const request = yield* HttpServerRequest; |
| 94 | const url = new URL(request.originalUrl); |
| 95 | const pathname = url.pathname; |
| 96 | const username = url.searchParams.get("username") ?? "missing-user"; |
| 97 | |
| 98 | // Full password auth flow: create → set permanent password → |
| 99 | // USER_PASSWORD_AUTH → getUser with the access token → delete. |
| 100 | if (request.method === "POST" && pathname === "/auth-flow") { |
| 101 | yield* admin |
| 102 | .adminCreateUser({ |
| 103 | Username: username, |
| 104 | MessageAction: "SUPPRESS", |
| 105 | UserAttributes: [ |
| 106 | { Name: "email", Value: `${username}@example.com` }, |
| 107 | { Name: "email_verified", Value: "true" }, |
| 108 | ], |
| 109 | }) |
| 110 | .pipe( |
| 111 | // rerun tolerance: an earlier partial run may have left the user |
| 112 | Effect.catchTag("UsernameExistsException", () => Effect.void), |
| 113 | ); |
| 114 | yield* admin.adminSetUserPassword({ |
| 115 | Username: username, |
| 116 | Password: PASSWORD, |
| 117 | Permanent: true, |
| 118 | }); |
| 119 | const signIn = yield* auth.initiateAuth({ |
| 120 | AuthFlow: "USER_PASSWORD_AUTH", |
| 121 | AuthParameters: { USERNAME: username, PASSWORD }, |
| 122 | }); |
| 123 | const accessToken = plain(signIn.AuthenticationResult?.AccessToken); |
| 124 | const me = accessToken ? yield* auth.getUser({ AccessToken: accessToken }) : undefined; |
| 125 | yield* admin.adminDeleteUser({ Username: username }); |
| 126 | return yield* HttpServerResponse.json({ |
| 127 | challengeName: signIn.ChallengeName, |
| 128 | idToken: plain(signIn.AuthenticationResult?.IdToken), |
| 129 | accessToken, |
| 130 | refreshToken: plain(signIn.AuthenticationResult?.RefreshToken), |
| 131 | tokenType: signIn.AuthenticationResult?.TokenType, |
| 132 | getUserUsername: plain(me?.Username), |
| 133 | }); |
| 134 | } |
| 135 | |
| 136 | // Admin user lifecycle: create → get → disable → enable → group |
| 137 | // membership → list → delete. |
| 138 | if (request.method === "POST" && pathname === "/user-lifecycle") { |
| 139 | yield* admin |
| 140 | .adminCreateUser({ |
| 141 | Username: username, |
| 142 | MessageAction: "SUPPRESS", |
| 143 | UserAttributes: [{ Name: "email", Value: `${username}@example.com` }], |
| 144 | }) |
| 145 | .pipe(Effect.catchTag("UsernameExistsException", () => Effect.void)); |
| 146 | const created = yield* admin.adminGetUser({ Username: username }); |
| 147 | yield* admin.adminDisableUser({ Username: username }); |
| 148 | const disabled = yield* admin.adminGetUser({ Username: username }); |
| 149 | yield* admin.adminEnableUser({ Username: username }); |
| 150 | const groupName = yield* GroupName; |
| 151 | yield* admin.adminAddUserToGroup({ |
| 152 | Username: username, |
| 153 | GroupName: groupName, |
| 154 | }); |
| 155 | const inGroup = yield* admin.listUsersInGroup({ |
| 156 | GroupName: groupName, |
| 157 | }); |
| 158 | yield* admin.adminRemoveUserFromGroup({ |
| 159 | Username: username, |
| 160 | GroupName: groupName, |
| 161 | }); |
| 162 | const listed = yield* admin.listUsers({ |
| 163 | Filter: `username = "${username}"`, |
| 164 | }); |
| 165 | yield* admin.adminDeleteUser({ Username: username }); |
| 166 | const gone = yield* admin.adminGetUser({ Username: username }).pipe( |
| 167 | Effect.map(() => false), |
| 168 | Effect.catchTag("UserNotFoundException", () => Effect.succeed(true)), |
| 169 | ); |
| 170 | return yield* HttpServerResponse.json({ |
| 171 | createdStatus: created.UserStatus, |
| 172 | disabledEnabled: disabled.Enabled, |
| 173 | groupMembers: (inGroup.Users ?? []).map((u) => plain(u.Username)), |
| 174 | listedCount: (listed.Users ?? []).length, |
| 175 | deleted: gone, |
| 176 | }); |
| 177 | } |
| 178 | |
| 179 | // Public sign-up (admin-confirmed since we cannot receive the email |
| 180 | // code) followed by password auth. |
| 181 | if (request.method === "POST" && pathname === "/sign-up-flow") { |
| 182 | const signedUp = yield* auth |
| 183 | .signUp({ |
| 184 | Username: username, |
| 185 | Password: PASSWORD, |
| 186 | UserAttributes: [{ Name: "email", Value: `${username}@example.com` }], |
| 187 | }) |
| 188 | .pipe( |
| 189 | Effect.map((r) => ({ |
| 190 | userConfirmed: r.UserConfirmed, |
| 191 | userSub: r.UserSub, |
| 192 | })), |
| 193 | Effect.catchTag("UsernameExistsException", () => |
| 194 | Effect.succeed({ |
| 195 | userConfirmed: false, |
| 196 | userSub: "already-exists", |
| 197 | }), |
| 198 | ), |
| 199 | ); |
| 200 | yield* admin.adminConfirmSignUp({ Username: username }).pipe( |
| 201 | // NotAuthorizedException: already CONFIRMED on rerun |
| 202 | Effect.catchTag("NotAuthorizedException", () => Effect.void), |
| 203 | ); |
| 204 | const confirmed = yield* admin.adminGetUser({ Username: username }); |
| 205 | const signIn = yield* auth.initiateAuth({ |
| 206 | AuthFlow: "USER_PASSWORD_AUTH", |
| 207 | AuthParameters: { USERNAME: username, PASSWORD }, |
| 208 | }); |
| 209 | yield* admin.adminDeleteUser({ Username: username }); |
| 210 | return yield* HttpServerResponse.json({ |
| 211 | userConfirmed: signedUp.userConfirmed, |
| 212 | userSub: signedUp.userSub, |
| 213 | confirmedStatus: confirmed.UserStatus, |
| 214 | hasIdToken: signIn.AuthenticationResult?.IdToken !== undefined, |
| 215 | }); |
| 216 | } |
| 217 | |
| 218 | // Self-service flows: change password, update/delete own attributes, |
| 219 | // refresh-token exchange, self-deletion. |
| 220 | if (request.method === "POST" && pathname === "/self-service") { |
| 221 | yield* admin |
| 222 | .adminCreateUser({ |
| 223 | Username: username, |
| 224 | MessageAction: "SUPPRESS", |
| 225 | UserAttributes: [ |
| 226 | { Name: "email", Value: `${username}@example.com` }, |
| 227 | { Name: "email_verified", Value: "true" }, |
| 228 | ], |
| 229 | }) |
| 230 | .pipe(Effect.catchTag("UsernameExistsException", () => Effect.void)); |
| 231 | yield* admin.adminSetUserPassword({ |
| 232 | Username: username, |
| 233 | Password: PASSWORD, |
| 234 | Permanent: true, |
| 235 | }); |
| 236 | const signIn = yield* auth.initiateAuth({ |
| 237 | AuthFlow: "USER_PASSWORD_AUTH", |
| 238 | AuthParameters: { USERNAME: username, PASSWORD }, |
| 239 | }); |
| 240 | const firstToken = plain(signIn.AuthenticationResult?.AccessToken)!; |
| 241 | yield* auth.changePassword({ |
| 242 | AccessToken: firstToken, |
| 243 | PreviousPassword: PASSWORD, |
| 244 | ProposedPassword: NEW_PASSWORD, |
| 245 | }); |
| 246 | const reAuth = yield* auth.initiateAuth({ |
| 247 | AuthFlow: "USER_PASSWORD_AUTH", |
| 248 | AuthParameters: { USERNAME: username, PASSWORD: NEW_PASSWORD }, |
| 249 | }); |
| 250 | const accessToken = plain(reAuth.AuthenticationResult?.AccessToken)!; |
| 251 | yield* auth.updateUserAttributes({ |
| 252 | AccessToken: accessToken, |
| 253 | UserAttributes: [{ Name: "nickname", Value: "self-service" }], |
| 254 | }); |
| 255 | const me = yield* auth.getUser({ AccessToken: accessToken }); |
| 256 | const nickname = plain(me.UserAttributes?.find((a) => a.Name === "nickname")?.Value); |
| 257 | yield* auth.deleteUserAttributes({ |
| 258 | AccessToken: accessToken, |
| 259 | UserAttributeNames: ["nickname"], |
| 260 | }); |
| 261 | const meAfter = yield* auth.getUser({ AccessToken: accessToken }); |
| 262 | const nicknameAfter = plain( |
| 263 | meAfter.UserAttributes?.find((a) => a.Name === "nickname")?.Value, |
| 264 | ); |
| 265 | const refreshed = yield* auth.getTokensFromRefreshToken({ |
| 266 | RefreshToken: plain(reAuth.AuthenticationResult?.RefreshToken)!, |
| 267 | }); |
| 268 | yield* auth.deleteUser({ AccessToken: accessToken }); |
| 269 | const gone = yield* admin.adminGetUser({ Username: username }).pipe( |
| 270 | Effect.map(() => false), |
| 271 | Effect.catchTag("UserNotFoundException", () => Effect.succeed(true)), |
| 272 | ); |
| 273 | return yield* HttpServerResponse.json({ |
| 274 | changedPasswordAuth: reAuth.AuthenticationResult?.AccessToken !== undefined, |
| 275 | nickname, |
| 276 | nicknameAfter: nicknameAfter ?? null, |
| 277 | refreshedHasAccessToken: refreshed.AuthenticationResult?.AccessToken !== undefined, |
| 278 | deleted: gone, |
| 279 | }); |
| 280 | } |
| 281 | |
| 282 | // Extended admin surface: attribute deletion, group listings, |
| 283 | // device listing. |
| 284 | if (request.method === "POST" && pathname === "/admin-extended") { |
| 285 | yield* admin |
| 286 | .adminCreateUser({ |
| 287 | Username: username, |
| 288 | MessageAction: "SUPPRESS", |
| 289 | UserAttributes: [{ Name: "email", Value: `${username}@example.com` }], |
| 290 | }) |
| 291 | .pipe(Effect.catchTag("UsernameExistsException", () => Effect.void)); |
| 292 | yield* admin.adminUpdateUserAttributes({ |
| 293 | Username: username, |
| 294 | UserAttributes: [{ Name: "nickname", Value: "admin-extended" }], |
| 295 | }); |
| 296 | const withNickname = yield* admin.adminGetUser({ |
| 297 | Username: username, |
| 298 | }); |
| 299 | yield* admin.adminDeleteUserAttributes({ |
| 300 | Username: username, |
| 301 | UserAttributeNames: ["nickname"], |
| 302 | }); |
| 303 | const withoutNickname = yield* admin.adminGetUser({ |
| 304 | Username: username, |
| 305 | }); |
| 306 | const groupName = yield* GroupName; |
| 307 | yield* admin.adminAddUserToGroup({ |
| 308 | Username: username, |
| 309 | GroupName: groupName, |
| 310 | }); |
| 311 | const userGroups = yield* admin.adminListGroupsForUser({ |
| 312 | Username: username, |
| 313 | }); |
| 314 | const allGroups = yield* admin.listGroups(); |
| 315 | const deviceCount = yield* admin.adminListDevices({ Username: username }).pipe( |
| 316 | Effect.map((r) => (r.Devices ?? []).length), |
| 317 | // device tracking is not configured on the fixture pool |
| 318 | Effect.catchTag("InvalidUserPoolConfigurationException", () => Effect.succeed(-1)), |
| 319 | ); |
| 320 | yield* admin.adminDeleteUser({ Username: username }); |
| 321 | const nicknameOf = (user: typeof withNickname): string | undefined => |
| 322 | plain(user.UserAttributes?.find((a) => a.Name === "nickname")?.Value); |
| 323 | return yield* HttpServerResponse.json({ |
| 324 | nickname: nicknameOf(withNickname), |
| 325 | nicknameAfter: nicknameOf(withoutNickname) ?? null, |
| 326 | userGroups: (userGroups.Groups ?? []).map((g) => g.GroupName), |
| 327 | allGroups: (allGroups.Groups ?? []).map((g) => g.GroupName), |
| 328 | deviceCount, |
| 329 | }); |
| 330 | } |
| 331 | |
| 332 | // Identity pool data plane: guest identity → AWS credentials and |
| 333 | // OIDC token, then identity administration. |
| 334 | if (request.method === "POST" && pathname === "/identity-flow") { |
| 335 | const got = yield* identityAuth.getId(); |
| 336 | const identityId = got.IdentityId!; |
| 337 | const creds = yield* identityAuth.getCredentialsForIdentity({ |
| 338 | IdentityId: identityId, |
| 339 | }); |
| 340 | const openId = yield* identityAuth.getOpenIdToken({ |
| 341 | IdentityId: identityId, |
| 342 | }); |
| 343 | const described = yield* identityAdmin.describeIdentity({ |
| 344 | IdentityId: identityId, |
| 345 | }); |
| 346 | const listed = yield* identityAdmin.listIdentities({ |
| 347 | MaxResults: 60, |
| 348 | }); |
| 349 | yield* identityAdmin.deleteIdentities({ |
| 350 | IdentityIdsToDelete: [identityId], |
| 351 | }); |
| 352 | return yield* HttpServerResponse.json({ |
| 353 | identityId, |
| 354 | hasAccessKeyId: creds.Credentials?.AccessKeyId !== undefined, |
| 355 | hasSessionToken: creds.Credentials?.SessionToken !== undefined, |
| 356 | hasOpenIdToken: openId.Token !== undefined, |
| 357 | describedIdentityId: described.IdentityId, |
| 358 | listedContains: (listed.Identities ?? []).some( |
| 359 | (identity) => identity.IdentityId === identityId, |
| 360 | ), |
| 361 | }); |
| 362 | } |
| 363 | |
| 364 | if (request.method === "GET" && pathname === "/config") { |
| 365 | return yield* HttpServerResponse.json({ |
| 366 | ok: true, |
| 367 | userPoolId: yield* UserPoolId, |
| 368 | clientId: yield* ClientId, |
| 369 | }); |
| 370 | } |
| 371 | |
| 372 | return yield* HttpServerResponse.json( |
| 373 | { error: "Not found", method: request.method, pathname }, |
| 374 | { status: 404 }, |
| 375 | ); |
| 376 | }).pipe( |
| 377 | // Surface typed operation failures in the 500 body so the test's |
| 378 | // retry logging shows the real cause instead of a generic message. |
| 379 | Effect.catch((error) => HttpServerResponse.json({ error: String(error) }, { status: 500 })), |
| 380 | Effect.orDie, |
| 381 | ), |
| 382 | }; |
| 383 | }).pipe( |
| 384 | Effect.provide( |
| 385 | Layer.mergeAll( |
| 386 | Cognito.UserPoolAdminHttp, |
| 387 | Cognito.UserPoolAuthHttp, |
| 388 | Cognito.IdentityPoolAuthHttp, |
| 389 | Cognito.IdentityPoolAdminHttp, |
| 390 | ), |
| 391 | ), |
| 392 | ), |
| 393 | ); |