feat: two-factor sign-in, required for sensitive permissions (#12)
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:
1 parent
69c55a72fb
commit
eca1884918
28 files changed
+4365
-62
No files matched your search
+38
-1
@@ -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())
|
||||
|
||||
@@ -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" } } }),
|
||||
],
|
||||
});
|
||||
|
||||
@@ -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. */
|
||||
|
||||
Reference in new issue
Block a user