Phase 3d (docs/design.md): two-factor sign-in, required for sensitive permissions. - **Sign-in:** Better Auth's `twoFactor` plugin, using an authenticator app (TOTP) with 10 backup codes. Once it's on, signing in asks for a code from the app or a backup code, and each backup code works once. - **Account page:** a new Two-Factor Sign-In card. - To turn it on: enter your password, scan the QR code (the key is also shown as text), keep the backup codes, and confirm with a code. - Once it's on, you can make new backup codes or turn it off; both ask for the password. - If you hold sensitive permissions, the card lists the ones that need it. - **Enforcement:** the sensitive permissions are `product:remove`, `person:ban`, `person:role`, `audit:read-sensitive`, `catalog:transfer`, `catalog:suspend`, `import:grant-on-behalf` and `settings:edit` (`permissions.ts` `sensitive`). Without two-factor on, they answer 403 `two_factor_required`, and API tokens get the same check through their owner. - Routes guarded only by the moderator check now also check the permission: removing products, ban and unban, roles, and settings. - **Console:** a reminder on every console page while two-factor is needed. The People list notes staff without two-factor, and each person's page shows "two-factor on". - **Closed Better Auth admin endpoints:** `/api/auth/admin/*` now answers 404. Admins could have used these endpoints to ban people or change roles without the check or the audit log. - **Tests:** a new end-to-end test, `test/two-factor.test.ts`. Moderation tests turn two-factor on for their accounts directly (`test/two-factor.ts`). All 57 API tests pass, and type checks pass. - **Checked on the scratch hub through the website:** - turning it on with a real code - the console reminder appearing and disappearing - signing in again needing a code - a Ban form while two-factor is off showing "Turn on two-factor sign-in on your account page first." - **Not checked in a browser:** the QR and sign-in code screens. - **Dependency:** `uqr` draws the QR code; it has no dependencies of its own. Phase 3d (docs/design.md): two-factor sign-in, required for sensitive permissions. - **Sign-in:** Better Auth's `twoFactor` plugin, using an authenticator app (TOTP) with 10 backup codes. Once it's on, signing in asks for a code from the app or a backup code, and each backup code works once. - **Account page:** a new Two-Factor Sign-In card. - To turn it on: enter your password, scan the QR code (the key is also shown as text), keep the backup codes, and confirm with a code. - Once it's on, you can make new backup codes or turn it off; both ask for the password. - If you hold sensitive permissions, the card lists the ones that need it. - **Enforcement:** the sensitive permissions are `product:remove`, `person:ban`, `person:role`, `audit:read-sensitive`, `catalog:transfer`, `catalog:suspend`, `import:grant-on-behalf` and `settings:edit` (`permissions.ts` `sensitive`). Without two-factor on, they answer 403 `two_factor_required`, and API tokens get the same check through their owner. - Routes guarded only by the moderator check now also check the permission: removing products, ban and unban, roles, and settings. - **Console:** a reminder on every console page while two-factor is needed. The People list notes staff without two-factor, and each person's page shows "two-factor on". - **Closed Better Auth admin endpoints:** `/api/auth/admin/*` now answers 404. Admins could have used these endpoints to ban people or change roles without the check or the audit log. - **Tests:** a new end-to-end test, `test/two-factor.test.ts`. Moderation tests turn two-factor on for their accounts directly (`test/two-factor.ts`). All 57 API tests pass, and type checks pass. - **Checked on the scratch hub through the website:** - turning it on with a real code - the console reminder appearing and disappearing - signing in again needing a code - a Ban form while two-factor is off showing "Turn on two-factor sign-in on your account page first." - **Not checked in a browser:** the QR and sign-in code screens. - **Dependency:** `uqr` draws the QR code; it has no dependencies of its own. Later: auditing when two-factor is turned on or off, and an optional "trust this browser". 🤖 Generated with [Claude Code](https://claude.com/claude-code) Later: auditing when two-factor is turned on or off, and an optional "trust this browser". 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: dhkatz <[email protected]>
133 lines
7.2 KiB
TypeScript
133 lines
7.2 KiB
TypeScript
// 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<void>;
|
|
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<string, string>();
|
|
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: "[email protected]", password, name: "root", username: "root" })).status).toBe(200);
|
|
const other = new Browser();
|
|
await other.call("POST", "/api/auth/sign-up/email", { email: "[email protected]", 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");
|
|
});
|