feat: two-factor sign-in, required for sensitive permissions (#12)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m16s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 13s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 19s

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]>
This commit was merged in pull request #12.
This commit is contained in:
dhkatz authored and dhkatz committed 2026-11-06 03:23:02 +00:00
1 parent 69c55a72fb
commit eca1884918
28 files changed
+4365 -62

No files matched your search

+38 -1
View File
@@ -48,7 +48,17 @@ import { Catalogs } from "./catalogs";
import { appealable, caseKinds, Cases, type Case, type CaseKind } from "./cases";
import { Notifications } from "./notifications";
import { maxGrants, maxTokenDays, tokenPrefix, Tokens } from "./tokens";
import { assignableCatalogRoles, Forbidden, hubScope, Permissions, roles as roleBundles, type Scope } from "./permissions";
import {
assignableCatalogRoles,
Forbidden,
hubScope,
Permissions,
roles as roleBundles,
sensitive,
TwoFactorRequired,
type Permission,
type Scope,
} from "./permissions";
const { user, session, imvuLink, linkChallenge, audit, hostedRoom, catalog, product, hosting } = schema;
@@ -211,6 +221,7 @@ export function createApp({
banned: p.banned === true,
banReason: p.banReason ?? "",
approved: p.approved,
twoFactor: p.twoFactorEnabled,
});
/** A person's picture, for the website's header: their first linked IMVU account's avatar picture (null if none,
@@ -291,10 +302,21 @@ export function createApp({
await perms.require(who, permission, scope);
} catch (e) {
if (e instanceof Forbidden) throw forbiddenProblem(e);
if (e instanceof TwoFactorRequired)
throw new Problem(403, "two_factor_required", e.message, { permission: e.permission });
throw e;
}
};
/** The sensitive permissions a person holds anywhere (hub-wide, or on a catalog's team): they need two-factor
* sign-in for those. */
const sensitiveHeld = async (me: Person): Promise<Permission[]> => {
const held = new Set([...perms.hub(me)].filter((p) => sensitive.includes(p)));
for (const c of await perms.teamCatalogs(me.id))
for (const p of await perms.at(me, catalogScope(c))) if (sensitive.includes(p)) held.add(p);
return sensitive.filter((p) => held.has(p));
};
/** Who's online that viewer may see: accounts showing their presence (moderators see all). */
const visibleOnline = async (viewer: Person | undefined) => {
const online = realtime.online();
@@ -941,6 +963,8 @@ export function createApp({
})),
computers: computers?.n ?? 0,
canLink: links.length < me.linkCap,
// Two-factor sign-in: on or off, and what needs it (sensitive permissions the person holds).
twoFactor: { enabled: me.twoFactorEnabled, neededFor: await sensitiveHeld(me) },
};
},
{ signedIn: true },
@@ -2050,6 +2074,7 @@ export function createApp({
.post(
"/products/:id/remove",
async ({ me, params, body }) => {
await need(me, "product:remove", hubScope);
const removed = await productCall(() => products.removeByModeration(params.id, body.reason.trim()));
await audited(me, "product.remove", params.id, { reason: body.reason.trim() }, {
product: params.id,
@@ -2678,6 +2703,8 @@ export function createApp({
return {
sections,
mine: { products: scope.products.length, catalogs: scope.catalogs.length, rooms: scope.rooms.length },
// Sensitive permissions held without two-factor sign-in: the console asks them to turn it on.
twoFactorNeededFor: me.twoFactorEnabled ? [] : await sensitiveHeld(me),
todo: {
drafts: scope.products.length ? await products.draftCount(me.id) : 0,
cases: await cases.openToDecide(me),
@@ -2787,6 +2814,7 @@ export function createApp({
"/console/settings",
async ({ me, body }) => {
if (me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can change the hub's settings.");
await need(me, "settings:edit", hubScope);
const from = await settings.registration();
await settings.setRegistration(body.registration);
if (from !== body.registration) await audited(me, "hub.registration", body.registration, { from });
@@ -2823,6 +2851,7 @@ export function createApp({
.post(
"/console/people/:id/ban",
async ({ me, params, body }) => {
await need(me, "person:ban", hubScope);
const p = await personById(params.id);
if (p.id === me.id) throw new Problem(400, "invalid", "You can't ban yourself.");
if (isModerator(p) && me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can ban moderators.");
@@ -2837,6 +2866,7 @@ export function createApp({
.post(
"/console/people/:id/unban",
async ({ me, params }) => {
await need(me, "person:ban", hubScope);
const p = await personById(params.id);
const [updated] = await db.update(user).set({ banned: false, banReason: null }).where(eq(user.id, p.id)).returning();
await audited(me, "person.unban", p.username ?? p.id);
@@ -2848,6 +2878,7 @@ export function createApp({
"/console/people/:id/role",
async ({ me, params, body }) => {
if (me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can change roles.");
await need(me, "person:role", hubScope);
const p = await personById(params.id);
if (p.id === me.id) throw new Problem(400, "invalid", "Another admin has to change your role.");
const [updated] = await db.update(user).set({ role: body.role }).where(eq(user.id, p.id)).returning();
@@ -2912,6 +2943,12 @@ export function createApp({
});
const app = new Elysia()
// Better Auth's admin endpoints (bans, roles, impersonation) aren't used: the hub's own routes do those, with
// permission and two-factor checks and the audit log.
.all("/api/auth/admin/*", ({ set }) => {
set.status = 404;
return { error: "not_found", message: "Not found." };
})
.all("/api/auth/*", ({ request }) => auth.handler(request))
.get("/.well-known/jwks.json", async () => auth.api.getJwks())
.get("/.well-known/t5de-keys.json", async () => signer.jwks())
+5 -2
View File
@@ -1,9 +1,9 @@
// Accounts, sessions and proxy sign-in, by Better Auth: email and password with usernames, roles and bans (admin),
// device sign-in for T5DE's proxy (RFC 8628), bearer tokens for the proxy's requests, and JWTs with published keys
// (for catalogs later).
// (for catalogs later), and two-factor sign-in (an authenticator app, with backup codes).
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, bearer, deviceAuthorization, jwt, username } from "better-auth/plugins";
import { admin, bearer, deviceAuthorization, jwt, twoFactor, username } from "better-auth/plugins";
import { count, schema, type Database } from "@t5de/db";
import { Settings } from "./settings";
@@ -69,6 +69,9 @@ export function createAuth(db: Database, config: AuthConfig) {
validateClient: (clientId) => clientId === proxyClientID,
}),
bearer(),
// Once it's on, signing in asks for a code from the app (or a backup code). The hub's own routes require it for
// sensitive permissions (permissions.ts `sensitive`).
twoFactor({ issuer: "T5DE", backupCodeOptions: { amount: 10, length: 10 } }),
jwt({ jwks: { keyPairConfig: { alg: "EdDSA", crv: "Ed25519" } } }),
],
});
+23 -2
View File
@@ -60,6 +60,18 @@ export const permissions = [
export type Permission = (typeof permissions)[number];
/** Permissions that need two-factor sign-in on: without it, using them answers 403 `two_factor_required`. */
export const sensitive: readonly Permission[] = [
"product:remove",
"person:ban",
"person:role",
"audit:read-sensitive",
"catalog:transfer",
"catalog:suspend",
"import:grant-on-behalf",
"settings:edit",
];
/** Where a permission applies. The hub covers everything. */
export type Scope = { type: "hub" } | { type: "catalog"; id: string } | { type: "product"; id: string };
@@ -144,7 +156,7 @@ export type RoleId = keyof typeof roles;
export const assignableCatalogRoles = ["catalog-operator"] as const;
/** A person, as the check needs them. Signed in with an API token, only what it grants too (the intersection). */
export type Who = { id: string; role: string; token?: { id: string; name: string; grants: TokenGrant[] } };
export type Who = { id: string; role: string; twoFactorEnabled?: boolean; token?: { id: string; name: string; grants: TokenGrant[] } };
/** Whether a token (if any) grants a permission at a scope: granted there, or hub-wide. */
export function granted(who: Who | undefined, permission: Permission, scope: Scope): boolean {
@@ -156,6 +168,13 @@ export function granted(who: Who | undefined, permission: Permission, scope: Sco
);
}
/** Thrown when a sensitive permission is held but two-factor sign-in is off. */
export class TwoFactorRequired extends Error {
constructor(readonly permission: Permission) {
super("Turn on two-factor sign-in on your account page first.");
}
}
/** Thrown when a permission is missing; the API answers 403 with what was missing. */
export class Forbidden extends Error {
constructor(
@@ -211,9 +230,11 @@ export class Permissions {
return (await this.at(who, scope)).has(permission);
}
/** Throws Forbidden unless the person holds the permission at the scope. */
/** Throws Forbidden unless the person holds the permission at the scope, and TwoFactorRequired if it's sensitive
* and they haven't turned two-factor sign-in on. */
async require(who: Who | undefined, permission: Permission, scope: Scope): Promise<void> {
if (!(await this.can(who, permission, scope))) throw new Forbidden(permission, scope);
if (sensitive.includes(permission) && !who?.twoFactorEnabled) throw new TwoFactorRequired(permission);
}
/** May `who` give (or take away) `role` at `scope`? Only if they hold every permission in it there. */
+2
View File
@@ -4,6 +4,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
@@ -75,6 +76,7 @@ async function person(name: string): Promise<Person> {
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
}
+2
View File
@@ -4,6 +4,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
@@ -75,6 +76,7 @@ async function person(name: string): Promise<Person> {
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
}
+2
View File
@@ -4,6 +4,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
@@ -75,6 +76,7 @@ async function person(name: string): Promise<Person> {
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
}
+2
View File
@@ -4,6 +4,7 @@ import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth, proxyClientID } from "../src/auth";
import { ImvuClient, type ImvuUser } from "../src/imvu";
import { twoFactorOn } from "./two-factor";
const webURL = "http://web.test";
const accounts = new Map<number, ImvuUser>();
@@ -239,6 +240,7 @@ describe("T5DE's proxy", () => {
// A ban closes the connection and ends the proxy's session.
const erinId = (await erin.call("GET", "/api/v1/me")).json.person.id;
await twoFactorOn(db, "alice");
const closed = new Promise((r) => (ws.onclose = r));
expect((await admin.call("POST", `/api/v1/console/people/${erinId}/ban`, { reason: "testing" })).status).toBe(200);
await closed;
+2
View File
@@ -4,6 +4,7 @@ import { createLocalJWKSet, jwtVerify } from "jose";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, imvuImage, parse, parseProduct, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
@@ -82,6 +83,7 @@ async function person(name: string, imvu?: { id: number; ageVerified: boolean })
accounts.get(imvu.id)!.tagline = started.json.challenge.code;
expect((await call(p, "POST", `/api/v1/account/links/${imvu.id}/check`)).status).toBe(200);
}
await twoFactorOn(db, name);
return p;
}
+5
View File
@@ -6,6 +6,7 @@ import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient } from "../src/imvu";
import { Settings } from "../src/settings";
import { twoFactorOn } from "./two-factor";
const webURL = "http://web.test";
let db: Database;
@@ -90,6 +91,10 @@ test("only admins open or close registration", async () => {
const mod = await signUp("dot");
const dot = (await call(admin, "GET", "/api/v1/console/people?waiting=true")).json.people[0];
await call(admin, "POST", `/api/v1/console/people/${dot.id}/approve`);
// Roles and hub settings are sensitive: two-factor sign-in first.
expect((await call(admin, "POST", `/api/v1/console/people/${dot.id}/role`, { role: "moderator" })).json.error).toBe("two_factor_required");
expect((await call(admin, "PUT", "/api/v1/console/settings", { registration: "open" })).json.error).toBe("two_factor_required");
await twoFactorOn(db, "ada");
await call(admin, "POST", `/api/v1/console/people/${dot.id}/role`, { role: "moderator" });
expect((await call(mod, "GET", "/api/v1/console/settings")).json).toEqual({ registration: "closed" });
expect((await call(mod, "PUT", "/api/v1/console/settings", { registration: "open" })).status).toBe(403);
+2
View File
@@ -4,6 +4,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
import { eq, openDatabase, schema, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
@@ -75,6 +76,7 @@ async function person(name: string): Promise<Person> {
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
}
+132
View File
@@ -0,0 +1,132 @@
// 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");
});
+7
View File
@@ -0,0 +1,7 @@
// Moderation tests act as people with two-factor sign-in on (sensitive permissions need it); two-factor.test.ts tests
// the sign-in itself.
import { eq, schema, type Database } from "@t5de/db";
/** Turns two-factor sign-in on for an account, as if they'd set it up. Signing in again would then ask for a code. */
export const twoFactorOn = (db: Database, username: string) =>
db.update(schema.user).set({ twoFactorEnabled: true }).where(eq(schema.user.username, username.toLowerCase()));