// Two-factor sign-in (docs/console.md): turning it on with an authenticator app, signing in with a code or a backup // code, and sensitive permissions needing it. import { afterAll, beforeAll, expect, test } from "bun:test"; import { createHmac } from "node:crypto"; import { openDatabase, type Database } from "@t5de/db"; import { createApp } from "../src/app"; import { createAuth } from "../src/auth"; import { ImvuClient } from "../src/imvu"; const webURL = "http://web.test"; const fakeIMVU = (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch; let db: Database; let close: () => Promise; let base: string; let stop: () => void; beforeAll(async () => { ({ db, close } = await openDatabase("memory")); const auth = createAuth(db, { apiURL: "http://api.test", webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false }); const hub = createApp({ db, auth, imvu: new ImvuClient("http://imvu.test", fakeIMVU), webURL }); hub.app.listen({ port: 0, hostname: "127.0.0.1" }); const server = hub.app.server as unknown as { port: number; stop: () => void }; stop = () => server.stop(); base = `http://127.0.0.1:${server.port}`; }); afterAll(async () => { stop(); await close(); }); /** A browser: keeps its cookies (sign-in replaces them). */ class Browser { cookies = new Map(); async call(method: string, path: string, body?: unknown) { const res = await fetch(base + path, { method, headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), Cookie: [...this.cookies].map(([k, v]) => `${k}=${v}`).join("; "), }, body: body !== undefined ? JSON.stringify(body) : undefined, }); for (const c of res.headers.getSetCookie()) { const [pair, ...attrs] = c.split(";"); const [k, v] = [pair!.slice(0, pair!.indexOf("=")), pair!.slice(pair!.indexOf("=") + 1)]; if (!v || attrs.some((a) => /max-age=0\b/i.test(a.trim()))) this.cookies.delete(k); else this.cookies.set(k, v); } const text = await res.text(); return { status: res.status, json: text ? JSON.parse(text) : undefined }; } } /** The current code for an otpauth:// URI's secret (RFC 6238: SHA-1, 6 digits, 30 seconds). */ function totp(uri: string): string { const secret = new URL(uri).searchParams.get("secret")!; const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; let bits = ""; for (const ch of secret.replace(/=+$/, "").toUpperCase()) bits += alphabet.indexOf(ch).toString(2).padStart(5, "0"); const key = Buffer.from(bits.match(/.{8}/g)!.map((b) => parseInt(b, 2))); const counter = Buffer.alloc(8); counter.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000 / 30))); const h = createHmac("sha1", key).update(counter).digest(); const o = h[h.length - 1]! & 0xf; return ((h.readUInt32BE(o) & 0x7fffffff) % 1_000_000).toString().padStart(6, "0"); } const password = "a long password"; test("sensitive permissions need two-factor sign-in; turning it on, signing in with a code or a backup code", async () => { const admin = new Browser(); expect((await admin.call("POST", "/api/auth/sign-up/email", { email: "root@example.test", password, name: "root", username: "root" })).status).toBe(200); const other = new Browser(); await other.call("POST", "/api/auth/sign-up/email", { email: "pat@example.test", password, name: "pat", username: "pat" }); const patId = (await other.call("GET", "/api/v1/me")).json.person.id; // Off: the account and the console say what needs it, and sensitive actions refuse. const before = (await admin.call("GET", "/api/v1/account")).json; expect(before.twoFactor.enabled).toBe(false); expect(before.twoFactor.neededFor).toContain("person:ban"); expect(before.twoFactor.neededFor).toContain("settings:edit"); expect((await admin.call("GET", "/api/v1/console")).json.twoFactorNeededFor).toContain("person:role"); const refused = await admin.call("POST", `/api/v1/console/people/${patId}/ban`, { reason: "testing" }); expect(refused.status).toBe(403); expect(refused.json).toMatchObject({ error: "two_factor_required", permission: "person:ban" }); // People with nothing sensitive aren't asked. expect((await other.call("GET", "/api/v1/account")).json.twoFactor).toEqual({ enabled: false, neededFor: [] }); // Better Auth's own admin endpoints are closed: they'd skip the check and the audit log. expect((await admin.call("GET", "/api/auth/admin/list-users")).status).toBe(404); expect((await admin.call("POST", "/api/auth/admin/ban-user", { userId: patId })).status).toBe(404); // Turning it on takes the password, then a code from the app. expect((await admin.call("POST", "/api/auth/two-factor/enable", { password: "wrong password!" })).status).toBe(400); const setup = (await admin.call("POST", "/api/auth/two-factor/enable", { password })).json; expect(setup.totpURI).toStartWith("otpauth://totp/T5DE:"); expect(setup.backupCodes).toHaveLength(10); expect((await admin.call("GET", "/api/v1/account")).json.twoFactor.enabled).toBe(false); expect((await admin.call("POST", "/api/auth/two-factor/verify-totp", { code: "000000" === totp(setup.totpURI) ? "111111" : "000000" })).status).toBe(401); expect((await admin.call("POST", "/api/auth/two-factor/verify-totp", { code: totp(setup.totpURI) })).status).toBe(200); const after = (await admin.call("GET", "/api/v1/account")).json; expect(after.twoFactor.enabled).toBe(true); expect(after.person.twoFactor).toBe(true); expect((await admin.call("GET", "/api/v1/console")).json.twoFactorNeededFor).toEqual([]); expect((await admin.call("POST", `/api/v1/console/people/${patId}/ban`, { reason: "testing" })).status).toBe(200); // Signing in now asks for a code: no session until it's given. const again = new Browser(); const first = await again.call("POST", "/api/auth/sign-in/username", { username: "root", password }); expect(first.json).toMatchObject({ twoFactorRedirect: true, twoFactorMethods: ["totp"] }); expect((await again.call("GET", "/api/v1/me")).status).toBe(401); expect((await again.call("POST", "/api/auth/two-factor/verify-totp", { code: totp(setup.totpURI) })).status).toBe(200); expect((await again.call("GET", "/api/v1/me")).json.person.username).toBe("root"); // A backup code works once. const lost = new Browser(); await lost.call("POST", "/api/auth/sign-in/username", { username: "root", password }); expect((await lost.call("POST", "/api/auth/two-factor/verify-backup-code", { code: setup.backupCodes[0] })).status).toBe(200); expect((await lost.call("GET", "/api/v1/me")).status).toBe(200); const reused = new Browser(); await reused.call("POST", "/api/auth/sign-in/username", { username: "root", password }); expect((await reused.call("POST", "/api/auth/two-factor/verify-backup-code", { code: setup.backupCodes[0] })).status).not.toBe(200); expect((await reused.call("GET", "/api/v1/me")).status).toBe(401); // Turning it off takes the password; sensitive actions refuse again. expect((await admin.call("POST", "/api/auth/two-factor/disable", { password })).status).toBe(200); expect((await admin.call("GET", "/api/v1/account")).json.twoFactor.enabled).toBe(false); expect((await admin.call("POST", `/api/v1/console/people/${patId}/unban`)).json.error).toBe("two_factor_required"); });