| 50 | |
| 51 | /** Verify a test admin through the product, retaining the test authenticator for later sign-ins. */ |
| 52 | export const verifyAdmin = (baseUrl: string, identity: Identity): Effect.Effect<Identity> => |
| 53 | Effect.promise(async () => { |
| 54 | const email = identity.credentials?.email; |
| 55 | if (!email) throw new Error("Test identity has no email"); |
| 56 | const headers = { |
| 57 | ...identity.headers, |
| 58 | origin: new URL(baseUrl).origin, |
| 59 | "content-type": "application/json", |
| 60 | }; |
| 61 | const status = await fetch(new URL("/api/auth/admin-mfa", baseUrl), { headers }); |
| 62 | if (status.ok && Option.isSome(decodeVerifiedState(await status.json()))) return identity; |
| 63 | const started = await fetch(new URL("/api/auth/admin-mfa/start", baseUrl), { |
| 64 | method: "POST", |
| 65 | headers, |
| 66 | body: "{}", |
| 67 | }); |
| 68 | if (!started.ok) throw new Error(`Admin enrollment failed (${started.status})`); |
| 69 | const raw: unknown = await started.json(); |
| 70 | const setup = Option.getOrNull(decodeSetup(raw)); |
| 71 | const secret = |
| 72 | setup?.secret ?? |
| 73 | (Option.isSome(decodeChallenge(raw)) ? testAuthenticators.get(email) : undefined); |
| 74 | if (!secret) throw new Error("Missing test authenticator"); |
| 75 | testAuthenticators.set(email, secret); |
| 76 | const pending = responseCookies(identity.headers?.cookie ?? "", started); |
| 77 | const verified = await fetch(new URL("/api/auth/admin-mfa/verify", baseUrl), { |
| 78 | method: "POST", |
| 79 | headers: { ...headers, cookie: pending }, |
| 80 | body: JSON.stringify({ code: new TOTP({ secret }).generate() }), |
| 81 | }); |
| 82 | if (!verified.ok || Option.isNone(decodeVerified(await verified.json()))) |
| 83 | throw new Error(`Admin verification failed (${verified.status})`); |
| 84 | const proof = verified.headers |
| 85 | .getSetCookie() |
| 86 | .find((cookie) => cookie.startsWith("__Host-executor-admin-mfa=")) |
| 87 | ?.split(";")[0]; |
| 88 | if (!proof) throw new Error("Admin verification set no proof cookie"); |
| 89 | const cookie = responseCookies(pending, verified); |
| 90 | return { |
| 91 | ...identity, |
| 92 | headers: { ...identity.headers, cookie }, |
| 93 | cookies: browserCookies(cookie), |
| 94 | }; |
| 95 | }); |
| 96 | |
| 97 | /** Complete the visible MFA prompt using enrollment or this test identity's authenticator. */ |
| 98 | export const verifyAdminInBrowser = async (page: Page, secret?: string): Promise<void> => { |