Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add two-step sign-in, sign-in lockout and sign-in audit events
Claude540f8dc73c75
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c31647a..eb478e8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,27 @@ All notable changes to SignuDoc are recorded here. The format followschange settings or the database in ways that need a migration step; eachrelease says when it does.+## [Unreleased]++### Sign-in security++- Two-step sign-in: anyone with an account can add an authenticator app+ under Settings, with ten single-use backup codes. Signing in then asks for+ a code after the password.+- Administrators can require two-step sign-in of everyone (Settings,+ Organization, Sign-in security), and reset it for someone who lost their+ phone (People).+- Ten wrong passwords for one email address within 15 minutes stop sign-in+ for that address for 15 minutes.+- The site audit trail now records sign-ins, failed sign-ins, lockouts,+ sign-outs, password changes and resets, two-step sign-in changes, logo+ changes and the email domain being added. It moved from the Part 11 panel+ to the new Sign-in security panel, and is there whether or not Part 11+ mode is on.++This release changes the database (`20261117090000_sign_in_security.sql`),+which the production build applies.+## [0.2.1] - 2026-11-16A smoother first deploy. No database change: this release needs nodiff --git a/db/migrations/20261117090000_sign_in_security.sql b/db/migrations/20261117090000_sign_in_security.sqlnew file mode 100644index 0000000..0e3e89f--- /dev/null+++ b/db/migrations/20261117090000_sign_in_security.sql@@ -0,0 +1,30 @@+-- Sign-in security: two-step sign-in (an authenticator app, with backup+-- codes) and the administrator's switch that requires it of everyone.+--+-- * user."twoFactorEnabled" and the "twoFactor" table are Better Auth's+-- two-factor plugin. The secret and the backup codes are stored encrypted+-- with BETTER_AUTH_SECRET.+-- * app_settings.require_two_factor: nobody can use the app until they have+-- set up two-step sign-in. Off unless an administrator turns it on.++alter table public."user"+ add column if not exists "twoFactorEnabled" boolean not null default false;++create table if not exists public."twoFactor" (+ id text primary key,+ secret text not null,+ "backupCodes" text not null,+ "userId" text not null references public."user"(id) on delete cascade,+ verified boolean not null default true,+ "failedVerificationCount" integer not null default 0,+ "lockedUntil" timestamptz+);++create index if not exists "twoFactor_userId_idx"+ on public."twoFactor" ("userId");++create index if not exists "twoFactor_secret_idx"+ on public."twoFactor" (secret);++alter table public.app_settings+ add column if not exists require_two_factor boolean not null default false;diff --git a/docs/part11/known-gaps.md b/docs/part11/known-gaps.mdindex 70735b4..ac02d1e 100644--- a/docs/part11/known-gaps.md+++ b/docs/part11/known-gaps.md@@ -6,9 +6,7 @@ What Part 11 mode does not do yet, and what to do instead. These are also listed| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ || **No idle timeout.** A signed-in session lasts up to 7 days. Each signature needs the password again, but someone at an unlocked computer could see records. | 11.200(a)(1)(ii), 11.10(d) | Screen lock by policy and device management (SOP-2). || **No password aging or reuse rules.** Passwords need 15 or more characters and are checked against breach lists, but they never expire. | 11.300(b) | Set a change interval in SOP-2 if your organization requires one. |-| **Sign-in lockout is a rate limit only, and sign-in attempts are not audited.** Wrong passwords at _signing_ lock the account and are in the audit trail. Wrong passwords at the normal _sign-in_ are rate limited but don't lock the account, and they are not recorded in either audit trail. | 11.300(d) | If you need to watch sign-in attempts, do it outside SignuDoc, for example with Vercel's firewall and log drains to your monitoring. || **No biometrics or passkeys.** Signing uses email and password. | 11.200(b) | Not needed: email and password meet 11.200(a). |-| **Some admin changes are not in the install audit trail.** These are the logo, and the sender-address check on the Email panel. Settings, roles, identity, locks and Part 11 mode are recorded. | 11.10(e) | Record logo and email changes in change control. || **No signature meaning on templates.** A draft made from a template needs a meaning chosen for each signer before it can be sent. | none | The send is refused until each meaning is chosen, so nothing goes out without one. || **Full database access can rewrite the audit chain** consistently. | 11.10(e) | Limit database access, and file audit exports outside the database (SOP-5). || **No built-in backup of the PDFs** in Vercel Blob. | 11.10(c) | Copy the Blob store on a schedule, and test a restore (SOP-5). |diff --git a/docs/part11/procedures.md b/docs/part11/procedures.mdindex 71b1962..d18870a 100644--- a/docs/part11/procedures.md+++ b/docs/part11/procedures.md@@ -41,7 +41,7 @@ Short templates for the procedures Part 11 expects you to have. Put each into yo## SOP-5 Audit trail review and records (11.10(c), (e))1. Every `[month]`, an administrator:- - opens Settings, Part 11 and confirms the site audit trail chain is intact;+ - opens Settings, Organization, Sign-in security and confirms the site audit trail chain is intact;- downloads the site audit trail CSV for the period and files it in `[location]`;- looks for unexpected settings changes, role changes, Part 11 mode changes, identity changes and locks.2. For each finished regulated record, the sender files the signed PDF, the certificate and the envelope's audit trail CSV in `[the record system]` within `[N]` days.diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex a9a7a1b..329aa05 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -154,6 +154,16 @@ The first time you open a new install it takes you to `/setup`. There you name y- **`SETUP_TOKEN`.** A new install can be claimed by whoever opens it first. If its URL will be public before you get to it, set `SETUP_TOKEN` to a secret of your own and the setup page will ask for it.- **An install from before this page existed** has accounts but no administrator. Set `SETUP_TOKEN`, sign in with the account that should be in charge, and open `/setup`. It asks for a support address if the install has none. Sign-up stays open, as it was, until that administrator changes it.+## Sign-in security++These cover the people with an account (senders and administrators). Signers who are only sent a document open it from their emailed link and are not affected.++- **Two-step sign-in.** Anyone can turn it on under Settings, Two-step sign-in: after the password, the site asks for a 6-digit code from an authenticator app such as 1Password, Google Authenticator or Microsoft Authenticator. Setting it up gives ten single-use backup codes for when the phone is not at hand. The key and the backup codes are stored encrypted with `BETTER_AUTH_SECRET`, so keep that secret the same: a new one makes every authenticator stop working.+- **Requiring it.** An administrator can require two-step sign-in of everyone under Settings, Organization, Sign-in security. They have to use it themselves first. From then on anyone who has not set it up sees only the setup page until they have, the API refuses their requests too, and nobody can turn theirs off.+- **Lost phone.** If someone loses their phone and their backup codes, an administrator can reset their two-step sign-in under People. That turns it off and signs them out everywhere; they sign in with their password and set it up again (at once, if it is required). A session lasts until it ends or, at most, five minutes after it was reset, because sessions are briefly cached in a signed cookie.+- **Wrong passwords.** Ten wrong passwords for one email address within 15 minutes stop sign-in for that address until the 15 minutes are up. This happens whether or not the address has an account, so it says nothing about which ones do. Ten wrong codes at the second step lock that step for 15 minutes in the same way.+- **The site audit trail** (Settings, Organization, Sign-in security) records each sign-in and failed sign-in with the address it came from, lockouts, sign-outs, password changes and resets, two-step sign-in being turned on, off or reset, new backup codes, and changes to settings, roles, the logo, the email domain, identity confirmations and signing locks. The rows form one hash chain, so a changed or removed row shows, and the trail downloads as CSV.+## Your responsibilitiesYour install carries your organization's name, not SignuDoc's. In Settings, link your own terms and privacy policy (without a privacy link, signers see a notice built from your settings at `/signer-privacy`; check it), keep the support address you gave at setup pointed at a mailbox someone reads, and choose how long finished documents are kept. Under GDPR your organization is the controller; Settings, Organization has the tools to answer a signer who asks for their data or for its erasure.diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex 4f76273..45e64e7 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -3,6 +3,7 @@ import pg from "pg";import { e2eDatabaseUrl, e2eSetupToken } from "../playwright.config";import { extractLink, extractLinks, waitForEmail } from "./support/outbox";+import { totpCode } from "./support/totp";import { writeSamplePdf } from "./support/sample-pdf";const PASSWORD = "correct horse battery staple 42";@@ -1214,3 +1215,169 @@ test("a signer signs with a qualified signature in their own name, through the s).toBeVisible();});});++test("two-step sign-in: an administrator sets it up and requires it of everyone", async ({+ browser,+ page,+}) => {+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });+ let adminEmail = "";+ let memberEmail = "";++ await database.connect();++ try {+ adminEmail =+ (+ await database.query<{ email: string }>(+ `select email from public."user" where role = 'admin' order by "createdAt" limit 1`,+ )+ ).rows[0]?.email ?? "";+ memberEmail =+ (+ await database.query<{ email: string }>(+ `+ select u.email from public."user" u+ where u.role = 'user' and u."emailVerified"+ and exists (+ select 1 from public.account a+ where a."userId" = u.id and a.password is not null+ )+ order by u."createdAt" limit 1+ `,+ )+ ).rows[0]?.email ?? "";+ } finally {+ await database.end();+ }++ expect(adminEmail).not.toBe("");+ expect(memberEmail).not.toBe("");++ let key = "";+ let backupCode = "";++ await test.step("requiring it is refused until the administrator uses it", async () => {+ await page.goto("/login");+ await page.getByLabel("Email").fill(adminEmail);+ await page.getByLabel("Password").fill(PASSWORD);+ await page.getByRole("button", { name: "Log in" }).click();+ await expect(page).toHaveURL(/\/dashboard$/);+ await page.goto("/settings");+ await page+ .getByRole("button", { name: "Require two-step sign-in" })+ .click();+ await expect(+ page.getByText(/Set up two-step sign-in for your own account first/),+ ).toBeVisible();+ });++ await test.step("the administrator sets up an authenticator app", async () => {+ await page.getByRole("button", { name: "Set up two-step sign-in" }).click();+ await page.getByLabel("Your password").fill(PASSWORD);+ await page.getByRole("button", { name: "Continue" }).click();+ await expect(+ page.getByRole("img", { name: "QR code for your authenticator app" }),+ ).toBeVisible();++ key = (await page.getByTestId("totp-secret").textContent()) ?? "";+ backupCode =+ (await page+ .getByRole("list", { name: "Backup codes" })+ .getByRole("listitem")+ .first()+ .textContent()) ?? "";++ expect(key.replace(/\s/g, "")).toMatch(/^[A-Z2-7]+$/);+ expect(backupCode).not.toBe("");++ await page.getByLabel("6-digit code").fill(totpCode(key));+ await page+ .getByRole("button", { name: "Turn on two-step sign-in" })+ .click();+ await expect(+ page.getByRole("button", { name: "Make new backup codes" }),+ ).toBeVisible();+ });++ await test.step("and requires it of everyone", async () => {+ await page+ .getByRole("button", { name: "Require two-step sign-in" })+ .click();+ await expect(page.getByText("Required for everyone")).toBeVisible();+ });++ await test.step("signing in now asks for the second step; a backup code works", async () => {+ const context = await browser.newContext();+ const adminPage = await context.newPage();++ await adminPage.goto("/login");+ await adminPage.getByLabel("Email").fill(adminEmail);+ await adminPage.getByLabel("Password").fill(PASSWORD);+ await adminPage.getByRole("button", { name: "Log in" }).click();+ await expect(+ adminPage.getByRole("heading", { name: "Enter your code" }),+ ).toBeVisible();+ await adminPage+ .getByRole("button", { name: "Lost your phone? Use a backup code" })+ .click();+ await adminPage.getByLabel("Backup code").fill(backupCode);+ await adminPage.getByRole("button", { name: "Continue" }).click();+ await expect(adminPage).toHaveURL(/\/dashboard$/);+ await context.close();+ });++ await test.step("someone without it is asked to set it up before anything else", async () => {+ const context = await browser.newContext();+ const memberPage = await context.newPage();++ await memberPage.goto("/login");+ await memberPage.getByLabel("Email").fill(memberEmail);+ await memberPage.getByLabel("Password").fill(PASSWORD);+ await memberPage.getByRole("button", { name: "Log in" }).click();+ await expect(memberPage).toHaveURL(/\/two-step-setup$/);+ await expect(+ memberPage.getByRole("heading", { name: "Set up two-step sign-in" }),+ ).toBeVisible();++ // The API refuses too, not only the pages.+ const envelopes = await memberPage.request.post("/api/envelopes", {+ data: {},+ });++ expect(envelopes.status()).toBe(403);+ await memberPage.goto("/dashboard");+ await expect(memberPage).toHaveURL(/\/two-step-setup$/);+ await context.close();+ });++ await test.step("the site audit trail has all of it", async () => {+ const siteAudit = (await (+ await page.request.get("/api/admin/audit")+ ).json()) as {+ chain: { ok: boolean };+ events: { event: string; metadata: Record<string, unknown> | null }[];+ };++ expect(siteAudit.chain.ok).toBe(true);++ const events = siteAudit.events.map((event) => event.event);++ expect(events).toContain("two_factor_enabled");+ expect(events).toContain("two_factor_requirement_changed");+ expect(+ siteAudit.events.some(+ (event) =>+ event.event === "sign_in_succeeded" &&+ event.metadata?.secondStep === "backup_code",+ ),+ ).toBe(true);+ });++ await test.step("the requirement can be lifted again", async () => {+ await page+ .getByRole("button", { name: "Stop requiring two-step sign-in" })+ .click();+ await expect(page.getByText("Optional", { exact: true })).toBeVisible();+ });+});diff --git a/e2e/support/totp.ts b/e2e/support/totp.tsnew file mode 100644index 0000000..a4dce28--- /dev/null+++ b/e2e/support/totp.ts@@ -0,0 +1,37 @@+import { createHmac } from "node:crypto";++// The 6-digit code an authenticator app shows for a key (RFC 6238), so the+// tests can sign in with two-step sign-in without a phone.++const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";++function base32Decode(value: string): Buffer {+ let bits = "";++ for (const character of value.replace(/[\s=]+/g, "").toUpperCase()) {+ bits += BASE32.indexOf(character).toString(2).padStart(5, "0");+ }++ const bytes: number[] = [];++ for (let index = 0; index + 8 <= bits.length; index += 8) {+ bytes.push(Number.parseInt(bits.slice(index, index + 8), 2));+ }++ return Buffer.from(bytes);+}++/** The code for a base32 key, as typed under the QR code. */+export function totpCode(base32Key: string, at = Date.now()): string {+ const counter = Buffer.alloc(8);++ counter.writeBigUInt64BE(BigInt(Math.floor(at / 30_000)));++ const digest = createHmac("sha1", base32Decode(base32Key))+ .update(counter)+ .digest();+ const offset = (digest[digest.length - 1] ?? 0) & 0xf;+ const value = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000;++ return String(value).padStart(6, "0");+}diff --git a/package-lock.json b/package-lock.jsonindex 246dac7..850b43a 100644--- a/package-lock.json+++ b/package-lock.json@@ -33,6 +33,7 @@"resend": "^6.38.0","tailwind-merge": "^3.7.0","tw-animate-css": "^1.4.0",+ "uqr": "^0.1.3","zod": "^4.6.7"},"devDependencies": {@@ -9767,6 +9768,12 @@"browserslist": ">= 4.21.0"}},+ "node_modules/uqr": {+ "version": "0.1.3",+ "resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.3.tgz",+ "integrity": "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==",+ "license": "MIT"+ },"node_modules/uri-js": {"version": "4.4.1","resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",diff --git a/package.json b/package.jsonindex 07faecf..db147f2 100644--- a/package.json+++ b/package.json@@ -48,6 +48,7 @@"resend": "^6.38.0","tailwind-merge": "^3.7.0","tw-animate-css": "^1.4.0",+ "uqr": "^0.1.3","zod": "^4.6.7"},"devDependencies": {diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsxindex 41b2f5d..0f84ee3 100644--- a/src/app/(app)/layout.tsx+++ b/src/app/(app)/layout.tsx@@ -10,6 +10,7 @@ import { buildBranding } from "@/lib/branding";import { emailNeedsAttention } from "@/lib/email-status";import { getInstallMetadata } from "@/lib/install";import { getSettings } from "@/lib/settings";+import { needsTwoFactorSetup } from "@/lib/sign-in-security";export function generateMetadata(): Promise<Metadata> {return getInstallMetadata();@@ -31,6 +32,12 @@ export default async function AuthenticatedAppLayout({isAdminUser(session.user.id),]);+ // The install requires two-step sign-in and this person has not set it+ // up: nothing else until they have.+ if (needsTwoFactorSetup(settings, session.user)) {+ redirect("/two-step-setup");+ }+return (<BrandingProvider branding={buildBranding(settings)}><AppShelldiff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsxindex 193d84e..71e4025 100644--- a/src/app/(app)/settings/page.tsx+++ b/src/app/(app)/settings/page.tsx@@ -4,12 +4,18 @@ import { UpdatesPanel } from "@/components/settings/updates-panel";import { isAdminUser } from "@/lib/auth/admin";import { getAuthSession } from "@/lib/auth/server";import { toOrganizationSettingsView } from "@/lib/organization-settings";-import { readStoredSettings, resolveSettings } from "@/lib/settings";+import {+ getSettings,+ readStoredSettings,+ resolveSettings,+} from "@/lib/settings";+import { usesTwoFactor } from "@/lib/sign-in-security";import { getUpdateStatus } from "@/lib/software-update";export default async function SettingsPage() {const session = await getAuthSession();const isAdmin = session ? await isAdminUser(session.user.id) : false;+ const settings = await getSettings();return (<div className="space-y-8">@@ -18,6 +24,10 @@ export default async function SettingsPage() {email: session?.user.email ?? "",fullName: session?.user.name ?? "",}}+ twoFactor={{+ enabled: session ? usesTwoFactor(session.user) : false,+ required: settings.requireTwoFactor,+ }}/>{isAdmin ? (<OrganizationSettingsdiff --git a/src/app/(auth)/two-step-setup/page.tsx b/src/app/(auth)/two-step-setup/page.tsxnew file mode 100644index 0000000..deb6215--- /dev/null+++ b/src/app/(auth)/two-step-setup/page.tsx@@ -0,0 +1,22 @@+import { redirect } from "next/navigation";++import { TwoStepSetupRequired } from "@/components/auth/two-step-setup-required";+import { getAuthSession } from "@/lib/auth/server";+import { getSettings } from "@/lib/settings";+import { needsTwoFactorSetup } from "@/lib/sign-in-security";++// Where the app sends someone who must set up two-step sign-in before+// anything else, because the install requires it.+export default async function TwoStepSetupPage() {+ const session = await getAuthSession();++ if (!session) {+ redirect("/login");+ }++ if (!needsTwoFactorSetup(await getSettings(), session.user)) {+ redirect("/dashboard");+ }++ return <TwoStepSetupRequired email={session.user.email} />;+}diff --git a/src/app/(canvas)/layout.tsx b/src/app/(canvas)/layout.tsxindex d4a4f4e..9d3b664 100644--- a/src/app/(canvas)/layout.tsx+++ b/src/app/(canvas)/layout.tsx@@ -5,7 +5,8 @@ import { redirect } from "next/navigation";import { BrandingProvider } from "@/components/layout/branding-provider";import { getAuthSession } from "@/lib/auth/server";import { getInstallMetadata } from "@/lib/install";-import { getBranding } from "@/lib/settings";+import { getBranding, getSettings } from "@/lib/settings";+import { needsTwoFactorSetup } from "@/lib/sign-in-security";export function generateMetadata(): Promise<Metadata> {return getInstallMetadata();@@ -22,6 +23,10 @@ export default async function CanvasLayout({redirect("/login");}+ if (needsTwoFactorSetup(await getSettings(), session.user)) {+ redirect("/two-step-setup");+ }+return (<BrandingProvider branding={await getBranding()}>{children}diff --git a/src/app/api/admin/email/route.ts b/src/app/api/admin/email/route.tsindex 4a355b4..eb78598 100644--- a/src/app/api/admin/email/route.ts+++ b/src/app/api/admin/email/route.ts@@ -8,6 +8,7 @@ import {recheckEmailDomain,} from "@/lib/email-status";import { sendTestEmail } from "@/lib/email-test";+import { recordAdminActivity } from "@/lib/services/admin-activity";import { logRouteError } from "@/lib/security/logging";import {applyRateLimit,@@ -96,6 +97,19 @@ export async function POST(request: Request) {? await addEmailDomain(): await recheckEmailDomain();+ if (parsed.data.action === "add_domain") {+ await recordAdminActivity({+ event: "email_domain_changed",+ metadata: {+ action: "added",+ domain: "domain" in status ? status.domain : null,+ state: status.state,+ },+ request,+ user: session.user,+ });+ }+return NextResponse.json({ status });} catch (error) {return failure(request, error, session.user.id);diff --git a/src/app/api/admin/logo/route.ts b/src/app/api/admin/logo/route.tsindex 6cea6fd..23d181d 100644--- a/src/app/api/admin/logo/route.ts+++ b/src/app/api/admin/logo/route.ts@@ -9,6 +9,7 @@ import {} from "@/lib/brand-logo";import { buildBrandLogoPath } from "@/lib/branding";import { logRouteError } from "@/lib/security/logging";+import { recordAdminActivity } from "@/lib/services/admin-activity";import {applyRateLimit,buildRateLimitKey,@@ -79,6 +80,13 @@ export async function PUT(request: Request) {const version = await saveBrandLogo(body);+ await recordAdminActivity({+ event: "logo_changed",+ metadata: { action: "replaced", version },+ request,+ user: session.user,+ });+return NextResponse.json({ logoUrl: buildBrandLogoPath(version) },{ headers: privateNoStore },@@ -115,6 +123,12 @@ export async function DELETE(request: Request) {try {await removeBrandLogo();+ await recordAdminActivity({+ event: "logo_changed",+ metadata: { action: "removed" },+ request,+ user: session.user,+ });return NextResponse.json({ logoUrl: null }, { headers: privateNoStore });} catch (error) {diff --git a/src/app/api/admin/people/[id]/two-factor/route.ts b/src/app/api/admin/people/[id]/two-factor/route.tsnew file mode 100644index 0000000..1b88660--- /dev/null+++ b/src/app/api/admin/people/[id]/two-factor/route.ts@@ -0,0 +1,96 @@+import { NextResponse } from "next/server";++import { requireAdminSession } from "@/lib/auth/admin";+import { listPeople } from "@/lib/people";+import { logRouteError } from "@/lib/security/logging";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import {+ getClientIpAddress,+ getRequestPathname,+ getRequestUserAgent,+} from "@/lib/security/request";+import { resetTwoFactor, SignInSecurityError } from "@/lib/sign-in-security";++type PersonRouteContext = {+ params: Promise<{+ id: string;+ }>;+};++const noStore = { "cache-control": "private, no-store" };++// Turns off someone's two-step sign-in, for a person who lost their phone+// and their backup codes, and signs them out everywhere. Administrators+// only. Answers with the list as it now stands, narrowed by `search`.+export async function DELETE(request: Request, context: PersonRouteContext) {+ const sessionResult = await requireAdminSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ const session = sessionResult;+ const { id } = await context.params;+ const rateLimitResponse = await applyRateLimit({+ category: "people_two_factor_reset",+ key: buildRateLimitKey(["people-two-factor", session.user.id]),+ limit: 30,+ request,+ userId: session.user.id,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ const search = new URL(request.url).searchParams.get("search") ?? "";+ const actor = {+ email: session.user.email,+ ipAddress: getClientIpAddress(request.headers),+ userAgent: getRequestUserAgent(request.headers),+ userId: session.user.id,+ };++ if (id === session.user.id) {+ return NextResponse.json(+ {+ error:+ "Turn off your own two-step sign-in under Settings, Two-step sign-in.",+ },+ { headers: noStore, status: 409 },+ );+ }++ try {+ await resetTwoFactor(actor, id);++ return NextResponse.json(+ { ...(await listPeople({ search })), you: session.user.id },+ { headers: noStore },+ );+ } catch (error) {+ if (error instanceof SignInSecurityError) {+ return NextResponse.json(+ { error: error.message },+ { headers: noStore, status: error.statusCode },+ );+ }++ logRouteError(error, {+ category: "people_two_factor_reset_failure",+ ipAddress: actor.ipAddress,+ message: "Unexpected failure while resetting two-step sign-in.",+ path: getRequestPathname(request),+ userId: session.user.id,+ });++ return NextResponse.json(+ { error: "That change could not be saved." },+ { headers: noStore, status: 500 },+ );+ }+}diff --git a/src/app/api/admin/security/route.ts b/src/app/api/admin/security/route.tsnew file mode 100644index 0000000..805130b--- /dev/null+++ b/src/app/api/admin/security/route.ts@@ -0,0 +1,101 @@+import { NextResponse } from "next/server";++import { requireAdminSession } from "@/lib/auth/admin";+import { logRouteError } from "@/lib/security/logging";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import {+ getClientIpAddress,+ getRequestPathname,+ getRequestUserAgent,+} from "@/lib/security/request";+import { getSettings, readStoredSettings } from "@/lib/settings";+import {+ setTwoFactorRequirement,+ SignInSecurityError,+} from "@/lib/sign-in-security";++const noStore = { "cache-control": "private, no-store" };++// Turns the two-step sign-in requirement on or off. Administrators only.+export async function PUT(request: Request) {+ const sessionResult = await requireAdminSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ const session = sessionResult;+ const rateLimitResponse = await applyRateLimit({+ category: "sign_in_security_change",+ key: buildRateLimitKey(["sign-in-security", session.user.id]),+ limit: 20,+ request,+ userId: session.user.id,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ const body = (await request.json().catch(() => null)) as {+ requireTwoFactor?: unknown;+ } | null;++ if (typeof body?.requireTwoFactor !== "boolean") {+ return NextResponse.json(+ { error: "Say whether two-step sign-in should be required." },+ { headers: noStore, status: 400 },+ );+ }++ if ((await getSettings()).hosted) {+ return NextResponse.json(+ { error: "This setting is for self-hosted installs." },+ { headers: noStore, status: 400 },+ );+ }++ try {+ await setTwoFactorRequirement(+ {+ email: session.user.email,+ ipAddress: getClientIpAddress(request.headers),+ userAgent: getRequestUserAgent(request.headers),+ userId: session.user.id,+ },+ body.requireTwoFactor,+ );++ return NextResponse.json(+ {+ requireTwoFactor:+ (await readStoredSettings())?.requireTwoFactor ?? false,+ },+ { headers: noStore },+ );+ } catch (error) {+ if (error instanceof SignInSecurityError) {+ return NextResponse.json(+ { error: error.message },+ { headers: noStore, status: error.statusCode },+ );+ }++ logRouteError(error, {+ category: "sign_in_security_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while changing sign-in security.",+ path: getRequestPathname(request),+ userId: session.user.id,+ });++ return NextResponse.json(+ { error: "That change could not be saved." },+ { headers: noStore, status: 500 },+ );+ }+}diff --git a/src/components/auth/login-shell.tsx b/src/components/auth/login-shell.tsxindex 118f670..20d4e5e 100644--- a/src/components/auth/login-shell.tsx+++ b/src/components/auth/login-shell.tsx@@ -20,6 +20,7 @@ const verificationRequiredMessage ="Verify your email before logging in. Check your inbox for a fresh link.";type AuthErrorLike = {+ code?: string;message?: string;};@@ -129,6 +130,8 @@ function LiveLoginShell({);const [isResendingVerification, setIsResendingVerification] = useState(false);const [showResendVerification, setShowResendVerification] = useState(false);+ // The password was right and the account uses two-step sign-in.+ const [needsSecondStep, setNeedsSecondStep] = useState(false);function handleChange(field: keyof LoginFormValues) {return (event: ChangeEvent<HTMLInputElement>) => {@@ -225,7 +228,12 @@ function LiveLoginShell({if (result.error) {const normalizedErrorMessage = normalizeAuthErrorMessage(result.error);- if (normalizedErrorMessage.includes("email not verified")) {+ if ((result.error as AuthErrorLike).code === "SIGN_IN_LOCKED") {+ setBannerMessage(+ result.error.message ??+ "Too many wrong passwords. Try again in 15 minutes.",+ );+ } else if (normalizedErrorMessage.includes("email not verified")) {setBannerMessage(verificationRequiredMessage);setShowResendVerification(true);} else {@@ -239,6 +247,16 @@ function LiveLoginShell({return;}+ if (+ result.data &&+ typeof result.data === "object" &&+ "twoFactorRedirect" in result.data+ ) {+ setNeedsSecondStep(true);+ setIsSubmitting(false);+ return;+ }+router.replace("/dashboard");}@@ -335,6 +353,19 @@ function LiveLoginShell({return <ResetPasswordCard resetToken={resetToken} />;}+ if (needsSecondStep) {+ return (+ <SecondStepCard+ onRestart={(message) => {+ setNeedsSecondStep(false);+ setValues((currentValues) => ({ ...currentValues, password: "" }));+ setBannerMessage(message);+ }}+ onSignedIn={() => router.replace("/dashboard")}+ />+ );+ }+const formLocked = isSubmitting;const forgotPasswordLocked = forgotPassword.isSubmitting;@@ -643,3 +674,153 @@ function ResetPasswordCard({ resetToken }: { resetToken: string }) {</section>);}++type SecondStepCardProps = {+ /** Back to the password, with a reason to show there. */+ onRestart: (message: string) => void;+ onSignedIn: () => void;+};++function SecondStepCard({ onRestart, onSignedIn }: SecondStepCardProps) {+ const [code, setCode] = useState("");+ const [useBackupCode, setUseBackupCode] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [isSubmitting, setIsSubmitting] = useState(false);++ async function handleSubmit(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();++ if (isSubmitting) {+ return;+ }++ const trimmed = code.replace(/\s+/g, "");++ if (!useBackupCode && !/^\d{6}$/.test(trimmed)) {+ setError("Enter the 6-digit code your authenticator app shows.");+ return;+ }++ if (useBackupCode && trimmed.length === 0) {+ setError("Enter one of your backup codes.");+ return;+ }++ setError(null);+ setIsSubmitting(true);++ try {+ const response = await fetch(+ useBackupCode+ ? "/api/auth/two-factor/verify-backup-code"+ : "/api/auth/two-factor/verify-totp",+ {+ body: JSON.stringify({ code: trimmed }),+ headers: { "content-type": "application/json" },+ method: "POST",+ },+ );++ if (response.ok) {+ onSignedIn();+ return;+ }++ const payload = (await response.json().catch(() => null)) as {+ code?: string;+ message?: string;+ } | null;++ switch (payload?.code) {+ case "INVALID_CODE":+ setError(+ "That code is not right. Check the time on your phone and try the newest code.",+ );+ break;+ case "INVALID_BACKUP_CODE":+ setError("That backup code is not right, or it was used before.");+ break;+ case "ACCOUNT_TEMPORARILY_LOCKED":+ setError(+ "Too many wrong codes. Two-step sign-in is locked for 15 minutes.",+ );+ break;+ case "TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE":+ onRestart("Too many wrong codes. Log in again to get a new try.");+ return;+ case "INVALID_TWO_FACTOR_COOKIE":+ onRestart("That took too long. Log in again.");+ return;+ default:+ setError("Something went wrong. Please try again.");+ }+ } catch {+ setError("Something went wrong. Please try again.");+ } finally {+ setIsSubmitting(false);+ }+ }++ return (+ <section className="panel w-full max-w-[460px] p-8 sm:p-10">+ <div className="space-y-7">+ <div className="space-y-2">+ <p className="section-eyebrow">Two-step sign-in</p>+ <h1 className="text-[clamp(1.875rem,4.5vw,2.375rem)] font-extrabold leading-[1.08] tracking-[-0.035em] text-(--fg)">+ {useBackupCode ? "Enter a backup code" : "Enter your code"}+ </h1>+ <p className="text-sm leading-6 text-(--secondary)">+ {useBackupCode+ ? "Each backup code works once."+ : "Open your authenticator app and enter the 6-digit code it shows."}+ </p>+ </div>++ {error ? (+ <p className="notice notice-danger" role="alert">+ {error}+ </p>+ ) : null}++ <form className="space-y-5" noValidate onSubmit={handleSubmit}>+ <FieldShell+ autoComplete="one-time-code"+ disabled={isSubmitting}+ label={useBackupCode ? "Backup code" : "6-digit code"}+ name="second-step-code"+ onChange={(event) => {+ setCode(event.target.value);+ setError(null);+ }}+ readOnly={isSubmitting}+ value={code}+ />+ <ShellButton+ className="w-full"+ disabled={isSubmitting}+ loading={isSubmitting}+ type="submit"+ >+ {isSubmitting ? "Checking..." : "Continue"}+ </ShellButton>+ </form>++ <div className="border-t border-(--border) pt-5 text-sm">+ <button+ className="w-fit p-0 text-left font-bold text-(--accent-ink) underline-offset-4 hover:underline"+ onClick={() => {+ setUseBackupCode((current) => !current);+ setCode("");+ setError(null);+ }}+ type="button"+ >+ {useBackupCode+ ? "Use a code from your app instead"+ : "Lost your phone? Use a backup code"}+ </button>+ </div>+ </div>+ </section>+ );+}diff --git a/src/components/auth/two-step-setup-required.tsx b/src/components/auth/two-step-setup-required.tsxnew file mode 100644index 0000000..ef8987d--- /dev/null+++ b/src/components/auth/two-step-setup-required.tsx@@ -0,0 +1,53 @@+"use client";++import { useState } from "react";++import { useBranding } from "@/components/layout/branding-provider";+import { TwoFactorPanel } from "@/components/settings/two-factor-panel";+import { ShellButton } from "@/components/shared/form-shell";++export function TwoStepSetupRequired({ email }: { email: string }) {+ const { productName } = useBranding();+ const [isSigningOut, setIsSigningOut] = useState(false);++ async function signOut() {+ setIsSigningOut(true);++ try {+ await fetch("/api/auth/sign-out", {+ body: "{}",+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ } finally {+ window.location.assign("/login");+ }+ }++ return (+ <div className="w-full max-w-[720px] space-y-5">+ <section className="panel space-y-3 p-8 sm:p-10">+ <p className="section-eyebrow">One more step</p>+ <h1 className="text-[clamp(1.875rem,4.5vw,2.375rem)] font-extrabold leading-[1.08] tracking-[-0.035em] text-(--fg)">+ Set up two-step sign-in+ </h1>+ <p className="text-sm leading-6 text-(--secondary)">+ Your organization requires two-step sign-in on {productName}. Set it+ up for {email} to continue. It takes about a minute with an+ authenticator app on your phone.+ </p>+ </section>++ <TwoFactorPanel enabled={false} required />++ <ShellButton+ className="w-fit"+ loading={isSigningOut}+ onClick={() => void signOut()}+ variant="ghost"+ >+ Sign out+ </ShellButton>+ </div>+ );+}diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsxindex b07a957..b5ce19e 100644--- a/src/components/settings/organization-settings.tsx+++ b/src/components/settings/organization-settings.tsx@@ -7,6 +7,7 @@ import { FieldShell, ShellButton } from "@/components/shared/form-shell";import { BrandingPanel } from "@/components/settings/branding-panel";import { Part11Panel } from "@/components/settings/part11-panel";import { PeoplePanel } from "@/components/settings/people-panel";+import { SecurityPanel } from "@/components/settings/security-panel";import { SignerDataPanel } from "@/components/settings/signer-data-panel";import type { EmailDnsRecord, EmailStatus } from "@/lib/email-status";import type {@@ -400,6 +401,10 @@ export function OrganizationSettings({one organization, so it has no list of them here. */}{!values.hosted ? <PeoplePanel part11Mode={values.part11Mode} /> : null}+ {!values.hosted ? (+ <SecurityPanel initialRequireTwoFactor={values.requireTwoFactor} />+ ) : null}+{!values.hosted ? (<Part11Panel initialEnabled={values.part11Mode} />) : null}diff --git a/src/components/settings/part11-panel.tsx b/src/components/settings/part11-panel.tsxindex 44bf87d..ae3624a 100644--- a/src/components/settings/part11-panel.tsx+++ b/src/components/settings/part11-panel.tsx@@ -1,92 +1,16 @@"use client";-import { useEffect, useState } from "react";+import { useState } from "react";-import type { SystemAuditEvent } from "@/lib/services/system-audit";--// Part 11 mode and the install's own audit trail. Administrators only.+// Part 11 mode. Administrators only. The install's audit trail is in the+// security panel.const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";-type AuditResponse = {- chain?:- | { events: number; ok: true }- | { brokenAtSequence: number; events: number; ok: false };- error?: string;- events?: SystemAuditEvent[];-} | null;--const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {- identity_verification_revoked: "Identity confirmation taken back",- identity_verified: "Identity confirmed",- part11_mode_changed: "Part 11 mode changed",- reauthentication_failed: "Wrong password while signing",- role_changed: "Role changed",- settings_changed: "Settings changed",- signing_locked: "Signing locked",- signing_unlocked: "Signing unlocked",-};--function describeEvent(event: SystemAuditEvent): string {- const metadata = event.metadata ?? {};- const target =- typeof metadata.targetName === "string"- ? `${metadata.targetName}${typeof metadata.targetEmail === "string" ? ` <${metadata.targetEmail}>` : ""}`- : null;-- switch (event.event) {- case "part11_mode_changed":- return metadata.to === true ? "Turned on" : "Turned off";- case "role_changed":- return `${target ?? "Account"}: ${String(metadata.from)} to ${String(metadata.to)}`;- case "settings_changed":- return typeof metadata.changes === "object" && metadata.changes- ? Object.keys(metadata.changes).join(", ")- : "";- case "identity_verified":- return `${target ?? ""}${typeof metadata.note === "string" ? `: ${metadata.note}` : ""}`;- case "reauthentication_failed":- case "signing_locked":- return typeof metadata.failedAttempts === "number"- ? `${String(metadata.failedAttempts)} wrong in a row`- : "";- default:- return target ?? "";- }-}-export function Part11Panel({ initialEnabled }: { initialEnabled: boolean }) {const enabled = initialEnabled;const [error, setError] = useState<string | null>(null);const [isSaving, setIsSaving] = useState(false);- const [audit, setAudit] = useState<AuditResponse>(null);- const [auditRevision, setAuditRevision] = useState(0);-- useEffect(() => {- const controller = new AbortController();-- fetch("/api/admin/audit", { signal: controller.signal })- .then(async (response) => {- const payload = (await response- .json()- .catch(() => null)) as AuditResponse;-- setAudit(- response.ok- ? payload- : { error: payload?.error ?? GENERIC_ERROR_MESSAGE },- );- })- .catch((loadError: unknown) => {- if (!(- loadError instanceof DOMException && loadError.name === "AbortError"- )) {- setAudit({ error: GENERIC_ERROR_MESSAGE });- }- });-- return () => controller.abort();- }, [auditRevision]);async function changeMode(next: boolean) {setIsSaving(true);@@ -164,75 +88,6 @@ export function Part11Panel({ initialEnabled }: { initialEnabled: boolean }) {: "Turn on Part 11 mode"}</button></div>-- <div className="space-y-3">- <div className="flex flex-wrap items-center justify-between gap-3">- <h4 className="text-[0.9375rem] font-bold text-(--fg)">- Site audit trail- </h4>- <div className="flex flex-wrap gap-2">- <button- className="btn-quiet"- onClick={() => setAuditRevision((value) => value + 1)}- type="button"- >- Refresh- </button>- <a className="btn-quiet" href="/api/admin/audit?format=csv">- Download as CSV- </a>- </div>- </div>- <p className="max-w-2xl text-sm leading-6 text-(--secondary)">- Changes to settings, roles, identity confirmations and signing locks.- Each envelope has its own trail too, which its sender can export from- the envelope's page.- </p>-- {audit?.error ? (- <div className="notice notice-danger" role="alert">- {audit.error}- </div>- ) : null}-- {audit?.chain ? (- <p- className={`notice ${audit.chain.ok ? "notice-success" : "notice-danger"}`}- role="status"- >- {audit.chain.ok- ? `Hash chain intact across ${String(audit.chain.events)} events.`- : `The hash chain is broken at event ${String(audit.chain.brokenAtSequence)}: a row was changed or removed.`}- </p>- ) : null}-- {audit?.events ? (- audit.events.length === 0 ? (- <p className="text-sm text-(--secondary)">Nothing recorded yet.</p>- ) : (- <ul aria-label="Site audit trail" className="space-y-2">- {audit.events.map((event) => (- <li className="well p-3 text-sm" key={event.id}>- <p className="font-semibold text-(--fg)">- {EVENT_LABELS[event.event] ?? event.event}- <span className="font-normal text-(--secondary)">- {" "}- {describeEvent(event)}- </span>- </p>- <p className="text-xs text-(--tertiary)">- {new Date(event.createdAt * 1000)- .toISOString()- .replace("T", " ")- .replace(/\.\d{3}Z$/, " UTC")}- {event.actorEmail ? ` · ${event.actorEmail}` : ""}- </p>- </li>- ))}- </ul>- )- ) : null}- </div></div>);}diff --git a/src/components/settings/people-panel.tsx b/src/components/settings/people-panel.tsxindex 9b52baf..1e3acbe 100644--- a/src/components/settings/people-panel.tsx+++ b/src/components/settings/people-panel.tsx@@ -57,6 +57,7 @@ export function PeoplePanel({ part11Mode = false }: { part11Mode?: boolean }) {const latestSearch = useRef(search);// Part 11: the person whose identity is being confirmed, and how.const [verifyingId, setVerifyingId] = useState<string | null>(null);+ const [resettingId, setResettingId] = useState<string | null>(null);const [verificationNote, setVerificationNote] = useState("");useEffect(() => {@@ -154,6 +155,44 @@ export function PeoplePanel({ part11Mode = false }: { part11Mode?: boolean }) {}}+ async function resetTwoFactorFor(person: Person) {+ if (pendingId) {+ return;+ }++ setPendingId(person.id);+ setError(null);++ try {+ const response = await fetch(+ `/api/admin/people/${encodeURIComponent(person.id)}/two-factor?search=${encodeURIComponent(search)}`,+ { method: "DELETE" },+ );+ const payload = (await response+ .json()+ .catch(() => null)) as PeopleResponse;+ const changed = readPeopleList(payload);++ if (!response.ok || !changed) {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return;+ }++ setResettingId(null);++ if (latestSearch.current !== search) {+ setReloads((count) => count + 1);+ return;+ }++ setList(changed);+ } catch {+ setError(GENERIC_ERROR_MESSAGE);+ } finally {+ setPendingId(null);+ }+ }+async function changePart11(person: Person,action: "revoke" | "unlock" | "verify",@@ -304,7 +343,49 @@ export function PeoplePanel({ part11Mode = false }: { part11Mode?: boolean }) {{person.signingLockedAt !== null ? (<span className="pill pill-danger">Signing locked</span>) : null}+ {person.twoFactorEnabled ? (+ <span className="pill pill-success">Two-step on</span>+ ) : null}</div>+ {person.twoFactorEnabled && !isYou ? (+ <div className="flex flex-wrap items-center gap-2 pt-1">+ {resettingId === person.id ? (+ <>+ <span className="text-sm text-(--secondary)">+ Turn off their two-step sign-in and sign them out+ everywhere?+ </span>+ <button+ className="btn-quiet btn-quiet-danger"+ disabled={pendingId !== null}+ onClick={() => void resetTwoFactorFor(person)}+ type="button"+ >+ {pendingId === person.id ? "Resetting..." : "Reset"}+ </button>+ <button+ className="btn-quiet"+ disabled={pendingId !== null}+ onClick={() => setResettingId(null)}+ type="button"+ >+ Cancel+ </button>+ </>+ ) : (+ <button+ aria-label={`Reset two-step sign-in for ${person.name}`}+ className="btn-quiet"+ disabled={pendingId !== null}+ onClick={() => setResettingId(person.id)}+ title="For someone who lost their phone and their backup codes."+ type="button"+ >+ Reset two-step sign-in+ </button>+ )}+ </div>+ ) : null}{/* Envelopes sent in Part 11 mode keep its rules after it isturned off, so the controls stay for anyone they stillconcern. */}diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsxnew file mode 100644index 0000000..23c7f9e--- /dev/null+++ b/src/components/settings/security-panel.tsx@@ -0,0 +1,279 @@+"use client";++import { useEffect, useState } from "react";++import type { SystemAuditEvent } from "@/lib/services/system-audit";++// Sign-in security and the install's own audit trail. Administrators only.++const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";++type AuditResponse = {+ chain?:+ | { events: number; ok: true }+ | { brokenAtSequence: number; events: number; ok: false };+ error?: string;+ events?: SystemAuditEvent[];+} | null;++const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {+ email_domain_changed: "Email domain changed",+ identity_verification_revoked: "Identity confirmation taken back",+ identity_verified: "Identity confirmed",+ logo_changed: "Logo changed",+ part11_mode_changed: "Part 11 mode changed",+ password_changed: "Password changed",+ password_reset: "Password reset by email link",+ reauthentication_failed: "Wrong password while signing",+ role_changed: "Role changed",+ settings_changed: "Settings changed",+ sign_in_failed: "Sign-in failed",+ sign_in_locked: "Sign-in stopped after wrong passwords",+ sign_in_succeeded: "Signed in",+ signed_out: "Signed out",+ signing_locked: "Signing locked",+ signing_unlocked: "Signing unlocked",+ two_factor_backup_codes_regenerated: "New backup codes made",+ two_factor_disabled: "Two-step sign-in turned off",+ two_factor_enabled: "Two-step sign-in turned on",+ two_factor_requirement_changed: "Two-step sign-in requirement changed",+ two_factor_reset: "Two-step sign-in reset by an administrator",+};++const SIGN_IN_FAILURE_REASONS: Record<string, string> = {+ ACCOUNT_TEMPORARILY_LOCKED: "second step locked after wrong codes",+ EMAIL_NOT_VERIFIED: "email address not confirmed yet",+ INVALID_BACKUP_CODE: "wrong backup code",+ INVALID_CODE: "wrong authenticator code",+ INVALID_EMAIL_OR_PASSWORD: "wrong email or password",+ TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: "too many wrong codes, signed out",+};++function describeEvent(event: SystemAuditEvent): string {+ const metadata = event.metadata ?? {};+ const target =+ typeof metadata.targetName === "string"+ ? `${metadata.targetName}${typeof metadata.targetEmail === "string" ? ` <${metadata.targetEmail}>` : ""}`+ : null;++ switch (event.event) {+ case "part11_mode_changed":+ case "two_factor_requirement_changed":+ return metadata.to === true ? "Turned on" : "Turned off";+ case "role_changed":+ return `${target ?? "Account"}: ${String(metadata.from)} to ${String(metadata.to)}`;+ case "settings_changed":+ return typeof metadata.changes === "object" && metadata.changes+ ? Object.keys(metadata.changes).join(", ")+ : "";+ case "identity_verified":+ return `${target ?? ""}${typeof metadata.note === "string" ? `: ${metadata.note}` : ""}`;+ case "reauthentication_failed":+ case "signing_locked":+ return typeof metadata.failedAttempts === "number"+ ? `${String(metadata.failedAttempts)} wrong in a row`+ : "";+ case "sign_in_failed":+ return typeof metadata.reason === "string"+ ? (SIGN_IN_FAILURE_REASONS[metadata.reason] ?? metadata.reason)+ : "";+ case "sign_in_succeeded":+ return metadata.secondStep === "backup_code"+ ? "with a backup code"+ : metadata.secondStep === "authenticator"+ ? "with an authenticator code"+ : "";+ case "logo_changed":+ return metadata.action === "removed" ? "Removed" : "Replaced";+ case "email_domain_changed":+ return typeof metadata.domain === "string" ? metadata.domain : "";+ default:+ return target ?? "";+ }+}++export function SecurityPanel({+ initialRequireTwoFactor,+}: {+ initialRequireTwoFactor: boolean;+}) {+ const [requireTwoFactor, setRequireTwoFactor] = useState(+ initialRequireTwoFactor,+ );+ const [error, setError] = useState<string | null>(null);+ const [isSaving, setIsSaving] = useState(false);+ const [audit, setAudit] = useState<AuditResponse>(null);+ const [auditRevision, setAuditRevision] = useState(0);++ useEffect(() => {+ const controller = new AbortController();++ fetch("/api/admin/audit", { signal: controller.signal })+ .then(async (response) => {+ const payload = (await response+ .json()+ .catch(() => null)) as AuditResponse;++ setAudit(+ response.ok+ ? payload+ : { error: payload?.error ?? GENERIC_ERROR_MESSAGE },+ );+ })+ .catch((loadError: unknown) => {+ if (!(+ loadError instanceof DOMException && loadError.name === "AbortError"+ )) {+ setAudit({ error: GENERIC_ERROR_MESSAGE });+ }+ });++ return () => controller.abort();+ }, [auditRevision]);++ async function changeRequirement(next: boolean) {+ setIsSaving(true);+ setError(null);++ try {+ const response = await fetch("/api/admin/security", {+ body: JSON.stringify({ requireTwoFactor: next }),+ headers: { "content-type": "application/json" },+ method: "PUT",+ });+ const payload = (await response.json().catch(() => null)) as {+ error?: string;+ requireTwoFactor?: boolean;+ } | null;++ if (!response.ok || typeof payload?.requireTwoFactor !== "boolean") {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return;+ }++ setRequireTwoFactor(payload.requireTwoFactor);+ setAuditRevision((value) => value + 1);+ } catch {+ setError(GENERIC_ERROR_MESSAGE);+ } finally {+ setIsSaving(false);+ }+ }++ return (+ <div className="space-y-5 border-t border-(--border) pt-8" id="security">+ <div className="space-y-2">+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">+ Sign-in security+ </h3>+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">+ Two-step sign-in asks for a code from an authenticator app (such as+ 1Password, Google Authenticator or Microsoft Authenticator) after the+ password. When you require it, anyone who has not set it up is asked+ to do so the next time they open the app, and can do nothing else+ until they have. Ten wrong passwords for one email address stop+ sign-in for it for 15 minutes either way.+ </p>+ </div>++ {error ? (+ <div className="notice notice-danger" role="alert">+ {error}+ </div>+ ) : null}++ <div className="flex flex-wrap items-center gap-3">+ <span+ className={`pill ${requireTwoFactor ? "pill-success" : "pill-neutral"}`}+ >+ {requireTwoFactor ? "Required for everyone" : "Optional"}+ </span>+ <button+ className={+ requireTwoFactor ? "btn-quiet btn-quiet-danger" : "btn-quiet"+ }+ disabled={isSaving}+ onClick={() => void changeRequirement(!requireTwoFactor)}+ type="button"+ >+ {isSaving+ ? "Saving..."+ : requireTwoFactor+ ? "Stop requiring two-step sign-in"+ : "Require two-step sign-in"}+ </button>+ </div>++ <div className="space-y-3">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <h4 className="text-[0.9375rem] font-bold text-(--fg)">+ Site audit trail+ </h4>+ <div className="flex flex-wrap gap-2">+ <button+ className="btn-quiet"+ onClick={() => setAuditRevision((value) => value + 1)}+ type="button"+ >+ Refresh+ </button>+ <a className="btn-quiet" href="/api/admin/audit?format=csv">+ Download as CSV+ </a>+ </div>+ </div>+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">+ Sign-ins and failed sign-ins, changes to how people sign in, and+ changes to settings, roles, the logo, identity confirmations and+ signing locks. Each envelope has its own trail too, which its sender+ can export from the envelope's page.+ </p>++ {audit?.error ? (+ <div className="notice notice-danger" role="alert">+ {audit.error}+ </div>+ ) : null}++ {audit?.chain ? (+ <p+ className={`notice ${audit.chain.ok ? "notice-success" : "notice-danger"}`}+ role="status"+ >+ {audit.chain.ok+ ? `Hash chain intact across ${String(audit.chain.events)} events.`+ : `The hash chain is broken at event ${String(audit.chain.brokenAtSequence)}: a row was changed or removed.`}+ </p>+ ) : null}++ {audit?.events ? (+ audit.events.length === 0 ? (+ <p className="text-sm text-(--secondary)">Nothing recorded yet.</p>+ ) : (+ <ul aria-label="Site audit trail" className="space-y-2">+ {audit.events.map((event) => (+ <li className="well p-3 text-sm" key={event.id}>+ <p className="font-semibold text-(--fg)">+ {EVENT_LABELS[event.event] ?? event.event}+ <span className="font-normal text-(--secondary)">+ {" "}+ {describeEvent(event)}+ </span>+ </p>+ <p className="text-xs text-(--tertiary)">+ {new Date(event.createdAt * 1000)+ .toISOString()+ .replace("T", " ")+ .replace(/\.\d{3}Z$/, " UTC")}+ {event.actorEmail ? ` · ${event.actorEmail}` : ""}+ {event.ipAddress ? ` · ${event.ipAddress}` : ""}+ </p>+ </li>+ ))}+ </ul>+ )+ ) : null}+ </div>+ </div>+ );+}diff --git a/src/components/settings/settings-shell.tsx b/src/components/settings/settings-shell.tsxindex adb556a..a103cc3 100644--- a/src/components/settings/settings-shell.tsx+++ b/src/components/settings/settings-shell.tsx@@ -5,6 +5,7 @@ import { useState, type ChangeEvent, type FormEvent } from "react";import { useBranding } from "@/components/layout/branding-provider";import { FieldShell, ShellButton } from "@/components/shared/form-shell";import { PageHeader } from "@/components/shared/page-header";+import { TwoFactorPanel } from "@/components/settings/two-factor-panel";import {Dialog,DialogContent,@@ -20,6 +21,7 @@ const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";type SettingsShellProps = {initialProfile?: ProfileValues;+ twoFactor?: { enabled: boolean; required: boolean };};type FeedbackTone = "error" | "success";@@ -160,6 +162,7 @@ function isNoOpEmailChangeMessage(message: string) {export function SettingsShell({initialProfile = defaultProfileValues,+ twoFactor = { enabled: false, required: false },}: SettingsShellProps) {const closureCopy = useClosureCopy();const [profileValues, setProfileValues] = useState(initialProfile);@@ -552,7 +555,7 @@ export function SettingsShell({return (<div className="space-y-5"><PageHeader- description="Manage your sender profile, password, and account lifecycle."+ description="Manage your sender profile, password, two-step sign-in and account lifecycle."title="Settings"/>@@ -656,6 +659,11 @@ export function SettingsShell({</div></div>+ <TwoFactorPanel+ enabled={twoFactor.enabled}+ required={twoFactor.required}+ />+<div className="panel p-6 sm:p-8"><div className="space-y-5"><SectionHeading title="Danger zone" />diff --git a/src/components/settings/two-factor-panel.tsx b/src/components/settings/two-factor-panel.tsxnew file mode 100644index 0000000..fee6e37--- /dev/null+++ b/src/components/settings/two-factor-panel.tsx@@ -0,0 +1,434 @@+"use client";++import { useMemo, useState, type FormEvent } from "react";+import { encode } from "uqr";++import { useBranding } from "@/components/layout/branding-provider";+import { FieldShell, ShellButton } from "@/components/shared/form-shell";++// Two-step sign-in for the signed-in person: set it up with an+// authenticator app, make new backup codes, or turn it off. The work is+// done by Better Auth's two-factor endpoints under /api/auth/two-factor.++const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";++type Step =+ | { kind: "idle" }+ | { kind: "confirm-password"; purpose: "disable" | "enable" | "codes" }+ | { backupCodes: string[]; kind: "scan"; totpURI: string }+ | { backupCodes: string[]; kind: "new-codes" };++type Feedback = { message: string; tone: "error" | "success" } | null;++type ApiPayload = {+ backupCodes?: string[];+ code?: string;+ message?: string;+ totpURI?: string;+} | null;++async function postAuth(path: string, body: unknown) {+ const response = await fetch(`/api/auth${path}`, {+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ const payload = (await response.json().catch(() => null)) as ApiPayload;++ return { ok: response.ok, payload };+}++function describeAuthError(payload: ApiPayload): string {+ switch (payload?.code) {+ case "INVALID_PASSWORD":+ return "That password is not right.";+ case "INVALID_CODE":+ return "That code is not right. Check the time on your phone and try the newest code.";+ case "TWO_FACTOR_REQUIRED_BY_ADMINISTRATOR":+ return payload.message ?? GENERIC_ERROR_MESSAGE;+ default:+ return payload?.message ?? GENERIC_ERROR_MESSAGE;+ }+}++/** The key inside the otpauth:// link, for typing in by hand. */+function readSecret(totpURI: string): string {+ try {+ return new URL(totpURI).searchParams.get("secret") ?? "";+ } catch {+ return "";+ }+}++function groupSecret(secret: string): string {+ return secret.replace(/(.{4})/g, "$1 ").trim();+}++function QrCode({ value }: { value: string }) {+ const path = useMemo(() => {+ const { data, size } = encode(value, { border: 2, ecc: "M" });+ const parts: string[] = [];++ for (let y = 0; y < size; y += 1) {+ for (let x = 0; x < size; x += 1) {+ if (data[y]?.[x]) {+ parts.push(`M${String(x)} ${String(y)}h1v1h-1z`);+ }+ }+ }++ return { d: parts.join(""), size };+ }, [value]);++ return (+ <svg+ aria-label="QR code for your authenticator app"+ className="h-48 w-48 rounded-lg bg-white p-1"+ role="img"+ shapeRendering="crispEdges"+ viewBox={`0 0 ${String(path.size)} ${String(path.size)}`}+ >+ <rect fill="#ffffff" height={path.size} width={path.size} />+ <path d={path.d} fill="#000000" />+ </svg>+ );+}++function BackupCodes({+ codes,+ productName,+}: {+ codes: string[];+ productName: string;+}) {+ const download = useMemo(() => {+ const text = [+ `${productName} backup codes`,+ "",+ "Each code works once, in place of a code from your authenticator app.",+ "",+ ...codes,+ "",+ ].join("\n");++ return `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`;+ }, [codes, productName]);++ return (+ <div className="space-y-3">+ <p className="text-sm leading-6 text-(--secondary)">+ Keep these backup codes somewhere safe, such as your password manager.+ Each one works once, in place of a code from your app, if you lose your+ phone. You will not see them again.+ </p>+ <ul+ aria-label="Backup codes"+ className="well grid grid-cols-2 gap-2 p-4 font-mono text-sm sm:grid-cols-5"+ >+ {codes.map((code) => (+ <li key={code}>{code}</li>+ ))}+ </ul>+ <a className="btn-quiet" download="backup-codes.txt" href={download}>+ Download codes+ </a>+ </div>+ );+}++export function TwoFactorPanel({+ enabled,+ required,+}: {+ enabled: boolean;+ required: boolean;+}) {+ const { productName } = useBranding();+ const [step, setStep] = useState<Step>({ kind: "idle" });+ const [password, setPassword] = useState("");+ const [code, setCode] = useState("");+ const [feedback, setFeedback] = useState<Feedback>(null);+ const [isBusy, setIsBusy] = useState(false);++ function start(purpose: "disable" | "enable" | "codes") {+ setPassword("");+ setFeedback(null);+ setStep({ kind: "confirm-password", purpose });+ }++ function cancel() {+ setPassword("");+ setCode("");+ setFeedback(null);+ setStep({ kind: "idle" });+ }++ async function handlePassword(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();++ if (isBusy || step.kind !== "confirm-password") {+ return;+ }++ if (!password) {+ setFeedback({ message: "Enter your password.", tone: "error" });+ return;+ }++ setIsBusy(true);+ setFeedback(null);++ try {+ if (step.purpose === "enable") {+ const { ok, payload } = await postAuth("/two-factor/enable", {+ issuer: productName,+ password,+ });++ if (!ok || !payload?.totpURI || !payload.backupCodes) {+ setFeedback({ message: describeAuthError(payload), tone: "error" });+ return;+ }++ setPassword("");+ setCode("");+ setStep({+ backupCodes: payload.backupCodes,+ kind: "scan",+ totpURI: payload.totpURI,+ });+ return;+ }++ if (step.purpose === "codes") {+ const { ok, payload } = await postAuth(+ "/two-factor/generate-backup-codes",+ { password },+ );++ if (!ok || !payload?.backupCodes) {+ setFeedback({ message: describeAuthError(payload), tone: "error" });+ return;+ }++ setPassword("");+ setStep({ backupCodes: payload.backupCodes, kind: "new-codes" });+ return;+ }++ const { ok, payload } = await postAuth("/two-factor/disable", {+ password,+ });++ if (!ok) {+ setFeedback({ message: describeAuthError(payload), tone: "error" });+ return;+ }++ // The session was replaced; reload so every part of the page agrees.+ window.location.reload();+ } catch {+ setFeedback({ message: GENERIC_ERROR_MESSAGE, tone: "error" });+ } finally {+ setIsBusy(false);+ }+ }++ async function handleCode(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();++ if (isBusy || step.kind !== "scan") {+ return;+ }++ const trimmed = code.replace(/\s+/g, "");++ if (!/^\d{6}$/.test(trimmed)) {+ setFeedback({+ message: "Enter the 6-digit code your app shows.",+ tone: "error",+ });+ return;+ }++ setIsBusy(true);+ setFeedback(null);++ try {+ const { ok, payload } = await postAuth("/two-factor/verify-totp", {+ code: trimmed,+ });++ if (!ok) {+ setFeedback({ message: describeAuthError(payload), tone: "error" });+ return;+ }++ window.location.reload();+ } catch {+ setFeedback({ message: GENERIC_ERROR_MESSAGE, tone: "error" });+ } finally {+ setIsBusy(false);+ }+ }++ return (+ <div className="panel p-6 sm:p-8" id="two-step-sign-in">+ <div className="space-y-5">+ <div className="flex flex-wrap items-center gap-3">+ <h2 className="text-xl font-extrabold tracking-[-0.02em] text-(--fg)">+ Two-step sign-in+ </h2>+ <span className={`pill ${enabled ? "pill-success" : "pill-neutral"}`}>+ {enabled ? "On" : "Off"}+ </span>+ </div>+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">+ After your password, {productName} asks for a 6-digit code from an+ authenticator app on your phone, such as 1Password, Google+ Authenticator or Microsoft Authenticator. Someone who learns your+ password still cannot sign in.+ {required ? " Your organization requires it." : ""}+ </p>++ {feedback ? (+ <p+ className={`notice ${feedback.tone === "success" ? "notice-success" : "notice-danger"}`}+ role={feedback.tone === "error" ? "alert" : "status"}+ >+ {feedback.message}+ </p>+ ) : null}++ {step.kind === "idle" ? (+ <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap">+ {enabled ? (+ <>+ <ShellButton onClick={() => start("codes")} variant="secondary">+ Make new backup codes+ </ShellButton>+ {required ? null : (+ <ShellButton+ onClick={() => start("disable")}+ variant="secondary"+ >+ Turn off two-step sign-in+ </ShellButton>+ )}+ </>+ ) : (+ <ShellButton className="w-fit" onClick={() => start("enable")}>+ Set up two-step sign-in+ </ShellButton>+ )}+ </div>+ ) : null}++ {step.kind === "confirm-password" ? (+ <form className="space-y-4" noValidate onSubmit={handlePassword}>+ <div className="max-w-sm">+ <FieldShell+ autoComplete="current-password"+ disabled={isBusy}+ label="Your password"+ name="two-factor-password"+ onChange={(event) => {+ setPassword(event.target.value);+ setFeedback(null);+ }}+ readOnly={false}+ type="password"+ value={password}+ />+ </div>+ <div className="flex flex-col gap-3 sm:flex-row">+ <ShellButton loading={isBusy} type="submit">+ {step.purpose === "enable"+ ? "Continue"+ : step.purpose === "codes"+ ? "Make new codes"+ : "Turn off"}+ </ShellButton>+ <ShellButton+ disabled={isBusy}+ onClick={cancel}+ variant="secondary"+ >+ Cancel+ </ShellButton>+ </div>+ </form>+ ) : null}++ {step.kind === "scan" ? (+ <div className="space-y-6">+ <div className="flex flex-col gap-5 sm:flex-row sm:items-start">+ <QrCode value={step.totpURI} />+ <div className="space-y-2 text-sm leading-6 text-(--secondary)">+ <p>+ <span className="font-semibold text-(--fg)">1.</span> Scan+ this code with your authenticator app.+ </p>+ <p>Or type in this key:</p>+ <p className="font-mono text-(--fg)" data-testid="totp-secret">+ {groupSecret(readSecret(step.totpURI))}+ </p>+ </div>+ </div>++ <div className="space-y-2">+ <p className="text-sm font-semibold text-(--fg)">+ 2. Save your backup codes+ </p>+ <BackupCodes codes={step.backupCodes} productName={productName} />+ </div>++ <form className="space-y-4" noValidate onSubmit={handleCode}>+ <p className="text-sm font-semibold text-(--fg)">+ 3. Enter the code your app shows+ </p>+ <div className="max-w-xs">+ <FieldShell+ autoComplete="one-time-code"+ disabled={isBusy}+ label="6-digit code"+ name="two-factor-setup-code"+ onChange={(event) => {+ setCode(event.target.value);+ setFeedback(null);+ }}+ readOnly={false}+ value={code}+ />+ </div>+ <div className="flex flex-col gap-3 sm:flex-row">+ <ShellButton loading={isBusy} type="submit">+ Turn on two-step sign-in+ </ShellButton>+ <ShellButton+ disabled={isBusy}+ onClick={cancel}+ variant="secondary"+ >+ Cancel+ </ShellButton>+ </div>+ </form>+ </div>+ ) : null}++ {step.kind === "new-codes" ? (+ <div className="space-y-4">+ <p className="notice notice-success" role="status">+ New backup codes made. The old ones no longer work.+ </p>+ <BackupCodes codes={step.backupCodes} productName={productName} />+ <ShellButton className="w-fit" onClick={cancel} variant="secondary">+ Done+ </ShellButton>+ </div>+ ) : null}+ </div>+ </div>+ );+}diff --git a/src/lib/auth/route-session.ts b/src/lib/auth/route-session.tsindex ac3b1d1..ccdfc41 100644--- a/src/lib/auth/route-session.ts+++ b/src/lib/auth/route-session.ts@@ -2,10 +2,9 @@ import { NextResponse } from "next/server";import { getAuthSessionFromHeaders } from "./server.ts";import { logSecurityEvent } from "../security/logging.ts";-import {- getClientIpAddress,- getRequestPathname,-} from "../security/request.ts";+import { getSettings } from "../settings.ts";+import { needsTwoFactorSetup } from "../sign-in-security.ts";+import { getClientIpAddress, getRequestPathname } from "../security/request.ts";export async function requireVerifiedSenderSession(request: Request) {const session = await getAuthSessionFromHeaders(request.headers);@@ -15,6 +14,13 @@ export async function requireVerifiedSenderSession(request: Request) {}if (session.user.emailVerified === true) {+ if (needsTwoFactorSetup(await getSettings(), session.user)) {+ return NextResponse.json(+ { error: "Set up two-step sign-in before continuing." },+ { status: 403 },+ );+ }+return session;}diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.tsindex f80b6ee..8158cb1 100644--- a/src/lib/auth/server.ts+++ b/src/lib/auth/server.ts@@ -1,7 +1,7 @@import { APIError, betterAuth } from "better-auth";import { createAuthMiddleware } from "better-auth/api";import { nextCookies } from "better-auth/next-js";-import { haveIBeenPwned } from "better-auth/plugins";+import { haveIBeenPwned, twoFactor } from "better-auth/plugins";import { headers } from "next/headers";import { redirect, unstable_rethrow } from "next/navigation";import { after } from "next/server";@@ -30,6 +30,8 @@ import {} from "../utils/env.ts";import { escapeHtml } from "../utils/html.ts";import { isRunningSetup } from "./setup-context.ts";+import { signInEvents } from "./sign-in-events.ts";+import { recordSystemAuditEvent } from "../services/system-audit.ts";type CreateAppAuthOptions = {database?: Pool;@@ -274,6 +276,21 @@ export function createAppAuth({}),]: []),+ // Two-step sign-in with an authenticator app, and ten single-use backup+ // codes for when the phone is not at hand. Both are stored encrypted+ // with BETTER_AUTH_SECRET. "Trust this device" is not offered, so every+ // sign-in asks for the second step.+ twoFactor({+ accountLockout: {+ durationSeconds: 15 * 60,+ enabled: true,+ maxFailedAttempts: 10,+ },+ backupCodeOptions: { amount: 10, length: 10 },+ skipVerificationOnEnable: false,+ }),+ // After the two-factor plugin: see sign-in-events.ts.+ signInEvents(),...(includeNextCookies ? [nextCookies()] : []),];return betterAuth({@@ -337,6 +354,18 @@ export function createAppAuth({minPasswordLength: 15,requireEmailVerification: true,revokeSessionsOnPasswordReset: true,+ onPasswordReset: async ({ user }) => {+ try {+ await recordSystemAuditEvent({+ actorEmail: user.email,+ actorUserId: user.id,+ event: "password_reset",+ targetUserId: user.id,+ });+ } catch (error) {+ console.error("[auth] Could not record a password reset:", error);+ }+ },sendResetPassword: async ({ url, user }) => {sendAuthEmailInBackground({buildContent: (branding) =>diff --git a/src/lib/auth/sign-in-events.ts b/src/lib/auth/sign-in-events.tsnew file mode 100644index 0000000..b50f8a4--- /dev/null+++ b/src/lib/auth/sign-in-events.ts@@ -0,0 +1,425 @@+import type { BetterAuthPlugin } from "better-auth";+import {+ APIError,+ createAuthMiddleware,+ getSessionFromCtx,+ isAPIError,+} from "better-auth/api";++import { getDb, queryOne } from "../db/connection.ts";+import { logSecurityEvent } from "../security/logging.ts";+import { getSettings } from "../settings.ts";+import {+ getClientIpAddress,+ getRequestUserAgent,+} from "../security/request.ts";+import {+ recordSystemAuditEvent,+ type RecordSystemAuditEventInput,+} from "../services/system-audit.ts";+import {+ clearFailedSignIns,+ countFailedSignIn,+ getSignInLockState,+ MAX_FAILED_SIGN_INS,+ SIGN_IN_LOCKED_MESSAGE,+} from "../sign-in-security.ts";++// Puts sign-ins and changes to how people sign in into the install's audit+// trail, and stops sign-in for an address after too many wrong passwords+// (sign-in-security.ts has the rules).+//+// It is a Better Auth plugin, listed after the two-factor plugin, because+// plugin hooks run in the order the plugins are listed: by the time this+// one sees a password sign-in, the two-factor plugin has already turned it+// into a request for the second step, or let it through.++const TWO_FACTOR_COOKIE_NAME = "two_factor";++const SECOND_STEP_PATHS = new Set([+ "/two-factor/verify-backup-code",+ "/two-factor/verify-otp",+ "/two-factor/verify-totp",+]);++// Paths whose actor is only known before the endpoint runs: each replaces+// or ends the session it was called with.+const SESSION_FIRST_PATHS = new Set([+ "/sign-out",+ "/two-factor/disable",+ "/two-factor/generate-backup-codes",+]);++type Actor = { email: string; userId: string };++type HookContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0];++function readEmail(body: unknown): string | null {+ if (+ typeof body === "object" &&+ body !== null &&+ "email" in body &&+ typeof body.email === "string" &&+ body.email.trim()+ ) {+ return body.email.trim().toLowerCase();+ }++ return null;+}++function readUser(value: unknown): { email: string; id: string } | null {+ if (typeof value !== "object" || value === null || !("user" in value)) {+ return null;+ }++ const user: unknown = value.user;++ if (+ typeof user === "object" &&+ user !== null &&+ "id" in user &&+ typeof user.id === "string" &&+ "email" in user &&+ typeof user.email === "string"+ ) {+ return { email: user.email, id: user.id };+ }++ return null;+}++function readFailureCode(returned: unknown): string {+ if (isAPIError(returned)) {+ const body: unknown = returned.body;++ if (+ typeof body === "object" &&+ body !== null &&+ "code" in body &&+ typeof body.code === "string"+ ) {+ return body.code;+ }++ return returned.status ? String(returned.status) : "error";+ }++ return "error";+}++function requestDetails(ctx: HookContext) {+ const headers = ctx.headers ?? ctx.request?.headers ?? new Headers();++ return {+ ipAddress: getClientIpAddress(headers),+ userAgent: getRequestUserAgent(headers),+ };+}++async function findUserIdByEmail(email: string): Promise<string | null> {+ const row = await queryOne<{ id: string }>(+ getDb(),+ `SELECT id FROM "user" WHERE lower(email) = $1`,+ [email],+ );++ return row?.id ?? null;+}++/**+ * Writes one event. A sign-in is never refused or undone because its record+ * could not be written; the failure is logged instead.+ */+async function record(+ ctx: HookContext,+ input: Omit<RecordSystemAuditEventInput, "ipAddress" | "userAgent">,+) {+ try {+ await recordSystemAuditEvent({ ...input, ...requestDetails(ctx) });+ } catch (error) {+ logSecurityEvent("error", {+ category: "sign_in_audit_failure",+ message: `Could not record "${input.event}" in the audit trail.`,+ metadata: { error: error instanceof Error ? error.message : "unknown" },+ userId: input.actorUserId ?? null,+ });+ }+}++export function signInEvents() {+ const sessionActors = new WeakMap<Request, Actor>();++ return {+ id: "signudoc-sign-in-events",+ hooks: {+ before: [+ {+ matcher: (ctx) => ctx.path === "/sign-in/email",+ handler: createAuthMiddleware(async (ctx) => {+ const email = readEmail(ctx.body);++ if (!email) {+ return;+ }++ const lock = await getSignInLockState(email);++ if (lock.locked) {+ throw new APIError("TOO_MANY_REQUESTS", {+ code: "SIGN_IN_LOCKED",+ message: SIGN_IN_LOCKED_MESSAGE,+ });+ }+ }),+ },+ {+ // An install that requires two-step sign-in does not let anyone+ // turn theirs off. An administrator can still reset it for+ // someone who lost their phone, and they set it up again.+ matcher: (ctx) => ctx.path === "/two-factor/disable",+ handler: createAuthMiddleware(async () => {+ if ((await getSettings()).requireTwoFactor) {+ throw new APIError("FORBIDDEN", {+ code: "TWO_FACTOR_REQUIRED_BY_ADMINISTRATOR",+ message:+ "Your organization requires two-step sign-in, so it cannot be turned off.",+ });+ }+ }),+ },+ {+ matcher: (ctx) => SESSION_FIRST_PATHS.has(ctx.path ?? ""),+ handler: createAuthMiddleware(async (ctx) => {+ if (!ctx.request) {+ return;+ }++ const session = await getSessionFromCtx(ctx).catch(() => null);++ if (session) {+ sessionActors.set(ctx.request, {+ email: session.user.email,+ userId: session.user.id,+ });+ }+ }),+ },+ ],+ after: [+ {+ matcher: (ctx) =>+ ctx.path === "/sign-in/email" ||+ ctx.path === "/change-password" ||+ SECOND_STEP_PATHS.has(ctx.path ?? "") ||+ SESSION_FIRST_PATHS.has(ctx.path ?? ""),+ handler: createAuthMiddleware(async (ctx) => {+ const returned: unknown = ctx.context.returned;+ const failed = isAPIError(returned) || returned instanceof Error;+ const path = ctx.path ?? "";++ if (path === "/sign-in/email") {+ await afterPasswordSignIn(ctx, returned, failed);+ return;+ }++ if (SECOND_STEP_PATHS.has(path)) {+ await afterSecondStep(ctx, returned, failed);+ return;+ }++ if (failed) {+ return;+ }++ if (path === "/change-password") {+ const user = readUser(returned);++ if (user) {+ await record(ctx, {+ actorEmail: user.email,+ actorUserId: user.id,+ event: "password_changed",+ targetUserId: user.id,+ });+ }++ return;+ }++ const actor = ctx.request+ ? sessionActors.get(ctx.request)+ : undefined;++ if (!actor) {+ return;+ }++ await record(ctx, {+ actorEmail: actor.email,+ actorUserId: actor.userId,+ event:+ path === "/sign-out"+ ? "signed_out"+ : path === "/two-factor/disable"+ ? "two_factor_disabled"+ : "two_factor_backup_codes_regenerated",+ targetUserId: actor.userId,+ });+ }),+ },+ ],+ },+ } satisfies BetterAuthPlugin;+}++async function afterPasswordSignIn(+ ctx: HookContext,+ returned: unknown,+ failed: boolean,+) {+ const email = readEmail(ctx.body);++ if (!email) {+ return;+ }++ if (failed) {+ const code = readFailureCode(returned);+ // The password was right; the address is not confirmed yet. Not a+ // guess, so it does not count towards the lockout.+ const wrongPassword = code !== "EMAIL_NOT_VERIFIED";+ const counted = wrongPassword ? await countFailedSignIn(email) : null;+ const userId = await findUserIdByEmail(email).catch(() => null);++ await record(ctx, {+ actorEmail: email,+ actorUserId: userId,+ event: "sign_in_failed",+ metadata: {+ method: "password",+ reason: code,+ ...(counted ? { failuresInWindow: counted.failures } : {}),+ },+ targetUserId: userId,+ });++ if (counted?.justLocked) {+ await record(ctx, {+ actorEmail: email,+ actorUserId: userId,+ event: "sign_in_locked",+ metadata: { failuresInWindow: MAX_FAILED_SIGN_INS },+ targetUserId: userId,+ });+ }++ return;+ }++ // The password was right but a second step is still to come. The sign-in+ // is recorded when that step is done.+ if (+ typeof returned === "object" &&+ returned !== null &&+ "twoFactorRedirect" in returned+ ) {+ return;+ }++ const user = readUser(returned);++ await clearFailedSignIns(email);++ if (user) {+ await record(ctx, {+ actorEmail: user.email,+ actorUserId: user.id,+ event: "sign_in_succeeded",+ metadata: { method: "password" },+ targetUserId: user.id,+ });+ }+}++async function afterSecondStep(+ ctx: HookContext,+ returned: unknown,+ failed: boolean,+) {+ const challengeCookie = await ctx+ .getSignedCookie(+ ctx.context.createAuthCookie(TWO_FACTOR_COOKIE_NAME).name,+ ctx.context.secret,+ )+ .catch(() => null);+ const method =+ ctx.path === "/two-factor/verify-backup-code"+ ? "backup_code"+ : "authenticator";++ // A signed-in person confirming the authenticator they are setting up.+ if (!challengeCookie) {+ const user = readUser(returned);++ if (+ !failed &&+ user &&+ typeof returned === "object" &&+ returned !== null &&+ "user" in returned &&+ (returned.user as { twoFactorEnabled?: unknown }).twoFactorEnabled ===+ false+ ) {+ await record(ctx, {+ actorEmail: user.email,+ actorUserId: user.id,+ event: "two_factor_enabled",+ targetUserId: user.id,+ });+ }++ return;+ }++ if (failed) {+ const pending = await ctx.context.internalAdapter+ .findVerificationValue(challengeCookie)+ .catch(() => null);+ const userId = pending?.value ?? null;+ const email = userId+ ? await queryOne<{ email: string }>(+ getDb(),+ `SELECT email FROM "user" WHERE id = $1`,+ [userId],+ )+ .then((row) => row?.email ?? null)+ .catch(() => null)+ : null;++ await record(ctx, {+ actorEmail: email,+ actorUserId: userId,+ event: "sign_in_failed",+ metadata: { method, reason: readFailureCode(returned) },+ targetUserId: userId,+ });++ return;+ }++ const user = readUser(returned);++ if (!user) {+ return;+ }++ await clearFailedSignIns(user.email);+ await record(ctx, {+ actorEmail: user.email,+ actorUserId: user.id,+ event: "sign_in_succeeded",+ metadata: { method: "password", secondStep: method },+ targetUserId: user.id,+ });+}diff --git a/src/lib/email-status.test.ts b/src/lib/email-status.test.tsindex a54222a..cb91b64 100644--- a/src/lib/email-status.test.ts+++ b/src/lib/email-status.test.ts@@ -18,6 +18,7 @@ const stored: AppSettings = {logoVersion: null,organizationName: "Acme Corp",part11Mode: false,+ requireTwoFactor: false,privacyUrl: null,retentionDays: null,senderAddress: "[email protected]",diff --git a/src/lib/organization-settings.test.ts b/src/lib/organization-settings.test.tsindex 452af04..2d09d67 100644--- a/src/lib/organization-settings.test.ts+++ b/src/lib/organization-settings.test.ts@@ -15,6 +15,7 @@ const stored: AppSettings = {logoVersion: null,organizationName: "Acme Corp",part11Mode: false,+ requireTwoFactor: false,privacyUrl: null,retentionDays: null,senderAddress: "[email protected]",diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.tsindex 2972a67..cef3b6d 100644--- a/src/lib/organization-settings.ts+++ b/src/lib/organization-settings.ts@@ -46,6 +46,8 @@ export type OrganizationSettingsView = {logoUrl: string | null;organizationName: string;privacyUrl: string;+ /** Everyone must use two-step sign-in. Changed in the security panel. */+ requireTwoFactor: boolean;/** Days, as typed. Empty keeps finished envelopes until deleted by hand. */retentionDays: string;senderAddress: string;@@ -70,6 +72,7 @@ export function toOrganizationSettingsView(organizationName: settings.organizationName ?? "",part11Mode: settings.part11Mode,privacyUrl: settings.privacyUrl ?? "",+ requireTwoFactor: settings.requireTwoFactor,retentionDays:settings.retentionDays === null ? "" : String(settings.retentionDays),senderAddress: settings.senderAddress ?? "",diff --git a/src/lib/people.ts b/src/lib/people.tsindex f1f069e..36d4708 100644--- a/src/lib/people.ts+++ b/src/lib/people.ts@@ -41,6 +41,8 @@ export type Person = {role: PersonRole;/** When wrong passwords at signing locked the account for signing. */signingLockedAt: number | null;+ /** Signs in with an authenticator code after the password. */+ twoFactorEnabled: boolean;};export type PeopleList = {@@ -74,6 +76,7 @@ type PersonRow = {name: string;role: string;signingLockedAt: number | null;+ twoFactorEnabled: boolean | null;};const PERSON_COLUMNS = `@@ -86,6 +89,7 @@ const PERSON_COLUMNS = `u.identity_verified_at AS "identityVerifiedAt",u.identity_verification_note AS "identityVerificationNote",u.signing_locked_at AS "signingLockedAt",+ u."twoFactorEnabled" AS "twoFactorEnabled",EXISTS (SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id) AS closing,@@ -113,6 +117,7 @@ function mapPerson(row: PersonRow): Person {name: row.name,role: row.role === "admin" ? "admin" : "user",signingLockedAt: row.signingLockedAt ?? null,+ twoFactorEnabled: row.twoFactorEnabled === true,};}diff --git a/src/lib/security/rate-limit.dbtest.ts b/src/lib/security/rate-limit.dbtest.tsindex d6e9aa2..4df9b3e 100644--- a/src/lib/security/rate-limit.dbtest.ts+++ b/src/lib/security/rate-limit.dbtest.ts@@ -5,7 +5,12 @@ import { after, before, test } from "node:test";import type pg from "pg";import { openTestDatabase } from "../db/test-database.ts";-import { consumeRateLimit, deleteExpiredRateLimits } from "./rate-limit.ts";+import {+ clearRateLimit,+ consumeRateLimit,+ deleteExpiredRateLimits,+ peekRateLimit,+} from "./rate-limit.ts";// The rate limit statement against a real Postgres. Run with// `npm run test:db`.@@ -43,14 +48,35 @@ test("requests up to the limit pass, the next one waits, and the count starts ovconst at = (offset: number) =>consumeRateLimit({ ...input, now: START + offset }, { database });- assert.deepEqual(await at(0), { allowed: true, retryAfterSeconds: 60 });- assert.deepEqual(await at(1000), { allowed: true, retryAfterSeconds: 59 });- assert.deepEqual(await at(15_000), { allowed: false, retryAfterSeconds: 45 });+ assert.deepEqual(await at(0), {+ allowed: true,+ count: 1,+ retryAfterSeconds: 60,+ });+ assert.deepEqual(await at(1000), {+ allowed: true,+ count: 2,+ retryAfterSeconds: 59,+ });+ assert.deepEqual(await at(15_000), {+ allowed: false,+ count: 3,+ retryAfterSeconds: 45,+ });// Trying again while blocked does not push the window back.- assert.deepEqual(await at(59_000), { allowed: false, retryAfterSeconds: 1 });- assert.deepEqual(await at(MINUTE), { allowed: true, retryAfterSeconds: 60 });+ assert.deepEqual(await at(59_000), {+ allowed: false,+ count: 4,+ retryAfterSeconds: 1,+ });+ assert.deepEqual(await at(MINUTE), {+ allowed: true,+ count: 1,+ retryAfterSeconds: 60,+ });assert.deepEqual(await at(MINUTE + 1), {allowed: true,+ count: 2,retryAfterSeconds: 60,});assert.equal((await at(MINUTE + 2)).allowed, false);@@ -141,3 +167,40 @@ test("finished windows are cleared and live ones are kept", async () => {[hash(live)],);});++test("peeking counts nothing, and clearing starts the count over", async () => {+ const key = uniqueKey("peek");+ const input = { key, limit: 2, windowMs: MINUTE };++ assert.deepEqual(+ await peekRateLimit({ ...input, now: START }, { database }),+ {+ allowed: true,+ count: 0,+ retryAfterSeconds: 1,+ },+ );++ await consumeRateLimit({ ...input, now: START }, { database });+ await consumeRateLimit({ ...input, now: START }, { database });++ const used = await peekRateLimit(+ { ...input, now: START + 10_000 },+ { database },+ );++ assert.deepEqual(used, { allowed: false, count: 2, retryAfterSeconds: 50 });+ assert.equal(+ (await peekRateLimit({ ...input, now: START + MINUTE }, { database }))+ .allowed,+ true,+ );++ await clearRateLimit(key, { database });++ assert.equal(+ (await consumeRateLimit({ ...input, now: START + 10_000 }, { database }))+ .count,+ 1,+ );+});diff --git a/src/lib/security/rate-limit.test.ts b/src/lib/security/rate-limit.test.tsindex e38944c..61bbfd7 100644--- a/src/lib/security/rate-limit.test.ts+++ b/src/lib/security/rate-limit.test.ts@@ -53,6 +53,7 @@ test("in memory, requests up to the limit are allowed and the next is not", () =assert.deepEqual(consumeRateLimitInMemory({ ...input, now: START + 10 }), {allowed: false,+ count: 4,retryAfterSeconds: 60,});});@@ -111,7 +112,11 @@ test("the database's count decides, and only a hash of the key is sent to it", a{ database },);- assert.deepEqual(decision, { allowed: false, retryAfterSeconds: 30 });+ assert.deepEqual(decision, {+ allowed: false,+ count: 6,+ retryAfterSeconds: 30,+ });const [hashedKey, now, windowMs] = queries[0]?.values ?? [];diff --git a/src/lib/security/rate-limit.ts b/src/lib/security/rate-limit.tsindex 6542843..8792e80 100644--- a/src/lib/security/rate-limit.ts+++ b/src/lib/security/rate-limit.ts@@ -13,6 +13,8 @@ import { getDb, type DbExecutor } from "../db/connection.ts";export type RateLimitDecision = {allowed: boolean;+ /** Requests counted in the current window, this one included. */+ count: number;/** Seconds until the current window ends. At least 1 when not allowed. */retryAfterSeconds: number;};@@ -64,6 +66,7 @@ function toDecision(): RateLimitDecision {return {allowed: count <= input.limit,+ count,retryAfterSeconds: Math.max(1, Math.ceil((expiresAt - now) / 1000)),};}@@ -186,6 +189,69 @@ export async function consumeRateLimit(}}+type PeekRateLimitInput = Omit<RateLimitInput, "windowMs">;++/**+ * Whether a limit is already used up, without counting anything. For limits+ * that count only some requests (failed sign-ins), checked before each one.+ */+export async function peekRateLimit(+ input: PeekRateLimitInput,+ { database }: ConsumeRateLimitOptions = {},+): Promise<RateLimitDecision> {+ const now = input.now ?? Date.now();+ let entry: MemoryEntry | undefined;++ try {+ const result = await (database ?? getDb()).query<{+ count: number;+ expires_at: number;+ }>(+ "select count, expires_at from public.rate_limits where key = $1 and expires_at > $2",+ [hashKey(input.key), now],+ );+ const row = result.rows[0];++ entry = row+ ? { count: row.count, expiresAt: Number(row.expires_at) }+ : undefined;+ } catch (error) {+ warnAboutFallback(error);++ const memoryEntry = memoryStore.get(input.key);++ entry =+ memoryEntry && memoryEntry.expiresAt > now ? memoryEntry : undefined;+ }++ if (!entry) {+ return { allowed: true, count: 0, retryAfterSeconds: 1 };+ }++ return {+ allowed: entry.count < input.limit,+ count: entry.count,+ retryAfterSeconds: Math.max(1, Math.ceil((entry.expiresAt - now) / 1000)),+ };+}++/** Forgets a limit's count, as after a sign-in that worked. */+export async function clearRateLimit(+ key: string,+ { database }: ConsumeRateLimitOptions = {},+): Promise<void> {+ memoryStore.delete(key);++ try {+ await (database ?? getDb()).query(+ "delete from public.rate_limits where key = $1",+ [hashKey(key)],+ );+ } catch (error) {+ warnAboutFallback(error);+ }+}+export function clearRateLimitStoreForTests() {memoryStore.clear();globalThis.__signudocRateLimitSweepAt = undefined;diff --git a/src/lib/services/admin-activity.ts b/src/lib/services/admin-activity.tsnew file mode 100644index 0000000..052cee8--- /dev/null+++ b/src/lib/services/admin-activity.ts@@ -0,0 +1,40 @@+import { logSecurityEvent } from "../security/logging.ts";+import {+ getClientIpAddress,+ getRequestUserAgent,+} from "../security/request.ts";+import {+ recordSystemAuditEvent,+ type SystemAuditEventType,+} from "./system-audit.ts";++/**+ * Records an administrator's change that has already been made elsewhere+ * (in Blob storage, or at the email provider), so it cannot share a+ * transaction with its audit row. A record that cannot be written is+ * logged, and the change still stands.+ */+export async function recordAdminActivity(input: {+ event: SystemAuditEventType;+ metadata?: Record<string, unknown>;+ request: Request;+ user: { email: string; id: string };+}): Promise<void> {+ try {+ await recordSystemAuditEvent({+ actorEmail: input.user.email,+ actorUserId: input.user.id,+ event: input.event,+ ipAddress: getClientIpAddress(input.request.headers),+ metadata: input.metadata ?? null,+ userAgent: getRequestUserAgent(input.request.headers),+ });+ } catch (error) {+ logSecurityEvent("error", {+ category: "admin_audit_failure",+ message: `Could not record "${input.event}" in the audit trail.`,+ metadata: { error: error instanceof Error ? error.message : "unknown" },+ userId: input.user.id,+ });+ }+}diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.tsindex f4f411e..4ce4a49 100644--- a/src/lib/services/system-audit.ts+++ b/src/lib/services/system-audit.ts@@ -24,6 +24,19 @@ export const systemAuditEventTypes = ["signing_locked","signing_unlocked","reauthentication_failed",+ "sign_in_succeeded",+ "sign_in_failed",+ "sign_in_locked",+ "signed_out",+ "password_changed",+ "password_reset",+ "two_factor_enabled",+ "two_factor_disabled",+ "two_factor_backup_codes_regenerated",+ "two_factor_reset",+ "two_factor_requirement_changed",+ "logo_changed",+ "email_domain_changed",] as const;export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.tsindex 739b95e..69f0235 100644--- a/src/lib/settings.test.ts+++ b/src/lib/settings.test.ts@@ -15,6 +15,7 @@ const stored: AppSettings = {logoVersion: null,organizationName: "Acme Corp",part11Mode: false,+ requireTwoFactor: false,privacyUrl: "https://acme.com/privacy",retentionDays: null,senderAddress: "[email protected]",diff --git a/src/lib/settings.ts b/src/lib/settings.tsindex f1d8f17..e4004af 100644--- a/src/lib/settings.ts+++ b/src/lib/settings.ts@@ -40,6 +40,11 @@ export type AppSettings = {*/part11Mode: boolean;privacyUrl: string | null;+ /**+ * Everyone must set up two-step sign-in (an authenticator app) before+ * they can use the app. See sign-in-security.ts.+ */+ requireTwoFactor: boolean;/*** Days a finished envelope is kept before the nightly job deletes it, or* null to keep finished envelopes until someone deletes them.@@ -90,6 +95,7 @@ type AppSettingsRow = {organization_name: string | null;part11_mode: boolean;privacy_url: string | null;+ require_two_factor: boolean;retention_days: number | null;sender_address: string | null;setup_completed_at: number | null;@@ -120,6 +126,7 @@ const LATER_SETTINGS_COLUMNS = [["retention_days"], // 20261113090000_signature_evidence["brand_color", "logo_hash"], // 20261114120000_branding["part11_mode"], // 20261115090000_part11_mode+ ["require_two_factor"], // 20261117090000_sign_in_security] as const;type LaterSettingsColumn = (typeof LATER_SETTINGS_COLUMNS)[number][number];@@ -149,6 +156,7 @@ const UNSET_SETTINGS: AppSettings = {organizationName: null,part11Mode: false,privacyUrl: null,+ requireTwoFactor: false,retentionDays: null,senderAddress: null,setupCompletedAt: null,@@ -215,6 +223,7 @@ function mapSettingsRow(row: StoredSettingsRow): AppSettings {organizationName: row.organization_name,part11Mode: row.part11_mode ?? false,privacyUrl: row.privacy_url,+ requireTwoFactor: row.require_two_factor ?? false,retentionDays: row.retention_days ?? null,senderAddress: row.sender_address,setupCompletedAt: row.setup_completed_at,@@ -379,10 +388,11 @@ async function saveSettingsLocked(retention_days,brand_color,part11_mode,+ require_two_factor,created_at,updated_at)- values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $12, $13, $10, $10)+ values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $12, $13, $14, $10, $10)on conflict (id) do update setallowed_email_domains = excluded.allowed_email_domains,email_ready_at = excluded.email_ready_at,@@ -396,6 +406,7 @@ async function saveSettingsLocked(retention_days = excluded.retention_days,brand_color = excluded.brand_color,part11_mode = excluded.part11_mode,+ require_two_factor = excluded.require_two_factor,updated_at = excluded.updated_atreturning ${SETTINGS_COLUMNS}`,@@ -413,6 +424,7 @@ async function saveSettingsLocked(next.retentionDays,next.brandColor,next.part11Mode,+ next.requireTwoFactor,],);diff --git a/src/lib/sign-in-security.dbtest.ts b/src/lib/sign-in-security.dbtest.tsnew file mode 100644index 0000000..d6eccbf--- /dev/null+++ b/src/lib/sign-in-security.dbtest.ts@@ -0,0 +1,484 @@+import assert from "node:assert/strict";+import { createHmac, randomUUID } from "node:crypto";+import { registerHooks } from "node:module";+import { after, before, beforeEach, test } from "node:test";++import type pg from "pg";++import type { createAppAuth as CreateAppAuth } from "./auth/server.ts";+import { replaceDbPoolForTests } from "./db/connection.ts";+import { openTestDatabase } from "./db/test-database.ts";+import { clearRateLimitStoreForTests } from "./security/rate-limit.ts";+import {+ listSystemAuditEvents,+ verifySystemAuditChain,+} from "./services/system-audit.ts";+import { invalidateSettingsCache, saveSettings } from "./settings.ts";+import {+ MAX_FAILED_SIGN_INS,+ resetTwoFactor,+ setTwoFactorRequirement,+ SignInSecurityError,+} from "./sign-in-security.ts";++// Sign-in security against a real Postgres and the real Better Auth+// endpoints: the lockout after wrong passwords, two-step sign-in, and what+// each of them writes to the install's audit trail. Run with+// `npm run test:db`.++const BASE_URL = "http://localhost:3999";+const PASSWORD = "a long enough passphrase";++const env = {+ APP_URL: BASE_URL,+ BETTER_AUTH_SECRET: "test-secret-that-is-long-enough-for-better-auth-0123",+ BETTER_AUTH_URL: BASE_URL,+ EMAIL_DRIVER: "capture",+ NODE_ENV: "test",+};++let database: pg.Pool;+let replaced: pg.Pool | null = null;+let auth: ReturnType<typeof CreateAppAuth>;++// The auth server imports next/headers and next/navigation, which Next.js+// resolves for itself. Plain Node needs the file name.+registerHooks({+ resolve(specifier, context, nextResolve) {+ if (/^next\/[a-z-]+$/.test(specifier)) {+ return nextResolve(`${specifier}.js`, context);+ }++ return nextResolve(specifier, context);+ },+});++type Cookies = Map<string, string>;++function cookieHeader(cookies: Cookies): string {+ return [...cookies].map(([name, value]) => `${name}=${value}`).join("; ");+}++function absorbCookies(response: Response, cookies: Cookies) {+ for (const line of response.headers.getSetCookie()) {+ const [pair] = line.split(";");+ const index = pair?.indexOf("=") ?? -1;++ if (!pair || index < 0) {+ continue;+ }++ const name = pair.slice(0, index).trim();+ const value = pair.slice(index + 1).trim();++ if (value === "" || /max-age=0/i.test(line)) {+ cookies.delete(name);+ } else {+ cookies.set(name, value);+ }+ }+}++async function call(+ path: string,+ body: unknown,+ cookies: Cookies = new Map(),+ ipAddress = "203.0.113.7",+): Promise<{ payload: Record<string, unknown> | null; status: number }> {+ const response = await auth.handler(+ new Request(`${BASE_URL}/api/auth${path}`, {+ body: JSON.stringify(body),+ headers: {+ "content-type": "application/json",+ cookie: cookieHeader(cookies),+ origin: BASE_URL,+ "user-agent": "sign-in-security dbtest",+ "x-forwarded-for": ipAddress,+ },+ method: "POST",+ }),+ );++ absorbCookies(response, cookies);++ return {+ payload: (await response.json().catch(() => null)) as Record<+ string,+ unknown+ > | null,+ status: response.status,+ };+}++async function createVerifiedUser(email: string, role = "user") {+ const context = await auth.$context;+ const id = randomUUID();++ await database.query(+ `insert into "user" (id, name, email, "emailVerified", role) values ($1, 'Pat Person', $2, true, $3)`,+ [id, email, role],+ );+ await database.query(+ `insert into account (id, "accountId", "providerId", "userId", password) values ($1, $2, 'credential', $2, $3)`,+ [randomUUID(), id, await context.password.hash(PASSWORD)],+ );++ return id;+}++async function signIn(email: string, password = PASSWORD) {+ const cookies: Cookies = new Map();+ const result = await call("/sign-in/email", { email, password }, cookies);++ return { ...result, cookies };+}++function base32Decode(value: string): Buffer {+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";+ let bits = "";++ for (const character of value.replace(/=+$/, "").toUpperCase()) {+ bits += alphabet.indexOf(character).toString(2).padStart(5, "0");+ }++ const bytes: number[] = [];++ for (let index = 0; index + 8 <= bits.length; index += 8) {+ bytes.push(Number.parseInt(bits.slice(index, index + 8), 2));+ }++ return Buffer.from(bytes);+}++/** RFC 6238, as an authenticator app works it out. */+function totp(totpURI: string, at = Date.now()): string {+ const secret = new URL(totpURI).searchParams.get("secret") ?? "";+ const counter = Buffer.alloc(8);++ counter.writeBigUInt64BE(BigInt(Math.floor(at / 30_000)));++ const digest = createHmac("sha1", base32Decode(secret))+ .update(counter)+ .digest();+ const offset = (digest[digest.length - 1] ?? 0) & 0xf;+ const value = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000;++ return String(value).padStart(6, "0");+}++async function enableTwoFactor(email: string) {+ const session = await signIn(email);++ assert.equal(session.status, 200);++ const enabled = await call(+ "/two-factor/enable",+ { issuer: "Acme Sign", password: PASSWORD },+ session.cookies,+ );++ assert.equal(enabled.status, 200, JSON.stringify(enabled.payload));++ const totpURI = String(enabled.payload?.totpURI);+ const backupCodes = enabled.payload?.backupCodes as string[];+ const verified = await call(+ "/two-factor/verify-totp",+ { code: totp(totpURI) },+ session.cookies,+ );++ assert.equal(verified.status, 200, JSON.stringify(verified.payload));++ return { backupCodes, cookies: session.cookies, totpURI };+}++async function events(type?: string) {+ const all = await listSystemAuditEvents({ limit: 1000 }, database);++ return type ? all.filter((event) => event.event === type) : all;+}++before(async () => {+ database = await openTestDatabase();+ replaced = replaceDbPoolForTests(database);++ const { createAppAuth } = await import("./auth/server.ts");++ auth = createAppAuth({ database, env, includeNextCookies: false });+});++beforeEach(async () => {+ await database.query(`truncate public."user" cascade`);+ await database.query("delete from public.system_audit_events");+ await database.query("delete from public.app_settings");+ await database.query("delete from public.rate_limits");+ await database.query("delete from public.verification");+ clearRateLimitStoreForTests();+ invalidateSettingsCache();+ await saveSettings({ signupMode: "open" }, database);+});++after(async () => {+ await database.query(`truncate public."user" cascade`);+ await database.query("delete from public.system_audit_events");+ await database.query("delete from public.app_settings");+ await database.query("delete from public.rate_limits");+ replaceDbPoolForTests(replaced ?? database);+ await database.end();+});++test("a password sign-in is recorded, with where it came from", async () => {+ const userId = await createVerifiedUser("[email protected]");+ const result = await signIn("[email protected]");++ assert.equal(result.status, 200);++ const [event] = await events("sign_in_succeeded");++ assert.equal(event?.actorUserId, userId);+ assert.equal(event?.ipAddress, "203.0.113.7");+ assert.equal(event?.userAgent, "sign-in-security dbtest");+ assert.deepEqual(event?.metadata, { method: "password" });+ assert.deepEqual(await verifySystemAuditChain(database), {+ events: (await events()).length,+ ok: true,+ });+});++test("ten wrong passwords stop sign-in for the address, even with the right one", async () => {+ await createVerifiedUser("[email protected]");++ for (let attempt = 1; attempt <= MAX_FAILED_SIGN_INS; attempt += 1) {+ const result = await signIn("[email protected]", "not the right password!!");++ assert.equal(result.status, 401, `attempt ${String(attempt)}`);+ }++ const locked = await signIn("[email protected]");++ assert.equal(locked.status, 429);+ assert.equal(locked.payload?.code, "SIGN_IN_LOCKED");++ const failures = await events("sign_in_failed");++ assert.equal(failures.length, MAX_FAILED_SIGN_INS);+ assert.equal(failures[0]?.metadata?.reason, "INVALID_EMAIL_OR_PASSWORD");+ assert.equal((await events("sign_in_locked")).length, 1);+ assert.equal((await events("sign_in_succeeded")).length, 0);+});++test("an address with no account is stopped the same way", async () => {+ for (let attempt = 1; attempt <= MAX_FAILED_SIGN_INS; attempt += 1) {+ await signIn("[email protected]", "not the right password!!");+ }++ const locked = await signIn("[email protected]", "not the right password!!");++ assert.equal(locked.status, 429);+ assert.equal(locked.payload?.code, "SIGN_IN_LOCKED");+});++test("a sign-in that works forgets the wrong passwords before it", async () => {+ await createVerifiedUser("[email protected]");++ for (let attempt = 1; attempt < MAX_FAILED_SIGN_INS; attempt += 1) {+ await signIn("[email protected]", "not the right password!!");+ }++ assert.equal((await signIn("[email protected]")).status, 200);+ assert.equal(+ (await signIn("[email protected]", "not the right password!!")).status,+ 401,+ );+ assert.equal((await signIn("[email protected]")).status, 200);+});++test("two-step sign-in: set up, then asked for at every sign-in", async () => {+ const userId = await createVerifiedUser("[email protected]");+ const { backupCodes, totpURI } = await enableTwoFactor("[email protected]");++ assert.equal(backupCodes.length, 10);+ assert.equal((await events("two_factor_enabled"))[0]?.actorUserId, userId);++ // The password alone no longer signs in.+ const first = await signIn("[email protected]");++ assert.equal(first.status, 200);+ assert.equal(first.payload?.twoFactorRedirect, true);+ assert.equal(+ [...first.cookies.keys()].some((name) => name.endsWith("session_token")),+ false,+ );++ // Two sign-ins recorded so far: the one that set it up, and none for this+ // one until the second step is done.+ assert.equal((await events("sign_in_succeeded")).length, 1);++ const wrong = await call(+ "/two-factor/verify-totp",+ { code: "000000" === totp(totpURI) ? "111111" : "000000" },+ first.cookies,+ );++ assert.equal(wrong.status, 401);+ assert.equal(+ (await events("sign_in_failed"))[0]?.metadata?.reason,+ "INVALID_CODE",+ );+ assert.equal((await events("sign_in_failed"))[0]?.actorUserId, userId);++ const right = await call(+ "/two-factor/verify-totp",+ { code: totp(totpURI) },+ first.cookies,+ );++ assert.equal(right.status, 200, JSON.stringify(right.payload));++ const signedIn = (await events("sign_in_succeeded"))[0];++ assert.deepEqual(signedIn?.metadata, {+ method: "password",+ secondStep: "authenticator",+ });++ // A backup code works once.+ const second = await signIn("[email protected]");+ const backup = await call(+ "/two-factor/verify-backup-code",+ { code: backupCodes[0] },+ second.cookies,+ );++ assert.equal(backup.status, 200, JSON.stringify(backup.payload));+ assert.equal(+ (await events("sign_in_succeeded"))[0]?.metadata?.secondStep,+ "backup_code",+ );++ const third = await signIn("[email protected]");+ const reused = await call(+ "/two-factor/verify-backup-code",+ { code: backupCodes[0] },+ third.cookies,+ );++ assert.equal(reused.status, 401);+});++test("turning two-step sign-in off and making new codes are recorded", async () => {+ await createVerifiedUser("[email protected]");++ const { cookies } = await enableTwoFactor("[email protected]");+ const codes = await call(+ "/two-factor/generate-backup-codes",+ { password: PASSWORD },+ cookies,+ );++ assert.equal(codes.status, 200);+ assert.equal((await events("two_factor_backup_codes_regenerated")).length, 1);++ const disabled = await call(+ "/two-factor/disable",+ { password: PASSWORD },+ cookies,+ );++ assert.equal(disabled.status, 200, JSON.stringify(disabled.payload));+ assert.equal((await events("two_factor_disabled")).length, 1);+});++test("requiring two-step sign-in: the administrator must use it first, and nobody can turn theirs off", async () => {+ const adminId = await createVerifiedUser("[email protected]", "admin");+ const actor = { email: "[email protected]", userId: adminId };++ await assert.rejects(+ setTwoFactorRequirement(actor, true, database),+ (error: unknown) =>+ error instanceof SignInSecurityError && error.statusCode === 409,+ );++ const { cookies } = await enableTwoFactor("[email protected]");++ await setTwoFactorRequirement(actor, true, database);+ invalidateSettingsCache();++ const changed = await events("two_factor_requirement_changed");++ assert.deepEqual(changed[0]?.metadata, { from: false, to: true });++ const disabled = await call(+ "/two-factor/disable",+ { password: PASSWORD },+ cookies,+ );++ assert.equal(disabled.status, 403);+ assert.equal(disabled.payload?.code, "TWO_FACTOR_REQUIRED_BY_ADMINISTRATOR");++ const member = await createVerifiedUser("[email protected]");++ await assert.rejects(+ setTwoFactorRequirement(+ { email: "[email protected]", userId: member },+ false,+ database,+ ),+ (error: unknown) =>+ error instanceof SignInSecurityError && error.statusCode === 403,+ );+});++test("an administrator's reset turns someone's two-step sign-in off and signs them out", async () => {+ const adminId = await createVerifiedUser("[email protected]", "admin");+ const memberId = await createVerifiedUser("[email protected]");++ await enableTwoFactor("[email protected]");+ await resetTwoFactor(+ { email: "[email protected]", userId: adminId },+ memberId,+ database,+ );++ const row = await database.query<{+ sessions: number;+ twoFactorEnabled: boolean;+ secrets: number;+ }>(+ `+ select+ u."twoFactorEnabled" as "twoFactorEnabled",+ (select count(*)::int from session s where s."userId" = u.id) as sessions,+ (select count(*)::int from "twoFactor" t where t."userId" = u.id) as secrets+ from "user" u where u.id = $1+ `,+ [memberId],+ );++ assert.deepEqual(row.rows[0], {+ secrets: 0,+ sessions: 0,+ twoFactorEnabled: false,+ });++ const [reset] = await events("two_factor_reset");++ assert.equal(reset?.actorUserId, adminId);+ assert.equal(reset?.targetUserId, memberId);++ // The password alone signs them in again.+ const again = await signIn("[email protected]");++ assert.equal(again.status, 200);+ assert.equal(again.payload?.twoFactorRedirect, undefined);+});++test("signing out is recorded", async () => {+ const userId = await createVerifiedUser("[email protected]");+ const { cookies } = await signIn("[email protected]");+ const result = await call("/sign-out", {}, cookies);++ assert.equal(result.status, 200);+ assert.equal((await events("signed_out"))[0]?.actorUserId, userId);+});diff --git a/src/lib/sign-in-security.ts b/src/lib/sign-in-security.tsnew file mode 100644index 0000000..bc1d1d5--- /dev/null+++ b/src/lib/sign-in-security.ts@@ -0,0 +1,264 @@+import {+ type DbExecutor,+ type DbPool,+ getDb,+ queryOne,+ withTransaction,+} from "./db/connection.ts";+import {+ clearRateLimit,+ consumeRateLimit,+ peekRateLimit,+} from "./security/rate-limit.ts";+import { recordSystemAuditEvent } from "./services/system-audit.ts";++// Sign-in security for the people who use the app (senders and+// administrators, not signers, who open their envelopes from an emailed+// link):+//+// - Two-step sign-in: an authenticator app code, or one of ten single-use+// backup codes, after the password. Better Auth's two-factor plugin does+// the work (auth/server.ts); this module holds the install's rules.+// - An administrator can require two-step sign-in of everyone. Until a+// person has set it up, the app shows them nothing but the setup.+// - Ten wrong passwords for one email address within fifteen minutes stop+// sign-in for that address until the fifteen minutes are up. The count is+// kept per address whether or not an account has it, so the answer says+// nothing about which addresses have accounts.+// - Sign-ins, failures, lockouts and changes to how someone signs in go in+// the install's audit trail (services/system-audit.ts).++export const MAX_FAILED_SIGN_INS = 10;+export const SIGN_IN_LOCKOUT_MS = 15 * 60 * 1000;++export const SIGN_IN_LOCKED_MESSAGE =+ "Too many wrong passwords for this email address. Try again in 15 minutes, or reset your password.";++export class SignInSecurityError extends Error {+ readonly statusCode: number;++ constructor(message: string, statusCode: number) {+ super(message);+ this.name = "SignInSecurityError";+ this.statusCode = statusCode;+ }+}++function failedSignInKey(email: string): string {+ return `sign-in-failures:${email.trim().toLowerCase()}`;+}++export type SignInLockState =+ { locked: false } | { locked: true; retryAfterSeconds: number };++/** Whether sign-in for this address is stopped by wrong passwords. */+export async function getSignInLockState(+ email: string,+ options: { database?: DbExecutor; now?: number } = {},+): Promise<SignInLockState> {+ const decision = await peekRateLimit(+ {+ key: failedSignInKey(email),+ limit: MAX_FAILED_SIGN_INS,+ now: options.now,+ },+ { database: options.database },+ );++ return decision.allowed+ ? { locked: false }+ : { locked: true, retryAfterSeconds: decision.retryAfterSeconds };+}++/**+ * Counts a wrong password for this address. `justLocked` is true for the+ * one that used up the allowance, so the lockout is recorded once.+ */+export async function countFailedSignIn(+ email: string,+ options: { database?: DbExecutor; now?: number } = {},+): Promise<{ failures: number; justLocked: boolean }> {+ const decision = await consumeRateLimit(+ {+ key: failedSignInKey(email),+ limit: MAX_FAILED_SIGN_INS,+ now: options.now,+ windowMs: SIGN_IN_LOCKOUT_MS,+ },+ { database: options.database },+ );++ return {+ failures: decision.count,+ justLocked: decision.count === MAX_FAILED_SIGN_INS,+ };+}++/** Forgets the wrong passwords for this address after a sign-in worked. */+export async function clearFailedSignIns(+ email: string,+ options: { database?: DbExecutor } = {},+): Promise<void> {+ await clearRateLimit(failedSignInKey(email), options);+}++/**+ * Whether this person must set up two-step sign-in before using the app.+ * `twoFactorEnabled` comes from the session, which is at most a few minutes+ * old; the setup itself replaces the session, so it is current right after.+ */+export function needsTwoFactorSetup(+ settings: { requireTwoFactor: boolean },+ user: object,+): boolean {+ return settings.requireTwoFactor && !usesTwoFactor(user);+}++/**+ * Whether a session's user has two-step sign-in on. The field is added by+ * the two-factor plugin, which the session's static type does not carry.+ */+export function usesTwoFactor(user: object): boolean {+ return (+ "twoFactorEnabled" in user &&+ (user as { twoFactorEnabled?: unknown }).twoFactorEnabled === true+ );+}++type Actor = {+ email: string;+ ipAddress?: string | null;+ userAgent?: string | null;+ userId: string;+};++async function lockActor(actor: Actor, tx: DbExecutor) {+ const row = await queryOne<{ role: string; twoFactorEnabled: boolean }>(+ tx,+ `SELECT role, "twoFactorEnabled" AS "twoFactorEnabled" FROM "user" WHERE id = $1`,+ [actor.userId],+ );++ if (row?.role !== "admin") {+ throw new SignInSecurityError("Only an administrator can do this.", 403);+ }++ return row;+}++/**+ * Turns the two-step sign-in requirement on or off. The administrator who+ * turns it on must already use two-step sign-in, so the switch is never+ * flipped by someone who has not tried what everyone else will be asked to+ * do.+ */+export async function setTwoFactorRequirement(+ actor: Actor,+ required: boolean,+ database: DbPool = getDb(),+): Promise<void> {+ const { readStoredSettings, saveSettings } = await import("./settings.ts");++ await withTransaction(async (tx) => {+ const actorRow = await lockActor(actor, tx);++ // Settings are one row; holding it keeps two changes from crossing.+ await tx.query(`SELECT id FROM app_settings WHERE id FOR UPDATE`);++ const current = await readStoredSettings(tx);+ const wasRequired = current?.requireTwoFactor ?? false;++ if (wasRequired === required) {+ return;+ }++ if (required && !actorRow.twoFactorEnabled) {+ throw new SignInSecurityError(+ "Set up two-step sign-in for your own account first, under Settings, Two-step sign-in.",+ 409,+ );+ }++ await saveSettings({ requireTwoFactor: required }, tx);+ await recordSystemAuditEvent(+ {+ actorEmail: actor.email,+ actorUserId: actor.userId,+ event: "two_factor_requirement_changed",+ ipAddress: actor.ipAddress ?? null,+ metadata: { from: wasRequired, to: required },+ userAgent: actor.userAgent ?? null,+ },+ tx,+ );+ }, database);+}++/**+ * For someone who lost their authenticator and their backup codes: an+ * administrator turns their two-step sign-in off and signs them out+ * everywhere. They sign in with their password and set it up again (at+ * once, if the install requires it).+ */+export async function resetTwoFactor(+ actor: Actor,+ targetUserId: string,+ database: DbPool = getDb(),+): Promise<void> {+ await withTransaction(async (tx) => {+ await lockActor(actor, tx);++ const target = await queryOne<{+ email: string;+ name: string;+ twoFactorEnabled: boolean;+ }>(+ tx,+ `+ SELECT email, name, "twoFactorEnabled" AS "twoFactorEnabled"+ FROM "user"+ WHERE id = $1+ FOR UPDATE+ `,+ [targetUserId],+ );++ if (!target) {+ throw new SignInSecurityError("That account no longer exists.", 404);+ }++ if (!target.twoFactorEnabled) {+ throw new SignInSecurityError(+ "This person does not use two-step sign-in.",+ 409,+ );+ }++ await tx.query(`DELETE FROM "twoFactor" WHERE "userId" = $1`, [+ targetUserId,+ ]);+ await tx.query(+ `UPDATE "user" SET "twoFactorEnabled" = false, "updatedAt" = now() WHERE id = $1`,+ [targetUserId],+ );+ // Trusted-device marks are kept as verification rows with the user's id+ // as their value.+ await tx.query(+ `DELETE FROM verification WHERE identifier LIKE 'trust-device-%' AND value = $1`,+ [targetUserId],+ );+ await tx.query(`DELETE FROM session WHERE "userId" = $1`, [targetUserId]);+ await recordSystemAuditEvent(+ {+ actorEmail: actor.email,+ actorUserId: actor.userId,+ event: "two_factor_reset",+ ipAddress: actor.ipAddress ?? null,+ metadata: { targetEmail: target.email, targetName: target.name },+ targetUserId,+ userAgent: actor.userAgent ?? null,+ },+ tx,+ );+ }, database);+}