feat: two-factor sign-in, required for sensitive permissions
Better Auth's twoFactor plugin: an authenticator app (TOTP) with 10 backup codes. Turning it on, making new backup codes and turning it off are on the account page, and signing in asks for a code once it's on. Sensitive permissions (product:remove, person:ban, person:role, settings:edit, catalog:suspend, ...) answer 403 two_factor_required without it, API tokens included; the console reminds people who need it. Better Auth's own admin endpoints are closed (404). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
69c55a72fb
commit
d5bc792190
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 { appealable, caseKinds, Cases, type Case, type CaseKind } from "./cases";
|
||||||
import { Notifications } from "./notifications";
|
import { Notifications } from "./notifications";
|
||||||
import { maxGrants, maxTokenDays, tokenPrefix, Tokens } from "./tokens";
|
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;
|
const { user, session, imvuLink, linkChallenge, audit, hostedRoom, catalog, product, hosting } = schema;
|
||||||
|
|
||||||
@@ -211,6 +221,7 @@ export function createApp({
|
|||||||
banned: p.banned === true,
|
banned: p.banned === true,
|
||||||
banReason: p.banReason ?? "",
|
banReason: p.banReason ?? "",
|
||||||
approved: p.approved,
|
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,
|
/** 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);
|
await perms.require(who, permission, scope);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof Forbidden) throw forbiddenProblem(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;
|
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). */
|
/** Who's online that viewer may see: accounts showing their presence (moderators see all). */
|
||||||
const visibleOnline = async (viewer: Person | undefined) => {
|
const visibleOnline = async (viewer: Person | undefined) => {
|
||||||
const online = realtime.online();
|
const online = realtime.online();
|
||||||
@@ -941,6 +963,8 @@ export function createApp({
|
|||||||
})),
|
})),
|
||||||
computers: computers?.n ?? 0,
|
computers: computers?.n ?? 0,
|
||||||
canLink: links.length < me.linkCap,
|
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 },
|
{ signedIn: true },
|
||||||
@@ -2050,6 +2074,7 @@ export function createApp({
|
|||||||
.post(
|
.post(
|
||||||
"/products/:id/remove",
|
"/products/:id/remove",
|
||||||
async ({ me, params, body }) => {
|
async ({ me, params, body }) => {
|
||||||
|
await need(me, "product:remove", hubScope);
|
||||||
const removed = await productCall(() => products.removeByModeration(params.id, body.reason.trim()));
|
const removed = await productCall(() => products.removeByModeration(params.id, body.reason.trim()));
|
||||||
await audited(me, "product.remove", params.id, { reason: body.reason.trim() }, {
|
await audited(me, "product.remove", params.id, { reason: body.reason.trim() }, {
|
||||||
product: params.id,
|
product: params.id,
|
||||||
@@ -2678,6 +2703,8 @@ export function createApp({
|
|||||||
return {
|
return {
|
||||||
sections,
|
sections,
|
||||||
mine: { products: scope.products.length, catalogs: scope.catalogs.length, rooms: scope.rooms.length },
|
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: {
|
todo: {
|
||||||
drafts: scope.products.length ? await products.draftCount(me.id) : 0,
|
drafts: scope.products.length ? await products.draftCount(me.id) : 0,
|
||||||
cases: await cases.openToDecide(me),
|
cases: await cases.openToDecide(me),
|
||||||
@@ -2787,6 +2814,7 @@ export function createApp({
|
|||||||
"/console/settings",
|
"/console/settings",
|
||||||
async ({ me, body }) => {
|
async ({ me, body }) => {
|
||||||
if (me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can change the hub's settings.");
|
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();
|
const from = await settings.registration();
|
||||||
await settings.setRegistration(body.registration);
|
await settings.setRegistration(body.registration);
|
||||||
if (from !== body.registration) await audited(me, "hub.registration", body.registration, { from });
|
if (from !== body.registration) await audited(me, "hub.registration", body.registration, { from });
|
||||||
@@ -2823,6 +2851,7 @@ export function createApp({
|
|||||||
.post(
|
.post(
|
||||||
"/console/people/:id/ban",
|
"/console/people/:id/ban",
|
||||||
async ({ me, params, body }) => {
|
async ({ me, params, body }) => {
|
||||||
|
await need(me, "person:ban", hubScope);
|
||||||
const p = await personById(params.id);
|
const p = await personById(params.id);
|
||||||
if (p.id === me.id) throw new Problem(400, "invalid", "You can't ban yourself.");
|
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.");
|
if (isModerator(p) && me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can ban moderators.");
|
||||||
@@ -2837,6 +2866,7 @@ export function createApp({
|
|||||||
.post(
|
.post(
|
||||||
"/console/people/:id/unban",
|
"/console/people/:id/unban",
|
||||||
async ({ me, params }) => {
|
async ({ me, params }) => {
|
||||||
|
await need(me, "person:ban", hubScope);
|
||||||
const p = await personById(params.id);
|
const p = await personById(params.id);
|
||||||
const [updated] = await db.update(user).set({ banned: false, banReason: null }).where(eq(user.id, p.id)).returning();
|
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);
|
await audited(me, "person.unban", p.username ?? p.id);
|
||||||
@@ -2848,6 +2878,7 @@ export function createApp({
|
|||||||
"/console/people/:id/role",
|
"/console/people/:id/role",
|
||||||
async ({ me, params, body }) => {
|
async ({ me, params, body }) => {
|
||||||
if (me.role !== "admin") throw new Problem(403, "forbidden", "Only admins can change roles.");
|
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);
|
const p = await personById(params.id);
|
||||||
if (p.id === me.id) throw new Problem(400, "invalid", "Another admin has to change your role.");
|
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();
|
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()
|
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))
|
.all("/api/auth/*", ({ request }) => auth.handler(request))
|
||||||
.get("/.well-known/jwks.json", async () => auth.api.getJwks())
|
.get("/.well-known/jwks.json", async () => auth.api.getJwks())
|
||||||
.get("/.well-known/t5de-keys.json", async () => signer.jwks())
|
.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),
|
// 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
|
// 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 { betterAuth } from "better-auth";
|
||||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
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 { count, schema, type Database } from "@t5de/db";
|
||||||
import { Settings } from "./settings";
|
import { Settings } from "./settings";
|
||||||
|
|
||||||
@@ -69,6 +69,9 @@ export function createAuth(db: Database, config: AuthConfig) {
|
|||||||
validateClient: (clientId) => clientId === proxyClientID,
|
validateClient: (clientId) => clientId === proxyClientID,
|
||||||
}),
|
}),
|
||||||
bearer(),
|
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" } } }),
|
jwt({ jwks: { keyPairConfig: { alg: "EdDSA", crv: "Ed25519" } } }),
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -60,6 +60,18 @@ export const permissions = [
|
|||||||
|
|
||||||
export type Permission = (typeof permissions)[number];
|
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. */
|
/** Where a permission applies. The hub covers everything. */
|
||||||
export type Scope = { type: "hub" } | { type: "catalog"; id: string } | { type: "product"; id: string };
|
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;
|
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). */
|
/** 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. */
|
/** 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 {
|
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. */
|
/** Thrown when a permission is missing; the API answers 403 with what was missing. */
|
||||||
export class Forbidden extends Error {
|
export class Forbidden extends Error {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -211,9 +230,11 @@ export class Permissions {
|
|||||||
return (await this.at(who, scope)).has(permission);
|
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> {
|
async require(who: Who | undefined, permission: Permission, scope: Scope): Promise<void> {
|
||||||
if (!(await this.can(who, permission, scope))) throw new Forbidden(permission, scope);
|
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. */
|
/** May `who` give (or take away) `role` at `scope`? Only if they hold every permission in it there. */
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
|
|||||||
import { openDatabase, type Database } from "@t5de/db";
|
import { openDatabase, type Database } from "@t5de/db";
|
||||||
import { createApp } from "../src/app";
|
import { createApp } from "../src/app";
|
||||||
import { createAuth } from "../src/auth";
|
import { createAuth } from "../src/auth";
|
||||||
|
import { twoFactorOn } from "./two-factor";
|
||||||
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
||||||
|
|
||||||
const webURL = "http://web.test";
|
const webURL = "http://web.test";
|
||||||
@@ -75,6 +76,7 @@ async function person(name: string): Promise<Person> {
|
|||||||
headers: { Origin: webURL, "Content-Type": "application/json" },
|
headers: { Origin: webURL, "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
|
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 };
|
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
|
|||||||
import { openDatabase, type Database } from "@t5de/db";
|
import { openDatabase, type Database } from "@t5de/db";
|
||||||
import { createApp } from "../src/app";
|
import { createApp } from "../src/app";
|
||||||
import { createAuth } from "../src/auth";
|
import { createAuth } from "../src/auth";
|
||||||
|
import { twoFactorOn } from "./two-factor";
|
||||||
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
||||||
|
|
||||||
const webURL = "http://web.test";
|
const webURL = "http://web.test";
|
||||||
@@ -75,6 +76,7 @@ async function person(name: string): Promise<Person> {
|
|||||||
headers: { Origin: webURL, "Content-Type": "application/json" },
|
headers: { Origin: webURL, "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
|
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 };
|
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
|
|||||||
import { openDatabase, type Database } from "@t5de/db";
|
import { openDatabase, type Database } from "@t5de/db";
|
||||||
import { createApp } from "../src/app";
|
import { createApp } from "../src/app";
|
||||||
import { createAuth } from "../src/auth";
|
import { createAuth } from "../src/auth";
|
||||||
|
import { twoFactorOn } from "./two-factor";
|
||||||
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
||||||
|
|
||||||
const webURL = "http://web.test";
|
const webURL = "http://web.test";
|
||||||
@@ -75,6 +76,7 @@ async function person(name: string): Promise<Person> {
|
|||||||
headers: { Origin: webURL, "Content-Type": "application/json" },
|
headers: { Origin: webURL, "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
|
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 };
|
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { openDatabase, type Database } from "@t5de/db";
|
|||||||
import { createApp } from "../src/app";
|
import { createApp } from "../src/app";
|
||||||
import { createAuth, proxyClientID } from "../src/auth";
|
import { createAuth, proxyClientID } from "../src/auth";
|
||||||
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
||||||
|
import { twoFactorOn } from "./two-factor";
|
||||||
|
|
||||||
const webURL = "http://web.test";
|
const webURL = "http://web.test";
|
||||||
const accounts = new Map<number, ImvuUser>();
|
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.
|
// A ban closes the connection and ends the proxy's session.
|
||||||
const erinId = (await erin.call("GET", "/api/v1/me")).json.person.id;
|
const erinId = (await erin.call("GET", "/api/v1/me")).json.person.id;
|
||||||
|
await twoFactorOn(db, "alice");
|
||||||
const closed = new Promise((r) => (ws.onclose = r));
|
const closed = new Promise((r) => (ws.onclose = r));
|
||||||
expect((await admin.call("POST", `/api/v1/console/people/${erinId}/ban`, { reason: "testing" })).status).toBe(200);
|
expect((await admin.call("POST", `/api/v1/console/people/${erinId}/ban`, { reason: "testing" })).status).toBe(200);
|
||||||
await closed;
|
await closed;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { createLocalJWKSet, jwtVerify } from "jose";
|
|||||||
import { openDatabase, type Database } from "@t5de/db";
|
import { openDatabase, type Database } from "@t5de/db";
|
||||||
import { createApp } from "../src/app";
|
import { createApp } from "../src/app";
|
||||||
import { createAuth } from "../src/auth";
|
import { createAuth } from "../src/auth";
|
||||||
|
import { twoFactorOn } from "./two-factor";
|
||||||
import { ImvuClient, imvuImage, parse, parseProduct, type ImvuUser } from "../src/imvu";
|
import { ImvuClient, imvuImage, parse, parseProduct, type ImvuUser } from "../src/imvu";
|
||||||
|
|
||||||
const webURL = "http://web.test";
|
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;
|
accounts.get(imvu.id)!.tagline = started.json.challenge.code;
|
||||||
expect((await call(p, "POST", `/api/v1/account/links/${imvu.id}/check`)).status).toBe(200);
|
expect((await call(p, "POST", `/api/v1/account/links/${imvu.id}/check`)).status).toBe(200);
|
||||||
}
|
}
|
||||||
|
await twoFactorOn(db, name);
|
||||||
return p;
|
return p;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { createApp } from "../src/app";
|
|||||||
import { createAuth } from "../src/auth";
|
import { createAuth } from "../src/auth";
|
||||||
import { ImvuClient } from "../src/imvu";
|
import { ImvuClient } from "../src/imvu";
|
||||||
import { Settings } from "../src/settings";
|
import { Settings } from "../src/settings";
|
||||||
|
import { twoFactorOn } from "./two-factor";
|
||||||
|
|
||||||
const webURL = "http://web.test";
|
const webURL = "http://web.test";
|
||||||
let db: Database;
|
let db: Database;
|
||||||
@@ -90,6 +91,10 @@ test("only admins open or close registration", async () => {
|
|||||||
const mod = await signUp("dot");
|
const mod = await signUp("dot");
|
||||||
const dot = (await call(admin, "GET", "/api/v1/console/people?waiting=true")).json.people[0];
|
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`);
|
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" });
|
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, "GET", "/api/v1/console/settings")).json).toEqual({ registration: "closed" });
|
||||||
expect((await call(mod, "PUT", "/api/v1/console/settings", { registration: "open" })).status).toBe(403);
|
expect((await call(mod, "PUT", "/api/v1/console/settings", { registration: "open" })).status).toBe(403);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
|
|||||||
import { eq, openDatabase, schema, type Database } from "@t5de/db";
|
import { eq, openDatabase, schema, type Database } from "@t5de/db";
|
||||||
import { createApp } from "../src/app";
|
import { createApp } from "../src/app";
|
||||||
import { createAuth } from "../src/auth";
|
import { createAuth } from "../src/auth";
|
||||||
|
import { twoFactorOn } from "./two-factor";
|
||||||
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
||||||
|
|
||||||
const webURL = "http://web.test";
|
const webURL = "http://web.test";
|
||||||
@@ -75,6 +76,7 @@ async function person(name: string): Promise<Person> {
|
|||||||
headers: { Origin: webURL, "Content-Type": "application/json" },
|
headers: { Origin: webURL, "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
|
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 };
|
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
@@ -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()));
|
||||||
@@ -12,6 +12,7 @@ import { AgeCard } from "./age-card";
|
|||||||
import { ChallengeCard } from "./challenge-card";
|
import { ChallengeCard } from "./challenge-card";
|
||||||
import { LinkCard } from "./link-card";
|
import { LinkCard } from "./link-card";
|
||||||
import { TokensCard } from "./tokens-card";
|
import { TokensCard } from "./tokens-card";
|
||||||
|
import { TwoFactorCard } from "./two-factor-card";
|
||||||
|
|
||||||
export const metadata: Metadata = { title: "Account" };
|
export const metadata: Metadata = { title: "Account" };
|
||||||
|
|
||||||
@@ -122,6 +123,8 @@ export default async function Account({ searchParams }: { searchParams: Promise<
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<TwoFactorCard enabled={account.twoFactor.enabled} neededFor={account.twoFactor.neededFor} />
|
||||||
|
|
||||||
<TokensCard data={tokens} />
|
<TokensCard data={tokens} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,291 @@
|
|||||||
|
"use client";
|
||||||
|
// Two-factor sign-in on the account page: turning it on (scan a code into an authenticator app, keep the backup codes,
|
||||||
|
// confirm with a code), new backup codes, and turning it off. Sensitive permissions need it on.
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { renderSVG } from "uqr";
|
||||||
|
import { CopyButton } from "@/components/copy-button";
|
||||||
|
import { ErrorText } from "@/components/forms";
|
||||||
|
import { Tag } from "@/components/status";
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { authClient } from "@/lib/auth-client";
|
||||||
|
|
||||||
|
type Stage =
|
||||||
|
| { kind: "idle" }
|
||||||
|
| { kind: "password"; then: "enable" | "codes" | "disable" }
|
||||||
|
| { kind: "setup"; uri: string; codes: string[] }
|
||||||
|
| { kind: "codes"; codes: string[] };
|
||||||
|
|
||||||
|
export function TwoFactorCard({
|
||||||
|
enabled,
|
||||||
|
neededFor,
|
||||||
|
}: {
|
||||||
|
enabled: boolean;
|
||||||
|
neededFor: string[];
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [stage, setStage] = useState<Stage>({ kind: "idle" });
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [pending, setPending] = useState(false);
|
||||||
|
|
||||||
|
async function run(fn: () => Promise<string | void>) {
|
||||||
|
setError("");
|
||||||
|
setPending(true);
|
||||||
|
const failed = await fn();
|
||||||
|
if (failed) setError(failed);
|
||||||
|
setPending(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function withPassword(
|
||||||
|
then: "enable" | "codes" | "disable",
|
||||||
|
password: string,
|
||||||
|
) {
|
||||||
|
if (then === "enable") {
|
||||||
|
const { data, error } = await authClient.twoFactor.enable({ password });
|
||||||
|
if (error || !data || !("totpURI" in data) || !data.totpURI)
|
||||||
|
return error?.message ?? "That didn't work. Try again.";
|
||||||
|
setStage({
|
||||||
|
kind: "setup",
|
||||||
|
uri: data.totpURI,
|
||||||
|
codes: data.backupCodes ?? [],
|
||||||
|
});
|
||||||
|
} else if (then === "codes") {
|
||||||
|
const { data, error } = await authClient.twoFactor.generateBackupCodes({
|
||||||
|
password,
|
||||||
|
});
|
||||||
|
if (error || !data)
|
||||||
|
return error?.message ?? "That didn't work. Try again.";
|
||||||
|
setStage({ kind: "codes", codes: data.backupCodes });
|
||||||
|
} else {
|
||||||
|
const { error } = await authClient.twoFactor.disable({ password });
|
||||||
|
if (error) return error.message ?? "That didn't work. Try again.";
|
||||||
|
setStage({ kind: "idle" });
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirm(code: string) {
|
||||||
|
const { error } = await authClient.twoFactor.verifyTotp({
|
||||||
|
code: code.replace(/\s+/g, ""),
|
||||||
|
});
|
||||||
|
if (error) return error.message ?? "That code didn't work. Try again.";
|
||||||
|
setStage({ kind: "idle" });
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitTo =
|
||||||
|
(fn: (form: FormData) => Promise<string | void>) =>
|
||||||
|
(e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const form = new FormData(e.currentTarget);
|
||||||
|
void run(() => fn(form));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
Two-Factor Sign-In {enabled && <Tag tone="strong">on</Tag>}
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Signing in asks for a code from an authenticator app on your phone as
|
||||||
|
well as your password.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{!enabled && neededFor.length > 0 && stage.kind !== "setup" && (
|
||||||
|
<Alert>
|
||||||
|
<AlertTitle>Turn this on to use everything you can do</AlertTitle>
|
||||||
|
<AlertDescription>
|
||||||
|
<span>
|
||||||
|
These need it:{" "}
|
||||||
|
{neededFor.map((p, i) => (
|
||||||
|
<span key={p}>
|
||||||
|
{i > 0 && ", "}
|
||||||
|
<span className="font-mono text-xs">{p}</span>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
.
|
||||||
|
</span>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{stage.kind === "idle" &&
|
||||||
|
(enabled ? (
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setStage({ kind: "password", then: "codes" })}
|
||||||
|
>
|
||||||
|
New backup codes
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setStage({ kind: "password", then: "disable" })}
|
||||||
|
>
|
||||||
|
Turn off
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
onClick={() => setStage({ kind: "password", then: "enable" })}
|
||||||
|
>
|
||||||
|
Turn on
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{stage.kind === "password" && (
|
||||||
|
<form
|
||||||
|
onSubmit={submitTo((f) =>
|
||||||
|
withPassword(stage.then, String(f.get("password"))),
|
||||||
|
)}
|
||||||
|
className="space-y-3"
|
||||||
|
>
|
||||||
|
<p className="text-sm">
|
||||||
|
{stage.then === "disable"
|
||||||
|
? neededFor.length > 0
|
||||||
|
? "Turning it off stops the things listed above working until you turn it on again. Enter your password."
|
||||||
|
: "Enter your password to turn it off."
|
||||||
|
: stage.then === "codes"
|
||||||
|
? "Your old backup codes stop working. Enter your password."
|
||||||
|
: "Enter your password to start."}
|
||||||
|
</p>
|
||||||
|
<div className="flex max-w-md flex-wrap gap-2">
|
||||||
|
<Input
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
aria-label="Password"
|
||||||
|
className="max-w-xs"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant={stage.then === "disable" ? "destructive" : "default"}
|
||||||
|
disabled={pending}
|
||||||
|
>
|
||||||
|
{pending
|
||||||
|
? "Checking…"
|
||||||
|
: stage.then === "disable"
|
||||||
|
? "Turn off"
|
||||||
|
: "Continue"}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setStage({ kind: "idle" })}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{stage.kind === "setup" && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<ol className="list-decimal space-y-4 pl-5 text-sm">
|
||||||
|
<li className="space-y-2">
|
||||||
|
<p>
|
||||||
|
Scan this with an authenticator app (such as Google
|
||||||
|
Authenticator, Microsoft Authenticator or 1Password).
|
||||||
|
</p>
|
||||||
|
<div
|
||||||
|
className="w-44 rounded-md bg-white p-2 [&>svg]:h-auto [&>svg]:w-full"
|
||||||
|
role="img"
|
||||||
|
aria-label="QR code for your authenticator app"
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: renderSVG(stage.uri, { border: 1 }),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Or enter this key:{" "}
|
||||||
|
<code className="font-mono text-xs break-all text-foreground">
|
||||||
|
{new URL(stage.uri).searchParams.get("secret")}
|
||||||
|
</code>
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
<li className="space-y-2">
|
||||||
|
<p>
|
||||||
|
Keep these backup codes somewhere safe. Each signs you in once
|
||||||
|
if you lose your phone.
|
||||||
|
</p>
|
||||||
|
<BackupCodes codes={stage.codes} />
|
||||||
|
</li>
|
||||||
|
<li className="space-y-2">
|
||||||
|
<p>Enter the code the app shows.</p>
|
||||||
|
<form
|
||||||
|
onSubmit={submitTo((f) => confirm(String(f.get("code"))))}
|
||||||
|
className="flex max-w-md flex-wrap gap-2"
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
name="code"
|
||||||
|
required
|
||||||
|
inputMode="numeric"
|
||||||
|
pattern="\s*[0-9]{6}\s*"
|
||||||
|
maxLength={8}
|
||||||
|
autoComplete="one-time-code"
|
||||||
|
aria-label="Code"
|
||||||
|
placeholder="123456"
|
||||||
|
className="w-32 font-mono"
|
||||||
|
/>
|
||||||
|
<Button type="submit" disabled={pending}>
|
||||||
|
{pending ? "Checking…" : "Turn on"}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setStage({ kind: "idle" })}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{stage.kind === "codes" && (
|
||||||
|
<div className="space-y-2 text-sm">
|
||||||
|
<p>
|
||||||
|
Your new backup codes. Keep them somewhere safe: they won't
|
||||||
|
be shown again.
|
||||||
|
</p>
|
||||||
|
<BackupCodes codes={stage.codes} />
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setStage({ kind: "idle" })}
|
||||||
|
>
|
||||||
|
Done
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && <ErrorText>{error}</ErrorText>}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function BackupCodes({ codes }: { codes: string[] }) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap items-start gap-3">
|
||||||
|
<ul className="grid grid-cols-2 gap-x-6 gap-y-1 rounded-md bg-muted px-3 py-2 font-mono text-xs">
|
||||||
|
{codes.map((c) => (
|
||||||
|
<li key={c}>{c}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<CopyButton text={codes.join("\n")} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,16 @@
|
|||||||
|
import Link from "next/link";
|
||||||
import { notFound, redirect } from "next/navigation";
|
import { notFound, redirect } from "next/navigation";
|
||||||
import { cache } from "react";
|
import { cache } from "react";
|
||||||
import { NavLink } from "@/components/header-client";
|
import { NavLink } from "@/components/header-client";
|
||||||
import { api, getMe, isModerator, unwrap, type ConsoleData, type Person } from "@/lib/api";
|
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||||
|
import {
|
||||||
|
api,
|
||||||
|
getMe,
|
||||||
|
isModerator,
|
||||||
|
unwrap,
|
||||||
|
type ConsoleData,
|
||||||
|
type Person,
|
||||||
|
} from "@/lib/api";
|
||||||
|
|
||||||
/** The signed-in moderator, or off to sign in; others get not found (these pages aren't for them). */
|
/** The signed-in moderator, or off to sign in; others get not found (these pages aren't for them). */
|
||||||
export async function requireModerator(path: string): Promise<Person> {
|
export async function requireModerator(path: string): Promise<Person> {
|
||||||
@@ -22,7 +31,9 @@ const loadConsole = cache(async (): Promise<ConsoleData | undefined> => {
|
|||||||
* The signed-in person and their console, or off to sign in. People who manage nothing get not found: the console
|
* The signed-in person and their console, or off to sign in. People who manage nothing get not found: the console
|
||||||
* is for those controlling a product, catalog or room.
|
* is for those controlling a product, catalog or room.
|
||||||
*/
|
*/
|
||||||
export async function requireConsole(path: string): Promise<{ me: Person; console: ConsoleData }> {
|
export async function requireConsole(
|
||||||
|
path: string,
|
||||||
|
): Promise<{ me: Person; console: ConsoleData }> {
|
||||||
const me = await getMe();
|
const me = await getMe();
|
||||||
if (!me) redirect(`/signin?next=${encodeURIComponent(path)}`);
|
if (!me) redirect(`/signin?next=${encodeURIComponent(path)}`);
|
||||||
const data = await loadConsole();
|
const data = await loadConsole();
|
||||||
@@ -43,18 +54,43 @@ const tabs: { section: Section; href: string; label: string }[] = [
|
|||||||
{ section: "audit", href: "/console/audit", label: "Audit" },
|
{ section: "audit", href: "/console/audit", label: "Audit" },
|
||||||
];
|
];
|
||||||
|
|
||||||
/** The console's sections this person may see. */
|
/** The console's sections this person may see, and a reminder when sensitive actions need two-factor sign-in. */
|
||||||
export async function ConsoleNav() {
|
export async function ConsoleNav() {
|
||||||
const sections = new Set<Section>((await loadConsole())?.sections ?? ["overview"]);
|
const data = await loadConsole();
|
||||||
|
const sections = new Set<Section>(data?.sections ?? ["overview"]);
|
||||||
|
const needed = data?.twoFactorNeededFor ?? [];
|
||||||
return (
|
return (
|
||||||
<nav className="mb-8 flex gap-1 border-b pb-3 text-sm">
|
<>
|
||||||
{tabs
|
{needed.length > 0 && (
|
||||||
.filter((t) => sections.has(t.section))
|
<Alert className="mb-6">
|
||||||
.map((t) => (
|
<AlertTitle>Turn on two-factor sign-in</AlertTitle>
|
||||||
<NavLink key={t.section} href={t.href} exact={t.section === "overview"}>
|
<AlertDescription>
|
||||||
{t.label}
|
<span>
|
||||||
</NavLink>
|
Some of what you can do here needs it ({needed.join(", ")}).{" "}
|
||||||
))}
|
<Link
|
||||||
</nav>
|
href="/account"
|
||||||
|
className="text-foreground underline underline-offset-4"
|
||||||
|
>
|
||||||
|
Turn it on in your account
|
||||||
|
</Link>
|
||||||
|
.
|
||||||
|
</span>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
<nav className="mb-8 flex gap-1 border-b pb-3 text-sm">
|
||||||
|
{tabs
|
||||||
|
.filter((t) => sections.has(t.section))
|
||||||
|
.map((t) => (
|
||||||
|
<NavLink
|
||||||
|
key={t.section}
|
||||||
|
href={t.href}
|
||||||
|
exact={t.section === "overview"}
|
||||||
|
>
|
||||||
|
{t.label}
|
||||||
|
</NavLink>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -36,6 +36,7 @@ export default async function PersonPage({ params }: { params: Promise<{ id: str
|
|||||||
</span>
|
</span>
|
||||||
{person.banned && <Tag tone="danger">banned: {person.banReason}</Tag>}
|
{person.banned && <Tag tone="danger">banned: {person.banReason}</Tag>}
|
||||||
{!person.approved && <Tag tone="strong">waiting for approval</Tag>}
|
{!person.approved && <Tag tone="strong">waiting for approval</Tag>}
|
||||||
|
{person.twoFactor && <Tag>two-factor on</Tag>}
|
||||||
</span>
|
</span>
|
||||||
</PageHeader>
|
</PageHeader>
|
||||||
<ConsoleNav />
|
<ConsoleNav />
|
||||||
|
|||||||
@@ -65,7 +65,12 @@ export default async function People({
|
|||||||
{p.username}
|
{p.username}
|
||||||
</Link>
|
</Link>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="capitalize">{p.role}</TableCell>
|
<TableCell>
|
||||||
|
<span className="capitalize">{p.role}</span>
|
||||||
|
{p.role !== "user" && !p.twoFactor && (
|
||||||
|
<span className="ml-2 text-xs text-muted-foreground">no two-factor</span>
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
<TableCell className="tabular-nums">{p.linkCap}</TableCell>
|
<TableCell className="tabular-nums">{p.linkCap}</TableCell>
|
||||||
<TableCell className="text-muted-foreground">
|
<TableCell className="text-muted-foreground">
|
||||||
<DateTime iso={p.createdAt} dateOnly />
|
<DateTime iso={p.createdAt} dateOnly />
|
||||||
|
|||||||
@@ -4,30 +4,56 @@ import { useRouter } from "next/navigation";
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { ErrorText } from "@/components/forms";
|
import { ErrorText } from "@/components/forms";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
|
import {
|
||||||
|
Field,
|
||||||
|
FieldDescription,
|
||||||
|
FieldGroup,
|
||||||
|
FieldLabel,
|
||||||
|
} from "@/components/ui/field";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { authClient } from "@/lib/auth-client";
|
import { authClient } from "@/lib/auth-client";
|
||||||
|
|
||||||
/** Signs in with Better Auth, then goes to next (already checked to be a path on this site). */
|
/** Signs in with Better Auth (then a code, if two-factor sign-in is on), then goes to next (already checked to be a
|
||||||
|
* path on this site). */
|
||||||
export function SignInForm({ next }: { next: string }) {
|
export function SignInForm({ next }: { next: string }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [pending, setPending] = useState(false);
|
const [pending, setPending] = useState(false);
|
||||||
|
// After the password, when two-factor sign-in is on: a code from the app, or a backup code.
|
||||||
|
const [step, setStep] = useState<"password" | "code" | "backup">("password");
|
||||||
|
|
||||||
|
const done = () => {
|
||||||
|
router.push(next);
|
||||||
|
router.refresh();
|
||||||
|
};
|
||||||
|
|
||||||
|
async function signIn(form: FormData) {
|
||||||
|
const { data, error } = await authClient.signIn.username({
|
||||||
|
username: String(form.get("username")),
|
||||||
|
password: String(form.get("password")),
|
||||||
|
});
|
||||||
|
if (error) return setError(error.message ?? "That didn't work. Try again.");
|
||||||
|
if (data && "twoFactorRedirect" in data && data.twoFactorRedirect)
|
||||||
|
return setStep("code");
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verify(form: FormData) {
|
||||||
|
const code = String(form.get("code")).replace(/\s+/g, "");
|
||||||
|
const { error } =
|
||||||
|
step === "code"
|
||||||
|
? await authClient.twoFactor.verifyTotp({ code })
|
||||||
|
: await authClient.twoFactor.verifyBackupCode({ code });
|
||||||
|
if (error)
|
||||||
|
return setError(error.message ?? "That code didn't work. Try again.");
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
|
||||||
async function submit(form: FormData) {
|
async function submit(form: FormData) {
|
||||||
setError("");
|
setError("");
|
||||||
setPending(true);
|
setPending(true);
|
||||||
const { error } = await authClient.signIn.username({
|
await (step === "password" ? signIn(form) : verify(form));
|
||||||
username: String(form.get("username")),
|
setPending(false);
|
||||||
password: String(form.get("password")),
|
|
||||||
});
|
|
||||||
if (error) {
|
|
||||||
setError(error.message ?? "That didn't work. Try again.");
|
|
||||||
setPending(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
router.push(next);
|
|
||||||
router.refresh();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -37,25 +63,84 @@ export function SignInForm({ next }: { next: string }) {
|
|||||||
void submit(new FormData(e.currentTarget));
|
void submit(new FormData(e.currentTarget));
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<FieldGroup>
|
{step === "password" ? (
|
||||||
<Field>
|
<FieldGroup>
|
||||||
<FieldLabel htmlFor="username">Username</FieldLabel>
|
<Field>
|
||||||
<Input id="username" name="username" autoComplete="username" required autoFocus />
|
<FieldLabel htmlFor="username">Username</FieldLabel>
|
||||||
</Field>
|
<Input
|
||||||
<Field>
|
id="username"
|
||||||
<FieldLabel htmlFor="password">Password</FieldLabel>
|
name="username"
|
||||||
<Input id="password" name="password" type="password" autoComplete="current-password" required />
|
autoComplete="username"
|
||||||
</Field>
|
required
|
||||||
{error && <ErrorText>{error}</ErrorText>}
|
autoFocus
|
||||||
<Field>
|
/>
|
||||||
<Button type="submit" disabled={pending}>
|
</Field>
|
||||||
{pending ? "Signing in…" : "Sign in"}
|
<Field>
|
||||||
</Button>
|
<FieldLabel htmlFor="password">Password</FieldLabel>
|
||||||
<FieldDescription className="text-center">
|
<Input
|
||||||
No account? <Link href="/signup">Create one</Link>
|
id="password"
|
||||||
</FieldDescription>
|
name="password"
|
||||||
</Field>
|
type="password"
|
||||||
</FieldGroup>
|
autoComplete="current-password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
{error && <ErrorText>{error}</ErrorText>}
|
||||||
|
<Field>
|
||||||
|
<Button type="submit" disabled={pending}>
|
||||||
|
{pending ? "Signing in…" : "Sign in"}
|
||||||
|
</Button>
|
||||||
|
<FieldDescription className="text-center">
|
||||||
|
No account? <Link href="/signup">Create one</Link>
|
||||||
|
</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
) : (
|
||||||
|
<FieldGroup key={step}>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="code">
|
||||||
|
{step === "code"
|
||||||
|
? "Code from your authenticator app"
|
||||||
|
: "Backup code"}
|
||||||
|
</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="code"
|
||||||
|
name="code"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
autoComplete="one-time-code"
|
||||||
|
{...(step === "code"
|
||||||
|
? {
|
||||||
|
inputMode: "numeric",
|
||||||
|
pattern: "\\s*[0-9]{6}\\s*",
|
||||||
|
maxLength: 8,
|
||||||
|
}
|
||||||
|
: { maxLength: 32 })}
|
||||||
|
className="font-mono"
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
{error && <ErrorText>{error}</ErrorText>}
|
||||||
|
<Field>
|
||||||
|
<Button type="submit" disabled={pending}>
|
||||||
|
{pending ? "Checking…" : "Sign in"}
|
||||||
|
</Button>
|
||||||
|
<FieldDescription className="text-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="underline underline-offset-4"
|
||||||
|
onClick={() => {
|
||||||
|
setError("");
|
||||||
|
setStep(step === "code" ? "backup" : "code");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{step === "code"
|
||||||
|
? "Use a backup code instead"
|
||||||
|
: "Use your authenticator app instead"}
|
||||||
|
</button>
|
||||||
|
</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
)}
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
// Better Auth in the browser: sign-up, sign-in and sign-out. Its requests go to /api/auth on this site, which Next
|
// Better Auth in the browser: sign-up, sign-in (with a two-factor code when it's on), sign-out, and two-factor setup.
|
||||||
// rewrites to the API, so the session cookie is set for this site.
|
// Its requests go to /api/auth on this site, which Next rewrites to the API, so the session cookie is set for this site.
|
||||||
"use client";
|
"use client";
|
||||||
import { createAuthClient } from "better-auth/react";
|
import { createAuthClient } from "better-auth/react";
|
||||||
import { usernameClient } from "better-auth/client/plugins";
|
import { twoFactorClient, usernameClient } from "better-auth/client/plugins";
|
||||||
|
|
||||||
export const authClient = createAuthClient({
|
export const authClient = createAuthClient({
|
||||||
baseURL: typeof window === "undefined" ? undefined : window.location.origin,
|
baseURL: typeof window === "undefined" ? undefined : window.location.origin,
|
||||||
plugins: [usernameClient()],
|
plugins: [usernameClient(), twoFactorClient()],
|
||||||
});
|
});
|
||||||
@@ -19,7 +19,8 @@
|
|||||||
"next": "16.4.3",
|
"next": "16.4.3",
|
||||||
"react": "19.3.1",
|
"react": "19.3.1",
|
||||||
"react-dom": "19.3.1",
|
"react-dom": "19.3.1",
|
||||||
"server-only": "^0.0.1"
|
"server-only": "^0.0.1",
|
||||||
|
"uqr": "^0.1.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4.3.3",
|
"@tailwindcss/postcss": "^4.3.3",
|
||||||
|
|||||||
@@ -14,8 +14,8 @@
|
|||||||
"@t5de/db": "workspace:*",
|
"@t5de/db": "workspace:*",
|
||||||
"better-auth": "1.7.14",
|
"better-auth": "1.7.14",
|
||||||
"elysia": "1.4.30",
|
"elysia": "1.4.30",
|
||||||
"jose": "^6.2.14",
|
"jose": "6.2.14",
|
||||||
"sanitize-html": "^2.18.1",
|
"sanitize-html": "2.18.1",
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/bun": "^1.4.4",
|
"@types/bun": "^1.4.4",
|
||||||
@@ -37,6 +37,7 @@
|
|||||||
"react": "19.3.1",
|
"react": "19.3.1",
|
||||||
"react-dom": "19.3.1",
|
"react-dom": "19.3.1",
|
||||||
"server-only": "^0.0.1",
|
"server-only": "^0.0.1",
|
||||||
|
"uqr": "^0.1.3",
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4.3.3",
|
"@tailwindcss/postcss": "^4.3.3",
|
||||||
@@ -884,6 +885,8 @@
|
|||||||
|
|
||||||
"update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A=="],
|
"update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A=="],
|
||||||
|
|
||||||
|
"uqr": ["[email protected]", "", {}, "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA=="],
|
||||||
|
|
||||||
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],
|
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],
|
||||||
|
|
||||||
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||||
|
|||||||
+2
-1
@@ -20,7 +20,8 @@ is. Codes: `invalid`, `signed_out`, `forbidden`, `not_found`, `no_such_imvu_acco
|
|||||||
| | |
|
| | |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `POST /api/auth/sign-up/email` | `{email, password, name, username}`. Usernames 3-32 of `A-Za-z0-9_`; passwords 10-256 characters. The first account is an admin. With registration closed, the others wait for approval (`approved: false`): every route but `/me` answers 403 `awaiting_approval`, and the rest of the hub treats them as signed out. |
|
| `POST /api/auth/sign-up/email` | `{email, password, name, username}`. Usernames 3-32 of `A-Za-z0-9_`; passwords 10-256 characters. The first account is an admin. With registration closed, the others wait for approval (`approved: false`): every route but `/me` answers 403 `awaiting_approval`, and the rest of the hub treats them as signed out. |
|
||||||
| `POST /api/auth/sign-in/username` | `{username, password}` |
|
| `POST /api/auth/sign-in/username` | `{username, password}`. With two-factor sign-in on, it answers `{twoFactorRedirect: true, twoFactorMethods: ["totp"]}` and no session: then `POST /api/auth/two-factor/verify-totp` `{code}` (from the app) or `/verify-backup-code` `{code}` signs in. |
|
||||||
|
| `POST /api/auth/two-factor/enable` | `{password}` → `{totpURI, backupCodes}`; on once `POST /api/auth/two-factor/verify-totp` `{code}` confirms it. `/two-factor/disable` and `/two-factor/generate-backup-codes` take `{password}`. Sensitive permissions need it on (docs/console.md). `/api/auth/admin/*` answers 404. |
|
||||||
| `POST /api/auth/sign-out` | |
|
| `POST /api/auth/sign-out` | |
|
||||||
| `GET /api/v1/me` | `{person}` (`approved` false while waiting), with `picture`: the avatar picture of their first linked IMVU account (from IMVU, kept an hour), or `null`, `console`: whether the console is for them, and `unread`: their unread notifications |
|
| `GET /api/v1/me` | `{person}` (`approved` false while waiting), with `picture`: the avatar picture of their first linked IMVU account (from IMVU, kept an hour), or `null`, `console`: whether the console is for them, and `unread`: their unread notifications |
|
||||||
| `GET /api/v1/hub` | (anyone) `{registration}`: `open` or `closed` |
|
| `GET /api/v1/hub` | (anyone) `{registration}`: `open` or `closed` |
|
||||||
|
|||||||
+12
-1
@@ -75,7 +75,18 @@ while viewing.
|
|||||||
Anyone holding a sensitive permission must have two-factor sign-in on (Better Auth's `twoFactor` plugin, TOTP with
|
Anyone holding a sensitive permission must have two-factor sign-in on (Better Auth's `twoFactor` plugin, TOTP with
|
||||||
backup codes): `product:remove`, `person:ban`, `person:role`, `audit:read-sensitive`, `catalog:transfer`,
|
backup codes): `product:remove`, `person:ban`, `person:role`, `audit:read-sensitive`, `catalog:transfer`,
|
||||||
`catalog:suspend`, `import:grant-on-behalf`, `settings:edit`. Without it, those actions answer 403
|
`catalog:suspend`, `import:grant-on-behalf`, `settings:edit`. Without it, those actions answer 403
|
||||||
`two_factor_required` and the console asks them to set it up. Giving someone such a role reminds them.
|
`two_factor_required` (with `permission`) and the console asks them to set it up. Giving someone such a role
|
||||||
|
reminds them.
|
||||||
|
|
||||||
|
Built (2026-11-05): `permissions.ts` `sensitive`; `require` throws `TwoFactorRequired` after the permission check,
|
||||||
|
so API tokens are covered too (their owner needs it on). Turning it on is on the account page: the password, then a
|
||||||
|
QR code (and the key as text) for an authenticator app, 10 backup codes, and a code from the app to confirm (Better
|
||||||
|
Auth's `/two-factor/enable` and `/verify-totp`). Signing in then asks for a code from the app or a backup code (each
|
||||||
|
works once). The account page can make new backup codes or turn it off (the password each time). `GET /account`
|
||||||
|
has `twoFactor: {enabled, neededFor}` (the sensitive permissions the person holds anywhere), `GET /console` has
|
||||||
|
`twoFactorNeededFor` (empty once it's on; the console shows a reminder), and people in the console show
|
||||||
|
`twoFactor`. Better Auth's own admin endpoints (`/api/auth/admin/*`) answer 404: bans and roles go through the hub's
|
||||||
|
routes, with the checks and the audit log. No "trust this browser": every sign-in asks.
|
||||||
|
|
||||||
## The console
|
## The console
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -478,8 +478,8 @@ Phases for products, catalogs and imports (products.md, console.md, imports.md):
|
|||||||
(to look into with the importer spike).
|
(to look into with the importer spike).
|
||||||
3. Cases (reports, appeals, reviews), file blocks and the catalogs' changes feed; notifications; API tokens;
|
3. Cases (reports, appeals, reviews), file blocks and the catalogs' changes feed; notifications; API tokens;
|
||||||
two-factor sign-in for sensitive permissions. Cases and notifications **done** (2026-11-05), without email, canned
|
two-factor sign-in for sensitive permissions. Cases and notifications **done** (2026-11-05), without email, canned
|
||||||
reasons, moderator notes or second approval. File blocks and API tokens **done** (2026-11-05); two-factor
|
reasons, moderator notes or second approval. File blocks, API tokens and two-factor sign-in **done**
|
||||||
sign-in next.
|
(2026-11-05); auditing turning two-factor on and off, and "trust this browser", later.
|
||||||
4. Imports: grants, recorded grants, requests, unclaimed creators, the job queue, `t5de-importer` (after its spike).
|
4. Imports: grants, recorded grants, requests, unclaimed creators, the job queue, `t5de-importer` (after its spike).
|
||||||
5. Charts and stats; mirroring between catalogs.
|
5. Charts and stats; mirroring between catalogs.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
CREATE TABLE "two_factor" (
|
||||||
|
"id" text PRIMARY KEY NOT NULL,
|
||||||
|
"user_id" text NOT NULL,
|
||||||
|
"secret" text NOT NULL,
|
||||||
|
"backup_codes" text NOT NULL,
|
||||||
|
"verified" boolean DEFAULT true NOT NULL,
|
||||||
|
"failed_verification_count" integer DEFAULT 0 NOT NULL,
|
||||||
|
"locked_until" timestamp with time zone
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "user" ADD COLUMN "two_factor_enabled" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||||
|
ALTER TABLE "two_factor" ADD CONSTRAINT "two_factor_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE INDEX "two_factor_user" ON "two_factor" USING btree ("user_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "two_factor_secret" ON "two_factor" USING btree ("secret");
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -106,6 +106,13 @@
|
|||||||
"when": 1793918993367,
|
"when": 1793918993367,
|
||||||
"tag": "0014_api_tokens",
|
"tag": "0014_api_tokens",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 15,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1793934143730,
|
||||||
|
"tag": "0015_two_factor",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -45,6 +45,8 @@ export const user = pgTable(
|
|||||||
linkCap: integer("link_cap").notNull().default(10),
|
linkCap: integer("link_cap").notNull().default(10),
|
||||||
// False while a new account waits for a moderator's approval (registration closed); it can only sign in.
|
// False while a new account waits for a moderator's approval (registration closed); it can only sign in.
|
||||||
approved: boolean("approved").notNull().default(true),
|
approved: boolean("approved").notNull().default(true),
|
||||||
|
// Two-factor sign-in (an authenticator app), required for sensitive permissions (docs/console.md).
|
||||||
|
twoFactorEnabled: boolean("two_factor_enabled").notNull().default(false),
|
||||||
},
|
},
|
||||||
(t) => [uniqueIndex("user_username_lower").on(sql`lower(${t.username})`)],
|
(t) => [uniqueIndex("user_username_lower").on(sql`lower(${t.username})`)],
|
||||||
);
|
);
|
||||||
@@ -112,6 +114,23 @@ export const jwks = pgTable("jwks", {
|
|||||||
crv: text("crv"),
|
crv: text("crv"),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Two-factor sign-in: the person's authenticator secret and backup codes (both encrypted by Better Auth).
|
||||||
|
export const twoFactor = pgTable(
|
||||||
|
"two_factor",
|
||||||
|
{
|
||||||
|
id: text("id").primaryKey(),
|
||||||
|
userId: text("user_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => user.id, { onDelete: "cascade" }),
|
||||||
|
secret: text("secret").notNull(),
|
||||||
|
backupCodes: text("backup_codes").notNull(),
|
||||||
|
verified: boolean("verified").notNull().default(true),
|
||||||
|
failedVerificationCount: integer("failed_verification_count").notNull().default(0),
|
||||||
|
lockedUntil: timestamp("locked_until", { withTimezone: true }),
|
||||||
|
},
|
||||||
|
(t) => [index("two_factor_user").on(t.userId), index("two_factor_secret").on(t.secret)],
|
||||||
|
);
|
||||||
|
|
||||||
// A T5DE proxy signing in: it shows userCode, the person approves it on the website.
|
// A T5DE proxy signing in: it shows userCode, the person approves it on the website.
|
||||||
export const deviceCode = pgTable("device_code", {
|
export const deviceCode = pgTable("device_code", {
|
||||||
id: text("id").primaryKey(),
|
id: text("id").primaryKey(),
|
||||||
|
|||||||
Reference in new issue
Block a user