Dough Git

commit

AA

commit
8d0f06dbca0e580b7a544a5abc1efaa147ce9419
author
Clove Twilight <[email protected]>
date
2026-10-26 06:32

diff --git a/.dev.vars.example b/.dev.vars.example
index f82447b..c772080 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -20,3 +20,6 @@ SETUP_TOKEN=
 # Resend API key. Leave empty locally and emails are printed to the terminal
 # instead of being sent.
 RESEND_API_KEY=
+
+# Contact address shown on /privacy and /terms for data and account requests.
+# CONTACT_EMAIL=
diff --git a/migrations/0004_security_notices.sql b/migrations/0004_security_notices.sql
new file mode 100644
index 0000000..4c3131c
--- /dev/null
+++ b/migrations/0004_security_notices.sql
@@ -0,0 +1,30 @@
+-- migrations/0004_security_notices.sql
+-- Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+-- Licensed under the DASL-1.2 Licence.
+
+-- Browsers an account has signed in from, keyed by a long-lived device cookie
+-- (stored hashed). Signing in from one that isn't listed emails the owner.
+CREATE TABLE known_devices (
+  user_id       TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  device_hash   TEXT NOT NULL,
+  first_seen_at INTEGER NOT NULL,
+  last_seen_at  INTEGER NOT NULL,
+  PRIMARY KEY (user_id, device_hash)
+);
+
+CREATE INDEX known_devices_seen ON known_devices (last_seen_at);
+
+-- Which device a session belongs to, so signing it out can forget the device.
+ALTER TABLE sessions ADD COLUMN device_hash TEXT;
+
+-- Links in security emails that sign a session (or everything) out without
+-- needing to sign in. `session_hash` NULL = the email had no session to name.
+CREATE TABLE signout_links (
+  token_hash   TEXT PRIMARY KEY,
+  user_id      TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  session_hash TEXT,
+  created_at   INTEGER NOT NULL,
+  expires_at   INTEGER NOT NULL
+);
+
+CREATE INDEX signout_links_user ON signout_links (user_id);
diff --git a/public/static/app.js b/public/static/app.js
index e967ddb..8be602c 100644
--- a/public/static/app.js
+++ b/public/static/app.js
@@ -160,6 +160,35 @@ function initLogin() {
   startConditional();
 }
 
+// --- second step after a password ------------------------------------------------
+
+function initMfa() {
+  const button = document.getElementById("passkey-mfa");
+  if (!button) return;
+
+  if (!window.PublicKeyCredential) {
+    button.disabled = true;
+    button.textContent = "Passkeys aren't supported in this browser";
+    return;
+  }
+
+  button.addEventListener("click", async () => {
+    showError("");
+    button.disabled = true;
+    try {
+      const { id, options } = await postJSON("/login/mfa/passkey/options");
+      const cred = await navigator.credentials.get({ publicKey: requestOptions(options) });
+      if (!cred) return;
+      const result = await postJSON("/login/mfa/passkey/verify", { id, response: credentialJSON(cred) });
+      window.location.href = result.redirect;
+    } catch (err) {
+      showError(webauthnMessage(err));
+    } finally {
+      button.disabled = false;
+    }
+  });
+}
+
 // --- account -----------------------------------------------------------------------
 
 function initAccount() {
@@ -216,5 +245,6 @@ document.addEventListener("click", async (ev) => {
 document.addEventListener("DOMContentLoaded", () => {
   const page = document.body.dataset.page;
   if (page === "login") initLogin();
+  if (page === "mfa") initMfa();
   if (page === "account") initAccount();
 });
diff --git a/public/static/style.css b/public/static/style.css
index 818a431..441a333 100644
--- a/public/static/style.css
+++ b/public/static/style.css
@@ -693,6 +693,32 @@ table.compact td {
   letter-spacing: 0.05em;
 }
 
+/* --- legal pages + footer ------------------------------------------------------- */
+
+.legal {
+  max-width: 68ch;
+}
+
+.legal h2 {
+  margin-top: 2rem;
+}
+
+.legal li {
+  margin: 0.35rem 0;
+}
+
+.site-footer {
+  display: flex;
+  justify-content: center;
+  gap: 1.25rem;
+  padding: 0 16px 2rem;
+  font-size: 0.8rem;
+}
+
+.site-footer a {
+  color: var(--muted);
+}
+
 ::selection {
   background: var(--accent);
   color: #fff;
diff --git a/src/data/cleanup.ts b/src/data/cleanup.ts
index 8342952..fa09230 100644
--- a/src/data/cleanup.ts
+++ b/src/data/cleanup.ts
@@ -18,6 +18,8 @@ export async function sweepExpired(env: Env): Promise<void> {
     env.DB.prepare("DELETE FROM webauthn_challenges WHERE expires_at <= ?").bind(ts),
     env.DB.prepare("DELETE FROM login_links WHERE expires_at <= ?").bind(ts),
     env.DB.prepare("DELETE FROM email_verifications WHERE expires_at <= ?").bind(ts),
+    env.DB.prepare("DELETE FROM signout_links WHERE expires_at <= ?").bind(ts),
+    env.DB.prepare("DELETE FROM known_devices WHERE last_seen_at <= ?").bind(ts - TTL.knownDevice),
     env.DB.prepare("DELETE FROM auth_codes WHERE expires_at <= ?").bind(ts),
     // Revoked or used refresh tokens are kept until they expire anyway, so reuse
     // of an old token can still be recognised and its family shut down.
diff --git a/src/data/notices.ts b/src/data/notices.ts
new file mode 100644
index 0000000..2fc2e88
--- /dev/null
+++ b/src/data/notices.ts
@@ -0,0 +1,190 @@
+/* src/data/notices.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { TTL, issuer, now, siteName, type AppContext, type Env } from "../env";
+import { randomToken, sha256Hex } from "../lib/crypto";
+import { clientIp, userAgent } from "../lib/http";
+import { sendMail } from "../lib/mail";
+import { date, describeAgent } from "../views/ui";
+import { getUser, revokeAllStatements, type UserRow } from "./users";
+
+export interface Notice {
+  subject: string;
+  /** What happened, in one or two sentences. May hold user input; escaped for HTML here. */
+  summary: string;
+  /**
+   * "self": done from a signed-in browser, so the email names that browser and
+   * offers to sign it out. "admin": done by an administrator.
+   */
+  by: "self" | "admin";
+  /** The session to offer to sign out. Defaults to the request's own. */
+  sessionHash?: string | null;
+  /** Send here instead of the account's verified address (the old address after a change). */
+  to?: string;
+}
+
+interface Origin {
+  when: number;
+  ip: string;
+  device: string;
+  place: string | null;
+}
+
+/**
+ * Emails the account owner about a sign-in or a change, in the background so
+ * the response isn't held up by the mail API. Only verified addresses get
+ * notices: an unverified one might not be theirs.
+ */
+export function notify(c: AppContext, userId: string, notice: Notice): void {
+  const cf = (c.req.raw as { cf?: { city?: string; country?: string } }).cf;
+  const origin: Origin = {
+    when: now(),
+    ip: clientIp(c),
+    device: describeAgent(userAgent(c)),
+    place: [cf?.city, cf?.country].filter(Boolean).join(", ") || null,
+  };
+  const sessionHash = notice.sessionHash === undefined ? (c.get("session")?.idHash ?? null) : notice.sessionHash;
+
+  const task = sendNotice(c.env, userId, { ...notice, sessionHash }, origin).catch((err) =>
+    console.error("[notice] couldn't send", err),
+  );
+  try {
+    c.executionCtx.waitUntil(task);
+  } catch {
+    // No execution context (local tools): the promise still runs.
+  }
+}
+
+async function sendNotice(env: Env, userId: string, notice: Notice, origin: Origin): Promise<void> {
+  const user = await getUser(env, userId);
+  if (!user) return;
+  const to = notice.to ?? (user.email_verified ? user.email : null);
+  if (!to) return;
+
+  const site = siteName(env);
+  const accountUrl = `${issuer(env)}/account`;
+  const link = notice.by === "self" ? await createSignoutLink(env, userId, notice.sessionHash ?? null) : null;
+
+  const details: [string, string][] =
+    notice.by === "self"
+      ? [
+          ["When", date(origin.when)],
+          ["Device", origin.device],
+          ["IP address", origin.place ? `${origin.ip} (${origin.place})` : origin.ip],
+        ]
+      : [["When", date(origin.when)]];
+
+  const text = [
+    `Hi ${user.name ?? user.username},`,
+    "",
+    notice.summary,
+    "",
+    ...details.map(([k, v]) => `${k}: ${v}`),
+    "",
+    ...(link
+      ? [
+          "If this was you, there's nothing to do.",
+          "If it wasn't, sign that device out right away, then change your password:",
+          link,
+        ]
+      : [`This was done by an administrator of ${site}. If you weren't expecting it, contact them.`]),
+    "",
+    `Your account: ${accountUrl}`,
+  ].join("\n");
+
+  const html =
+    `<p>Hi ${escapeHtml(user.name ?? user.username)},</p>` +
+    `<p>${escapeHtml(notice.summary)}</p>` +
+    `<table>${details
+      .map(([k, v]) => `<tr><td style="padding-right:1em;color:#666">${k}</td><td>${escapeHtml(v)}</td></tr>`)
+      .join("")}</table>` +
+    (link
+      ? `<p>If this was you, there's nothing to do.</p>` +
+        `<p>If it wasn't, <a href="${link}">sign that device out right away</a>, then change your password.</p>`
+      : `<p>This was done by an administrator of ${escapeHtml(site)}. If you weren't expecting it, contact them.</p>`) +
+    `<p><a href="${accountUrl}">Your account</a></p>`;
+
+  await sendMail(env, { to, subject: `${notice.subject} · ${site}`, text, html });
+}
+
+/**
+ * The goodbye email. Composed from the row before it's deleted, since the
+ * background send would otherwise find no account to write to.
+ */
+export function notifyAccountDeleted(c: AppContext, user: UserRow): void {
+  if (!user.email || !user.email_verified) return;
+  const site = siteName(c.env);
+  const name = user.name ?? user.username;
+  const summary = `Your ${site} account @${user.username} was deleted on ${date(now())}, along with its passkeys, sessions and app sign-ins.`;
+  const footer = "If you didn't do this, someone had access to your account. Contact the administrator straight away.";
+  const task = sendMail(c.env, {
+    to: user.email,
+    subject: `Your account was deleted · ${site}`,
+    text: `Hi ${name},\n\n${summary}\n\n${footer}`,
+    html: `<p>Hi ${escapeHtml(name)},</p><p>${escapeHtml(summary)}</p><p>${footer}</p>`,
+  }).catch((err) => console.error("[notice] couldn't send", err));
+  try {
+    c.executionCtx.waitUntil(task);
+  } catch {
+    // No execution context (local tools): the promise still runs.
+  }
+}
+
+function escapeHtml(s: string): string {
+  return s.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
+}
+
+// --- sign-out links ----------------------------------------------------------------
+
+async function createSignoutLink(env: Env, userId: string, sessionHash: string | null): Promise<string> {
+  const token = randomToken(32);
+  const ts = now();
+  await env.DB.prepare(
+    "INSERT INTO signout_links (token_hash, user_id, session_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?)",
+  )
+    .bind(await sha256Hex(token), userId, sessionHash, ts, ts + TTL.signoutLink)
+    .run();
+  return `${issuer(env)}/security/${token}`;
+}
+
+export interface SignoutTarget {
+  user_id: string;
+  username: string;
+  session_hash: string | null;
+  /** The named session is still signed in. */
+  session_live: number;
+}
+
+/** Links keep working until they expire: every action they take is safe to repeat. */
+export async function peekSignoutLink(env: Env, token: string): Promise<SignoutTarget | null> {
+  return env.DB.prepare(
+    `SELECT l.user_id, u.username, l.session_hash,
+            EXISTS (SELECT 1 FROM sessions s WHERE s.id_hash = l.session_hash AND s.expires_at > ?) AS session_live
+     FROM signout_links l JOIN users u ON u.id = l.user_id
+     WHERE l.token_hash = ? AND l.expires_at > ?`,
+  )
+    .bind(now(), await sha256Hex(token), now())
+    .first<SignoutTarget>();
+}
+
+/** Ends one session and forgets its browser, so signing in there again sends another notice. */
+export async function signOutDevice(env: Env, userId: string, sessionHash: string): Promise<void> {
+  await env.DB.batch([
+    env.DB.prepare(
+      `DELETE FROM known_devices WHERE user_id = ? AND device_hash =
+         (SELECT device_hash FROM sessions WHERE id_hash = ? AND user_id = ?)`,
+    ).bind(userId, sessionHash, userId),
+    env.DB.prepare("DELETE FROM sessions WHERE id_hash = ? AND user_id = ?").bind(sessionHash, userId),
+  ]);
+}
+
+/** Ends every session and app token, and forgets every browser. */
+export async function signOutEverywhere(env: Env, userId: string): Promise<void> {
+  await env.DB.batch([
+    env.DB.prepare("DELETE FROM known_devices WHERE user_id = ?").bind(userId),
+    ...revokeAllStatements(env, userId),
+  ]);
+}
diff --git a/src/data/passkeys.ts b/src/data/passkeys.ts
index f9adda3..7aacd64 100644
--- a/src/data/passkeys.ts
+++ b/src/data/passkeys.ts
@@ -51,8 +51,12 @@ export async function renamePasskey(env: Env, userId: string, id: string, name:
   await env.DB.prepare("UPDATE passkeys SET name = ? WHERE id = ? AND user_id = ?").bind(name, id, userId).run();
 }
 
-export async function deletePasskey(env: Env, userId: string, id: string): Promise<void> {
-  await env.DB.prepare("DELETE FROM passkeys WHERE id = ? AND user_id = ?").bind(id, userId).run();
+/** Returns the removed passkey's name, or null if there was nothing to remove. */
+export async function deletePasskey(env: Env, userId: string, id: string): Promise<string | null> {
+  const row = await env.DB.prepare("DELETE FROM passkeys WHERE id = ? AND user_id = ? RETURNING name")
+    .bind(id, userId)
+    .first<{ name: string }>();
+  return row?.name ?? null;
 }
 
 async function saveChallenge(
@@ -166,16 +170,24 @@ export async function finishRegistration(
 
 // --- authentication ------------------------------------------------------------
 
+/**
+ * With no `userId`, a passkey-only sign-in: no allowCredentials, since passkeys
+ * are discoverable and the username never has to be typed. With one, the
+ * second step after a password, limited to that account's passkeys.
+ */
 export async function authenticationOptions(
   env: Env,
+  userId: string | null = null,
 ): Promise<{ id: string; options: PublicKeyCredentialRequestOptionsJSON }> {
-  // No allowCredentials: passkeys are discoverable, so the browser offers
-  // whichever ones it holds for this site and the username never has to be typed.
+  const allowCredentials = userId
+    ? (await listPasskeys(env, userId)).map((p) => ({ id: p.id, transports: JSON.parse(p.transports) as string[] }))
+    : undefined;
   const options = await generateAuthenticationOptions({
     rpID: rpId(env),
     userVerification: "required",
+    allowCredentials,
   });
-  const id = await saveChallenge(env, options.challenge, "login", null);
+  const id = await saveChallenge(env, options.challenge, "login", userId);
   return { id, options };
 }
 
@@ -185,16 +197,18 @@ export async function finishAuthentication(
   env: Env,
   challengeId: string,
   response: AuthenticationResponseJSON,
+  userId: string | null = null,
 ): Promise<AuthResult> {
   const failure = { ok: false, error: "That passkey couldn't be used to sign in." } as const;
 
-  const challenge = await takeChallenge(env, challengeId, "login", null);
+  const challenge = await takeChallenge(env, challengeId, "login", userId);
   if (!challenge) return { ok: false, error: "That sign-in attempt expired. Please try again." };
 
   const passkey = await env.DB.prepare("SELECT * FROM passkeys WHERE id = ?")
     .bind(String(response?.id ?? ""))
     .first<PasskeyRow>();
   if (!passkey) return { ok: false, error: "This passkey isn't registered here. It may have been removed." };
+  if (userId && passkey.user_id !== userId) return { ok: false, error: "That passkey belongs to a different account." };
 
   const handle = response.response?.userHandle;
   if (handle) {
diff --git a/src/data/sessions.ts b/src/data/sessions.ts
index 99feba8..4c4fd52 100644
--- a/src/data/sessions.ts
+++ b/src/data/sessions.ts
@@ -8,6 +8,8 @@ import { getCookie, setCookie, deleteCookie } from "hono/cookie";
 import { ADMIN_GROUP, TTL, isSecure, now, type AppContext, type CurrentUser, type Env, type SessionInfo } from "../env";
 import { randomToken, sha256Hex } from "../lib/crypto";
 import { clientIp, userAgent } from "../lib/http";
+import { amrLabel } from "../views/ui";
+import { notify } from "./notices";
 import { groupsFor, markLogin } from "./users";
 
 function cookieName(env: Env, base: string): string {
@@ -17,6 +19,7 @@ function cookieName(env: Env, base: string): string {
 
 export const sessionCookie = (env: Env) => cookieName(env, "sso_session");
 export const pendingCookie = (env: Env) => cookieName(env, "sso_pending");
+export const deviceCookie = (env: Env) => cookieName(env, "sso_device");
 
 export function writeCookie(c: AppContext, name: string, value: string, maxAge: number): void {
   setCookie(c, name, value, {
@@ -32,19 +35,30 @@ export function clearCookie(c: AppContext, name: string): void {
   deleteCookie(c, name, { path: "/", secure: isSecure(c.env) });
 }
 
-export async function startSession(c: AppContext, userId: string, amr: string[]): Promise<void> {
+/**
+ * Signs the browser in. Unless `alert` is false (a brand-new account), signing
+ * in from a browser this account hasn't used before emails the owner.
+ */
+export async function startSession(
+  c: AppContext,
+  userId: string,
+  amr: string[],
+  opts: { alert?: boolean } = {},
+): Promise<void> {
   // Drop whatever session this browser already had so ids never get reused
   // across a re-authentication.
   await endSession(c);
 
+  const device = await rememberDevice(c, userId);
   const token = randomToken(32);
+  const idHash = await sha256Hex(token);
   const ts = now();
   await c.env.DB.prepare(
-    `INSERT INTO sessions (id_hash, user_id, csrf, auth_time, amr, ip, user_agent, created_at, last_seen_at, expires_at)
-     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    `INSERT INTO sessions (id_hash, user_id, csrf, auth_time, amr, ip, user_agent, created_at, last_seen_at, expires_at, device_hash)
+     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
   )
     .bind(
-      await sha256Hex(token),
+      idHash,
       userId,
       randomToken(24),
       ts,
@@ -54,10 +68,46 @@ export async function startSession(c: AppContext, userId: string, amr: string[])
       ts,
       ts,
       ts + TTL.session,
+      device.hash,
     )
     .run();
   await markLogin(c.env, userId);
   writeCookie(c, sessionCookie(c.env), token, TTL.session);
+
+  if (device.isNew && opts.alert !== false) {
+    notify(c, userId, {
+      subject: "New sign-in",
+      summary: `Your account was signed in to from a device it hasn't used before, with ${amrLabel(amr)}.`,
+      by: "self",
+      sessionHash: idHash,
+    });
+  }
+}
+
+/**
+ * Every browser carries a random device id (one cookie, whoever signs in).
+ * Returns its hash and whether this account is seeing it for the first time.
+ */
+async function rememberDevice(c: AppContext, userId: string): Promise<{ hash: string; isNew: boolean }> {
+  let token = getCookie(c, deviceCookie(c.env));
+  if (!token || !/^[\w-]{20,64}$/.test(token)) token = randomToken(32);
+  writeCookie(c, deviceCookie(c.env), token, TTL.knownDevice);
+
+  const hash = await sha256Hex(token);
+  const ts = now();
+  const inserted = await c.env.DB.prepare(
+    `INSERT INTO known_devices (user_id, device_hash, first_seen_at, last_seen_at) VALUES (?, ?, ?, ?)
+     ON CONFLICT (user_id, device_hash) DO NOTHING`,
+  )
+    .bind(userId, hash, ts, ts)
+    .run();
+  const isNew = inserted.meta.changes === 1;
+  if (!isNew) {
+    await c.env.DB.prepare("UPDATE known_devices SET last_seen_at = ? WHERE user_id = ? AND device_hash = ?")
+      .bind(ts, userId, hash)
+      .run();
+  }
+  return { hash, isNew };
 }
 
 export async function endSession(c: AppContext): Promise<void> {
@@ -155,10 +205,6 @@ export async function listSessions(env: Env, userId: string): Promise<SessionLis
   return results;
 }
 
-export async function revokeSession(env: Env, userId: string, idHash: string): Promise<void> {
-  await env.DB.prepare("DELETE FROM sessions WHERE user_id = ? AND id_hash = ?").bind(userId, idHash).run();
-}
-
 export async function revokeOtherSessions(env: Env, userId: string, keepIdHash: string): Promise<void> {
   await env.DB.prepare("DELETE FROM sessions WHERE user_id = ? AND id_hash != ?").bind(userId, keepIdHash).run();
 }
diff --git a/src/env.ts b/src/env.ts
index 2509985..179458a 100644
--- a/src/env.ts
+++ b/src/env.ts
@@ -15,6 +15,8 @@ export interface Env {
   REGISTRATION?: string;
   RESEND_API_KEY?: string;
   MAIL_FROM: string;
+  /** Shown on /privacy and /terms for data and account requests. */
+  CONTACT_EMAIL?: string;
 }
 
 export interface SessionInfo {
@@ -61,6 +63,10 @@ export const TTL = {
   emailVerification: 60 * 60 * 24,
   /** A used refresh token is honoured again for this long (racing app instances). */
   refreshReuseGrace: 60,
+  /** A browser that hasn't signed in for this long counts as new again. */
+  knownDevice: 60 * 60 * 24 * 365,
+  /** Sign-out links in security emails. */
+  signoutLink: 60 * 60 * 24 * 7,
   /** Retired signing keys stay in the JWKS this long so issued tokens verify. */
   retiredKey: 60 * 60 * 24 * 2,
 } as const;
diff --git a/src/main.ts b/src/main.ts
index 21000a2..ceba677 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -15,6 +15,8 @@ import { account } from "./routes/account";
 import { admin } from "./routes/admin";
 import { register } from "./routes/register";
 import { verify } from "./routes/verify";
+import { security } from "./routes/security";
+import { legal } from "./routes/legal";
 
 const app = new Hono<AppEnv>();
 
@@ -70,6 +72,8 @@ app.route("/", oidc);
 app.route("/", login);
 app.route("/", register);
 app.route("/", verify);
+app.route("/", security);
+app.route("/", legal);
 app.route("/", setup);
 app.route("/", account);
 app.route("/", admin);
diff --git a/src/oidc/endpoints.tsx b/src/oidc/endpoints.tsx
index c98f46e..f88eb49 100644
--- a/src/oidc/endpoints.tsx
+++ b/src/oidc/endpoints.tsx
@@ -53,6 +53,8 @@ oidc.get("/.well-known/openid-configuration", (c) => {
     userinfo_endpoint: `${iss}/userinfo`,
     jwks_uri: `${iss}/.well-known/jwks.json`,
     end_session_endpoint: `${iss}/end-session`,
+    op_policy_uri: `${iss}/privacy`,
+    op_tos_uri: `${iss}/terms`,
     revocation_endpoint: `${iss}/revoke`,
     scopes_supported: SUPPORTED_SCOPES,
     claims_supported: SUPPORTED_CLAIMS,
diff --git a/src/routes/account.tsx b/src/routes/account.tsx
index 002ea4d..9894889 100644
--- a/src/routes/account.tsx
+++ b/src/routes/account.tsx
@@ -8,12 +8,12 @@ import { Hono } from "hono";
 import { Key, Save, Shield } from "pixelarticons/react";
 import { renderSVG } from "uqr";
 import type { RegistrationResponseJSON } from "@simplewebauthn/server";
-import { siteName, type AppContext, type AppEnv } from "../env";
+import { ADMIN_GROUP, siteName, type AppContext, type AppEnv } from "../env";
 import { audit } from "../lib/audit";
 import { decrypt, encrypt } from "../lib/crypto";
 import { form, readJson } from "../lib/http";
 import { requireCsrf, requireUser } from "../lib/guards";
-import { hashPassword, passwordProblem, PASSWORD_MIN } from "../lib/password";
+import { hashPassword, passwordProblem, PASSWORD_MIN, verifyPassword } from "../lib/password";
 import { generateTotpSecret, otpauthUri, verifyTotp } from "../lib/totp";
 import { cleanText, emailProblem, pictureProblem } from "../lib/validate";
 import {
@@ -24,9 +24,11 @@ import {
   registrationOptions,
   renamePasskey,
 } from "../data/passkeys";
-import { endSession, listSessions, revokeOtherSessions, revokeSession } from "../data/sessions";
+import { notify, notifyAccountDeleted, signOutDevice } from "../data/notices";
+import { endSession, listSessions, revokeOtherSessions } from "../data/sessions";
 import {
   claimTotpStep,
+  deleteUser,
   disableTotp,
   enableTotp,
   getUser,
@@ -37,7 +39,7 @@ import {
 } from "../data/users";
 import { sendVerificationEmail } from "../data/verifications";
 import { render } from "../views/layout";
-import { Csrf, ErrorNote, Field, Flash, Section, date, describeAgent, relative } from "../views/ui";
+import { Csrf, ErrorNote, Field, Flash, Section, amrLabel, date, describeAgent, relative } from "../views/ui";
 
 export const account = new Hono<AppEnv>();
 
@@ -50,16 +52,6 @@ async function me(c: AppContext): Promise<UserRow> {
   return user;
 }
 
-function amrLabel(amr: string): string {
-  const list = JSON.parse(amr) as string[];
-  if (list.includes("swk") || list.includes("hwk")) return "passkey";
-  if (list.includes("otp") && list.includes("pwd")) return "password + code";
-  if (list.includes("pwd")) return "password";
-  if (list.includes("link")) return "sign-in link";
-  if (list.includes("setup")) return "setup";
-  return "unknown";
-}
-
 async function accountPage(c: AppContext, opts: { error?: string; status?: 400 } = {}) {
   const user = await me(c);
   const session = c.get("session")!;
@@ -183,7 +175,10 @@ async function accountPage(c: AppContext, opts: { error?: string; status?: 400 }
         )}
       </Section>
 
-      <Section title="Two-factor codes" description="Asks for a code from an authenticator app after your password. Passkey sign-ins don't need it.">
+      <Section
+        title="Two-factor codes"
+        description="Asks for a code from an authenticator app after your password. Once you have a passkey or codes, a password alone can't sign in: it always needs one of them too. Passkey sign-ins need nothing else."
+      >
         {!user.password_hash ? (
           <p class="muted">Set a password first.</p>
         ) : user.totp_secret ? (
@@ -219,7 +214,7 @@ async function accountPage(c: AppContext, opts: { error?: string; status?: 400 }
                 {s.id_hash === session.idHash && <span class="badge">This browser</span>}
                 <br />
                 <small class="muted">
-                  {s.ip ?? "unknown IP"} · via {amrLabel(s.amr)} · signed in {date(s.created_at)} · active {relative(s.last_seen_at)}
+                  {s.ip ?? "unknown IP"} · via {amrLabel(JSON.parse(s.amr) as string[])} · signed in {date(s.created_at)} · active {relative(s.last_seen_at)}
                 </small>
               </div>
               <form method="post" action={`/account/sessions/${s.id_hash}/revoke`}>
@@ -236,6 +231,27 @@ async function accountPage(c: AppContext, opts: { error?: string; status?: 400 }
           </form>
         )}
       </Section>
+
+      <Section
+        title="Delete account"
+        description="Permanently deletes your account, passkeys, sessions and app sign-ins. Apps you've used may keep their own copy of your details; ask them separately. This can't be undone."
+      >
+        <form
+          method="post"
+          action="/account/delete"
+          class="stack"
+          data-confirm="Delete your account for good? This can't be undone."
+        >
+          <Csrf token={csrf} />
+          <Field label={`Type your username (${user.username}) to confirm`} name="confirm" required autocomplete="off" maxlength={64} />
+          {user.password_hash && (
+            <Field label="Password" name="password" type="password" required autocomplete="current-password" maxlength={512} />
+          )}
+          <div>
+            <button type="submit" class="danger">Delete my account</button>
+          </div>
+        </form>
+      </Section>
     </>,
   );
 }
@@ -255,6 +271,22 @@ account.post("/account/profile", async (c) => {
   const user = await me(c);
   await updateProfile(c.env, user, update);
   await audit(c, "account.profile");
+
+  const emailChanged = update.email !== user.email;
+  if (emailChanged && user.email && user.email_verified) {
+    // The old address hears about it: the new one isn't verified yet.
+    notify(c, user.id, {
+      subject: "Your email address was changed",
+      summary: update.email
+        ? `The email address on your account was changed from ${user.email} to ${update.email}.`
+        : `The email address ${user.email} was removed from your account.`,
+      by: "self",
+      to: user.email,
+    });
+  } else if (!emailChanged && (update.name !== user.name || update.picture !== user.picture)) {
+    notify(c, user.id, { subject: "Your profile was updated", summary: "Your name or picture was changed.", by: "self" });
+  }
+
   if (update.email && update.email !== user.email) {
     const sent = await sendVerificationEmail(c.env, user.id, update.email);
     return c.redirect(`/account?m=${sent === "sent" ? "verify-sent" : "verify-failed"}`);
@@ -284,6 +316,11 @@ account.post("/account/passkeys/verify", async (c) => {
   if (!result.ok) return c.json({ error: result.error }, 400);
 
   await audit(c, "account.passkey_added", { detail: name });
+  notify(c, c.get("user")!.id, {
+    subject: "A passkey was added",
+    summary: `A passkey named "${name}" was added to your account. It can sign in without a password.`,
+    by: "self",
+  });
   return c.json({ redirect: "/account?m=passkey-added" });
 });
 
@@ -303,8 +340,15 @@ account.post("/account/passkeys/:id/delete", async (c) => {
       status: 400,
     });
   }
-  await deletePasskey(c.env, user.id, c.req.param("id"));
+  const name = await deletePasskey(c.env, user.id, c.req.param("id"));
   await audit(c, "account.passkey_removed");
+  if (name) {
+    notify(c, user.id, {
+      subject: "A passkey was removed",
+      summary: `The passkey "${name}" was removed from your account.`,
+      by: "self",
+    });
+  }
   return c.redirect("/account?m=passkey-removed");
 });
 
@@ -322,6 +366,13 @@ account.post("/account/password", async (c) => {
   await setPasswordHash(c.env, user.id, await hashPassword(password));
   await revokeOtherSessions(c.env, user.id, c.get("session")!.idHash);
   await audit(c, "account.password_set");
+  notify(c, user.id, {
+    subject: user.password_hash ? "Your password was changed" : "A password was added",
+    summary: user.password_hash
+      ? "Your password was changed, and your other sessions were signed out."
+      : "A password was added to your account.",
+    by: "self",
+  });
   return c.redirect("/account?m=password-set");
 });
 
@@ -332,6 +383,11 @@ account.post("/account/password/remove", async (c) => {
   }
   await setPasswordHash(c.env, user.id, null);
   await audit(c, "account.password_removed");
+  notify(c, user.id, {
+    subject: "Your password was removed",
+    summary: "The password (and any two-factor codes) was removed from your account. It now signs in with passkeys only.",
+    by: "self",
+  });
   return c.redirect("/account?m=password-removed");
 });
 
@@ -396,6 +452,11 @@ account.post("/account/totp/confirm", async (c) => {
 
   await enableTotp(c.env, user.id, user.totp_pending, step);
   await audit(c, "account.totp_enabled");
+  notify(c, user.id, {
+    subject: "Two-factor codes turned on",
+    summary: "Two-factor codes were turned on. Password sign-ins now also need a code or a passkey.",
+    by: "self",
+  });
   return c.redirect("/account?m=totp-enabled");
 });
 
@@ -410,6 +471,11 @@ account.post("/account/totp/disable", async (c) => {
   }
   await disableTotp(c.env, user.id);
   await audit(c, "account.totp_disabled");
+  notify(c, user.id, {
+    subject: "Two-factor codes turned off",
+    summary: "Two-factor codes were turned off for your account.",
+    by: "self",
+  });
   return c.redirect("/account?m=totp-disabled");
 });
 
@@ -427,6 +493,42 @@ account.post("/account/sessions/:id/revoke", async (c) => {
     await endSession(c);
     return c.redirect("/login?m=signed-out");
   }
-  await revokeSession(c.env, c.get("user")!.id, id);
+  await signOutDevice(c.env, c.get("user")!.id, id);
   return c.redirect("/account?m=session-revoked");
 });
+
+// --- deletion --------------------------------------------------------------------
+
+account.post("/account/delete", async (c) => {
+  const user = await me(c);
+  const body = await form(c);
+
+  if ((body.confirm ?? "").trim().toLowerCase() !== user.username.toLowerCase()) {
+    return accountPage(c, { error: "Type your username exactly to delete your account.", status: 400 });
+  }
+  if (user.password_hash && !(await verifyPassword((body.password ?? "").slice(0, 512), user.password_hash))) {
+    return accountPage(c, { error: "That password isn't right, so your account wasn't deleted.", status: 400 });
+  }
+  if (c.get("user")!.isAdmin) {
+    const admins = await c.env.DB.prepare(
+      `SELECT COUNT(*) AS n FROM user_groups g JOIN users u ON u.id = g.user_id
+       WHERE g.group_name = ? AND u.disabled = 0`,
+    )
+      .bind(ADMIN_GROUP)
+      .first<{ n: number }>();
+    if ((admins?.n ?? 0) <= 1) {
+      return accountPage(c, {
+        error: `You're the only admin. Add another member to ${ADMIN_GROUP} before deleting your account.`,
+        status: 400,
+      });
+    }
+  }
+
+  // Everything else (passkeys, sessions, tokens, devices, links) goes with the
+  // user row. The security log keeps only the id, until it expires.
+  notifyAccountDeleted(c, user);
+  await deleteUser(c.env, user.id);
+  await audit(c, "account.deleted", { actor: null, target: user.id });
+  await endSession(c);
+  return c.redirect("/login?m=account-deleted");
+});
diff --git a/src/routes/admin.tsx b/src/routes/admin.tsx
index 59a6963..c75ae85 100644
--- a/src/routes/admin.tsx
+++ b/src/routes/admin.tsx
@@ -37,6 +37,7 @@ import { createGroup, deleteGroup, listGroups, updateGroup, type GroupRow } from
 import { listKeys, rotateKeys } from "../data/keys";
 import { createLoginLink, hasOpenLoginLink, revokeLoginLinks } from "../data/links";
 import { deletePasskey, listPasskeys } from "../data/passkeys";
+import { notify } from "../data/notices";
 import { listSessions } from "../data/sessions";
 import {
   adminUpdateUser,
@@ -435,9 +436,27 @@ admin.post("/admin/users/:id/profile", async (c) => {
   const problem = usernameProblem(update.username) ?? emailProblem(update.email) ?? pictureProblem(update.picture);
   if (problem) return userPage(c, id, { error: problem });
 
+  const before = await getUser(c.env, id);
   const error = await adminUpdateUser(c.env, id, update);
   if (error) return userPage(c, id, { error });
   await audit(c, "admin.user_updated", { target: id });
+  if (before) {
+    const changed = [
+      before.username !== update.username && `username to @${update.username}`,
+      before.email !== update.email && (update.email ? `email address to ${update.email}` : "email address (removed)"),
+      (before.name !== update.name || before.picture !== update.picture) && "name or picture",
+    ].filter((x): x is string => Boolean(x));
+    if (changed.length > 0) {
+      // A changed address: tell the old one, which the owner can still read.
+      const oldAddress = before.email !== update.email && before.email_verified ? before.email : undefined;
+      notify(c, id, {
+        subject: "An admin updated your account",
+        summary: `An administrator changed your ${changed.join(", ")}.`,
+        by: "admin",
+        ...(oldAddress ? { to: oldAddress } : {}),
+      });
+    }
+  }
   return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=user-saved`);
 });
 
@@ -463,6 +482,11 @@ admin.post("/admin/users/:id/link", async (c) => {
   const ttl = Number((await form(c)).ttl);
   const link = await createLoginLink(c.env, id, c.get("user")!.id, LINK_TTLS.has(ttl) ? ttl : 3600);
   await audit(c, "admin.link_created", { target: id, detail: `ttl=${ttl}` });
+  notify(c, id, {
+    subject: "A sign-in link was created for you",
+    summary: "An administrator created a one-time link that signs in to your account without a password or passkey.",
+    by: "admin",
+  });
   return userPage(c, id, { link });
 });
 
@@ -475,8 +499,11 @@ admin.post("/admin/users/:id/link/revoke", async (c) => {
 
 admin.post("/admin/users/:id/passkeys/:pid/delete", async (c) => {
   const id = c.req.param("id");
-  await deletePasskey(c.env, id, c.req.param("pid"));
+  const name = await deletePasskey(c.env, id, c.req.param("pid"));
   await audit(c, "admin.passkey_removed", { target: id });
+  if (name) {
+    notify(c, id, { subject: "A passkey was removed", summary: `An administrator removed your passkey "${name}".`, by: "admin" });
+  }
   return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=credential-removed`);
 });
 
@@ -484,6 +511,11 @@ admin.post("/admin/users/:id/password/remove", async (c) => {
   const id = c.req.param("id");
   await setPasswordHash(c.env, id, null);
   await audit(c, "admin.password_removed", { target: id });
+  notify(c, id, {
+    subject: "Your password was removed",
+    summary: "An administrator removed your password (and any two-factor codes).",
+    by: "admin",
+  });
   return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=credential-removed`);
 });
 
@@ -491,6 +523,11 @@ admin.post("/admin/users/:id/totp/reset", async (c) => {
   const id = c.req.param("id");
   await disableTotp(c.env, id);
   await audit(c, "admin.totp_reset", { target: id });
+  notify(c, id, {
+    subject: "Two-factor codes turned off",
+    summary: "An administrator turned off two-factor codes for your account.",
+    by: "admin",
+  });
   return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=credential-removed`);
 });
 
@@ -498,6 +535,11 @@ admin.post("/admin/users/:id/signout", async (c) => {
   const id = c.req.param("id");
   await c.env.DB.batch(revokeAllStatements(c.env, id));
   await audit(c, "admin.user_signed_out", { target: id });
+  notify(c, id, {
+    subject: "You were signed out everywhere",
+    summary: "An administrator signed your account out of every browser and app.",
+    by: "admin",
+  });
   if (id === c.get("user")!.id) return c.redirect("/login?m=signed-out");
   return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=user-signed-out`);
 });
@@ -508,6 +550,7 @@ admin.post("/admin/users/:id/disable", async (c) => {
   await setDisabled(c.env, id, true);
   await revokeLoginLinks(c.env, id);
   await audit(c, "admin.user_disabled", { target: id });
+  notify(c, id, { subject: "Your account was disabled", summary: "An administrator disabled your account.", by: "admin" });
   return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=user-disabled`);
 });
 
@@ -515,6 +558,7 @@ admin.post("/admin/users/:id/enable", async (c) => {
   const id = c.req.param("id");
   await setDisabled(c.env, id, false);
   await audit(c, "admin.user_enabled", { target: id });
+  notify(c, id, { subject: "Your account was enabled", summary: "An administrator enabled your account again.", by: "admin" });
   return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=user-enabled`);
 });
 
diff --git a/src/routes/legal.tsx b/src/routes/legal.tsx
new file mode 100644
index 0000000..77ec43c
--- /dev/null
+++ b/src/routes/legal.tsx
@@ -0,0 +1,204 @@
+/* src/routes/legal.tsx
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { Hono } from "hono";
+import { siteName, type AppContext, type AppEnv } from "../env";
+import { render } from "../views/layout";
+
+/** Bump when either page changes in substance. */
+const UPDATED = "26 October 2026";
+const OPERATOR = "Clove Nytrix Doughmination Twilight";
+
+export const legal = new Hono<AppEnv>();
+
+function Contact(props: { c: AppContext }) {
+  const email = props.c.env.CONTACT_EMAIL;
+  return email ? <a href={`mailto:${email}`}>{email}</a> : <>the administrator of this server</>;
+}
+
+legal.get("/privacy", (c) => {
+  const site = siteName(c.env);
+  return render(
+    c,
+    { title: "Privacy policy" },
+    <article class="legal">
+      <p class="eyebrow">Last updated {UPDATED}</p>
+      <h1>Privacy policy</h1>
+      <p>
+        {site} is a single sign-on service run by {OPERATOR}. It lets you sign in to other apps with one account. This
+        page says what it stores about you, why, and for how long. Questions or requests: <Contact c={c} />.
+      </p>
+
+      <h2>What we store</h2>
+      <ul>
+        <li>
+          <strong>Your account:</strong> username, display name, email address (and whether you've verified it), and
+          the picture URL you give us.
+        </li>
+        <li>
+          <strong>How you sign in:</strong> your password as a one-way hash (we never store or see the password
+          itself), your passkeys' public keys (your device keeps the private key), and your two-factor secret,
+          encrypted.
+        </li>
+        <li>
+          <strong>Sessions:</strong> for each signed-in browser, its IP address, browser and operating system (from
+          the User-Agent header), how you signed in, and when.
+        </li>
+        <li>
+          <strong>Known devices:</strong> a random ID for each browser you've signed in from, so we can tell you
+          about sign-ins from new ones.
+        </li>
+        <li>
+          <strong>Security log:</strong> sign-ins, failed sign-ins and account changes, with the IP address they
+          came from.
+        </li>
+        <li>
+          <strong>Groups:</strong> any groups an administrator puts you in, which decide which apps you can use.
+        </li>
+      </ul>
+      <p>We don't use analytics, advertising or tracking of any kind, and we never sell your data.</p>
+
+      <h2>Why</h2>
+      <p>
+        Only to run the service: signing you in, keeping your account secure, telling you about sign-ins and changes,
+        and stopping abuse such as password guessing. The legal basis is that it's needed to provide the service you
+        signed up for, and our legitimate interest in keeping accounts secure.
+      </p>
+
+      <h2>Cookies</h2>
+      <p>Three cookies, all strictly necessary, none used for tracking:</p>
+      <ul>
+        <li>
+          <code>sso_session</code>: keeps you signed in, for up to a day.
+        </li>
+        <li>
+          <code>sso_pending</code>: remembers a half-finished sign-in while you enter a code or use a passkey, for up
+          to 10 minutes.
+        </li>
+        <li>
+          <code>sso_device</code>: a random ID for this browser, so a sign-in from a new device can be flagged. Kept
+          for a year.
+        </li>
+      </ul>
+
+      <h2>Who else sees it</h2>
+      <ul>
+        <li>
+          <strong>Apps you sign in to</strong> receive what they ask for and you use: an ID for your account, and
+          depending on the app, your username, display name, picture, email address and groups. Each app's own
+          privacy policy covers what it does with them.
+        </li>
+        <li>
+          <strong>Cloudflare</strong> hosts the service and its database, and sees the traffic, including your IP
+          address.
+        </li>
+        <li>
+          <strong>Resend</strong> delivers our emails, so it sees your email address and the messages we send you.
+        </li>
+        <li>
+          <strong>Administrators</strong> of this server can see account details, sessions and the security log, to
+          run it and help you.
+        </li>
+      </ul>
+      <p>Those providers may process data outside your country, under their own safeguards.</p>
+
+      <h2>How long we keep it</h2>
+      <ul>
+        <li>Your account: until it's deleted.</li>
+        <li>Sessions: one day. Apps can stay signed in for up to 30 days unless you sign out everywhere.</li>
+        <li>Known devices: a year after a browser last signs in.</li>
+        <li>Security log: 180 days.</li>
+        <li>Email links (verification, sign-out): a day to a week, then they're deleted.</li>
+      </ul>
+
+      <h2>Your rights</h2>
+      <p>
+        You can see and change most of your details on your account page, sign out any session, and delete your
+        account at any time from the bottom of that page. Deleting it immediately removes your account and everything
+        linked to it; security log entries keep only an anonymous account ID and expire on their own within 180 days.
+        You can also ask for a copy of your data, or for corrections, by contacting <Contact c={c} />. If you think we've mishandled your data, you can complain to your data protection authority (in
+        the UK, the ICO).
+      </p>
+
+      <h2>Children</h2>
+      <p>The service isn't meant for children under 13.</p>
+
+      <h2>Changes</h2>
+      <p>If this policy changes in a way that matters, we'll update the date above and tell you by email.</p>
+    </article>,
+  );
+});
+
+legal.get("/terms", (c) => {
+  const site = siteName(c.env);
+  return render(
+    c,
+    { title: "Terms of service" },
+    <article class="legal">
+      <p class="eyebrow">Last updated {UPDATED}</p>
+      <h1>Terms of service</h1>
+      <p>
+        These terms apply to your use of {site}, a single sign-on service run by {OPERATOR}. By creating an account or
+        signing in, you agree to them. How we handle your data is in the <a href="/privacy">privacy policy</a>.
+      </p>
+
+      <h2>Your account</h2>
+      <ul>
+        <li>Give an email address that's yours, and keep it up to date so security emails reach you.</li>
+        <li>
+          Keep your password, passkeys and two-factor device safe. You're responsible for what's done with your
+          account. If you think someone else has access, sign them out from your account page (or the link in our
+          email) and change your password straight away.
+        </li>
+        <li>One person per account. Don't share it, and don't sign in to accounts that aren't yours.</li>
+        <li>You must be at least 13 to have an account.</li>
+      </ul>
+
+      <h2>Acceptable use</h2>
+      <p>Don't:</p>
+      <ul>
+        <li>try to get into other people's accounts, or guess passwords or codes;</li>
+        <li>probe, overload or attack the service, or get around its rate limits and security;</li>
+        <li>pick a username, display name or picture that impersonates someone or is abusive;</li>
+        <li>use the service for anything illegal.</li>
+      </ul>
+
+      <h2>Apps you sign in to</h2>
+      <p>
+        {site} only signs you in. The apps you use with it are run under their own terms, and we aren't responsible
+        for them.
+      </p>
+
+      <h2>Suspension and closing accounts</h2>
+      <p>
+        We can disable or delete an account that breaks these terms or puts the service or other people at risk,
+        usually after telling you. You can delete your own account at any time from your account page.
+      </p>
+
+      <h2>The service</h2>
+      <p>
+        {site} is a personal project, provided as it is and without guarantees. We work to keep it secure and
+        available, but it may sometimes be down, change, or be shut down; if it's shutting down, we'll try to give
+        you notice. As far as the law allows, we aren't liable for losses from using it or being unable to. Nothing
+        here limits liability that can't be limited by law.
+      </p>
+
+      <h2>Changes</h2>
+      <p>
+        We may update these terms. If a change matters, we'll update the date above and tell you by email; using the
+        service afterwards means you accept them.
+      </p>
+
+      <h2>Law</h2>
+      <p>These terms are governed by the laws of England and Wales.</p>
+
+      <h2>Contact</h2>
+      <p>
+        <Contact c={c} />
+      </p>
+    </article>,
+  );
+});
diff --git a/src/routes/login.tsx b/src/routes/login.tsx
index b271ffa..b468791 100644
--- a/src/routes/login.tsx
+++ b/src/routes/login.tsx
@@ -15,17 +15,18 @@ import { burnPasswordCheck, hashPassword, needsRehash, verifyPassword } from "..
 import { attempt, clearAttempts } from "../lib/ratelimit";
 import { verifyTotp } from "../lib/totp";
 import { normaliseUsername } from "../lib/validate";
-import { authenticationOptions, finishAuthentication } from "../data/passkeys";
+import { authenticationOptions, countPasskeys, finishAuthentication } from "../data/passkeys";
 import { consumeLoginLink, peekLoginLink } from "../data/links";
 import {
   endSession,
   finishPendingLogin,
   peekPendingLogin,
+  type PendingLogin,
   spendPendingAttempt,
   startPendingLogin,
   startSession,
 } from "../data/sessions";
-import { claimTotpStep, countUsers, getUser, getUserByUsername, setPasswordHash } from "../data/users";
+import { claimTotpStep, countUsers, getUser, getUserByUsername, setPasswordHash, type UserRow } from "../data/users";
 import { render } from "../views/layout";
 import { ErrorNote, Field, Flash } from "../views/ui";
 
@@ -149,9 +150,10 @@ login.post("/login/password", async (c) => {
     await setPasswordHash(c.env, user.id, await hashPassword(password));
   }
 
-  if (user.totp_secret) {
+  // Accounts with a passkey or two-factor codes need one of them as well.
+  if (await secondStepFor(c, user)) {
     await startPendingLogin(c, user.id, returnTo);
-    return c.redirect("/login/totp");
+    return c.redirect("/login/mfa");
   }
 
   await startSession(c, user.id, ["pwd"]);
@@ -159,30 +161,64 @@ login.post("/login/password", async (c) => {
   return c.redirect(returnTo);
 });
 
-function totpPage(c: AppContext, error?: string) {
+interface SecondStep {
+  totp: boolean;
+  passkey: boolean;
+}
+
+/** What a password sign-in still needs: a code, a passkey, or (neither set up) nothing. */
+async function secondStepFor(c: AppContext, user: UserRow): Promise<SecondStep | null> {
+  const step = { totp: Boolean(user.totp_secret), passkey: (await countPasskeys(c.env, user.id)) > 0 };
+  return step.totp || step.passkey ? step : null;
+}
+
+function secondStepPage(c: AppContext, step: SecondStep, error?: string) {
   return render(
     c,
-    { title: "Two-factor code", narrow: true, status: error ? 401 : 200 },
-    <div class="card">
-      <h1>Enter your code</h1>
-      <p class="muted">Open your authenticator app and enter the 6-digit code for this account.</p>
+    { title: "Confirm it's you", page: "mfa", narrow: true, status: error ? 401 : 200 },
+    <div class="card" id="mfa">
+      <h1>One more step</h1>
+      <p class="muted">
+        {step.totp && step.passkey
+          ? "Use one of your passkeys, or enter the code from your authenticator app."
+          : step.passkey
+            ? "Use one of your passkeys to finish signing in."
+            : "Open your authenticator app and enter the 6-digit code for this account."}
+      </p>
       <ErrorNote error={error} />
-      <form method="post" action="/login/totp" class="stack">
-        <Field
-          label="Code"
-          name="code"
-          required
-          autocomplete="one-time-code"
-          inputmode="numeric"
-          pattern="[0-9 ]{6,7}"
-          maxlength={7}
-          autofocus
-        />
-        <button type="submit" class="primary wide">
-          <Login class="icon" aria-hidden="true" />
-          Continue
+      <p class="notice error hidden" id="passkey-error" role="alert"></p>
+
+      {step.passkey && (
+        <button type="button" class={step.totp ? "wide" : "primary wide"} id="passkey-mfa">
+          <Key class="icon" aria-hidden="true" />
+          Use a passkey
         </button>
-      </form>
+      )}
+
+      {step.passkey && step.totp && (
+        <div class="divider">
+          <span>or enter a code</span>
+        </div>
+      )}
+
+      {step.totp && (
+        <form method="post" action="/login/mfa" class="stack">
+          <Field
+            label="Code"
+            name="code"
+            required
+            autocomplete="one-time-code"
+            inputmode="numeric"
+            pattern="[0-9 ]{6,7}"
+            maxlength={7}
+            autofocus
+          />
+          <button type="submit" class="primary wide">
+            <Login class="icon" aria-hidden="true" />
+            Continue
+          </button>
+        </form>
+      )}
 
       <p class="muted small">
         <a class="btn wide" href="/login">Start over</a>
@@ -191,32 +227,47 @@ function totpPage(c: AppContext, error?: string) {
   );
 }
 
-login.get("/login/totp", async (c) => {
-  if (!(await peekPendingLogin(c))) return c.redirect("/login");
-  return totpPage(c);
+/** The account half-way through a password sign-in, if it can still finish. */
+async function pendingUser(c: AppContext): Promise<{ pending: PendingLogin; user: UserRow; step: SecondStep } | null> {
+  const pending = await peekPendingLogin(c);
+  if (!pending) return null;
+  const user = await getUser(c.env, pending.user_id);
+  const step = user && !user.disabled ? await secondStepFor(c, user) : null;
+  if (!user || !step) {
+    await finishPendingLogin(c, pending.id_hash);
+    return null;
+  }
+  return { pending, user, step };
+}
+
+login.get("/login/mfa", async (c) => {
+  const found = await pendingUser(c);
+  if (!found) return c.redirect("/login");
+  return secondStepPage(c, found.step);
 });
 
-login.post("/login/totp", async (c) => {
+login.post("/login/mfa", async (c) => {
   const body = await form(c);
   const pending = await spendPendingAttempt(c, TOTP_ATTEMPTS);
   if (!pending) return c.redirect("/login");
 
   const user = await getUser(c.env, pending.user_id);
-  if (!user || user.disabled || !user.totp_secret) {
+  const step = user && !user.disabled ? await secondStepFor(c, user) : null;
+  if (!user || !step || !user.totp_secret) {
     await finishPendingLogin(c, pending.id_hash);
     return c.redirect("/login");
   }
 
   const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_secret);
-  const step = await verifyTotp(secret, body.code ?? "", user.totp_last_step);
-  if (step === null || !(await claimTotpStep(c.env, user.id, step))) {
+  const totpStep = await verifyTotp(secret, body.code ?? "", user.totp_last_step);
+  if (totpStep === null || !(await claimTotpStep(c.env, user.id, totpStep))) {
     await audit(c, "login.failed", { actor: user.id, target: user.username, detail: "totp" });
     const left = TOTP_ATTEMPTS - pending.attempts;
     if (left <= 0) {
       await finishPendingLogin(c, pending.id_hash);
       return c.redirect("/login");
     }
-    return totpPage(c, `That code didn't work. ${left} ${left === 1 ? "try" : "tries"} left.`);
+    return secondStepPage(c, step, `That code didn't work. ${left} ${left === 1 ? "try" : "tries"} left.`);
   }
 
   await finishPendingLogin(c, pending.id_hash);
@@ -225,6 +276,34 @@ login.post("/login/totp", async (c) => {
   return c.redirect(safeReturn(pending.return_to));
 });
 
+login.post("/login/mfa/passkey/options", async (c) => {
+  if (!(await attempt(c.env, `passkey-ip:${clientIp(c)}`, 120, WINDOW))) {
+    return c.json({ error: "Too many sign-in attempts. Wait a few minutes and try again." }, 429);
+  }
+  const found = await pendingUser(c);
+  if (!found?.step.passkey) return c.json({ error: "This sign-in expired. Start over." }, 401);
+  return c.json(await authenticationOptions(c.env, found.user.id));
+});
+
+login.post("/login/mfa/passkey/verify", async (c) => {
+  const body = await readJson<{ id?: string; response?: AuthenticationResponseJSON }>(c);
+  if (!body?.id || !body.response) return c.json({ error: "Malformed request." }, 400);
+  const found = await pendingUser(c);
+  if (!found) return c.json({ error: "This sign-in expired. Start over." }, 401);
+  const { pending, user } = found;
+
+  const result = await finishAuthentication(c.env, body.id, body.response, user.id);
+  if (!result.ok) {
+    await audit(c, "login.failed", { actor: user.id, target: user.username, detail: "passkey (second step)" });
+    return c.json({ error: result.error }, 401);
+  }
+
+  await finishPendingLogin(c, pending.id_hash);
+  await startSession(c, user.id, ["pwd", ...result.amr]);
+  await audit(c, "login.password_passkey", { actor: user.id, target: user.username });
+  return c.json({ redirect: safeReturn(pending.return_to) });
+});
+
 login.post("/login/passkey/options", async (c) => {
   if (!(await attempt(c.env, `passkey-ip:${clientIp(c)}`, 120, WINDOW))) {
     return c.json({ error: "Too many sign-in attempts. Wait a few minutes and try again." }, 429);
diff --git a/src/routes/register.tsx b/src/routes/register.tsx
index 1a45eca..b1e5b56 100644
--- a/src/routes/register.tsx
+++ b/src/routes/register.tsx
@@ -95,6 +95,10 @@ function registerPage(c: AppContext, values: RegisterValues, error?: string) {
                 />
                 <Field label="Confirm password" name="confirm" type="password" required autocomplete="new-password"
                     maxlength={PASSWORD_MAX} />
+                <p class="muted small">
+                    By creating an account you agree to the <a href="/terms">terms</a> and{" "}
+                    <a href="/privacy">privacy policy</a>.
+                </p>
                 <button type="submit" class="primary wide">
                     <UserPlus class="icon" aria-hidden="true" />
                     Create account
@@ -150,7 +154,7 @@ register.post("/register", async (c) => {
     if (!result.ok) return registerPage(c, values, UNAVAILABLE);
 
     const sent = await sendVerificationEmail(c.env, result.id, email);
-    await startSession(c, result.id, ["pwd"]);
+    await startSession(c, result.id, ["pwd"], { alert: false });
     await audit(c, "register", { actor: result.id, target: username });
     // From an app: back to /authorize, which asks them to verify before continuing.
     if (returnTo !== "/account") return c.redirect(returnTo);
diff --git a/src/routes/security.tsx b/src/routes/security.tsx
new file mode 100644
index 0000000..d5f50ae
--- /dev/null
+++ b/src/routes/security.tsx
@@ -0,0 +1,109 @@
+/* src/routes/security.tsx
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { Hono } from "hono";
+import { Login, Logout } from "pixelarticons/react";
+import type { AppContext, AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { clientIp, form } from "../lib/http";
+import { attempt } from "../lib/ratelimit";
+import { peekSignoutLink, signOutDevice, signOutEverywhere } from "../data/notices";
+import { render } from "../views/layout";
+
+/** The "wasn't me" links in security emails. They work without signing in. */
+export const security = new Hono<AppEnv>();
+
+function unusable(c: AppContext) {
+  return render(
+    c,
+    { title: "Link expired", narrow: true, status: 410 },
+    <div class="card">
+      <h1>This link has expired</h1>
+      <p class="muted">
+        Sign in to see and sign out your sessions. If you can't sign in, ask an admin to sign you out everywhere.
+      </p>
+      <p>
+        <a class="btn primary" href="/login">
+          <Login class="icon" aria-hidden="true" />
+          Sign in
+        </a>
+      </p>
+    </div>,
+  );
+}
+
+// Mail scanners follow GETs, so signing out takes a deliberate POST.
+security.get("/security/:token", async (c) => {
+  const target = await peekSignoutLink(c.env, c.req.param("token"));
+  if (!target) return unusable(c);
+  const action = `/security/${c.req.param("token")}`;
+  return render(
+    c,
+    { title: "Secure your account", narrow: true },
+    <div class="card stack">
+      <h1>Wasn't you?</h1>
+      <p class="muted">
+        Sign the device out of <strong>@{target.username}</strong>. Then sign in yourself and change your password.
+      </p>
+      {target.session_live ? (
+        <form method="post" action={action}>
+          <input type="hidden" name="scope" value="device" />
+          <button type="submit" class="primary wide">
+            <Logout class="icon" aria-hidden="true" />
+            Sign out that device
+          </button>
+        </form>
+      ) : (
+        <p class="notice">That device's session has already ended.</p>
+      )}
+      <form method="post" action={action} data-confirm="Sign out every browser and app, including this one?">
+        <input type="hidden" name="scope" value="all" />
+        <button type="submit" class="danger wide">
+          <Logout class="icon" aria-hidden="true" />
+          Sign out everywhere
+        </button>
+      </form>
+      <p class="muted small">"Everywhere" also signs out the apps you use with this account.</p>
+    </div>,
+  );
+});
+
+security.post("/security/:token", async (c) => {
+  if (!(await attempt(c.env, `signout-ip:${clientIp(c)}`, 30, 15 * 60))) {
+    return c.text("Too many attempts. Wait a few minutes and try again.", 429);
+  }
+  const target = await peekSignoutLink(c.env, c.req.param("token"));
+  if (!target) return unusable(c);
+
+  const everywhere = (await form(c)).scope === "all";
+  if (everywhere) {
+    await signOutEverywhere(c.env, target.user_id);
+  } else if (target.session_hash) {
+    await signOutDevice(c.env, target.user_id, target.session_hash);
+  }
+  await audit(c, everywhere ? "security.signed_out_everywhere" : "security.signed_out_device", {
+    actor: null,
+    target: target.user_id,
+  });
+
+  return render(
+    c,
+    { title: "Signed out", narrow: true },
+    <div class="card">
+      <h1>{everywhere ? "Signed out everywhere" : "That device is signed out"}</h1>
+      <p class="muted">
+        Now sign in, change your password, and check your passkeys and two-factor settings for anything you didn't
+        add.
+      </p>
+      <p>
+        <a class="btn primary" href="/login?return=%2Faccount">
+          <Login class="icon" aria-hidden="true" />
+          Sign in
+        </a>
+      </p>
+    </div>,
+  );
+});
diff --git a/src/routes/setup.tsx b/src/routes/setup.tsx
index a378cf0..7dec9f5 100644
--- a/src/routes/setup.tsx
+++ b/src/routes/setup.tsx
@@ -104,7 +104,7 @@ setup.post("/setup", async (c) => {
   });
   if (!id) return closed(c);
 
-  await startSession(c, id, ["setup"]);
+  await startSession(c, id, ["setup"], { alert: false });
   await audit(c, "setup.complete", { actor: id, target: username });
   return c.redirect("/account?m=setup-done");
 });
diff --git a/src/views/layout.tsx b/src/views/layout.tsx
index 40f50f6..d757a04 100644
--- a/src/views/layout.tsx
+++ b/src/views/layout.tsx
@@ -63,6 +63,10 @@ export async function render(c: AppContext, opts: PageOptions, body: Child): Pro
           )}
         </header>
         <main class={opts.narrow ? "narrow" : "wide"}>{body}</main>
+        <footer class="site-footer">
+          <a href="/privacy">Privacy</a>
+          <a href="/terms">Terms</a>
+        </footer>
       </body>
     </html>
   );
diff --git a/src/views/ui.tsx b/src/views/ui.tsx
index aff10f7..a6153ea 100644
--- a/src/views/ui.tsx
+++ b/src/views/ui.tsx
@@ -10,6 +10,7 @@ import type { Child } from "hono/jsx";
 // crafted link can't put words in this site's mouth.
 const MESSAGES: Record<string, string> = {
   "signed-out": "You're signed out.",
+  "account-deleted": "Your account has been deleted.",
   "setup-done": "Your admin account is ready. Add a passkey or password below so you can sign in again.",
   "link-welcome": "You're signed in. Add a passkey (or a password) now so you can sign in next time.",
   "welcome-verify": "Welcome! We've emailed you a link to verify your address. Add a passkey below while you wait.",
@@ -128,6 +129,18 @@ export function relative(ts: number | null | undefined): string {
   return future ? `in ${text}` : `${text} ago`;
 }
 
+/** How a session signed in, from its RFC 8176 `amr` list. */
+export function amrLabel(amr: string[]): string {
+  const passkey = amr.includes("swk") || amr.includes("hwk");
+  if (passkey && amr.includes("pwd")) return "password + passkey";
+  if (passkey) return "passkey";
+  if (amr.includes("otp") && amr.includes("pwd")) return "password + code";
+  if (amr.includes("pwd")) return "password";
+  if (amr.includes("link")) return "sign-in link";
+  if (amr.includes("setup")) return "setup";
+  return "unknown";
+}
+
 /** Short, friendly browser + OS guess for session lists. */
 export function describeAgent(ua: string | null): string {
   if (!ua) return "Unknown device";
diff --git a/wrangler.jsonc b/wrangler.jsonc
index bf7dd11..c10000b 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -46,7 +46,8 @@
 		"SITE_NAME": "Doughmination SSO",
 		"REGISTRATION": "open",
 		// Sender for verification emails. The domain must be verified in Resend.
-		"MAIL_FROM": "Doughmination SSO <[email protected]>"
+		"MAIL_FROM": "Doughmination SSO <[email protected]>",
+		"CONTACT_EMAIL": "[email protected]"
 	}
 	// Secrets (wrangler secret put <NAME>):
 	//   KEY_ENCRYPTION_KEY  encrypts signing keys + TOTP secrets at rest