Dough Git

commit

meow

commit
41a8567e958893c489480ec025641b3ed6998105
author
Clove Twilight <[email protected]>
date
2026-10-28 20:11

diff --git a/.svelte-check/svelte/web/src/++App.svelte.ts b/.svelte-check/svelte/web/src/++App.svelte.ts
new file mode 100644
index 0000000..516456e
--- /dev/null
+++ b/.svelte-check/svelte/web/src/++App.svelte.ts
@@ -0,0 +1,199 @@
+///<reference types="svelte" />
+;
+import type { Component } from "svelte";
+import { ArrowLeft, LayoutGrid, LogOut, Settings as SettingsIcon, Shield } from "@lucide/svelte";
+import { api, errorText } from "./lib/api";
+import { here, navigate, reload, route } from "./lib/router.svelte";
+import { session } from "./lib/session.svelte";
+import Card from "./components/Card.svelte";
+
+import Login from "./pages/Login.svelte";
+import Mfa from "./pages/Mfa.svelte";
+import LoginLink from "./pages/LoginLink.svelte";
+import Register from "./pages/Register.svelte";
+import Setup from "./pages/Setup.svelte";
+import Forgot from "./pages/Forgot.svelte";
+import Reset from "./pages/Reset.svelte";
+import VerifyEmail from "./pages/VerifyEmail.svelte";
+import Security from "./pages/Security.svelte";
+import Apps from "./pages/Apps.svelte";
+import Settings from "./pages/Settings.svelte";
+import TotpSetup from "./pages/TotpSetup.svelte";
+import Privacy from "./pages/Privacy.svelte";
+import Terms from "./pages/Terms.svelte";
+import AuthorizeNotice from "./pages/AuthorizeNotice.svelte";
+import EndSession from "./pages/EndSession.svelte";
+import ErrorPage from "./pages/ErrorPage.svelte";
+import NotFound from "./pages/NotFound.svelte";
+import Users from "./pages/admin/Users.svelte";
+import UserDetail from "./pages/admin/UserDetail.svelte";
+import Groups from "./pages/admin/Groups.svelte";
+import Clients from "./pages/admin/Clients.svelte";
+import ClientDetail from "./pages/admin/ClientDetail.svelte";
+import Keys from "./pages/admin/Keys.svelte";
+import Audit from "./pages/admin/Audit.svelte";
+import Reserved from "./pages/admin/Reserved.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+
+  type Page = Component<{ params: Record<string, string> }>;
+
+  interface Route {
+    pattern: string;
+    page: Page;
+    /** Centered card layout for sign-in screens. */
+    narrow?: boolean;
+    access?: "user" | "admin";
+  }
+
+  // These paths are also the links in our emails (verify-email, security,
+  // reset, login/link), so they mustn't change.
+  const ROUTES: Route[] = [
+    { pattern: "/login", page: Login, narrow: true },
+    { pattern: "/login/mfa", page: Mfa, narrow: true },
+    { pattern: "/login/link/:token", page: LoginLink, narrow: true },
+    { pattern: "/register", page: Register, narrow: true },
+    { pattern: "/setup", page: Setup, narrow: true },
+    { pattern: "/forgot", page: Forgot, narrow: true },
+    { pattern: "/reset/:token", page: Reset, narrow: true },
+    { pattern: "/verify-email/:token", page: VerifyEmail, narrow: true },
+    { pattern: "/security/:token", page: Security, narrow: true },
+    { pattern: "/apps", page: Apps, access: "user" },
+    { pattern: "/settings", page: Settings, access: "user" },
+    { pattern: "/settings/totp", page: TotpSetup, narrow: true, access: "user" },
+    { pattern: "/admin/users", page: Users, access: "admin" },
+    { pattern: "/admin/users/:id", page: UserDetail, access: "admin" },
+    { pattern: "/admin/groups", page: Groups, access: "admin" },
+    { pattern: "/admin/clients", page: Clients, access: "admin" },
+    { pattern: "/admin/clients/:id", page: ClientDetail, access: "admin" },
+    { pattern: "/admin/keys", page: Keys, access: "admin" },
+    { pattern: "/admin/audit", page: Audit, access: "admin" },
+    { pattern: "/admin/reserved", page: Reserved, access: "admin" },
+    { pattern: "/privacy", page: Privacy },
+    { pattern: "/terms", page: Terms },
+    { pattern: "/authorize/notice", page: AuthorizeNotice, narrow: true },
+    { pattern: "/end-session/confirm", page: EndSession, narrow: true },
+    { pattern: "/error", page: ErrorPage, narrow: true },
+  ];
+
+  const REDIRECTS: Record<string, () => string> = {
+    "/": () => (session.user ? "/apps" : "/login"),
+    "/admin": () => "/admin/users",
+    // The old name for /settings, still linked from emails sent before the rename.
+    "/account": () => "/settings" + route.search,
+  };
+
+  function match(path: string): { route: Route; params: Record<string, string> } {
+    const parts = path.replace(/\/+$/, "").split("/");
+    for (const r of ROUTES) {
+      const want = r.pattern.split("/");
+      if (want.length !== parts.length) continue;
+      const params: Record<string, string> = {};
+      if (want.every((w, i) => (w.startsWith(":") ? (params[w.slice(1)] = decodeURIComponent(parts[i]!)) : w === parts[i]))) {
+        return { route: r, params };
+      }
+    }
+    return { route: { pattern: "*", page: NotFound, narrow: true }, params: {} };
+  }
+
+  $effect(() => {
+    const to = REDIRECTS[route.path];
+    if (to) navigate(to(), { replace: true });
+  });
+
+  const current = $derived(match(route.path));
+  const needsSignIn = $derived(current.route.access !== undefined && !session.user);
+  const forbidden = $derived(current.route.access === "admin" && session.user !== null && !session.user.isAdmin);
+
+  $effect(() => {
+    if (needsSignIn) reload(`/login?${new URLSearchParams({ return: here() })}`);
+  });
+
+  let signOutError = $state("");
+  async function signOut() {
+    try {
+      const { redirect } = await api<{ redirect: string }>("/api/logout", {});
+      reload(redirect);
+    } catch (err) {
+      signOutError = errorText(err);
+    }
+  }
+;
+async () => {
+
+ { svelteHTML.createElement("header", { "class":`topbar`,});
+   { svelteHTML.createElement("a", {   "class":`brand`,"href":session.user ? "/apps" : "/login",});session.site; }
+  if(session.user){
+     { svelteHTML.createElement("nav", {});
+       { svelteHTML.createElement("a", {   "class":`btn small`,"href":`/apps`,}); { const $$_dirGtuoyaL3C = __sveltets_2_ensureComponent(LayoutGrid); new $$_dirGtuoyaL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}  }
+       { svelteHTML.createElement("a", {   "class":`btn small`,"href":`/settings`,}); { const $$_nocIsgnitteS3C = __sveltets_2_ensureComponent(SettingsIcon); new $$_nocIsgnitteS3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}  }
+      if(session.user.isAdmin){
+         { svelteHTML.createElement("a", {   "class":`btn small`,"href":`/admin/users`,}); { const $$_dleihS3C = __sveltets_2_ensureComponent(Shield); new $$_dleihS3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}  }
+      }
+       { svelteHTML.createElement("button", {     "type":`button`,"class":`small`,"onclick":signOut,});
+         { const $$_tuOgoL3C = __sveltets_2_ensureComponent(LogOut); new $$_tuOgoL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}  
+       }
+     }
+  }
+ }
+
+ { svelteHTML.createElement("main", { "class":current.route.narrow || forbidden ? "narrow" : "wide",});
+  if(signOutError){ { svelteHTML.createElement("p", {   "class":`notice error`,"role":`alert`,});signOutError; }}
+  if(needsSignIn || REDIRECTS[route.path]){
+    
+  } else if (forbidden){
+     { const $$_draC1C = __sveltets_2_ensureComponent(Card); new $$_draC1C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Admins only`,"lead":`Your account isn't in the admin group for this server.`,}});
+       { svelteHTML.createElement("p", {});
+         { svelteHTML.createElement("a", {   "class":`btn primary`,"href":`/apps`,}); { const $$_tfeLworrA4C = __sveltets_2_ensureComponent(ArrowLeft); new $$_tfeLworrA4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}     }
+       }
+     Card}
+  }else{
+    route.path; {
+      const Page = current.route.page;
+       { const $$_egaP1C = __sveltets_2_ensureComponent(Page); new $$_egaP1C({ target: __sveltets_2_any(), props: {  "params":current.params,}});}
+    }
+  }
+ }
+
+ { svelteHTML.createElement("footer", { "class":`site-footer`,});
+   { svelteHTML.createElement("a", { "href":`/privacy`,});  }
+   { svelteHTML.createElement("a", { "href":`/terms`,});  }
+ }
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const App__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type App__SvelteComponent_ = ReturnType<typeof App__SvelteComponent_>;
+/*Ωignore_endΩ*/export default App__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/App.d.svelte.ts b/.svelte-check/svelte/web/src/App.d.svelte.ts
new file mode 100644
index 0000000..6d6fd77
--- /dev/null
+++ b/.svelte-check/svelte/web/src/App.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++App.svelte.ts";
+export * from "./++App.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/++AdminTabs.svelte.ts b/.svelte-check/svelte/web/src/components/++AdminTabs.svelte.ts
new file mode 100644
index 0000000..546e54d
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++AdminTabs.svelte.ts
@@ -0,0 +1,28 @@
+///<reference types="svelte" />
+;
+import { route } from "../lib/router.svelte";
+function $$render() {
+
+  
+
+  const TABS = [
+    ["/admin/users", "Users"],
+    ["/admin/groups", "Groups"],
+    ["/admin/clients", "Applications"],
+    ["/admin/keys", "Signing keys"],
+    ["/admin/audit", "Audit log"],
+    ["/admin/reserved", "Reserved names"],
+  ] as const;
+;
+async () => {
+
+ { svelteHTML.createElement("nav", { "class":`tabs`,});
+     for(let [href, label] of __sveltets_2_ensureArray(TABS)){href;
+     { svelteHTML.createElement("a", {  href,"class":route.path === href || route.path.startsWith(href + "/") ? "active" : undefined,});label; }
+  }
+ }
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: "", slots: {}, events: {} }}
+const AdminTabs__SvelteComponent_ = __sveltets_2_isomorphic_component(__sveltets_2_with_any_event($$render()));
+/*Ωignore_startΩ*/type AdminTabs__SvelteComponent_ = InstanceType<typeof AdminTabs__SvelteComponent_>;
+/*Ωignore_endΩ*/export default AdminTabs__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/++Card.svelte.ts b/.svelte-check/svelte/web/src/components/++Card.svelte.ts
new file mode 100644
index 0000000..f47b421
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++Card.svelte.ts
@@ -0,0 +1,27 @@
+///<reference types="svelte" />
+;// A narrow page's single card: a title, an optional lead paragraph, then content.
+
+import type { Snippet } from "svelte";
+import Title from "./Title.svelte";
+
+;type $$ComponentProps =  { title: string; lead?: string; children?: Snippet };function $$render() {
+
+  
+  
+  
+
+  let { title, lead, children }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":title,}});}
+ { svelteHTML.createElement("div", { "class":`card`,});
+   { svelteHTML.createElement("h1", {});title; }
+  if(lead){ { svelteHTML.createElement("p", { "class":`muted`,});lead; }}
+  ;__sveltets_2_ensureSnippet(children?.());
+ }
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Card__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Card__SvelteComponent_ = ReturnType<typeof Card__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Card__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/++ClientFields.svelte.ts b/.svelte-check/svelte/web/src/components/++ClientFields.svelte.ts
new file mode 100644
index 0000000..14c6124
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++ClientFields.svelte.ts
@@ -0,0 +1,47 @@
+///<reference types="svelte" />
+;
+  export interface ClientValues {
+    name: string;
+    homeUrl: string;
+    redirectUris: string;
+    postLogoutRedirectUris: string;
+    allowedGroups: string[];
+  }
+;;
+
+import Field from "./Field.svelte";
+import GroupChecks, { type GroupOption } from "./GroupChecks.svelte";
+
+;type $$ComponentProps =  { values: ClientValues; groups: GroupOption[] };function $$render() {
+
+  
+  
+
+  let { values = $bindable(), groups }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props()/*Ωignore_startΩ*/;values;/*Ωignore_endΩ*/;
+;
+async () => {
+
+
+
+ { const $$_dleiF0C = __sveltets_2_ensureComponent(Field); const $$_dleiF0 = new $$_dleiF0C({ target: __sveltets_2_any(), props: {            "label":`Name`,"name":`name`,value:values.name,"required":true,"maxlength":100,"autocomplete":`off`,"hint":`Shown to people when they're asked to sign in.`,}});/*Ωignore_startΩ*/() => values.name = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF0.$$bindings = 'value';}
+ { const $$_dleiF0C = __sveltets_2_ensureComponent(Field); const $$_dleiF0 = new $$_dleiF0C({ target: __sveltets_2_any(), props: {                 "label":`Website`,"name":`homeUrl`,"type":`url`,value:values.homeUrl,"maxlength":2048,"autocomplete":`off`,"placeholder":`https://app.example.com/`,"hint":`Optional. Where the app lives: with one, it's listed on everyone's “Your apps” page (if their groups allow it).`,}});/*Ωignore_startΩ*/() => values.homeUrl = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF0.$$bindings = 'value';}
+ { svelteHTML.createElement("label", { "class":`field`,});
+   { svelteHTML.createElement("span", {});  }
+   { svelteHTML.createElement("textarea", {     "bind:value":values.redirectUris,"rows":3,"required":true,"placeholder":`https://app.example.com/auth/callback`,});/*Ωignore_startΩ*/() => values.redirectUris = __sveltets_2_any(null);/*Ωignore_endΩ*/ }
+   { svelteHTML.createElement("small", { "class":`muted`,});     }
+ }
+ { svelteHTML.createElement("label", { "class":`field`,});
+   { svelteHTML.createElement("span", {});   }
+   { svelteHTML.createElement("textarea", {     "bind:value":values.postLogoutRedirectUris,"rows":2,"placeholder":`https://app.example.com/`,});/*Ωignore_startΩ*/() => values.postLogoutRedirectUris = __sveltets_2_any(null);/*Ωignore_endΩ*/ }
+   { svelteHTML.createElement("small", { "class":`muted`,});           }
+ }
+ { svelteHTML.createElement("fieldset", {});
+   { svelteHTML.createElement("legend", {});    }
+   { svelteHTML.createElement("p", { "class":`muted small`,});       }
+   { const $$_skcehCpuorG1C = __sveltets_2_ensureComponent(GroupChecks); const $$_skcehCpuorG1 = new $$_skcehCpuorG1C({ target: __sveltets_2_any(), props: {   groups,selected:values.allowedGroups,}});/*Ωignore_startΩ*/() => values.allowedGroups = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_skcehCpuorG1.$$bindings = 'selected';}
+ }
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings('values'), slots: {}, events: {} }}
+const ClientFields__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type ClientFields__SvelteComponent_ = ReturnType<typeof ClientFields__SvelteComponent_>;
+/*Ωignore_endΩ*/export default ClientFields__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/++CopyRow.svelte.ts b/.svelte-check/svelte/web/src/components/++CopyRow.svelte.ts
new file mode 100644
index 0000000..2bcb91e
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++CopyRow.svelte.ts
@@ -0,0 +1,29 @@
+///<reference types="svelte" />
+;
+;type $$ComponentProps =  { value: string; label: string };function $$render() {
+
+  let { value, label }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+  let input: HTMLInputElement;
+  let copied = $state(false);
+
+  async function copy() {
+    try {
+      await navigator.clipboard.writeText(value);
+      copied = true;
+      setTimeout(() => (copied = false), 1500);
+    } catch {
+      input.select();
+    }
+  }
+;
+async () => {
+
+ { svelteHTML.createElement("p", { "class":`copyrow`,});
+   { const $$_input1 = svelteHTML.createElement("input", {        "type":`text`,"readonly":true,value,"aria-label":label,});input = $$_input1;}
+   { svelteHTML.createElement("button", {   "type":`button`,"onclick":copy,});copied ? "Copied" : "Copy"; }
+ }
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const CopyRow__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type CopyRow__SvelteComponent_ = ReturnType<typeof CopyRow__SvelteComponent_>;
+/*Ωignore_endΩ*/export default CopyRow__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/++Field.svelte.ts b/.svelte-check/svelte/web/src/components/++Field.svelte.ts
new file mode 100644
index 0000000..bcb2dc6
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++Field.svelte.ts
@@ -0,0 +1,44 @@
+///<reference types="svelte" />
+;
+import { focus } from "../lib/action.svelte";
+
+;type $$ComponentProps =  {
+    label: string;
+    name: string;
+    value?: string | null;
+    type?: string;
+    hint?: string;
+    autofocus?: boolean;
+    required?: boolean;
+    autocomplete?: HTMLInputElement["autocomplete"] | null;
+    placeholder?: string;
+    maxlength?: number;
+    inputmode?: "numeric" | "email" | "text";
+    pattern?: string;
+    disabled?: boolean;
+  };function $$render() {
+
+  
+
+  let {
+    label,
+    name,
+    value = $bindable(""),
+    type = "text",
+    hint,
+    autofocus = false,
+    ...rest
+  }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props()/*Ωignore_startΩ*/;value;/*Ωignore_endΩ*/;
+;
+async () => {
+
+ { svelteHTML.createElement("label", { "class":`field`,});
+   { svelteHTML.createElement("span", {});label; }
+   {const $$action_0 = __sveltets_2_ensureAction(focus(svelteHTML.mapElementTag('input'),(autofocus)));{ svelteHTML.createElement("input", __sveltets_2_union($$action_0), {      type,name,"bind:value":value,...rest,});/*Ωignore_startΩ*/() => value = __sveltets_2_any(null);/*Ωignore_endΩ*/}}
+  if(hint){ { svelteHTML.createElement("small", { "class":`muted`,});hint; }}
+ }
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings('value'), slots: {}, events: {} }}
+const Field__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Field__SvelteComponent_ = ReturnType<typeof Field__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Field__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/++Flash.svelte.ts b/.svelte-check/svelte/web/src/components/++Flash.svelte.ts
new file mode 100644
index 0000000..20d9f97
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++Flash.svelte.ts
@@ -0,0 +1,21 @@
+///<reference types="svelte" />
+;// A success note named by `?m=` in the URL (fixed codes only, see lib/messages).
+
+import { MESSAGES } from "../lib/messages";
+import { query } from "../lib/router.svelte";
+function $$render() {
+
+  
+  
+  
+
+  const text = $derived(MESSAGES[query().get("m") ?? ""] ?? "");
+;
+async () => {
+
+if(text){ { svelteHTML.createElement("p", {   "class":`notice ok`,"role":`status`,});text; }}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Flash__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Flash__SvelteComponent_ = ReturnType<typeof Flash__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Flash__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/++GroupChecks.svelte.ts b/.svelte-check/svelte/web/src/components/++GroupChecks.svelte.ts
new file mode 100644
index 0000000..e0ec539
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++GroupChecks.svelte.ts
@@ -0,0 +1,35 @@
+///<reference types="svelte" />
+;
+  export interface GroupOption {
+    name: string;
+    description: string;
+  }
+;;
+;type $$ComponentProps =  { groups: GroupOption[]; selected?: string[] };function $$render() {
+
+  let { groups, selected = $bindable([]) }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props()/*Ωignore_startΩ*/;selected;/*Ωignore_endΩ*/;
+;
+async () => {
+
+
+
+if(groups.length === 0){
+   { svelteHTML.createElement("p", { "class":`muted`,});   }
+}else{
+   { svelteHTML.createElement("div", { "class":`checks`,});
+       for(let g of __sveltets_2_ensureArray(groups)){g.name;
+       { svelteHTML.createElement("label", { "class":`check`,});
+         { svelteHTML.createElement("input", {     "type":`checkbox`,"value":g.name,});selected = __sveltets_2_any(null);}
+         { svelteHTML.createElement("span", {});
+          g.name;
+          if(g.description){ { svelteHTML.createElement("small", { "class":`muted`,});  g.description; }}
+         }
+       }
+    }
+   }
+}
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings('selected'), slots: {}, events: {} }}
+const GroupChecks__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type GroupChecks__SvelteComponent_ = ReturnType<typeof GroupChecks__SvelteComponent_>;
+/*Ωignore_endΩ*/export default GroupChecks__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/++Notes.svelte.ts b/.svelte-check/svelte/web/src/components/++Notes.svelte.ts
new file mode 100644
index 0000000..03f3804
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++Notes.svelte.ts
@@ -0,0 +1,16 @@
+///<reference types="svelte" />
+;
+;type $$ComponentProps =  { ok?: string | null; error?: string | null };function $$render() {
+
+  // The success note and/or error for an action. Errors are announced to screen readers.
+  let { ok = "", error = "" }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+;
+async () => {
+
+if(ok){ { svelteHTML.createElement("p", {   "class":`notice ok`,"role":`status`,});ok; }}
+if(error){ { svelteHTML.createElement("p", {   "class":`notice error`,"role":`alert`,});error; }}
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Notes__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Notes__SvelteComponent_ = ReturnType<typeof Notes__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Notes__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/++Section.svelte.ts b/.svelte-check/svelte/web/src/components/++Section.svelte.ts
new file mode 100644
index 0000000..920587a
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++Section.svelte.ts
@@ -0,0 +1,22 @@
+///<reference types="svelte" />
+;
+import type { Snippet } from "svelte";
+
+;type $$ComponentProps =  { title: string; description?: string; children: Snippet };function $$render() {
+
+  
+
+  let { title, description, children }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+;
+async () => {
+
+ { svelteHTML.createElement("section", { "class":`panel`,});
+   { svelteHTML.createElement("h2", {});title; }
+  if(description){ { svelteHTML.createElement("p", { "class":`muted`,});description; }}
+  ;__sveltets_2_ensureSnippet(children());
+ }
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Section__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Section__SvelteComponent_ = ReturnType<typeof Section__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Section__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/++Title.svelte.ts b/.svelte-check/svelte/web/src/components/++Title.svelte.ts
new file mode 100644
index 0000000..cd48a29
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/++Title.svelte.ts
@@ -0,0 +1,20 @@
+///<reference types="svelte" />
+;
+import { session } from "../lib/session.svelte";
+
+;type $$ComponentProps =  { text: string };function $$render() {
+
+  
+
+  let { text }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+;
+async () => {
+
+ { svelteHTML.createElement("svelte:head", {});
+   { svelteHTML.createElement("title", {});text;  session.site; }
+ }
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Title__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Title__SvelteComponent_ = ReturnType<typeof Title__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Title__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/components/AdminTabs.d.svelte.ts b/.svelte-check/svelte/web/src/components/AdminTabs.d.svelte.ts
new file mode 100644
index 0000000..384c460
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/AdminTabs.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++AdminTabs.svelte.ts";
+export * from "./++AdminTabs.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/Card.d.svelte.ts b/.svelte-check/svelte/web/src/components/Card.d.svelte.ts
new file mode 100644
index 0000000..e2e64ee
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/Card.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Card.svelte.ts";
+export * from "./++Card.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/ClientFields.d.svelte.ts b/.svelte-check/svelte/web/src/components/ClientFields.d.svelte.ts
new file mode 100644
index 0000000..40f2a91
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/ClientFields.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++ClientFields.svelte.ts";
+export * from "./++ClientFields.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/CopyRow.d.svelte.ts b/.svelte-check/svelte/web/src/components/CopyRow.d.svelte.ts
new file mode 100644
index 0000000..8514229
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/CopyRow.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++CopyRow.svelte.ts";
+export * from "./++CopyRow.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/Field.d.svelte.ts b/.svelte-check/svelte/web/src/components/Field.d.svelte.ts
new file mode 100644
index 0000000..0090882
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/Field.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Field.svelte.ts";
+export * from "./++Field.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/Flash.d.svelte.ts b/.svelte-check/svelte/web/src/components/Flash.d.svelte.ts
new file mode 100644
index 0000000..e56d8e9
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/Flash.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Flash.svelte.ts";
+export * from "./++Flash.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/GroupChecks.d.svelte.ts b/.svelte-check/svelte/web/src/components/GroupChecks.d.svelte.ts
new file mode 100644
index 0000000..2447829
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/GroupChecks.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++GroupChecks.svelte.ts";
+export * from "./++GroupChecks.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/Notes.d.svelte.ts b/.svelte-check/svelte/web/src/components/Notes.d.svelte.ts
new file mode 100644
index 0000000..49a70a7
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/Notes.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Notes.svelte.ts";
+export * from "./++Notes.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/Section.d.svelte.ts b/.svelte-check/svelte/web/src/components/Section.d.svelte.ts
new file mode 100644
index 0000000..b67672d
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/Section.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Section.svelte.ts";
+export * from "./++Section.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/components/Title.d.svelte.ts b/.svelte-check/svelte/web/src/components/Title.d.svelte.ts
new file mode 100644
index 0000000..ca45904
--- /dev/null
+++ b/.svelte-check/svelte/web/src/components/Title.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Title.svelte.ts";
+export * from "./++Title.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/++Account.svelte.ts b/.svelte-check/svelte/web/src/pages/++Account.svelte.ts
new file mode 100644
index 0000000..86912b2
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Account.svelte.ts
@@ -0,0 +1,321 @@
+///<reference types="svelte" />
+;
+import { KeyRound, Save } from "@lucide/svelte";
+import { api, confirmed } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { date, relative } from "../lib/format";
+import { navigate, reload } from "../lib/router.svelte";
+import { createPasskey, passkeyMessage, passkeysSupported } from "../lib/webauthn";
+import Field from "../components/Field.svelte";
+import Flash from "../components/Flash.svelte";
+import Notes from "../components/Notes.svelte";
+import Section from "../components/Section.svelte";
+import Title from "../components/Title.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+
+  interface AccountData {
+    username: string;
+    name: string | null;
+    email: string | null;
+    emailVerified: boolean;
+    picture: string | null;
+    hasPassword: boolean;
+    totp: boolean;
+    recentAuth: boolean;
+    passkeys: { id: string; name: string; synced: boolean; createdAt: number; lastUsedAt: number | null }[];
+    sessions: {
+      id: string;
+      current: boolean;
+      device: string;
+      ip: string | null;
+      method: string;
+      createdAt: number;
+      lastSeenAt: number;
+    }[];
+  }
+
+  const PASSWORD_MIN = 10;
+
+  let data = $state<AccountData | null>(null);
+  const profile = $state({ name: "", email: "", picture: "" });
+  const passwords = $state({ password: "", confirm: "" });
+  const removal = $state({ confirm: "", password: "" });
+  let newPasskeyName = $state("");
+  let totpCode = $state("");
+  let renames = $state<Record<string, string>>({});
+
+  // One Action per section, so each shows its own result next to its form.
+  const load = new Action();
+  const profileAction = new Action();
+  const passkeyAction = new Action();
+  const passwordAction = new Action();
+  const totpAction = new Action();
+  const sessionAction = new Action();
+  const deleteAction = new Action();
+
+  async function refresh() {
+    const d = await api<AccountData>("/api/account");
+    data = d;
+    Object.assign(profile, { name: d.name ?? "", email: d.email ?? "", picture: d.picture ?? "" });
+    renames = Object.fromEntries(d.passkeys.map((p) => [p.id, p.name]));
+  }
+  load.run(refresh);
+
+  /** Runs `call` in a section; on success shows its message and reloads the page's data. */
+  async function act(section: Action, call: () => Promise<{ message?: string | null; redirect?: string }>) {
+    await section.run(async () => {
+      const res = await call();
+      if (res.redirect) return reload(res.redirect);
+      await refresh();
+      return res;
+    });
+  }
+
+  const post = (path: string, body: object = {}) => api<{ message?: string; redirect?: string }>(path, body);
+
+  function saveProfile(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(profileAction, () => post("/api/account/profile", profile));
+  }
+
+  async function addPasskey(ev: SubmitEvent) {
+    ev.preventDefault();
+    passkeyAction.busy = true;
+    passkeyAction.error = "";
+    passkeyAction.message = "";
+    try {
+      if (await createPasskey(newPasskeyName.trim())) {
+        newPasskeyName = "";
+        await refresh();
+        passkeyAction.message = "Passkey added.";
+      }
+    } catch (err) {
+      passkeyAction.error = passkeyMessage(err);
+    } finally {
+      passkeyAction.busy = false;
+    }
+  }
+
+  function renamePasskey(ev: SubmitEvent, id: string) {
+    ev.preventDefault();
+    act(passkeyAction, () => post(`/api/account/passkeys/${encodeURIComponent(id)}/rename`, { name: renames[id] }));
+  }
+
+  function removePasskey(id: string, name: string) {
+    if (!confirmed(`Remove the passkey "${name}"?`)) return;
+    act(passkeyAction, () => post(`/api/account/passkeys/${encodeURIComponent(id)}/delete`));
+  }
+
+  function setPassword(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(passwordAction, async () => {
+      try {
+        return await post("/api/account/password", passwords);
+      } finally {
+        passwords.password = passwords.confirm = "";
+      }
+    });
+  }
+
+  function removePassword() {
+    if (!confirmed("Remove your password? You'll only be able to sign in with a passkey.")) return;
+    act(passwordAction, () => post("/api/account/password/remove"));
+  }
+
+  function disableTotp(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(totpAction, async () => {
+      try {
+        return await post("/api/account/totp/disable", { code: totpCode });
+      } finally {
+        totpCode = "";
+      }
+    });
+  }
+
+  function resendVerification() {
+    act(profileAction, () => post("/api/account/email/verify"));
+  }
+
+  function revokeSession(id: string) {
+    act(sessionAction, () => post(`/api/account/sessions/${encodeURIComponent(id)}/revoke`));
+  }
+
+  function revokeOthers() {
+    act(sessionAction, () => post("/api/account/sessions/revoke-others"));
+  }
+
+  function deleteAccount(ev: SubmitEvent) {
+    ev.preventDefault();
+    if (!confirmed("Delete your account for good? This can't be undone.")) return;
+    act(deleteAction, () => post("/api/account/delete", removal));
+  }
+
+  const supported = passkeysSupported();
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Your account`,}});}
+
+if(load.error){
+   { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+} else if (data){
+   { svelteHTML.createElement("h1", {}); data.name ?? data.username; }
+   { const $$_hsalF0C = __sveltets_2_ensureComponent(Flash); new $$_hsalF0C({ target: __sveltets_2_any(), props: {}});}
+  if(!data.recentAuth){
+     { svelteHTML.createElement("p", { "class":`notice`,});
+                
+       { svelteHTML.createElement("a", {  "href":`/login?${new URLSearchParams({ return: "/account", reauth: "1" })}`,...__sveltets_2_empty({"data-reload":true}),});   } 
+     }
+  }
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Profile`,"description":`Shared with the apps you sign in to.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":profileAction.message,"error":profileAction.error,}});}
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":saveProfile,});
+       { svelteHTML.createElement("label", { "class":`field`,});
+         { svelteHTML.createElement("span", {});  }
+          { svelteHTML.createElement("input", {    "type":`text`,"value":data.username,"disabled":true,});}
+         { svelteHTML.createElement("small", { "class":`muted`,});      }
+       }
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {          "label":`Display name`,"name":`name`,value:profile.name,"autocomplete":`name`,"maxlength":100,}});/*Ωignore_startΩ*/() => profile.name = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {               "label":`Email`,"name":`email`,"type":`email`,value:profile.email,"autocomplete":`email`,"maxlength":254,"hint":data.email ? (data.emailVerified ? "Verified." : "Not verified.") : undefined,}});/*Ωignore_startΩ*/() => profile.email = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Picture URL`,"name":`picture`,"type":`url`,value:profile.picture,"maxlength":2048,"placeholder":`https://…`,}});/*Ωignore_startΩ*/() => profile.picture = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { svelteHTML.createElement("div", {});
+         { svelteHTML.createElement("button", {   "type":`submit`,"disabled":profileAction.busy,}); { const $$_evaS4C = __sveltets_2_ensureComponent(Save); new $$_evaS4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   }
+       }
+     }
+    if(data.email && !data.emailVerified){
+       { svelteHTML.createElement("div", { "class":`inline-edit`,});
+         { svelteHTML.createElement("small", { "class":`muted`,});data.email;    }
+         { svelteHTML.createElement("button", {       "type":`button`,"class":`small`,"onclick":resendVerification,"disabled":profileAction.busy,});
+            
+         }
+       }
+    }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Passkeys`,"description":`The quickest and safest way to sign in: your device unlocks with a fingerprint, face or PIN.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":passkeyAction.message,"error":passkeyAction.error,}});}
+    if(data.passkeys.length === 0){
+       { svelteHTML.createElement("p", { "class":`muted`,});   }
+    }else{
+       { svelteHTML.createElement("ul", { "class":`rows`,});
+           for(let p of __sveltets_2_ensureArray(data.passkeys)){p.id;
+           { svelteHTML.createElement("li", {});
+             { svelteHTML.createElement("div", { "class":`grow`,});
+               { svelteHTML.createElement("form", {   "class":`inline-edit`,"onsubmit":(ev) => renamePasskey(ev, p.id),});
+                  { svelteHTML.createElement("input", {        "type":`text`,"bind:value":renames[p.id],"maxlength":60,"aria-label":`Passkey name`,"required":true,});/*Ωignore_startΩ*/() => renames[p.id] = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+                 { svelteHTML.createElement("button", {     "type":`submit`,"class":`small`,"disabled":passkeyAction.busy,});  }
+               }
+               { svelteHTML.createElement("small", { "class":`muted`,});
+                p.synced ? "Synced" : "This device only";   date(p.createdAt);    relative(p.lastUsedAt);
+               }
+             }
+             { svelteHTML.createElement("button", {       "type":`button`,"class":`danger small`,"onclick":() => removePasskey(p.id, p.name),"disabled":passkeyAction.busy,});
+              
+             }
+           }
+        }
+       }
+    }
+     { svelteHTML.createElement("form", {   "class":`inline-edit`,"onsubmit":addPasskey,});
+       { svelteHTML.createElement("input", {          "type":`text`,"bind:value":newPasskeyName,"placeholder":`Name, e.g. Phone`,"maxlength":60,"aria-label":`New passkey name`,});/*Ωignore_startΩ*/() => newPasskeyName = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary`,"disabled":!supported || passkeyAction.busy,});
+         { const $$_dnuoRyeK3C = __sveltets_2_ensureComponent(KeyRound); new $$_dnuoRyeK3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+        supported ? "Add a passkey" : "Passkeys aren't supported in this browser";
+       }
+     }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Password`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":passwordAction.message,"error":passwordAction.error,}});}
+     { svelteHTML.createElement("p", { "class":`muted`,});
+      data.hasPassword
+        ? "You can sign in with a password."
+        : "No password set. Add one as a fallback for devices without your passkeys.";
+     }
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":setPassword,});
+        { svelteHTML.createElement("input", {        "type":`text`,"name":`username`,"value":data.username,"autocomplete":`username`,"hidden":true,});}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {                "label":data.hasPassword ? "New password" : "Password","name":`password`,"type":`password`,value:passwords.password,"required":true,"autocomplete":`new-password`,"maxlength":512,"hint":`At least ${PASSWORD_MIN} characters. A long phrase beats a short tricky one.`,}});/*Ωignore_startΩ*/() => passwords.password = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Confirm password`,"name":`confirm`,"type":`password`,value:passwords.confirm,"required":true,"autocomplete":`new-password`,"maxlength":512,}});/*Ωignore_startΩ*/() => passwords.confirm = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { svelteHTML.createElement("div", {});
+         { svelteHTML.createElement("button", {   "type":`submit`,"disabled":passwordAction.busy,});data.hasPassword ? "Change password" : "Set password"; }
+       }
+     }
+    if(data.hasPassword){
+       { svelteHTML.createElement("p", {});
+         { svelteHTML.createElement("button", {       "type":`button`,"class":`danger small`,"onclick":removePassword,"disabled":data.passkeys.length === 0 || passwordAction.busy,});
+           
+         }
+        if(data.passkeys.length === 0){ { svelteHTML.createElement("small", { "class":`muted`,});     }}
+       }
+    }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {     children:() => { return __sveltets_2_any(0); },"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.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":totpAction.message,"error":totpAction.error,}});}
+    if(!data.hasPassword){
+       { svelteHTML.createElement("p", { "class":`muted`,});    }
+    } else if (data.totp){
+       { svelteHTML.createElement("form", {   "class":`inline-edit`,"onsubmit":disableTotp,});
+         { svelteHTML.createElement("span", { "class":`badge ok`,});  }
+         { svelteHTML.createElement("input", {                "type":`text`,"bind:value":totpCode,"placeholder":`Current code`,"inputmode":`numeric`,"autocomplete":`one-time-code`,"maxlength":7,"required":true,"aria-label":`Current code`,});/*Ωignore_startΩ*/() => totpCode = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+         { svelteHTML.createElement("button", {     "type":`submit`,"class":`danger`,"disabled":totpAction.busy,});  }
+       }
+    }else{
+       { svelteHTML.createElement("button", {   "type":`button`,"onclick":() => navigate("/account/totp"),});     }
+    }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Sessions`,"description":`Browsers signed in to this server. Apps you've signed in to keep their own sessions.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":sessionAction.message,"error":sessionAction.error,}});}
+     { svelteHTML.createElement("ul", { "class":`rows`,});
+         for(let s of __sveltets_2_ensureArray(data.sessions)){s.id;
+         { svelteHTML.createElement("li", {});
+           { svelteHTML.createElement("div", { "class":`grow`,});
+             { svelteHTML.createElement("strong", {});s.device; }
+            if(s.current){ { svelteHTML.createElement("span", { "class":`badge`,});  }}
+             { svelteHTML.createElement("br", {});}
+             { svelteHTML.createElement("small", { "class":`muted`,});
+              s.ip ?? "unknown IP";   s.method;    date(s.createdAt);   relative(s.lastSeenAt);
+             }
+           }
+           { svelteHTML.createElement("button", {       "type":`button`,"class":`small`,"onclick":() => revokeSession(s.id),"disabled":sessionAction.busy,});  }
+         }
+      }
+     }
+    if(data.sessions.length > 1){
+       { svelteHTML.createElement("button", {       "type":`button`,"class":`danger small`,"onclick":revokeOthers,"disabled":sessionAction.busy,});    }
+    }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {     children:() => { return __sveltets_2_any(0); },"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.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":deleteAction.error,}});}
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":deleteAccount,});
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {          "label":`Type your username (${data.username}) to confirm`,"name":`confirm`,value:removal.confirm,"required":true,"autocomplete":`off`,"maxlength":64,}});/*Ωignore_startΩ*/() => removal.confirm = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+      if(data.hasPassword){
+         { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Password`,"name":`password`,"type":`password`,value:removal.password,"required":true,"autocomplete":`current-password`,"maxlength":512,}});/*Ωignore_startΩ*/() => removal.password = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+      }
+       { svelteHTML.createElement("div", {});
+         { svelteHTML.createElement("button", {     "type":`submit`,"class":`danger`,"disabled":deleteAction.busy,});   }
+       }
+     }
+   Section}
+}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Account__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Account__SvelteComponent_ = ReturnType<typeof Account__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Account__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Apps.svelte.ts b/.svelte-check/svelte/web/src/pages/++Apps.svelte.ts
new file mode 100644
index 0000000..4b84001
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Apps.svelte.ts
@@ -0,0 +1,76 @@
+///<reference types="svelte" />
+;
+import { ExternalLink } from "@lucide/svelte";
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { session } from "../lib/session.svelte";
+import Flash from "../components/Flash.svelte";
+import Notes from "../components/Notes.svelte";
+import Title from "../components/Title.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+
+  interface App {
+    id: string;
+    name: string;
+    url: string;
+  }
+
+  let apps = $state<App[] | null>(null);
+  const load = new Action();
+  load.run(async () => (apps = await api<App[]>("/api/apps")));
+
+  function host(url: string): string {
+    try {
+      return new URL(url).host;
+    } catch {
+      return url;
+    }
+  }
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Your apps`,}});}
+ { svelteHTML.createElement("h1", {}); session.user?.name ?? session.user?.username; }
+ { const $$_hsalF0C = __sveltets_2_ensureComponent(Flash); new $$_hsalF0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+
+if(apps){
+  if(apps.length === 0){
+     { svelteHTML.createElement("section", { "class":`panel`,});
+       { svelteHTML.createElement("h2", {});   }
+       { svelteHTML.createElement("p", { "class":`muted`,});
+                    
+        if(session.user?.isAdmin){       { svelteHTML.createElement("a", { "href":`/admin/clients`,});   }   }
+       }
+     }
+  }else{
+     { svelteHTML.createElement("p", { "class":`muted`,});       session.user?.username;  }
+     { svelteHTML.createElement("ul", { "class":`apps`,});
+         for(let app of __sveltets_2_ensureArray(apps)){app.id;
+         { svelteHTML.createElement("li", {});
+           { svelteHTML.createElement("a", {     "class":`app-tile`,"href":app.url,"rel":`noopener`,});
+             { svelteHTML.createElement("span", {   "class":`app-mark`,"aria-hidden":`true`,});app.name.slice(0, 1).toUpperCase(); }
+             { svelteHTML.createElement("span", { "class":`app-text`,});
+               { svelteHTML.createElement("strong", {});app.name; }
+               { svelteHTML.createElement("small", { "class":`muted`,});host(app.url); }
+             }
+             { const $$_kniLlanretxE3C = __sveltets_2_ensureComponent(ExternalLink); new $$_kniLlanretxE3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+           }
+         }
+      }
+     }
+  }
+}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Apps__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Apps__SvelteComponent_ = ReturnType<typeof Apps__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Apps__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++AuthorizeNotice.svelte.ts b/.svelte-check/svelte/web/src/pages/++AuthorizeNotice.svelte.ts
new file mode 100644
index 0000000..a9c606d
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++AuthorizeNotice.svelte.ts
@@ -0,0 +1,69 @@
+///<reference types="svelte" />
+;
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { navigate, reload, route } from "../lib/router.svelte";
+import Card from "../components/Card.svelte";
+import Notes from "../components/Notes.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+
+  // /authorize sends people here (with its own query) when it has something to
+  // explain. Asking the API again keeps the decision on the server.
+  type Notice =
+    | { kind: "error"; code: string }
+    | { kind: "redirect"; url: string }
+    | { kind: "denied"; client: string; username: string; back: string }
+    | { kind: "verify-email"; client: string; email: string | null; retry: string };
+
+  let notice = $state<Notice | null>(null);
+  const load = new Action();
+  const signOut = new Action();
+
+  load.run(async () => {
+    const n = await api<Notice>(`/api/authorize/notice${route.search}`);
+    if (n.kind === "redirect") reload(n.url);
+    else if (n.kind === "error") navigate(`/error?code=${encodeURIComponent(n.code)}`, { replace: true });
+    else notice = n;
+  });
+
+  async function switchAccount() {
+    // Sign out, then sign in again and pick up this same request.
+    await signOut.run(async () => {
+      await api("/api/logout", {});
+      reload(`/login?${new URLSearchParams({ return: `/authorize${route.search}` })}`);
+    });
+  }
+;
+async () => {
+
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+if(notice?.kind === "denied"){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`No access to ${notice.client}`,}});
+     { svelteHTML.createElement("p", { "class":`muted`,});
+           { svelteHTML.createElement("strong", {}); notice.username; }      notice.client;   
+           
+     }
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":signOut.error,}});}
+     { svelteHTML.createElement("button", {       "type":`button`,"class":`wide`,"onclick":switchAccount,"disabled":signOut.busy,});     }
+     { svelteHTML.createElement("p", { "class":`small`,}); { svelteHTML.createElement("a", {   "class":`btn wide`,"href":notice.back,});  notice.client; } }
+   Card}
+} else if (notice?.kind === "verify-email"){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Verify your email first`,}});
+     { svelteHTML.createElement("p", { "class":`muted`,});
+      if(notice.email){      { svelteHTML.createElement("strong", {});notice.email; }      }else{            notice.client; }
+     }
+     { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn primary wide`,"href":notice.retry,});    } }
+     { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn wide`,"href":`/settings`,});    } }
+   Card}
+}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const AuthorizeNotice__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type AuthorizeNotice__SvelteComponent_ = ReturnType<typeof AuthorizeNotice__SvelteComponent_>;
+/*Ωignore_endΩ*/export default AuthorizeNotice__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Contact.svelte.ts b/.svelte-check/svelte/web/src/pages/++Contact.svelte.ts
new file mode 100644
index 0000000..1526c0b
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Contact.svelte.ts
@@ -0,0 +1,15 @@
+///<reference types="svelte" />
+;
+import { session } from "../lib/session.svelte";
+function $$render() {
+
+  
+;
+async () => {
+
+if(session.contact){ { svelteHTML.createElement("a", { "href":`mailto:${session.contact}`,});session.contact; }}else{    }
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: "", slots: {}, events: {} }}
+const Contact__SvelteComponent_ = __sveltets_2_isomorphic_component(__sveltets_2_with_any_event($$render()));
+/*Ωignore_startΩ*/type Contact__SvelteComponent_ = InstanceType<typeof Contact__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Contact__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++EndSession.svelte.ts b/.svelte-check/svelte/web/src/pages/++EndSession.svelte.ts
new file mode 100644
index 0000000..837e091
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++EndSession.svelte.ts
@@ -0,0 +1,64 @@
+///<reference types="svelte" />
+;
+import { LogOut } from "@lucide/svelte";
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { navigate, query, reload, route } from "../lib/router.svelte";
+import Card from "../components/Card.svelte";
+import Notes from "../components/Notes.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+
+  // RP-initiated logout without proof it came from the app: confirm first.
+  const q = query();
+  const request = {
+    client_id: q.get("client_id") ?? "",
+    post_logout_redirect_uri: q.get("post_logout_redirect_uri") ?? "",
+    state: q.get("state") ?? "",
+  };
+
+  let info = $state<{ client: string | null; username: string | null; returnTo: string | null } | null>(null);
+  const load = new Action();
+  const act = new Action();
+
+  load.run(async () => {
+    try {
+      info = await api(`/api/end-session${route.search}`);
+    } catch (err) {
+      navigate("/error?code=logout_bad_redirect", { replace: true });
+      throw err;
+    }
+  });
+
+  async function signOut() {
+    await act.run(async () => reload((await api<{ redirect: string }>("/api/end-session", request)).redirect));
+  }
+;
+async () => {
+
+if(info){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Sign out?`,}});
+     { svelteHTML.createElement("p", { "class":`muted`,});
+      info.client ? `${info.client} wants to sign you out` : "Sign out";info.username ? ` of @${info.username}` : "";   
+     }
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":act.error,}});}
+     { svelteHTML.createElement("button", {       "type":`button`,"class":`primary wide`,"onclick":signOut,"disabled":act.busy,});
+       { const $$_tuOgoL2C = __sveltets_2_ensureComponent(LogOut); new $$_tuOgoL2C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+       
+     }
+    if(info.returnTo){
+       { svelteHTML.createElement("p", { "class":`small`,}); { svelteHTML.createElement("a", {   "class":`btn wide`,"href":info.returnTo,});      } }
+    }
+   Card}
+}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const EndSession__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type EndSession__SvelteComponent_ = ReturnType<typeof EndSession__SvelteComponent_>;
+/*Ωignore_endΩ*/export default EndSession__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++ErrorPage.svelte.ts b/.svelte-check/svelte/web/src/pages/++ErrorPage.svelte.ts
new file mode 100644
index 0000000..eac7fac
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++ErrorPage.svelte.ts
@@ -0,0 +1,25 @@
+///<reference types="svelte" />
+;
+import { ERRORS } from "../lib/messages";
+import { query } from "../lib/router.svelte";
+import Card from "../components/Card.svelte";
+function $$render() {
+
+  
+  
+  
+
+  // Fixed messages only: the code picks one, so a crafted link can't write the text.
+  const error = ERRORS[query().get("code") ?? ""] ?? {
+    title: "Something went wrong",
+    text: "That request couldn't be completed. Go back to the app and try again.",
+  };
+;
+async () => {
+
+ { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {    "title":error.title,"lead":error.text,}});}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: "", slots: {}, events: {} }}
+const ErrorPage__SvelteComponent_ = __sveltets_2_isomorphic_component(__sveltets_2_with_any_event($$render()));
+/*Ωignore_startΩ*/type ErrorPage__SvelteComponent_ = InstanceType<typeof ErrorPage__SvelteComponent_>;
+/*Ωignore_endΩ*/export default ErrorPage__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Forgot.svelte.ts b/.svelte-check/svelte/web/src/pages/++Forgot.svelte.ts
new file mode 100644
index 0000000..08b167c
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Forgot.svelte.ts
@@ -0,0 +1,54 @@
+///<reference types="svelte" />
+;
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import Card from "../components/Card.svelte";
+import Field from "../components/Field.svelte";
+import Notes from "../components/Notes.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+
+  let account = $state("");
+  let sent = $state(false);
+  const form = new Action();
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    // The answer is the same whether or not the account exists.
+    await form.run(async () => {
+      await api("/api/forgot", { account });
+      sent = true;
+    });
+  }
+;
+async () => {
+
+ { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Forgot your password?`,}});
+  if(sent){
+     { svelteHTML.createElement("p", {   "class":`notice ok`,"role":`status`,});
+                         
+     }
+     { svelteHTML.createElement("p", { "class":`muted`,});         }
+  }else{
+     { svelteHTML.createElement("p", { "class":`muted`,});
+                          
+      
+     }
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":submit,});
+       { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {  "error":form.error,}});}
+        { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {          "label":`Username or email`,"name":`account`,value:account,"required":true,"autocomplete":`username`,"maxlength":254,"autofocus":true,}});/*Ωignore_startΩ*/() => account = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary wide`,"disabled":form.busy,});   }
+     }
+  }
+   { svelteHTML.createElement("p", { "class":`muted small`,}); { svelteHTML.createElement("a", { "href":`/login`,});    } }
+ Card}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Forgot__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Forgot__SvelteComponent_ = ReturnType<typeof Forgot__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Forgot__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Login.svelte.ts b/.svelte-check/svelte/web/src/pages/++Login.svelte.ts
new file mode 100644
index 0000000..f7f3896
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Login.svelte.ts
@@ -0,0 +1,128 @@
+///<reference types="svelte" />
+;
+import { KeyRound } from "@lucide/svelte";
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { navigate, query, reload } from "../lib/router.svelte";
+import { session } from "../lib/session.svelte";
+import { conditionalAvailable, getPasskey, passkeyMessage, passkeysSupported } from "../lib/webauthn";
+import Card from "../components/Card.svelte";
+import Field from "../components/Field.svelte";
+import Flash from "../components/Flash.svelte";
+import Notes from "../components/Notes.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+
+  const q = query();
+  const returnTo = safeReturn(q.get("return"));
+  const reauth = q.get("reauth") === "1";
+
+  /** Same rule as the server: only paths on this site. */
+  function safeReturn(raw: string | null): string {
+    if (!raw || !raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return "/apps";
+    return raw;
+  }
+
+  let username = $state(reauth ? (session.user?.username ?? "") : "");
+  let password = $state("");
+  const form = new Action();
+  let passkeyError = $state("");
+  let passkeyBusy = $state(false);
+  const supported = passkeysSupported();
+
+  // Already signed in (and not confirming it's you): straight on.
+  if (session.user && !reauth) reload(returnTo);
+  else if (session.needsSetup) navigate("/setup", { replace: true });
+
+  // Saved passkeys are offered straight from the username field's autofill.
+  // Cancelled when the page goes away or the button is used instead.
+  let conditional: AbortController | null = null;
+  async function startConditional() {
+    if (!supported || !(await conditionalAvailable())) return;
+    conditional = new AbortController();
+    try {
+      const to = await getPasskey("/api/login/passkey", { return: returnTo }, { conditional: conditional.signal });
+      if (to) reload(to);
+    } catch (err) {
+      if ((err as { name?: string })?.name !== "AbortError") passkeyError = passkeyMessage(err);
+    }
+  }
+  $effect(() => {
+    if (session.user && !reauth) return;
+    startConditional();
+    return () => conditional?.abort();
+  });
+
+  async function passkeySignIn() {
+    conditional?.abort();
+    passkeyBusy = true;
+    passkeyError = "";
+    try {
+      const to = await getPasskey("/api/login/passkey", { return: returnTo });
+      if (to) reload(to);
+    } catch (err) {
+      passkeyError = passkeyMessage(err);
+    } finally {
+      passkeyBusy = false;
+      startConditional();
+    }
+  }
+
+  async function passwordSignIn(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      const res = await api<{ redirect?: string; mfa?: object }>("/api/login/password", {
+        username,
+        password,
+        return: returnTo,
+      });
+      password = "";
+      if (res.mfa) navigate("/login/mfa");
+      else if (res.redirect) reload(res.redirect);
+    });
+  }
+;
+async () => {
+
+ { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":reauth ? "Confirm it's you" : "Sign in","lead":reauth ? "This needs a fresh sign-in. It only takes a moment." : undefined,}});
+   { const $$_hsalF1C = __sveltets_2_ensureComponent(Flash); new $$_hsalF1C({ target: __sveltets_2_any(), props: {}});}
+   { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":passkeyError,}});}
+
+   { svelteHTML.createElement("button", {       "type":`button`,"class":`primary wide`,"onclick":passkeySignIn,"disabled":!supported || passkeyBusy,});
+     { const $$_dnuoRyeK2C = __sveltets_2_ensureComponent(KeyRound); new $$_dnuoRyeK2C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+    supported ? "Sign in with a passkey" : "Passkeys aren't supported in this browser";
+   }
+
+   { svelteHTML.createElement("div", { "class":`divider`,}); { svelteHTML.createElement("span", {});    } }
+
+   { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":passwordSignIn,});
+     { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {  "error":form.error,}});}
+     { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Username`,"name":`username`,value:username,"required":true,"autocomplete":`username webauthn`,"maxlength":64,"autofocus":!username,}});/*Ωignore_startΩ*/() => username = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+     { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {              "label":`Password`,"name":`password`,"type":`password`,value:password,"required":true,"autocomplete":`current-password`,"maxlength":512,"autofocus":Boolean(username),}});/*Ωignore_startΩ*/() => password = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+     { svelteHTML.createElement("button", {     "type":`submit`,"class":`wide`,"disabled":form.busy,});  }
+   }
+
+  if(!reauth){
+     { svelteHTML.createElement("p", { "class":`muted small`,}); { svelteHTML.createElement("a", { "href":`/forgot`,});   } }
+    if(session.registration){
+       { svelteHTML.createElement("p", { "class":`muted small`,});
+           { svelteHTML.createElement("a", { "href":`/register?${new URLSearchParams({ return: returnTo })}`,});   }
+       }
+    }
+  }
+ Card}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Login__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Login__SvelteComponent_ = ReturnType<typeof Login__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Login__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++LoginLink.svelte.ts b/.svelte-check/svelte/web/src/pages/++LoginLink.svelte.ts
new file mode 100644
index 0000000..1f7956b
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++LoginLink.svelte.ts
@@ -0,0 +1,57 @@
+///<reference types="svelte" />
+;
+import { LogIn } from "@lucide/svelte";
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { reload } from "../lib/router.svelte";
+import { session } from "../lib/session.svelte";
+import Card from "../components/Card.svelte";
+import Notes from "../components/Notes.svelte";
+
+;type $$ComponentProps =  { params: Record<string, string> };function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+
+  let { params }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+  const path = $derived(`/api/login/link/${encodeURIComponent(params.token ?? "")}`);
+
+  let target = $state<{ userId: string; username: string; name: string | null } | null>(null);
+  const load = new Action();
+  const use = new Action();
+  load.run(async () => (target = await api(path)));
+
+  // Link scanners follow GETs, so using the link takes a deliberate click.
+  async function signIn() {
+    await use.run(async () => reload((await api<{ redirect: string }>(path, {})).redirect));
+  }
+;
+async () => {
+
+if(load.error){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {    "title":`This link can't be used`,"lead":`It has expired, was already used, or was replaced by a newer one. Ask an admin for a new link.`,}});}
+} else if (target){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Sign in as ${target.name ?? target.username}`,}});
+     { svelteHTML.createElement("p", { "class":`muted`,});
+              { svelteHTML.createElement("strong", {}); target.username; }      
+     }
+    if(session.user && session.user.id !== target.userId){
+       { svelteHTML.createElement("p", { "class":`notice`,});     session.user.username;    }
+    }
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":use.error,}});}
+     { svelteHTML.createElement("button", {       "type":`button`,"class":`primary wide`,"onclick":signIn,"disabled":use.busy,});
+       { const $$_nIgoL2C = __sveltets_2_ensureComponent(LogIn); new $$_nIgoL2C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+      
+     }
+   Card}
+}
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const LoginLink__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type LoginLink__SvelteComponent_ = ReturnType<typeof LoginLink__SvelteComponent_>;
+/*Ωignore_endΩ*/export default LoginLink__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Mfa.svelte.ts b/.svelte-check/svelte/web/src/pages/++Mfa.svelte.ts
new file mode 100644
index 0000000..4eb2ef0
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Mfa.svelte.ts
@@ -0,0 +1,101 @@
+///<reference types="svelte" />
+;
+import { KeyRound, LogIn } from "@lucide/svelte";
+import { ApiError, api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { navigate, reload } from "../lib/router.svelte";
+import { getPasskey, passkeyMessage, passkeysSupported } from "../lib/webauthn";
+import Card from "../components/Card.svelte";
+import Field from "../components/Field.svelte";
+import Notes from "../components/Notes.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+
+  let step = $state<{ totp: boolean; passkey: boolean } | null>(null);
+  let code = $state("");
+  const form = new Action();
+  let passkeyError = $state("");
+  let passkeyBusy = $state(false);
+  const supported = passkeysSupported();
+
+  /** The half-finished sign-in is gone (expired, or too many tries): back to the start. */
+  function restartIfNeeded(err: unknown) {
+    if (err instanceof ApiError && err.data.restart) navigate("/login", { replace: true });
+  }
+
+  api<{ totp: boolean; passkey: boolean }>("/api/login/mfa").then((s) => (step = s), restartIfNeeded);
+
+  async function submitCode(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      try {
+        const { redirect } = await api<{ redirect: string }>("/api/login/mfa", { code });
+        reload(redirect);
+      } catch (err) {
+        code = "";
+        restartIfNeeded(err);
+        throw err;
+      }
+    });
+  }
+
+  async function usePasskey() {
+    passkeyBusy = true;
+    passkeyError = "";
+    try {
+      const to = await getPasskey("/api/login/mfa/passkey");
+      if (to) reload(to);
+    } catch (err) {
+      restartIfNeeded(err);
+      passkeyError = passkeyMessage(err);
+    } finally {
+      passkeyBusy = false;
+    }
+  }
+;
+async () => {
+
+  { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {    children:() => { return __sveltets_2_any(0); },"title":`One more step`,"lead":!step
+    ? undefined
+    : 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.",}});
+  if(step){
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":passkeyError,}});}
+    if(step.passkey){
+       { svelteHTML.createElement("button", {       "type":`button`,"class":step.totp ? "wide" : "primary wide","onclick":usePasskey,"disabled":!supported || passkeyBusy,});
+         { const $$_dnuoRyeK2C = __sveltets_2_ensureComponent(KeyRound); new $$_dnuoRyeK2C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+        supported ? "Use a passkey" : "Passkeys aren't supported in this browser";
+       }
+    }
+    if(step.passkey && step.totp){
+       { svelteHTML.createElement("div", { "class":`divider`,}); { svelteHTML.createElement("span", {});    } }
+    }
+    if(step.totp){
+       { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":submitCode,});
+         { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {  "error":form.error,}});}
+          { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {              "label":`Code`,"name":`code`,value:code,"required":true,"autocomplete":`one-time-code`,"inputmode":`numeric`,"pattern":"[0-9 ]{6,7}","maxlength":7,"autofocus":true,}});/*Ωignore_startΩ*/() => code = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+         { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary wide`,"disabled":form.busy,});
+           { const $$_nIgoL3C = __sveltets_2_ensureComponent(LogIn); new $$_nIgoL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+          
+         }
+       }
+    }
+  }
+   { svelteHTML.createElement("p", { "class":`muted small`,}); { svelteHTML.createElement("a", {   "class":`btn wide`,"href":`/login`,});  } }
+ Card}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Mfa__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Mfa__SvelteComponent_ = ReturnType<typeof Mfa__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Mfa__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++NotFound.svelte.ts b/.svelte-check/svelte/web/src/pages/++NotFound.svelte.ts
new file mode 100644
index 0000000..bd5cdec
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++NotFound.svelte.ts
@@ -0,0 +1,19 @@
+///<reference types="svelte" />
+;
+import { session } from "../lib/session.svelte";
+import Card from "../components/Card.svelte";
+function $$render() {
+
+  
+  
+;
+async () => {
+
+ { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Page not found`,"lead":`There's nothing at this address.`,}});
+   { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn primary`,"href":session.user ? "/apps" : "/login",});session.user ? "Your apps" : "Sign in"; } }
+ Card}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: "", slots: {}, events: {} }}
+const NotFound__SvelteComponent_ = __sveltets_2_isomorphic_component(__sveltets_2_with_any_event($$render()));
+/*Ωignore_startΩ*/type NotFound__SvelteComponent_ = InstanceType<typeof NotFound__SvelteComponent_>;
+/*Ωignore_endΩ*/export default NotFound__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Privacy.svelte.ts b/.svelte-check/svelte/web/src/pages/++Privacy.svelte.ts
new file mode 100644
index 0000000..c00ea17
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Privacy.svelte.ts
@@ -0,0 +1,119 @@
+///<reference types="svelte" />
+;
+import { session } from "../lib/session.svelte";
+import Title from "../components/Title.svelte";
+import Contact from "./Contact.svelte";
+import { OPERATOR, UPDATED } from "../lib/legal";
+function $$render() {
+
+  
+  
+  
+  
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Privacy policy`,}});}
+ { svelteHTML.createElement("article", { "class":`legal`,});
+   { svelteHTML.createElement("p", { "class":`eyebrow`,});  UPDATED; }
+   { svelteHTML.createElement("h1", {});  }
+   { svelteHTML.createElement("p", {});
+    session.site;        OPERATOR;           
+                     { const $$_tcatnoC2C = __sveltets_2_ensureComponent(Contact); new $$_tcatnoC2C({ target: __sveltets_2_any(), props: {}});}
+   }
+
+   { svelteHTML.createElement("h2", {});   }
+   { svelteHTML.createElement("ul", {});
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("strong", {});  }            
+          
+     }
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("strong", {});    }              
+                    
+     }
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("strong", {});  }             
+             
+     }
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("strong", {});  }                
+         
+     }
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("strong", {});  }             
+     }
+     { svelteHTML.createElement("li", {}); { svelteHTML.createElement("strong", {});  }               }
+   }
+   { svelteHTML.createElement("p", {});                }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {});
+                      
+                       
+            
+   }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {});         }
+   { svelteHTML.createElement("ul", {});
+     { svelteHTML.createElement("li", {}); { svelteHTML.createElement("code", {});  }          }
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("code", {});  }                 
+      
+     }
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("code", {});  }                   
+      
+     }
+   }
+
+   { svelteHTML.createElement("h2", {});    }
+   { svelteHTML.createElement("ul", {});
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("strong", {});     }               
+                       
+          
+     }
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("strong", {});  }              
+     }
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("strong", {});  }               
+     }
+     { svelteHTML.createElement("li", {});
+       { svelteHTML.createElement("strong", {});  }               
+        
+     }
+   }
+   { svelteHTML.createElement("p", {});            }
+
+   { svelteHTML.createElement("h2", {});     }
+   { svelteHTML.createElement("ul", {});
+     { svelteHTML.createElement("li", {});     }
+     { svelteHTML.createElement("li", {});                  }
+     { svelteHTML.createElement("li", {});          }
+     { svelteHTML.createElement("li", {});    }
+     { svelteHTML.createElement("li", {});              }
+   }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {});
+                         
+                      
+                        
+                { const $$_tcatnoC2C = __sveltets_2_ensureComponent(Contact); new $$_tcatnoC2C({ target: __sveltets_2_any(), props: {}});}       
+                
+   }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {});        }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {});                   }
+ }
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: "", slots: {}, events: {} }}
+const Privacy__SvelteComponent_ = __sveltets_2_isomorphic_component(__sveltets_2_with_any_event($$render()));
+/*Ωignore_startΩ*/type Privacy__SvelteComponent_ = InstanceType<typeof Privacy__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Privacy__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Register.svelte.ts b/.svelte-check/svelte/web/src/pages/++Register.svelte.ts
new file mode 100644
index 0000000..9bb43eb
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Register.svelte.ts
@@ -0,0 +1,75 @@
+///<reference types="svelte" />
+;
+import { LogIn, UserPlus } from "@lucide/svelte";
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { navigate, query, reload } from "../lib/router.svelte";
+import { session } from "../lib/session.svelte";
+import Card from "../components/Card.svelte";
+import Field from "../components/Field.svelte";
+import Notes from "../components/Notes.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+
+  const PASSWORD_MIN = 10;
+  const returnTo = query().get("return") ?? "/apps";
+
+  if (session.user) reload(returnTo.startsWith("/") && !returnTo.startsWith("//") ? returnTo : "/apps");
+  else if (session.needsSetup) navigate("/setup", { replace: true });
+
+  const values = $state({ username: "", name: "", email: "", password: "", confirm: "" });
+  const form = new Action();
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      try {
+        reload((await api<{ redirect: string }>("/api/register", { ...values, return: returnTo })).redirect);
+      } finally {
+        // Never keep the password around after a failed attempt.
+        values.password = values.confirm = "";
+      }
+    });
+  }
+;
+async () => {
+
+if(!session.registration){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Sign-ups are closed`,"lead":`Accounts on this server are created by an admin.`,}});
+     { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn primary`,"href":`/login`,}); { const $$_nIgoL3C = __sveltets_2_ensureComponent(LogIn); new $$_nIgoL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   } }
+   Card}
+}else{
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Create an account`,"lead":`You can add a passkey straight after.`,}});
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":submit,});
+       { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {  "error":form.error,}});}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Username`,"name":`username`,value:values.username,"required":true,"autocomplete":`username`,"maxlength":32,"autofocus":true,"hint":`Lowercase letters, digits, dots, dashes or underscores. You can't change it later.`,}});/*Ωignore_startΩ*/() => values.username = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {          "label":`Display name`,"name":`name`,value:values.name,"autocomplete":`name`,"maxlength":100,}});/*Ωignore_startΩ*/() => values.name = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {              "label":`Email`,"name":`email`,"type":`email`,value:values.email,"required":true,"autocomplete":`email`,"maxlength":254,"hint":`We'll send a link to verify it.`,}});/*Ωignore_startΩ*/() => values.email = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {              "label":`Password`,"name":`password`,"type":`password`,value:values.password,"required":true,"autocomplete":`new-password`,"maxlength":512,"hint":`At least ${PASSWORD_MIN} characters.`,}});/*Ωignore_startΩ*/() => values.password = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Confirm password`,"name":`confirm`,"type":`password`,value:values.confirm,"required":true,"autocomplete":`new-password`,"maxlength":512,}});/*Ωignore_startΩ*/() => values.confirm = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { svelteHTML.createElement("p", { "class":`muted small`,});
+                 { svelteHTML.createElement("a", { "href":`/terms`,});  }   { svelteHTML.createElement("a", { "href":`/privacy`,});  }
+       }
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary wide`,"disabled":form.busy,});
+         { const $$_sulPresU3C = __sveltets_2_ensureComponent(UserPlus); new $$_sulPresU3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+         
+       }
+     }
+     { svelteHTML.createElement("p", { "class":`muted small`,});
+           { svelteHTML.createElement("a", { "href":`/login?${new URLSearchParams({ return: returnTo })}`,});  }
+     }
+   Card}
+}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Register__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Register__SvelteComponent_ = ReturnType<typeof Register__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Register__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Reset.svelte.ts b/.svelte-check/svelte/web/src/pages/++Reset.svelte.ts
new file mode 100644
index 0000000..217ee5b
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Reset.svelte.ts
@@ -0,0 +1,68 @@
+///<reference types="svelte" />
+;
+import { KeyRound } from "@lucide/svelte";
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { reload } from "../lib/router.svelte";
+import Card from "../components/Card.svelte";
+import Field from "../components/Field.svelte";
+import Notes from "../components/Notes.svelte";
+
+;type $$ComponentProps =  { params: Record<string, string> };function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+
+  let { params }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+  const path = $derived(`/api/reset/${encodeURIComponent(params.token ?? "")}`);
+
+  let username = $state<string | null>(null);
+  let password = $state("");
+  let confirm = $state("");
+  const load = new Action();
+  const form = new Action();
+  load.run(async () => (username = (await api<{ username: string }>(path)).username));
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      try {
+        reload((await api<{ redirect: string }>(path, { password, confirm })).redirect);
+      } finally {
+        password = confirm = "";
+      }
+    });
+  }
+;
+async () => {
+
+if(load.error){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`This link can't be used`,"lead":`It has expired, was already used, or a newer one was sent.`,}});
+     { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn primary`,"href":`/forgot`,});    } }
+   Card}
+} else if (username){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Choose a new password`,}});
+     { svelteHTML.createElement("p", { "class":`muted`,});  { svelteHTML.createElement("strong", {}); username; }              }
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":submit,});
+       { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {  "error":form.error,}});}
+      
+        { svelteHTML.createElement("input", {        "type":`text`,"name":`username`,"value":username,"autocomplete":`username`,"hidden":true,});}
+        { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {              "label":`New password`,"name":`password`,"type":`password`,value:password,"required":true,"autocomplete":`new-password`,"maxlength":512,"hint":`At least 10 characters.`,"autofocus":true,}});/*Ωignore_startΩ*/() => password = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Confirm password`,"name":`confirm`,"type":`password`,value:confirm,"required":true,"autocomplete":`new-password`,"maxlength":512,}});/*Ωignore_startΩ*/() => confirm = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary wide`,"disabled":form.busy,});
+         { const $$_dnuoRyeK3C = __sveltets_2_ensureComponent(KeyRound); new $$_dnuoRyeK3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+         
+       }
+     }
+   Card}
+}
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Reset__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Reset__SvelteComponent_ = ReturnType<typeof Reset__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Reset__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Security.svelte.ts b/.svelte-check/svelte/web/src/pages/++Security.svelte.ts
new file mode 100644
index 0000000..3e249a1
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Security.svelte.ts
@@ -0,0 +1,69 @@
+///<reference types="svelte" />
+;
+import { LogIn, LogOut } from "@lucide/svelte";
+import { api, confirmed } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import Card from "../components/Card.svelte";
+import Notes from "../components/Notes.svelte";
+
+;type $$ComponentProps =  { params: Record<string, string> };function $$render() {
+
+  
+  
+  
+  
+  
+
+  // The "wasn't me" links in security emails. They work without signing in.
+  let { params }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+  const path = $derived(`/api/security/${encodeURIComponent(params.token ?? "")}`);
+
+  let target = $state<{ username: string; sessionLive: boolean } | null>(null);
+  let result = $state<{ everywhere: boolean } | null>(null);
+  const load = new Action();
+  const act = new Action();
+  load.run(async () => (target = await api(path)));
+
+  async function signOut(scope: "device" | "all") {
+    if (scope === "all" && !confirmed("Sign out every browser and app, including this one?")) return;
+    await act.run(async () => (result = await api(path, { scope })));
+  }
+;
+async () => {
+
+if(result){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {     children:() => { return __sveltets_2_any(0); },"title":result.everywhere ? "Signed out everywhere" : "That device is signed out","lead":`Now sign in, change your password, and check your passkeys and two-factor settings for anything you didn't add.`,}});
+     { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {    "class":`btn primary`,"href":`/login?return=%2Fsettings`,...__sveltets_2_empty({"data-reload":true}),}); { const $$_nIgoL3C = __sveltets_2_ensureComponent(LogIn); new $$_nIgoL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   } }
+   Card}
+} else if (load.error){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`This link has expired`,"lead":`Sign in to see and sign out your sessions in Settings. If you can't sign in, ask an admin to sign you out everywhere.`,}});
+     { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn primary`,"href":`/login`,}); { const $$_nIgoL3C = __sveltets_2_ensureComponent(LogIn); new $$_nIgoL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   } }
+   Card}
+} else if (target){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Wasn't you?`,}});
+     { svelteHTML.createElement("p", { "class":`muted`,});
+            { svelteHTML.createElement("strong", {}); target.username; }        
+     }
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":act.error,}});}
+     { svelteHTML.createElement("div", { "class":`stack`,});
+      if(target.sessionLive){
+         { svelteHTML.createElement("button", {       "type":`button`,"class":`primary wide`,"onclick":() => signOut("device"),"disabled":act.busy,});
+           { const $$_tuOgoL3C = __sveltets_2_ensureComponent(LogOut); new $$_tuOgoL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+             
+         }
+      }else{
+         { svelteHTML.createElement("p", { "class":`notice`,});      }
+      }
+       { svelteHTML.createElement("button", {       "type":`button`,"class":`danger wide`,"onclick":() => signOut("all"),"disabled":act.busy,});
+         { const $$_tuOgoL3C = __sveltets_2_ensureComponent(LogOut); new $$_tuOgoL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+          
+       }
+     }
+     { svelteHTML.createElement("p", { "class":`muted small`,});           }
+   Card}
+}
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Security__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Security__SvelteComponent_ = ReturnType<typeof Security__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Security__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Settings.svelte.ts b/.svelte-check/svelte/web/src/pages/++Settings.svelte.ts
new file mode 100644
index 0000000..3e5d0c6
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Settings.svelte.ts
@@ -0,0 +1,321 @@
+///<reference types="svelte" />
+;
+import { KeyRound, Save } from "@lucide/svelte";
+import { api, confirmed } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { date, relative } from "../lib/format";
+import { navigate, reload } from "../lib/router.svelte";
+import { createPasskey, passkeyMessage, passkeysSupported } from "../lib/webauthn";
+import Field from "../components/Field.svelte";
+import Flash from "../components/Flash.svelte";
+import Notes from "../components/Notes.svelte";
+import Section from "../components/Section.svelte";
+import Title from "../components/Title.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+
+  interface AccountData {
+    username: string;
+    name: string | null;
+    email: string | null;
+    emailVerified: boolean;
+    picture: string | null;
+    hasPassword: boolean;
+    totp: boolean;
+    recentAuth: boolean;
+    passkeys: { id: string; name: string; synced: boolean; createdAt: number; lastUsedAt: number | null }[];
+    sessions: {
+      id: string;
+      current: boolean;
+      device: string;
+      ip: string | null;
+      method: string;
+      createdAt: number;
+      lastSeenAt: number;
+    }[];
+  }
+
+  const PASSWORD_MIN = 10;
+
+  let data = $state<AccountData | null>(null);
+  const profile = $state({ name: "", email: "", picture: "" });
+  const passwords = $state({ password: "", confirm: "" });
+  const removal = $state({ confirm: "", password: "" });
+  let newPasskeyName = $state("");
+  let totpCode = $state("");
+  let renames = $state<Record<string, string>>({});
+
+  // One Action per section, so each shows its own result next to its form.
+  const load = new Action();
+  const profileAction = new Action();
+  const passkeyAction = new Action();
+  const passwordAction = new Action();
+  const totpAction = new Action();
+  const sessionAction = new Action();
+  const deleteAction = new Action();
+
+  async function refresh() {
+    const d = await api<AccountData>("/api/account");
+    data = d;
+    Object.assign(profile, { name: d.name ?? "", email: d.email ?? "", picture: d.picture ?? "" });
+    renames = Object.fromEntries(d.passkeys.map((p) => [p.id, p.name]));
+  }
+  load.run(refresh);
+
+  /** Runs `call` in a section; on success shows its message and reloads the page's data. */
+  async function act(section: Action, call: () => Promise<{ message?: string | null; redirect?: string }>) {
+    await section.run(async () => {
+      const res = await call();
+      if (res.redirect) return reload(res.redirect);
+      await refresh();
+      return res;
+    });
+  }
+
+  const post = (path: string, body: object = {}) => api<{ message?: string; redirect?: string }>(path, body);
+
+  function saveProfile(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(profileAction, () => post("/api/account/profile", profile));
+  }
+
+  async function addPasskey(ev: SubmitEvent) {
+    ev.preventDefault();
+    passkeyAction.busy = true;
+    passkeyAction.error = "";
+    passkeyAction.message = "";
+    try {
+      if (await createPasskey(newPasskeyName.trim())) {
+        newPasskeyName = "";
+        await refresh();
+        passkeyAction.message = "Passkey added.";
+      }
+    } catch (err) {
+      passkeyAction.error = passkeyMessage(err);
+    } finally {
+      passkeyAction.busy = false;
+    }
+  }
+
+  function renamePasskey(ev: SubmitEvent, id: string) {
+    ev.preventDefault();
+    act(passkeyAction, () => post(`/api/account/passkeys/${encodeURIComponent(id)}/rename`, { name: renames[id] }));
+  }
+
+  function removePasskey(id: string, name: string) {
+    if (!confirmed(`Remove the passkey "${name}"?`)) return;
+    act(passkeyAction, () => post(`/api/account/passkeys/${encodeURIComponent(id)}/delete`));
+  }
+
+  function setPassword(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(passwordAction, async () => {
+      try {
+        return await post("/api/account/password", passwords);
+      } finally {
+        passwords.password = passwords.confirm = "";
+      }
+    });
+  }
+
+  function removePassword() {
+    if (!confirmed("Remove your password? You'll only be able to sign in with a passkey.")) return;
+    act(passwordAction, () => post("/api/account/password/remove"));
+  }
+
+  function disableTotp(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(totpAction, async () => {
+      try {
+        return await post("/api/account/totp/disable", { code: totpCode });
+      } finally {
+        totpCode = "";
+      }
+    });
+  }
+
+  function resendVerification() {
+    act(profileAction, () => post("/api/account/email/verify"));
+  }
+
+  function revokeSession(id: string) {
+    act(sessionAction, () => post(`/api/account/sessions/${encodeURIComponent(id)}/revoke`));
+  }
+
+  function revokeOthers() {
+    act(sessionAction, () => post("/api/account/sessions/revoke-others"));
+  }
+
+  function deleteAccount(ev: SubmitEvent) {
+    ev.preventDefault();
+    if (!confirmed("Delete your account for good? This can't be undone.")) return;
+    act(deleteAction, () => post("/api/account/delete", removal));
+  }
+
+  const supported = passkeysSupported();
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Settings`,}});}
+
+if(load.error){
+   { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+} else if (data){
+   { svelteHTML.createElement("h1", {});  }
+   { const $$_hsalF0C = __sveltets_2_ensureComponent(Flash); new $$_hsalF0C({ target: __sveltets_2_any(), props: {}});}
+  if(!data.recentAuth){
+     { svelteHTML.createElement("p", { "class":`notice`,});
+                
+       { svelteHTML.createElement("a", {  "href":`/login?${new URLSearchParams({ return: "/settings", reauth: "1" })}`,...__sveltets_2_empty({"data-reload":true}),});   } 
+     }
+  }
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Profile`,"description":`Shared with the apps you sign in to.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":profileAction.message,"error":profileAction.error,}});}
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":saveProfile,});
+       { svelteHTML.createElement("label", { "class":`field`,});
+         { svelteHTML.createElement("span", {});  }
+          { svelteHTML.createElement("input", {    "type":`text`,"value":data.username,"disabled":true,});}
+         { svelteHTML.createElement("small", { "class":`muted`,});      }
+       }
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {          "label":`Display name`,"name":`name`,value:profile.name,"autocomplete":`name`,"maxlength":100,}});/*Ωignore_startΩ*/() => profile.name = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {               "label":`Email`,"name":`email`,"type":`email`,value:profile.email,"autocomplete":`email`,"maxlength":254,"hint":data.email ? (data.emailVerified ? "Verified." : "Not verified.") : undefined,}});/*Ωignore_startΩ*/() => profile.email = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Picture URL`,"name":`picture`,"type":`url`,value:profile.picture,"maxlength":2048,"placeholder":`https://…`,}});/*Ωignore_startΩ*/() => profile.picture = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { svelteHTML.createElement("div", {});
+         { svelteHTML.createElement("button", {   "type":`submit`,"disabled":profileAction.busy,}); { const $$_evaS4C = __sveltets_2_ensureComponent(Save); new $$_evaS4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   }
+       }
+     }
+    if(data.email && !data.emailVerified){
+       { svelteHTML.createElement("div", { "class":`inline-edit`,});
+         { svelteHTML.createElement("small", { "class":`muted`,});data.email;    }
+         { svelteHTML.createElement("button", {       "type":`button`,"class":`small`,"onclick":resendVerification,"disabled":profileAction.busy,});
+            
+         }
+       }
+    }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Passkeys`,"description":`The quickest and safest way to sign in: your device unlocks with a fingerprint, face or PIN.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":passkeyAction.message,"error":passkeyAction.error,}});}
+    if(data.passkeys.length === 0){
+       { svelteHTML.createElement("p", { "class":`muted`,});   }
+    }else{
+       { svelteHTML.createElement("ul", { "class":`rows`,});
+           for(let p of __sveltets_2_ensureArray(data.passkeys)){p.id;
+           { svelteHTML.createElement("li", {});
+             { svelteHTML.createElement("div", { "class":`grow`,});
+               { svelteHTML.createElement("form", {   "class":`inline-edit`,"onsubmit":(ev) => renamePasskey(ev, p.id),});
+                  { svelteHTML.createElement("input", {        "type":`text`,"bind:value":renames[p.id],"maxlength":60,"aria-label":`Passkey name`,"required":true,});/*Ωignore_startΩ*/() => renames[p.id] = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+                 { svelteHTML.createElement("button", {     "type":`submit`,"class":`small`,"disabled":passkeyAction.busy,});  }
+               }
+               { svelteHTML.createElement("small", { "class":`muted`,});
+                p.synced ? "Synced" : "This device only";   date(p.createdAt);    relative(p.lastUsedAt);
+               }
+             }
+             { svelteHTML.createElement("button", {       "type":`button`,"class":`danger small`,"onclick":() => removePasskey(p.id, p.name),"disabled":passkeyAction.busy,});
+              
+             }
+           }
+        }
+       }
+    }
+     { svelteHTML.createElement("form", {   "class":`inline-edit`,"onsubmit":addPasskey,});
+       { svelteHTML.createElement("input", {          "type":`text`,"bind:value":newPasskeyName,"placeholder":`Name, e.g. Phone`,"maxlength":60,"aria-label":`New passkey name`,});/*Ωignore_startΩ*/() => newPasskeyName = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary`,"disabled":!supported || passkeyAction.busy,});
+         { const $$_dnuoRyeK3C = __sveltets_2_ensureComponent(KeyRound); new $$_dnuoRyeK3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+        supported ? "Add a passkey" : "Passkeys aren't supported in this browser";
+       }
+     }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Password`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":passwordAction.message,"error":passwordAction.error,}});}
+     { svelteHTML.createElement("p", { "class":`muted`,});
+      data.hasPassword
+        ? "You can sign in with a password."
+        : "No password set. Add one as a fallback for devices without your passkeys.";
+     }
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":setPassword,});
+        { svelteHTML.createElement("input", {        "type":`text`,"name":`username`,"value":data.username,"autocomplete":`username`,"hidden":true,});}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {                "label":data.hasPassword ? "New password" : "Password","name":`password`,"type":`password`,value:passwords.password,"required":true,"autocomplete":`new-password`,"maxlength":512,"hint":`At least ${PASSWORD_MIN} characters. A long phrase beats a short tricky one.`,}});/*Ωignore_startΩ*/() => passwords.password = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Confirm password`,"name":`confirm`,"type":`password`,value:passwords.confirm,"required":true,"autocomplete":`new-password`,"maxlength":512,}});/*Ωignore_startΩ*/() => passwords.confirm = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { svelteHTML.createElement("div", {});
+         { svelteHTML.createElement("button", {   "type":`submit`,"disabled":passwordAction.busy,});data.hasPassword ? "Change password" : "Set password"; }
+       }
+     }
+    if(data.hasPassword){
+       { svelteHTML.createElement("p", {});
+         { svelteHTML.createElement("button", {       "type":`button`,"class":`danger small`,"onclick":removePassword,"disabled":data.passkeys.length === 0 || passwordAction.busy,});
+           
+         }
+        if(data.passkeys.length === 0){ { svelteHTML.createElement("small", { "class":`muted`,});     }}
+       }
+    }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {     children:() => { return __sveltets_2_any(0); },"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.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":totpAction.message,"error":totpAction.error,}});}
+    if(!data.hasPassword){
+       { svelteHTML.createElement("p", { "class":`muted`,});    }
+    } else if (data.totp){
+       { svelteHTML.createElement("form", {   "class":`inline-edit`,"onsubmit":disableTotp,});
+         { svelteHTML.createElement("span", { "class":`badge ok`,});  }
+         { svelteHTML.createElement("input", {                "type":`text`,"bind:value":totpCode,"placeholder":`Current code`,"inputmode":`numeric`,"autocomplete":`one-time-code`,"maxlength":7,"required":true,"aria-label":`Current code`,});/*Ωignore_startΩ*/() => totpCode = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+         { svelteHTML.createElement("button", {     "type":`submit`,"class":`danger`,"disabled":totpAction.busy,});  }
+       }
+    }else{
+       { svelteHTML.createElement("button", {   "type":`button`,"onclick":() => navigate("/settings/totp"),});     }
+    }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Sessions`,"description":`Browsers signed in to this server. Apps you've signed in to keep their own sessions.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":sessionAction.message,"error":sessionAction.error,}});}
+     { svelteHTML.createElement("ul", { "class":`rows`,});
+         for(let s of __sveltets_2_ensureArray(data.sessions)){s.id;
+         { svelteHTML.createElement("li", {});
+           { svelteHTML.createElement("div", { "class":`grow`,});
+             { svelteHTML.createElement("strong", {});s.device; }
+            if(s.current){ { svelteHTML.createElement("span", { "class":`badge`,});  }}
+             { svelteHTML.createElement("br", {});}
+             { svelteHTML.createElement("small", { "class":`muted`,});
+              s.ip ?? "unknown IP";   s.method;    date(s.createdAt);   relative(s.lastSeenAt);
+             }
+           }
+           { svelteHTML.createElement("button", {       "type":`button`,"class":`small`,"onclick":() => revokeSession(s.id),"disabled":sessionAction.busy,});  }
+         }
+      }
+     }
+    if(data.sessions.length > 1){
+       { svelteHTML.createElement("button", {       "type":`button`,"class":`danger small`,"onclick":revokeOthers,"disabled":sessionAction.busy,});    }
+    }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {     children:() => { return __sveltets_2_any(0); },"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.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":deleteAction.error,}});}
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":deleteAccount,});
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {          "label":`Type your username (${data.username}) to confirm`,"name":`confirm`,value:removal.confirm,"required":true,"autocomplete":`off`,"maxlength":64,}});/*Ωignore_startΩ*/() => removal.confirm = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+      if(data.hasPassword){
+         { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Password`,"name":`password`,"type":`password`,value:removal.password,"required":true,"autocomplete":`current-password`,"maxlength":512,}});/*Ωignore_startΩ*/() => removal.password = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+      }
+       { svelteHTML.createElement("div", {});
+         { svelteHTML.createElement("button", {     "type":`submit`,"class":`danger`,"disabled":deleteAction.busy,});   }
+       }
+     }
+   Section}
+}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Settings__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Settings__SvelteComponent_ = ReturnType<typeof Settings__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Settings__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Setup.svelte.ts b/.svelte-check/svelte/web/src/pages/++Setup.svelte.ts
new file mode 100644
index 0000000..49ad274
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Setup.svelte.ts
@@ -0,0 +1,70 @@
+///<reference types="svelte" />
+;
+import { LogIn, UserPlus } from "@lucide/svelte";
+import { ApiError, api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { reload } from "../lib/router.svelte";
+import Card from "../components/Card.svelte";
+import Field from "../components/Field.svelte";
+import Notes from "../components/Notes.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+
+  let status = $state<"open" | "done" | "unconfigured" | null>(null);
+  const values = $state({ token: "", username: "", name: "", email: "" });
+  const form = new Action();
+
+  api<{ state: "open" | "done" | "unconfigured" }>("/api/setup").then((r) => (status = r.state));
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      try {
+        reload((await api<{ redirect: string }>("/api/setup", values)).redirect);
+      } catch (err) {
+        if (err instanceof ApiError && err.data.done) status = "done";
+        throw err;
+      }
+    });
+  }
+;
+async () => {
+
+if(status === "done"){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Setup is done`,"lead":`This server already has accounts.`,}});
+     { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn primary`,"href":`/login`,}); { const $$_nIgoL3C = __sveltets_2_ensureComponent(LogIn); new $$_nIgoL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   } }
+   Card}
+} else if (status === "unconfigured"){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Almost there`,}});
+     { svelteHTML.createElement("p", {});
+         { svelteHTML.createElement("code", {});  }   { svelteHTML.createElement("code", {});    }   { svelteHTML.createElement("code", {});  }
+               
+     }
+   Card}
+} else if (status === "open"){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Create the first admin`,"lead":`This page only works while the server has no accounts. You'll add a passkey or password straight after.`,}});
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":submit,});
+       { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {  "error":form.error,}});}
+        { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Setup token`,"name":`token`,"type":`password`,value:values.token,"required":true,"autocomplete":`off`,"hint":`The SETUP_TOKEN secret.`,"autofocus":true,}});/*Ωignore_startΩ*/() => values.token = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {          "label":`Username`,"name":`username`,value:values.username,"required":true,"autocomplete":`username`,"maxlength":32,}});/*Ωignore_startΩ*/() => values.username = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {          "label":`Display name`,"name":`name`,value:values.name,"autocomplete":`name`,"maxlength":100,}});/*Ωignore_startΩ*/() => values.name = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Email`,"name":`email`,"type":`email`,value:values.email,"autocomplete":`email`,"maxlength":254,}});/*Ωignore_startΩ*/() => values.email = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary wide`,"disabled":form.busy,});
+         { const $$_sulPresU3C = __sveltets_2_ensureComponent(UserPlus); new $$_sulPresU3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+          
+       }
+     }
+   Card}
+}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Setup__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Setup__SvelteComponent_ = ReturnType<typeof Setup__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Setup__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++Terms.svelte.ts b/.svelte-check/svelte/web/src/pages/++Terms.svelte.ts
new file mode 100644
index 0000000..54d60db
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++Terms.svelte.ts
@@ -0,0 +1,82 @@
+///<reference types="svelte" />
+;
+import { session } from "../lib/session.svelte";
+import Title from "../components/Title.svelte";
+import Contact from "./Contact.svelte";
+import { OPERATOR, UPDATED } from "../lib/legal";
+function $$render() {
+
+  
+  
+  
+  
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Terms of service`,}});}
+ { svelteHTML.createElement("article", { "class":`legal`,});
+   { svelteHTML.createElement("p", { "class":`eyebrow`,});  UPDATED; }
+   { svelteHTML.createElement("h1", {});   }
+   { svelteHTML.createElement("p", {});
+           session.site;       OPERATOR;    
+                    { svelteHTML.createElement("a", { "href":`/privacy`,});  }
+   }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("ul", {});
+     { svelteHTML.createElement("li", {});                 }
+     { svelteHTML.createElement("li", {});
+                      
+                          
+         
+     }
+     { svelteHTML.createElement("li", {});                }
+     { svelteHTML.createElement("li", {});          }
+   }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {});  }
+   { svelteHTML.createElement("ul", {});
+     { svelteHTML.createElement("li", {});            }
+     { svelteHTML.createElement("li", {});              }
+     { svelteHTML.createElement("li", {});             }
+     { svelteHTML.createElement("li", {});      }
+   }
+
+   { svelteHTML.createElement("h2", {});     }
+   { svelteHTML.createElement("p", {});
+    session.site;                    
+     
+   }
+
+   { svelteHTML.createElement("h2", {});    }
+   { svelteHTML.createElement("p", {});
+                        
+                   
+   }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {});
+    session.site;                  
+                        
+                         
+          
+   }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {});
+                         
+        
+   }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {});           }
+
+   { svelteHTML.createElement("h2", {});  }
+   { svelteHTML.createElement("p", {}); { const $$_tcatnoC2C = __sveltets_2_ensureComponent(Contact); new $$_tcatnoC2C({ target: __sveltets_2_any(), props: {}});} }
+ }
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: "", slots: {}, events: {} }}
+const Terms__SvelteComponent_ = __sveltets_2_isomorphic_component(__sveltets_2_with_any_event($$render()));
+/*Ωignore_startΩ*/type Terms__SvelteComponent_ = InstanceType<typeof Terms__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Terms__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++TotpSetup.svelte.ts b/.svelte-check/svelte/web/src/pages/++TotpSetup.svelte.ts
new file mode 100644
index 0000000..9c92184
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++TotpSetup.svelte.ts
@@ -0,0 +1,60 @@
+///<reference types="svelte" />
+;
+import { Shield } from "@lucide/svelte";
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { navigate } from "../lib/router.svelte";
+import Card from "../components/Card.svelte";
+import Field from "../components/Field.svelte";
+import Notes from "../components/Notes.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+
+  let setup = $state<{ qr: string; secret: string } | null>(null);
+  let code = $state("");
+  const start = new Action();
+  const form = new Action();
+
+  // Each visit makes a fresh secret; it only takes effect once a code from it is confirmed.
+  start.run(async () => (setup = await api("/api/account/totp/start", {})));
+
+  async function confirm(ev: SubmitEvent) {
+    ev.preventDefault();
+    const done = await form.run(() => api("/api/account/totp/confirm", { code }));
+    if (done) navigate("/settings?m=totp-enabled");
+    else code = "";
+  }
+;
+async () => {
+
+ { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Scan this code`,"lead":`Use any authenticator app (1Password, Aegis, Google Authenticator…), then enter the code it shows.`,}});
+   { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":start.error || form.error,}});}
+  if(setup){
+     { svelteHTML.createElement("img", {          "class":`qr`,"src":setup.qr,"alt":`QR code for your authenticator app`,"width":`220`,"height":`220`,});}
+     { svelteHTML.createElement("details", {});
+       { svelteHTML.createElement("summary", {});   }
+       { svelteHTML.createElement("p", {});    }
+       { svelteHTML.createElement("p", { "class":`secret`,}); { svelteHTML.createElement("code", {});setup.secret; } }
+     }
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":confirm,});
+        { const $$_dleiF2C = __sveltets_2_ensureComponent(Field); const $$_dleiF2 = new $$_dleiF2C({ target: __sveltets_2_any(), props: {            "label":`Code`,"name":`code`,value:code,"required":true,"inputmode":`numeric`,"autocomplete":`one-time-code`,"maxlength":7,"autofocus":true,}});/*Ωignore_startΩ*/() => code = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF2.$$bindings = 'value';}
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary wide`,"disabled":form.busy,});
+         { const $$_dleihS3C = __sveltets_2_ensureComponent(Shield); new $$_dleihS3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+         
+       }
+     }
+  }
+   { svelteHTML.createElement("p", { "class":`small`,}); { svelteHTML.createElement("a", {   "class":`btn wide`,"href":`/settings`,});  } }
+ Card}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const TotpSetup__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type TotpSetup__SvelteComponent_ = ReturnType<typeof TotpSetup__SvelteComponent_>;
+/*Ωignore_endΩ*/export default TotpSetup__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/++VerifyEmail.svelte.ts b/.svelte-check/svelte/web/src/pages/++VerifyEmail.svelte.ts
new file mode 100644
index 0000000..7e5abcd
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/++VerifyEmail.svelte.ts
@@ -0,0 +1,61 @@
+///<reference types="svelte" />
+;
+import { Check, LogIn } from "@lucide/svelte";
+import { api } from "../lib/api";
+import { Action } from "../lib/action.svelte";
+import { reload } from "../lib/router.svelte";
+import Card from "../components/Card.svelte";
+import Notes from "../components/Notes.svelte";
+
+;type $$ComponentProps =  { params: Record<string, string> };function $$render() {
+
+  
+  
+  
+  
+  
+  
+
+  let { params }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+  const path = $derived(`/api/verify-email/${encodeURIComponent(params.token ?? "")}`);
+
+  let email = $state<string | null>(null);
+  let done = $state(false);
+  const load = new Action();
+  const verify = new Action();
+  load.run(async () => (email = (await api<{ email: string }>(path)).email));
+
+  // Mail scanners follow GETs, so verifying takes a deliberate click.
+  async function confirm() {
+    await verify.run(async () => {
+      const { signedIn } = await api<{ signedIn: boolean }>(path, {});
+      if (signedIn) reload("/settings?m=email-verified");
+      else done = true;
+    });
+  }
+;
+async () => {
+
+if(done){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Email verified`,"lead":`Thanks! You can close this tab, or sign in.`,}});
+     { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn primary`,"href":`/login`,}); { const $$_nIgoL3C = __sveltets_2_ensureComponent(LogIn); new $$_nIgoL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   } }
+   Card}
+} else if (load.error || verify.error){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`This link can't be used`,"lead":`It has expired, was already used, or a newer one was sent. You can send a new one from your settings.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":verify.error && !verify.error.startsWith("This link") ? verify.error : "",}});}
+     { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn primary`,"href":`/settings`,});  } }
+   Card}
+} else if (email){
+   { const $$_draC0C = __sveltets_2_ensureComponent(Card); new $$_draC0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Verify your email`,}});
+     { svelteHTML.createElement("p", { "class":`muted`,});   { svelteHTML.createElement("strong", {});email; }   }
+     { svelteHTML.createElement("button", {       "type":`button`,"class":`primary wide`,"onclick":confirm,"disabled":verify.busy,});
+       { const $$_kcehC2C = __sveltets_2_ensureComponent(Check); new $$_kcehC2C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+      
+     }
+   Card}
+}
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const VerifyEmail__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type VerifyEmail__SvelteComponent_ = ReturnType<typeof VerifyEmail__SvelteComponent_>;
+/*Ωignore_endΩ*/export default VerifyEmail__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/Account.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Account.d.svelte.ts
new file mode 100644
index 0000000..51780bb
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Account.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Account.svelte.ts";
+export * from "./++Account.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Apps.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Apps.d.svelte.ts
new file mode 100644
index 0000000..bb429aa
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Apps.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Apps.svelte.ts";
+export * from "./++Apps.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/AuthorizeNotice.d.svelte.ts b/.svelte-check/svelte/web/src/pages/AuthorizeNotice.d.svelte.ts
new file mode 100644
index 0000000..2afc885
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/AuthorizeNotice.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++AuthorizeNotice.svelte.ts";
+export * from "./++AuthorizeNotice.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Contact.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Contact.d.svelte.ts
new file mode 100644
index 0000000..4464db5
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Contact.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Contact.svelte.ts";
+export * from "./++Contact.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/EndSession.d.svelte.ts b/.svelte-check/svelte/web/src/pages/EndSession.d.svelte.ts
new file mode 100644
index 0000000..96e7501
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/EndSession.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++EndSession.svelte.ts";
+export * from "./++EndSession.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/ErrorPage.d.svelte.ts b/.svelte-check/svelte/web/src/pages/ErrorPage.d.svelte.ts
new file mode 100644
index 0000000..667e8a8
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/ErrorPage.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++ErrorPage.svelte.ts";
+export * from "./++ErrorPage.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Forgot.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Forgot.d.svelte.ts
new file mode 100644
index 0000000..7e6737c
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Forgot.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Forgot.svelte.ts";
+export * from "./++Forgot.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Login.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Login.d.svelte.ts
new file mode 100644
index 0000000..4936bef
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Login.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Login.svelte.ts";
+export * from "./++Login.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/LoginLink.d.svelte.ts b/.svelte-check/svelte/web/src/pages/LoginLink.d.svelte.ts
new file mode 100644
index 0000000..45fbc16
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/LoginLink.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++LoginLink.svelte.ts";
+export * from "./++LoginLink.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Mfa.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Mfa.d.svelte.ts
new file mode 100644
index 0000000..6c5502c
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Mfa.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Mfa.svelte.ts";
+export * from "./++Mfa.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/NotFound.d.svelte.ts b/.svelte-check/svelte/web/src/pages/NotFound.d.svelte.ts
new file mode 100644
index 0000000..7810312
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/NotFound.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++NotFound.svelte.ts";
+export * from "./++NotFound.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Privacy.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Privacy.d.svelte.ts
new file mode 100644
index 0000000..2797cbb
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Privacy.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Privacy.svelte.ts";
+export * from "./++Privacy.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Register.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Register.d.svelte.ts
new file mode 100644
index 0000000..7a024bb
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Register.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Register.svelte.ts";
+export * from "./++Register.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Reset.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Reset.d.svelte.ts
new file mode 100644
index 0000000..c3e8c68
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Reset.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Reset.svelte.ts";
+export * from "./++Reset.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Security.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Security.d.svelte.ts
new file mode 100644
index 0000000..16bfba9
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Security.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Security.svelte.ts";
+export * from "./++Security.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Settings.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Settings.d.svelte.ts
new file mode 100644
index 0000000..74582fc
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Settings.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Settings.svelte.ts";
+export * from "./++Settings.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Setup.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Setup.d.svelte.ts
new file mode 100644
index 0000000..8cb7e3c
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Setup.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Setup.svelte.ts";
+export * from "./++Setup.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/Terms.d.svelte.ts b/.svelte-check/svelte/web/src/pages/Terms.d.svelte.ts
new file mode 100644
index 0000000..c751da6
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/Terms.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Terms.svelte.ts";
+export * from "./++Terms.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/TotpSetup.d.svelte.ts b/.svelte-check/svelte/web/src/pages/TotpSetup.d.svelte.ts
new file mode 100644
index 0000000..d7d0d15
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/TotpSetup.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++TotpSetup.svelte.ts";
+export * from "./++TotpSetup.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/VerifyEmail.d.svelte.ts b/.svelte-check/svelte/web/src/pages/VerifyEmail.d.svelte.ts
new file mode 100644
index 0000000..af8574a
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/VerifyEmail.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++VerifyEmail.svelte.ts";
+export * from "./++VerifyEmail.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/admin/++Audit.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/++Audit.svelte.ts
new file mode 100644
index 0000000..7d683cc
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/++Audit.svelte.ts
@@ -0,0 +1,62 @@
+///<reference types="svelte" />
+;
+import { api } from "../../lib/api";
+import { Action } from "../../lib/action.svelte";
+import { date, relative } from "../../lib/format";
+import AdminTabs from "../../components/AdminTabs.svelte";
+import Notes from "../../components/Notes.svelte";
+import Section from "../../components/Section.svelte";
+import Title from "../../components/Title.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+
+  interface Entry {
+    id: number;
+    at: number;
+    actor: string | null;
+    action: string;
+    target: string | null;
+    ip: string | null;
+    detail: string | null;
+  }
+
+  let entries = $state<Entry[]>([]);
+  const load = new Action();
+  load.run(async () => (entries = await api<Entry[]>("/api/admin/audit")));
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Audit log`,}});}
+ { const $$_sbaTnimdA0C = __sveltets_2_ensureComponent(AdminTabs); new $$_sbaTnimdA0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Recent activity`,"description":`The latest 200 events. Kept for 180 days.`,}});
+   { svelteHTML.createElement("div", { "class":`table-wrap`,});
+     { svelteHTML.createElement("table", { "class":`compact`,});
+       { svelteHTML.createElement("thead", {}); { svelteHTML.createElement("tr", {}); { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } } }
+       { svelteHTML.createElement("tbody", {});
+           for(let e of __sveltets_2_ensureArray(entries)){e.id;
+           { svelteHTML.createElement("tr", {});
+             { svelteHTML.createElement("td", { "title":date(e.at),});relative(e.at); }
+             { svelteHTML.createElement("td", {});if(e.actor){ e.actor;}else{ { svelteHTML.createElement("span", { "class":`muted`,});  }} }
+             { svelteHTML.createElement("td", {}); { svelteHTML.createElement("code", {});e.action; }if(e.detail){ { svelteHTML.createElement("small", { "class":`muted`,}); e.detail; }} }
+             { svelteHTML.createElement("td", {});e.target ?? ""; }
+             { svelteHTML.createElement("td", {});e.ip ?? ""; }
+           }
+        }
+       }
+     }
+   }
+ Section}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Audit__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Audit__SvelteComponent_ = ReturnType<typeof Audit__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Audit__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/admin/++ClientDetail.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/++ClientDetail.svelte.ts
new file mode 100644
index 0000000..48f1edd
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/++ClientDetail.svelte.ts
@@ -0,0 +1,170 @@
+///<reference types="svelte" />
+;
+import { untrack } from "svelte";
+import { Save } from "@lucide/svelte";
+import { api, confirmed } from "../../lib/api";
+import { Action } from "../../lib/action.svelte";
+import { navigate } from "../../lib/router.svelte";
+import AdminTabs from "../../components/AdminTabs.svelte";
+import ClientFields, { type ClientValues } from "../../components/ClientFields.svelte";
+import CopyRow from "../../components/CopyRow.svelte";
+import type { GroupOption } from "../../components/GroupChecks.svelte";
+import Notes from "../../components/Notes.svelte";
+import Section from "../../components/Section.svelte";
+import Title from "../../components/Title.svelte";
+import { newSecrets, type ClientData } from "./Clients.svelte";
+
+;type $$ComponentProps =  { params: Record<string, string> };function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+
+  let { params }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+  const base = $derived(`/api/admin/clients/${encodeURIComponent(params.id ?? "")}`);
+
+  let client = $state<ClientData | null>(null);
+  let groups = $state<GroupOption[]>([]);
+  let values = $state<ClientValues>({ name: "", homeUrl: "", redirectUris: "", postLogoutRedirectUris: "", allowedGroups: [] });
+  // A secret just created on the previous page (taken, so it's only ever shown
+  // once), or one from rotating it here.
+  let secret = $state<string | null>(
+    untrack(() => {
+      const created = newSecrets.get(params.id ?? "") ?? null;
+      newSecrets.delete(params.id ?? "");
+      return created;
+    }),
+  );
+
+  const load = new Action();
+  const settings = new Action();
+  const secretAction = new Action();
+  const deleteAction = new Action();
+
+  async function refresh() {
+    const [c, g] = await Promise.all([api<ClientData>(base), api<GroupOption[]>("/api/admin/groups")]);
+    client = c;
+    groups = g;
+    values = {
+      name: c.name,
+      homeUrl: c.homeUrl ?? "",
+      redirectUris: c.redirectUris.join("\n"),
+      postLogoutRedirectUris: c.postLogoutRedirectUris.join("\n"),
+      allowedGroups: [...c.allowedGroups],
+    };
+  }
+  load.run(refresh);
+
+  async function save(ev: SubmitEvent) {
+    ev.preventDefault();
+    await settings.run(async () => {
+      const res = await api(base, values);
+      await refresh();
+      return res;
+    });
+  }
+
+  async function rotate() {
+    const message = client!.isPublic
+      ? "Give this app a secret and make it confidential?"
+      : "Replace the secret? The old one stops working immediately.";
+    if (!confirmed(message)) return;
+    await secretAction.run(async () => {
+      secret = (await api<{ secret: string }>(`${base}/secret`, {})).secret;
+      await refresh();
+    });
+  }
+
+  async function makePublic() {
+    if (!confirmed("Remove the secret and make this a public PKCE client?")) return;
+    await secretAction.run(async () => {
+      const res = await api(`${base}/public`, {});
+      secret = null;
+      await refresh();
+      return res;
+    });
+  }
+
+  async function remove() {
+    if (!confirmed(`Delete ${client!.name}? People won't be able to sign in to it.`)) return;
+    const done = await deleteAction.run(() => api(`${base}/delete`, {}));
+    if (done) navigate("/admin/clients?m=client-deleted");
+  }
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":client?.name ?? "Application",}});}
+ { const $$_sbaTnimdA0C = __sveltets_2_ensureComponent(AdminTabs); new $$_sbaTnimdA0C({ target: __sveltets_2_any(), props: {}});}
+ { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn small`,"href":`/admin/clients`,});   } }
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+
+if(client){
+   { svelteHTML.createElement("h1", {});client.name; }
+
+  if(secret){
+     { svelteHTML.createElement("div", { "class":`notice ok`,});
+       { svelteHTML.createElement("p", {}); { svelteHTML.createElement("strong", {});  }              }
+       { const $$_woRypoC1C = __sveltets_2_ensureComponent(CopyRow); new $$_woRypoC1C({ target: __sveltets_2_any(), props: {    "value":secret,"label":`Client secret`,}});}
+     }
+  }
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Connecting the app`,}});
+     { svelteHTML.createElement("dl", { "class":`kv`,});
+         for(let [k, v] of __sveltets_2_ensureArray(([
+        ["Issuer", client.issuer],
+        ["Discovery", client.discovery],
+        ["Client id", client.id],
+        ["Token auth", client.isPublic ? "none (PKCE)" : "client_secret_basic or client_secret_post"],
+        ["Scopes", "openid profile email groups (+ offline_access for refresh tokens)"],
+      ]))){k;
+         { svelteHTML.createElement("dt", {});k; }
+         { svelteHTML.createElement("dd", {}); { svelteHTML.createElement("code", {});v; } }
+      }
+     }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Settings`,}});
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":save,});
+       { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {    "ok":settings.message,"error":settings.error,}});}
+       { const $$_sdleiFtneilC2C = __sveltets_2_ensureComponent(ClientFields); const $$_sdleiFtneilC2 = new $$_sdleiFtneilC2C({ target: __sveltets_2_any(), props: {   values,groups,}});/*Ωignore_startΩ*/() => values = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_sdleiFtneilC2.$$bindings = 'values';}
+       { svelteHTML.createElement("div", {});
+         { svelteHTML.createElement("button", {   "type":`submit`,"disabled":settings.busy,}); { const $$_evaS4C = __sveltets_2_ensureComponent(Save); new $$_evaS4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}  }
+       }
+     }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Client secret`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":secretAction.message,"error":secretAction.error,}});}
+     { svelteHTML.createElement("p", { "class":`muted`,});
+      client.isPublic
+        ? "This is a public client: it has no secret and must use PKCE."
+        : "Rotating the secret breaks the app until it's given the new one.";
+     }
+     { svelteHTML.createElement("div", { "class":`buttons`,});
+       { svelteHTML.createElement("button", {     "type":`button`,"onclick":rotate,"disabled":secretAction.busy,});client.isPublic ? "Create a secret" : "Rotate secret"; }
+      if(!client.isPublic){
+         { svelteHTML.createElement("button", {       "type":`button`,"class":`danger`,"onclick":makePublic,"disabled":secretAction.busy,});  }
+      }
+     }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Delete application`,"description":`Its refresh tokens stop working immediately; issued access tokens are refused by /userinfo.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":deleteAction.error,}});}
+     { svelteHTML.createElement("button", {       "type":`button`,"class":`danger`,"onclick":remove,"disabled":deleteAction.busy,});  }
+   Section}
+}
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const ClientDetail__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type ClientDetail__SvelteComponent_ = ReturnType<typeof ClientDetail__SvelteComponent_>;
+/*Ωignore_endΩ*/export default ClientDetail__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/admin/++Clients.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/++Clients.svelte.ts
new file mode 100644
index 0000000..50b1929
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/++Clients.svelte.ts
@@ -0,0 +1,132 @@
+///<reference types="svelte" />
+;
+  export interface ClientData {
+    id: string;
+    name: string;
+    homeUrl: string | null;
+    isPublic: boolean;
+    redirectUris: string[];
+    postLogoutRedirectUris: string[];
+    allowedGroups: string[];
+    issuer: string;
+    discovery: string;
+  }
+
+  /** Shown once, on the page the app is opened on after creating it. Never kept beyond this tab. */
+  export const newSecrets = new Map<string, string>();
+;;
+
+import { AppWindow } from "@lucide/svelte";
+import { api } from "../../lib/api";
+import { Action } from "../../lib/action.svelte";
+import { navigate } from "../../lib/router.svelte";
+import AdminTabs from "../../components/AdminTabs.svelte";
+import ClientFields, { type ClientValues } from "../../components/ClientFields.svelte";
+import Field from "../../components/Field.svelte";
+import Flash from "../../components/Flash.svelte";
+import type { GroupOption } from "../../components/GroupChecks.svelte";
+import Notes from "../../components/Notes.svelte";
+import Section from "../../components/Section.svelte";
+import Title from "../../components/Title.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+
+  let clients = $state<ClientData[]>([]);
+  let groups = $state<GroupOption[]>([]);
+  let values = $state<ClientValues>({ name: "", homeUrl: "", redirectUris: "", postLogoutRedirectUris: "", allowedGroups: [] });
+  let type = $state<"confidential" | "public">("confidential");
+  let clientId = $state("");
+  const load = new Action();
+  const create = new Action();
+
+  load.run(async () => {
+    [clients, groups] = await Promise.all([api<ClientData[]>("/api/admin/clients"), api<GroupOption[]>("/api/admin/groups")]);
+  });
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await create.run(async () => {
+      const { id, secret } = await api<{ id: string; secret: string | null }>("/api/admin/clients", { ...values, type, clientId });
+      if (secret) newSecrets.set(id, secret);
+      navigate(`/admin/clients/${encodeURIComponent(id)}`);
+    });
+  }
+;
+async () => {
+
+
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Applications`,}});}
+ { const $$_sbaTnimdA0C = __sveltets_2_ensureComponent(AdminTabs); new $$_sbaTnimdA0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_hsalF0C = __sveltets_2_ensureComponent(Flash); new $$_hsalF0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Applications`,"description":`Each app that signs people in through this server is an OpenID Connect client.`,}});
+  if(clients.length === 0){
+     { svelteHTML.createElement("p", { "class":`muted`,});   }
+  }else{
+     { svelteHTML.createElement("div", { "class":`table-wrap`,});
+       { svelteHTML.createElement("table", {});
+         { svelteHTML.createElement("thead", {}); { svelteHTML.createElement("tr", {}); { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } } }
+         { svelteHTML.createElement("tbody", {});
+             for(let cl of __sveltets_2_ensureArray(clients)){cl.id;
+             { svelteHTML.createElement("tr", {});
+               { svelteHTML.createElement("td", {});
+                 { svelteHTML.createElement("a", {   "class":`btn small`,"href":`/admin/clients/${encodeURIComponent(cl.id)}`,});cl.name; }
+                if(!cl.homeUrl){ { svelteHTML.createElement("br", {});} { svelteHTML.createElement("small", { "class":`muted`,});    }}
+               }
+               { svelteHTML.createElement("td", {}); { svelteHTML.createElement("code", {});cl.id; } }
+               { svelteHTML.createElement("td", {});cl.isPublic ? "public (PKCE)" : "confidential"; }
+               { svelteHTML.createElement("td", {});   for(let g of __sveltets_2_ensureArray(cl.allowedGroups)){g; { svelteHTML.createElement("span", { "class":`badge`,});g; }}  }
+             }
+          }
+         }
+       }
+     }
+  }
+ Section}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Add an application`,}});
+   { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":submit,});
+     { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {  "error":create.error,}});}
+     { const $$_sdleiFtneilC2C = __sveltets_2_ensureComponent(ClientFields); const $$_sdleiFtneilC2 = new $$_sdleiFtneilC2C({ target: __sveltets_2_any(), props: {   values,groups,}});/*Ωignore_startΩ*/() => values = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_sdleiFtneilC2.$$bindings = 'values';}
+     { svelteHTML.createElement("fieldset", {});
+       { svelteHTML.createElement("legend", {});  }
+       { svelteHTML.createElement("label", { "class":`check`,});
+         { svelteHTML.createElement("input", {     "type":`radio`,"value":`confidential`,});type = __sveltets_2_any(null);}
+         { svelteHTML.createElement("span", {});  { svelteHTML.createElement("small", { "class":`muted`,});            } }
+       }
+       { svelteHTML.createElement("label", { "class":`check`,});
+         { svelteHTML.createElement("input", {     "type":`radio`,"value":`public`,});type = __sveltets_2_any(null);}
+         { svelteHTML.createElement("span", {});  { svelteHTML.createElement("small", { "class":`muted`,});               } }
+       }
+     }
+     { svelteHTML.createElement("details", {});
+       { svelteHTML.createElement("summary", {});  }
+       { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {             "label":`Client id`,"name":`client_id`,value:clientId,"maxlength":128,"autocomplete":`off`,"hint":`Leave blank for a random id. Set it to keep an app's existing client id when moving it over from another provider.`,}});/*Ωignore_startΩ*/() => clientId = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+     }
+     { svelteHTML.createElement("div", {});
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary`,"disabled":create.busy,});
+         { const $$_wodniWppA4C = __sveltets_2_ensureComponent(AppWindow); new $$_wodniWppA4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+         
+       }
+     }
+   }
+ Section}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Clients__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Clients__SvelteComponent_ = ReturnType<typeof Clients__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Clients__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/admin/++Groups.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/++Groups.svelte.ts
new file mode 100644
index 0000000..a5c5694
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/++Groups.svelte.ts
@@ -0,0 +1,112 @@
+///<reference types="svelte" />
+;
+import { Save, Users } from "@lucide/svelte";
+import { api, confirmed } from "../../lib/api";
+import { Action } from "../../lib/action.svelte";
+import { plural } from "../../lib/format";
+import AdminTabs from "../../components/AdminTabs.svelte";
+import Field from "../../components/Field.svelte";
+import Notes from "../../components/Notes.svelte";
+import Section from "../../components/Section.svelte";
+import Title from "../../components/Title.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+  
+
+  const ADMIN_GROUP = "auth-admin";
+
+  interface Group {
+    name: string;
+    description: string;
+    members: number;
+  }
+
+  let groups = $state<Group[]>([]);
+  let descriptions = $state<Record<string, string>>({});
+  const values = $state({ name: "", description: "" });
+  const load = new Action();
+  const list = new Action();
+  const create = new Action();
+
+  async function refresh() {
+    groups = await api<Group[]>("/api/admin/groups");
+    descriptions = Object.fromEntries(groups.map((g) => [g.name, g.description]));
+  }
+  load.run(refresh);
+
+  async function act(section: Action, path: string, body: object = {}) {
+    await section.run(async () => {
+      const res = await api(path, body);
+      await refresh();
+      return res;
+    });
+  }
+
+  function save(ev: SubmitEvent, name: string) {
+    ev.preventDefault();
+    act(list, `/api/admin/groups/${encodeURIComponent(name)}`, { description: descriptions[name] });
+  }
+
+  function remove(name: string) {
+    if (confirmed(`Delete the group "${name}"? Members lose it immediately.`)) {
+      act(list, `/api/admin/groups/${encodeURIComponent(name)}/delete`);
+    }
+  }
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await act(create, "/api/admin/groups", values);
+    if (!create.error) Object.assign(values, { name: "", description: "" });
+  }
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Groups`,}});}
+ { const $$_sbaTnimdA0C = __sveltets_2_ensureComponent(AdminTabs); new $$_sbaTnimdA0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Groups`,"description":"Apps receive group names in the `groups` claim. Name them after what they allow, e.g. system-owner or inbox-admin.",}});
+   { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":list.message,"error":list.error,}});}
+   { svelteHTML.createElement("ul", { "class":`rows`,});
+       for(let g of __sveltets_2_ensureArray(groups)){g.name;
+       { svelteHTML.createElement("li", {});
+         { svelteHTML.createElement("div", { "class":`grow`,});
+           { svelteHTML.createElement("strong", {});g.name; }  { svelteHTML.createElement("small", { "class":`muted`,});plural(g.members, "member"); }
+           { svelteHTML.createElement("form", {   "class":`inline-edit`,"onsubmit":(ev) => save(ev, g.name),});
+             { svelteHTML.createElement("input", {          "type":`text`,"bind:value":descriptions[g.name],"maxlength":200,"placeholder":`Description`,"aria-label":`Description of ${g.name}`,});/*Ωignore_startΩ*/() => descriptions[g.name] = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+             { svelteHTML.createElement("button", {     "type":`submit`,"class":`small`,"disabled":list.busy,}); { const $$_evaS6C = __sveltets_2_ensureComponent(Save); new $$_evaS6C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}  }
+           }
+         }
+        if(g.name !== ADMIN_GROUP){
+           { svelteHTML.createElement("button", {       "type":`button`,"class":`danger small`,"onclick":() => remove(g.name),"disabled":list.busy,});  }
+        }
+       }
+    }
+   }
+ Section}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`New group`,}});
+   { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":submit,});
+     { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {    "ok":create.message,"error":create.error,}});}
+     { svelteHTML.createElement("div", { "class":`grid2`,});
+       { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {          "label":`Name`,"name":`name`,value:values.name,"required":true,"maxlength":64,"autocomplete":`off`,}});/*Ωignore_startΩ*/() => values.name = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+       { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {          "label":`Description`,"name":`description`,value:values.description,"maxlength":200,"autocomplete":`off`,}});/*Ωignore_startΩ*/() => values.description = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+     }
+     { svelteHTML.createElement("div", {});
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary`,"disabled":create.busy,}); { const $$_sresU4C = __sveltets_2_ensureComponent(Users); new $$_sresU4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   }
+     }
+   }
+ Section}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Groups__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Groups__SvelteComponent_ = ReturnType<typeof Groups__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Groups__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/admin/++Keys.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/++Keys.svelte.ts
new file mode 100644
index 0000000..569e2d2
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/++Keys.svelte.ts
@@ -0,0 +1,61 @@
+///<reference types="svelte" />
+;
+import { api, confirmed } from "../../lib/api";
+import { Action } from "../../lib/action.svelte";
+import { date } from "../../lib/format";
+import AdminTabs from "../../components/AdminTabs.svelte";
+import Notes from "../../components/Notes.svelte";
+import Section from "../../components/Section.svelte";
+import Title from "../../components/Title.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+
+  let keys = $state<{ kid: string; alg: string; createdAt: number; retiredAt: number | null }[]>([]);
+  const load = new Action();
+  const rotate = new Action();
+
+  const refresh = async () => void (keys = await api("/api/admin/keys"));
+  load.run(refresh);
+
+  async function rotateNow() {
+    if (!confirmed("Rotate the signing key?")) return;
+    await rotate.run(async () => {
+      const res = await api("/api/admin/keys/rotate", {});
+      await refresh();
+      return res;
+    });
+  }
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Signing keys`,}});}
+ { const $$_sbaTnimdA0C = __sveltets_2_ensureComponent(AdminTabs); new $$_sbaTnimdA0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Signing keys`,"description":`Tokens are signed with the newest active key. Apps pick up new keys from the JWKS automatically. A key is created on first use.`,}});
+   { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":rotate.message,"error":rotate.error,}});}
+   { svelteHTML.createElement("ul", { "class":`rows`,});
+       for(let k of __sveltets_2_ensureArray(keys)){k.kid;
+       { svelteHTML.createElement("li", {});
+         { svelteHTML.createElement("div", { "class":`grow`,});
+           { svelteHTML.createElement("code", {});k.kid; }  { svelteHTML.createElement("span", { "class":`badge ${k.retiredAt ? "" : "ok"}`,});k.retiredAt ? "retired" : "active"; }
+           { svelteHTML.createElement("br", {});}
+           { svelteHTML.createElement("small", { "class":`muted`,});k.alg;   date(k.createdAt);k.retiredAt ? ` · retired ${date(k.retiredAt)}` : ""; }
+         }
+       }
+    }
+   }
+   { svelteHTML.createElement("button", {     "type":`button`,"onclick":rotateNow,"disabled":rotate.busy,});  }
+ Section}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Keys__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Keys__SvelteComponent_ = ReturnType<typeof Keys__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Keys__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/admin/++Reserved.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/++Reserved.svelte.ts
new file mode 100644
index 0000000..de70029
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/++Reserved.svelte.ts
@@ -0,0 +1,92 @@
+///<reference types="svelte" />
+;
+import { Save } from "@lucide/svelte";
+import { api, confirmed } from "../../lib/api";
+import { Action } from "../../lib/action.svelte";
+import AdminTabs from "../../components/AdminTabs.svelte";
+import Field from "../../components/Field.svelte";
+import Notes from "../../components/Notes.svelte";
+import Section from "../../components/Section.svelte";
+import Title from "../../components/Title.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+
+  let reserved = $state<{ username: string; note: string }[]>([]);
+  let builtin = $state<string[]>([]);
+  const values = $state({ username: "", note: "" });
+  const load = new Action();
+  const list = new Action();
+  const create = new Action();
+
+  async function refresh() {
+    ({ reserved, builtin } = await api<{ reserved: { username: string; note: string }[]; builtin: string[] }>("/api/admin/reserved"));
+  }
+  load.run(refresh);
+
+  async function act(section: Action, path: string, body: object = {}) {
+    await section.run(async () => {
+      const res = await api(path, body);
+      await refresh();
+      return res;
+    });
+  }
+
+  function release(name: string) {
+    if (confirmed(`Release "${name}"? Anyone can then sign up with it.`)) {
+      act(list, `/api/admin/reserved/${encodeURIComponent(name)}/delete`);
+    }
+  }
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await act(create, "/api/admin/reserved", values);
+    if (!create.error) Object.assign(values, { username: "", note: "" });
+  }
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Reserved names`,}});}
+ { const $$_sbaTnimdA0C = __sveltets_2_ensureComponent(AdminTabs); new $$_sbaTnimdA0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+
+  { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {    children:() => { return __sveltets_2_any(0); },"title":`Reserved names`,"description":`Nobody can sign up with these, or with anything that reads the same: dots, dashes and underscores are ignored, and look-alikes such as 0 for o or 1 for l are folded, so reserving noreply also blocks no-reply and n0reply. Admins can still create accounts with them.`,}});
+   { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":list.message,"error":list.error,}});}
+   { svelteHTML.createElement("ul", { "class":`rows`,});
+       for(let r of __sveltets_2_ensureArray(reserved)){r.username;
+       { svelteHTML.createElement("li", {});
+         { svelteHTML.createElement("div", { "class":`grow`,}); { svelteHTML.createElement("strong", {});r.username; } if(r.note){ { svelteHTML.createElement("small", { "class":`muted`,});r.note; }} }
+         { svelteHTML.createElement("button", {       "type":`button`,"class":`danger small`,"onclick":() => release(r.username),"disabled":list.busy,});  }
+       }
+    }
+   }
+ Section}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Reserve a name`,}});
+   { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":submit,});
+     { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {    "ok":create.message,"error":create.error,}});}
+     { svelteHTML.createElement("div", { "class":`grid2`,});
+       { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {          "label":`Username`,"name":`username`,value:values.username,"required":true,"maxlength":32,"autocomplete":`off`,}});/*Ωignore_startΩ*/() => values.username = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+       { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {            "label":`Note`,"name":`note`,value:values.note,"maxlength":200,"autocomplete":`off`,"hint":`Why, or who it's held for.`,}});/*Ωignore_startΩ*/() => values.note = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+     }
+     { svelteHTML.createElement("div", {});
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary`,"disabled":create.busy,}); { const $$_evaS4C = __sveltets_2_ensureComponent(Save); new $$_evaS4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}  }
+     }
+   }
+ Section}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Always reserved`,"description":`Built into the code (src/data/reserved.ts).`,}});
+   { svelteHTML.createElement("p", { "class":`muted small`,});builtin.join(", "); }
+ Section}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Reserved__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Reserved__SvelteComponent_ = ReturnType<typeof Reserved__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Reserved__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/admin/++UserDetail.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/++UserDetail.svelte.ts
new file mode 100644
index 0000000..91396fa
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/++UserDetail.svelte.ts
@@ -0,0 +1,277 @@
+///<reference types="svelte" />
+;
+import { Link, Save } from "@lucide/svelte";
+import { api, confirmed } from "../../lib/api";
+import { Action } from "../../lib/action.svelte";
+import { date, plural, relative } from "../../lib/format";
+import { navigate, reload } from "../../lib/router.svelte";
+import AdminTabs from "../../components/AdminTabs.svelte";
+import CopyRow from "../../components/CopyRow.svelte";
+import Field from "../../components/Field.svelte";
+import Flash from "../../components/Flash.svelte";
+import GroupChecks, { type GroupOption } from "../../components/GroupChecks.svelte";
+import Notes from "../../components/Notes.svelte";
+import Section from "../../components/Section.svelte";
+import Title from "../../components/Title.svelte";
+;
+
+  interface UserData {
+    id: string;
+    username: string;
+    name: string | null;
+    email: string | null;
+    emailVerified: boolean;
+    picture: string | null;
+    disabled: boolean;
+    createdAt: number;
+    lastLoginAt: number | null;
+    hasPassword: boolean;
+    totp: boolean;
+    groups: string[];
+    passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];
+    sessionCount: number;
+    openLinkExpiresAt: number | null;
+    self: boolean;
+  };
+;type $$ComponentProps =  { params: Record<string, string> };function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+
+
+  let { params }:/*Ωignore_startΩ*/$$ComponentProps/*Ωignore_endΩ*/ = $props();
+  const base = $derived(`/api/admin/users/${encodeURIComponent(params.id ?? "")}`);
+
+  let user = $state<UserData | null>(null);
+  let allGroups = $state<GroupOption[]>([]);
+  const profile = $state({ username: "", name: "", email: "", picture: "", emailVerified: false });
+  let groups = $state<string[]>([]);
+  let ttl = $state("3600");
+  let link = $state<{ url: string; expiresAt: number } | null>(null);
+  let deleteConfirm = $state("");
+
+  const load = new Action();
+  const profileAction = new Action();
+  const groupsAction = new Action();
+  const linkAction = new Action();
+  const methodsAction = new Action();
+  const accessAction = new Action();
+  const deleteAction = new Action();
+
+  async function refresh() {
+    const [u, g] = await Promise.all([api<UserData>(base), api<GroupOption[]>("/api/admin/groups")]);
+    user = u;
+    allGroups = g;
+    Object.assign(profile, {
+      username: u.username,
+      name: u.name ?? "",
+      email: u.email ?? "",
+      picture: u.picture ?? "",
+      emailVerified: u.emailVerified,
+    });
+    groups = [...u.groups];
+  }
+  load.run(refresh);
+
+  /** Posts to `base + path`; on success shows the message and reloads this user. */
+  async function act(section: Action, path: string, body: object = {}) {
+    await section.run(async () => {
+      const res = await api<{ message?: string; redirect?: string }>(base + path, body);
+      if (res.redirect) return reload(res.redirect);
+      await refresh();
+      return res;
+    });
+  }
+
+  function saveProfile(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(profileAction, "/profile", profile);
+  }
+
+  function saveGroups(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(groupsAction, "/groups", { groups });
+  }
+
+  async function createLink(ev: SubmitEvent) {
+    ev.preventDefault();
+    await linkAction.run(async () => {
+      link = await api(base + "/link", { ttl: Number(ttl) });
+      await refresh();
+    });
+  }
+
+  function confirmThen(message: string, section: Action, path: string) {
+    if (confirmed(message)) act(section, path);
+  }
+
+  async function remove(ev: SubmitEvent) {
+    ev.preventDefault();
+    const done = await deleteAction.run(() => api(base + "/delete", { confirm: deleteConfirm }));
+    if (done) navigate("/admin/users?m=user-deleted");
+  }
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":user ? `@${user.username}` : "User",}});}
+ { const $$_sbaTnimdA0C = __sveltets_2_ensureComponent(AdminTabs); new $$_sbaTnimdA0C({ target: __sveltets_2_any(), props: {}});}
+ { svelteHTML.createElement("p", {}); { svelteHTML.createElement("a", {   "class":`btn small`,"href":`/admin/users`,});   } }
+ { const $$_hsalF0C = __sveltets_2_ensureComponent(Flash); new $$_hsalF0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+
+if(user){
+   { svelteHTML.createElement("h1", {});
+    user.name ?? user.username;  { svelteHTML.createElement("small", { "class":`muted`,}); user.username; }
+    if(user.disabled){ { svelteHTML.createElement("span", { "class":`badge danger`,});  }}
+   }
+   { svelteHTML.createElement("p", { "class":`muted`,});
+      { svelteHTML.createElement("code", {});user.id; }   date(user.createdAt);    relative(user.lastLoginAt);
+   }
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Profile`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":profileAction.message,"error":profileAction.error,}});}
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":saveProfile,});
+       { svelteHTML.createElement("div", { "class":`grid2`,});
+         { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {            "label":`Username`,"name":`username`,value:profile.username,"required":true,"maxlength":32,"autocomplete":`off`,"hint":`Apps may use this as a mailbox or URL; changing it can break things there.`,}});/*Ωignore_startΩ*/() => profile.username = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+         { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {          "label":`Display name`,"name":`name`,value:profile.name,"maxlength":100,"autocomplete":`off`,}});/*Ωignore_startΩ*/() => profile.name = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+         { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {            "label":`Email`,"name":`email`,"type":`email`,value:profile.email,"maxlength":254,"autocomplete":`off`,}});/*Ωignore_startΩ*/() => profile.email = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+         { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {            "label":`Picture URL`,"name":`picture`,"type":`url`,value:profile.picture,"maxlength":2048,"autocomplete":`off`,}});/*Ωignore_startΩ*/() => profile.picture = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+         { svelteHTML.createElement("label", { "class":`check`,});
+           { svelteHTML.createElement("input", {    "type":`checkbox`,"bind:checked":profile.emailVerified,});/*Ωignore_startΩ*/() => profile.emailVerified = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+           { svelteHTML.createElement("span", {});   }
+         }
+       }
+       { svelteHTML.createElement("div", {});
+         { svelteHTML.createElement("button", {   "type":`submit`,"disabled":profileAction.busy,}); { const $$_evaS4C = __sveltets_2_ensureComponent(Save); new $$_evaS4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   }
+       }
+     }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Groups`,"description":"Sent to apps in the `groups` claim, and used to limit who can open each application.",}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":groupsAction.message,"error":groupsAction.error,}});}
+     { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":saveGroups,});
+       { const $$_skcehCpuorG2C = __sveltets_2_ensureComponent(GroupChecks); const $$_skcehCpuorG2 = new $$_skcehCpuorG2C({ target: __sveltets_2_any(), props: {    "groups":allGroups,selected:groups,}});/*Ωignore_startΩ*/() => groups = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_skcehCpuorG2.$$bindings = 'selected';}
+       { svelteHTML.createElement("div", {});
+         { svelteHTML.createElement("button", {   "type":`submit`,"disabled":groupsAction.busy,}); { const $$_evaS4C = __sveltets_2_ensureComponent(Save); new $$_evaS4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}   }
+       }
+     }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Sign-in link`,"description":`A one-time link that signs this person in so they can add a passkey or password. Use it for new accounts and lost devices.`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":linkAction.message,"error":linkAction.error,}});}
+    if(link){
+       { svelteHTML.createElement("div", { "class":`notice ok`,});
+         { svelteHTML.createElement("p", {});
+           { svelteHTML.createElement("strong", {});  }     user.username;      relative(link.expiresAt);
+              
+         }
+         { const $$_woRypoC2C = __sveltets_2_ensureComponent(CopyRow); new $$_woRypoC2C({ target: __sveltets_2_any(), props: {    "value":link.url,"label":`Sign-in link`,}});}
+       }
+    }
+    if(user.openLinkExpiresAt){
+       { svelteHTML.createElement("div", { "class":`inline-edit`,});
+         { svelteHTML.createElement("span", {});    relative(user.openLinkExpiresAt);  }
+         { svelteHTML.createElement("button", {       "type":`button`,"class":`small`,"onclick":() => { link = null; act(linkAction, "/link/revoke"); },"disabled":linkAction.busy,});
+           
+         }
+       }
+    }
+     { svelteHTML.createElement("form", {   "class":`inline-edit`,"onsubmit":createLink,});
+       { svelteHTML.createElement("label", {});
+         
+         { svelteHTML.createElement("select", { "bind:value":ttl,});/*Ωignore_startΩ*/() => ttl = __sveltets_2_any(null);/*Ωignore_endΩ*/
+           { svelteHTML.createElement("option", { "value":`900`,});  }
+           { svelteHTML.createElement("option", { "value":`3600`,});  }
+           { svelteHTML.createElement("option", { "value":`86400`,});  }
+           { svelteHTML.createElement("option", { "value":`604800`,});  }
+         }
+       }
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary`,"disabled":linkAction.busy,});
+         { const $$_kniL3C = __sveltets_2_ensureComponent(Link); new $$_kniL3C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+        user.openLinkExpiresAt ? "Replace link" : "Create link";
+       }
+     }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Sign-in methods`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":methodsAction.message,"error":methodsAction.error,}});}
+     { svelteHTML.createElement("ul", { "class":`rows`,});
+         for(let p of __sveltets_2_ensureArray(user.passkeys)){p.id;
+         { svelteHTML.createElement("li", {});
+           { svelteHTML.createElement("div", { "class":`grow`,});
+             { svelteHTML.createElement("strong", {}); p.name; }
+             { svelteHTML.createElement("br", {});}
+             { svelteHTML.createElement("small", { "class":`muted`,}); date(p.createdAt);    relative(p.lastUsedAt); }
+           }
+           { svelteHTML.createElement("button", {         "type":`button`,"class":`danger small`,"disabled":methodsAction.busy,"onclick":() => confirmThen(`Remove the passkey "${p.name}"?`, methodsAction, `/passkeys/${encodeURIComponent(p.id)}/delete`),});
+            
+           }
+         }
+      }
+      if(user.hasPassword){
+         { svelteHTML.createElement("li", {});
+           { svelteHTML.createElement("div", { "class":`grow`,}); { svelteHTML.createElement("strong", {});  } }
+           { svelteHTML.createElement("button", {         "type":`button`,"class":`danger small`,"disabled":methodsAction.busy,"onclick":() => confirmThen("Remove this password (and any two-factor setup)?", methodsAction, "/password/remove"),});
+            
+           }
+         }
+      }
+      if(user.totp){
+         { svelteHTML.createElement("li", {});
+           { svelteHTML.createElement("div", { "class":`grow`,}); { svelteHTML.createElement("strong", {});  } }
+           { svelteHTML.createElement("button", {         "type":`button`,"class":`danger small`,"disabled":methodsAction.busy,"onclick":() => confirmThen("Turn off two-factor codes for this account?", methodsAction, "/totp/reset"),});
+             
+           }
+         }
+      }
+      if(!user.passkeys.length && !user.hasPassword){
+         { svelteHTML.createElement("li", { "class":`muted`,});          }
+      }
+     }
+   Section}
+
+   { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Access`,}});
+     { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {    "ok":accessAction.message,"error":accessAction.error,}});}
+     { svelteHTML.createElement("p", { "class":`muted`,});plural(user.sessionCount, "active browser session");    }
+     { svelteHTML.createElement("div", { "class":`buttons`,});
+       { svelteHTML.createElement("button", {       "type":`button`,"disabled":accessAction.busy,"onclick":() => confirmThen("Sign this account out of every browser and application?", accessAction, "/signout"),});
+          
+       }
+      if(!user.self){
+        if(user.disabled){
+           { svelteHTML.createElement("button", {     "type":`button`,"disabled":accessAction.busy,"onclick":() => act(accessAction, "/enable"),});  }
+        }else{
+           { svelteHTML.createElement("button", {         "type":`button`,"class":`danger`,"disabled":accessAction.busy,"onclick":() => confirmThen("Disable this account? They'll be signed out everywhere.", accessAction, "/disable"),});
+             
+           }
+        }
+      }
+     }
+   Section}
+
+  if(!user.self){
+     { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Delete account`,"description":`Permanent. Apps keep whatever they stored about this person; a new account will get a new subject id.`,}});
+       { const $$_setoN1C = __sveltets_2_ensureComponent(Notes); new $$_setoN1C({ target: __sveltets_2_any(), props: {  "error":deleteAction.error,}});}
+       { svelteHTML.createElement("form", {   "class":`inline-edit`,"onsubmit":remove,});
+         { svelteHTML.createElement("input", {          "type":`text`,"bind:value":deleteConfirm,"placeholder":`Type ${user.username} to confirm`,"required":true,"autocomplete":`off`,"aria-label":`Confirm username`,});/*Ωignore_startΩ*/() => deleteConfirm = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+         { svelteHTML.createElement("button", {     "type":`submit`,"class":`danger`,"disabled":deleteAction.busy,});  }
+       }
+     Section}
+  }
+}
+};
+return { props: {} as any as $$ComponentProps, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const UserDetail__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type UserDetail__SvelteComponent_ = ReturnType<typeof UserDetail__SvelteComponent_>;
+/*Ωignore_endΩ*/export default UserDetail__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/admin/++Users.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/++Users.svelte.ts
new file mode 100644
index 0000000..c65300e
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/++Users.svelte.ts
@@ -0,0 +1,131 @@
+///<reference types="svelte" />
+;
+import { UserPlus } from "@lucide/svelte";
+import { api } from "../../lib/api";
+import { Action } from "../../lib/action.svelte";
+import { relative } from "../../lib/format";
+import { navigate } from "../../lib/router.svelte";
+import AdminTabs from "../../components/AdminTabs.svelte";
+import Field from "../../components/Field.svelte";
+import Flash from "../../components/Flash.svelte";
+import GroupChecks, { type GroupOption } from "../../components/GroupChecks.svelte";
+import Notes from "../../components/Notes.svelte";
+import Section from "../../components/Section.svelte";
+import Title from "../../components/Title.svelte";
+function $$render() {
+
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+  
+
+  interface UserRow {
+    id: string;
+    username: string;
+    name: string | null;
+    disabled: boolean;
+    groups: string[];
+    passkeys: number;
+    hasPassword: boolean;
+    totp: boolean;
+    lastLoginAt: number | null;
+  }
+
+  let users = $state<UserRow[]>([]);
+  let groups = $state<GroupOption[]>([]);
+  const fresh = () => ({ username: "", name: "", email: "", emailVerified: false, subject: "", groups: [] as string[] });
+  let values = $state(fresh());
+  const load = new Action();
+  const create = new Action();
+
+  load.run(async () => {
+    [users, groups] = await Promise.all([api<UserRow[]>("/api/admin/users"), api<GroupOption[]>("/api/admin/groups")]);
+  });
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await create.run(async () => {
+      const { id } = await api<{ id: string }>("/api/admin/users", values);
+      navigate(`/admin/users/${encodeURIComponent(id)}?m=user-created`);
+    });
+  }
+;
+async () => {
+
+ { const $$_eltiT0C = __sveltets_2_ensureComponent(Title); new $$_eltiT0C({ target: __sveltets_2_any(), props: {  "text":`Users`,}});}
+ { const $$_sbaTnimdA0C = __sveltets_2_ensureComponent(AdminTabs); new $$_sbaTnimdA0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_hsalF0C = __sveltets_2_ensureComponent(Flash); new $$_hsalF0C({ target: __sveltets_2_any(), props: {}});}
+ { const $$_setoN0C = __sveltets_2_ensureComponent(Notes); new $$_setoN0C({ target: __sveltets_2_any(), props: {  "error":load.error,}});}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: { children:() => { return __sveltets_2_any(0); },"title":`Users (${users.length})`,}});
+   { svelteHTML.createElement("div", { "class":`table-wrap`,});
+     { svelteHTML.createElement("table", {});
+       { svelteHTML.createElement("thead", {});
+         { svelteHTML.createElement("tr", {}); { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } { svelteHTML.createElement("th", {});  } }
+       }
+       { svelteHTML.createElement("tbody", {});
+           for(let u of __sveltets_2_ensureArray(users)){u.id;
+           { svelteHTML.createElement("tr", {});
+             { svelteHTML.createElement("td", {});
+               { svelteHTML.createElement("a", {   "class":`btn small`,"href":`/admin/users/${encodeURIComponent(u.id)}`,});u.name ?? u.username; }
+               { svelteHTML.createElement("br", {});}
+               { svelteHTML.createElement("small", { "class":`muted`,}); u.username; }
+              if(u.disabled){ { svelteHTML.createElement("span", { "class":`badge danger`,});  }}
+             }
+             { svelteHTML.createElement("td", {});
+                 for(let g of __sveltets_2_ensureArray(u.groups)){g; { svelteHTML.createElement("span", { "class":`badge`,});g; }} { svelteHTML.createElement("span", { "class":`muted`,});  }
+             }
+             { svelteHTML.createElement("td", {});
+              if(u.passkeys > 0){ { svelteHTML.createElement("span", { "class":`badge`,});u.passkeys; u.passkeys === 1 ? "" : "s"; }}
+              if(u.hasPassword){ { svelteHTML.createElement("span", { "class":`badge`,}); u.totp ? " + 2FA" : ""; }}
+              if(!u.passkeys && !u.hasPassword){ { svelteHTML.createElement("span", { "class":`muted`,});  }}
+             }
+             { svelteHTML.createElement("td", {});relative(u.lastLoginAt); }
+           }
+        }
+       }
+     }
+   }
+ Section}
+
+ { const $$_noitceS0C = __sveltets_2_ensureComponent(Section); new $$_noitceS0C({ target: __sveltets_2_any(), props: {   children:() => { return __sveltets_2_any(0); },"title":`Add a user`,"description":`They'll need a sign-in link from their page to set up a passkey or password.`,}});
+   { svelteHTML.createElement("form", {   "class":`stack`,"onsubmit":submit,});
+     { const $$_setoN2C = __sveltets_2_ensureComponent(Notes); new $$_setoN2C({ target: __sveltets_2_any(), props: {  "error":create.error,}});}
+     { svelteHTML.createElement("div", { "class":`grid2`,});
+       { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {          "label":`Username`,"name":`username`,value:values.username,"required":true,"maxlength":32,"autocomplete":`off`,}});/*Ωignore_startΩ*/() => values.username = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+       { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {          "label":`Display name`,"name":`name`,value:values.name,"maxlength":100,"autocomplete":`off`,}});/*Ωignore_startΩ*/() => values.name = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+       { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {            "label":`Email`,"name":`email`,"type":`email`,value:values.email,"maxlength":254,"autocomplete":`off`,}});/*Ωignore_startΩ*/() => values.email = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+       { svelteHTML.createElement("label", { "class":`check`,});
+         { svelteHTML.createElement("input", {    "type":`checkbox`,"bind:checked":values.emailVerified,});/*Ωignore_startΩ*/() => values.emailVerified = __sveltets_2_any(null);/*Ωignore_endΩ*/}
+         { svelteHTML.createElement("span", {});   }
+       }
+     }
+     { svelteHTML.createElement("fieldset", {});
+       { svelteHTML.createElement("legend", {});  }
+       { const $$_skcehCpuorG3C = __sveltets_2_ensureComponent(GroupChecks); const $$_skcehCpuorG3 = new $$_skcehCpuorG3C({ target: __sveltets_2_any(), props: {   groups,selected:values.groups,}});/*Ωignore_startΩ*/() => values.groups = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_skcehCpuorG3.$$bindings = 'selected';}
+     }
+     { svelteHTML.createElement("details", {});
+       { svelteHTML.createElement("summary", {});  }
+       { const $$_dleiF3C = __sveltets_2_ensureComponent(Field); const $$_dleiF3 = new $$_dleiF3C({ target: __sveltets_2_any(), props: {             "label":`Subject id`,"name":`subject`,value:values.subject,"maxlength":64,"autocomplete":`off`,"hint":"The permanent `sub` apps see. Leave blank for a random UUID. Set it to carry an account over from another identity provider without apps treating it as a new person.",}});/*Ωignore_startΩ*/() => values.subject = __sveltets_2_any(null);/*Ωignore_endΩ*/$$_dleiF3.$$bindings = 'value';}
+     }
+     { svelteHTML.createElement("div", {});
+       { svelteHTML.createElement("button", {     "type":`submit`,"class":`primary`,"disabled":create.busy,});
+         { const $$_sulPresU4C = __sveltets_2_ensureComponent(UserPlus); new $$_sulPresU4C({ target: __sveltets_2_any(), props: {    "class":`icon`,"aria-hidden":`true`,}});}
+         
+       }
+     }
+   }
+ Section}
+};
+return { props: {} as Record<string, never>, exports: {}, bindings: __sveltets_$$bindings(''), slots: {}, events: {} }}
+const Users__SvelteComponent_ = __sveltets_2_fn_component($$render());
+/*Ωignore_startΩ*/type Users__SvelteComponent_ = ReturnType<typeof Users__SvelteComponent_>;
+/*Ωignore_endΩ*/export default Users__SvelteComponent_;
\ No newline at end of file
diff --git a/.svelte-check/svelte/web/src/pages/admin/Audit.d.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/Audit.d.svelte.ts
new file mode 100644
index 0000000..24ce931
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/Audit.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Audit.svelte.ts";
+export * from "./++Audit.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/admin/ClientDetail.d.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/ClientDetail.d.svelte.ts
new file mode 100644
index 0000000..875b76f
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/ClientDetail.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++ClientDetail.svelte.ts";
+export * from "./++ClientDetail.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/admin/Clients.d.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/Clients.d.svelte.ts
new file mode 100644
index 0000000..2b0e47d
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/Clients.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Clients.svelte.ts";
+export * from "./++Clients.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/admin/Groups.d.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/Groups.d.svelte.ts
new file mode 100644
index 0000000..c986bb2
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/Groups.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Groups.svelte.ts";
+export * from "./++Groups.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/admin/Keys.d.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/Keys.d.svelte.ts
new file mode 100644
index 0000000..1dbe219
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/Keys.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Keys.svelte.ts";
+export * from "./++Keys.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/admin/Reserved.d.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/Reserved.d.svelte.ts
new file mode 100644
index 0000000..222ed2a
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/Reserved.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Reserved.svelte.ts";
+export * from "./++Reserved.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/admin/UserDetail.d.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/UserDetail.d.svelte.ts
new file mode 100644
index 0000000..e1559f9
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/UserDetail.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++UserDetail.svelte.ts";
+export * from "./++UserDetail.svelte.ts";
diff --git a/.svelte-check/svelte/web/src/pages/admin/Users.d.svelte.ts b/.svelte-check/svelte/web/src/pages/admin/Users.d.svelte.ts
new file mode 100644
index 0000000..15cef2e
--- /dev/null
+++ b/.svelte-check/svelte/web/src/pages/admin/Users.d.svelte.ts
@@ -0,0 +1,2 @@
+export { default } from "./++Users.svelte.ts";
+export * from "./++Users.svelte.ts";
diff --git a/.svelte-check/tsconfig.json b/.svelte-check/tsconfig.json
new file mode 100644
index 0000000..f8a0fcf
--- /dev/null
+++ b/.svelte-check/tsconfig.json
@@ -0,0 +1,63 @@
+{
+  "extends": "../web/tsconfig.json",
+  "compilerOptions": {
+    "rootDirs": [
+      "../web",
+      "svelte"
+    ],
+    "allowArbitraryExtensions": true,
+    "noEmit": true,
+    "incremental": false,
+    "tsBuildInfoFile": "tsbuildinfo.json"
+  },
+  "files": [
+    "../node_modules/svelte-check/dist/src/svelte-shims-v4.d.ts",
+    "../node_modules/svelte/svelte-html.d.ts"
+  ],
+  "include": [
+    "../web/src/**/*.ts",
+    "../web/src/**/*.svelte",
+    "svelte/src/**/*.ts",
+    "svelte/src/**/*.d.svelte.ts"
+  ],
+  "exclude": [
+    "../web/src/App.svelte",
+    "../web/src/components/AdminTabs.svelte",
+    "../web/src/components/Card.svelte",
+    "../web/src/components/ClientFields.svelte",
+    "../web/src/components/CopyRow.svelte",
+    "../web/src/components/Field.svelte",
+    "../web/src/components/Flash.svelte",
+    "../web/src/components/GroupChecks.svelte",
+    "../web/src/components/Notes.svelte",
+    "../web/src/components/Section.svelte",
+    "../web/src/components/Title.svelte",
+    "../web/src/pages/Apps.svelte",
+    "../web/src/pages/AuthorizeNotice.svelte",
+    "../web/src/pages/Contact.svelte",
+    "../web/src/pages/EndSession.svelte",
+    "../web/src/pages/ErrorPage.svelte",
+    "../web/src/pages/Forgot.svelte",
+    "../web/src/pages/Login.svelte",
+    "../web/src/pages/LoginLink.svelte",
+    "../web/src/pages/Mfa.svelte",
+    "../web/src/pages/NotFound.svelte",
+    "../web/src/pages/Privacy.svelte",
+    "../web/src/pages/Register.svelte",
+    "../web/src/pages/Reset.svelte",
+    "../web/src/pages/Security.svelte",
+    "../web/src/pages/Settings.svelte",
+    "../web/src/pages/Setup.svelte",
+    "../web/src/pages/Terms.svelte",
+    "../web/src/pages/TotpSetup.svelte",
+    "../web/src/pages/VerifyEmail.svelte",
+    "../web/src/pages/admin/Audit.svelte",
+    "../web/src/pages/admin/ClientDetail.svelte",
+    "../web/src/pages/admin/Clients.svelte",
+    "../web/src/pages/admin/Groups.svelte",
+    "../web/src/pages/admin/Keys.svelte",
+    "../web/src/pages/admin/Reserved.svelte",
+    "../web/src/pages/admin/UserDetail.svelte",
+    "../web/src/pages/admin/Users.svelte"
+  ]
+}
\ No newline at end of file
diff --git a/migrations/0005_password_resets.sql b/migrations/0005_password_resets.sql
new file mode 100644
index 0000000..fe29635
--- /dev/null
+++ b/migrations/0005_password_resets.sql
@@ -0,0 +1,15 @@
+-- migrations/0005_password_resets.sql
+-- Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+-- Licensed under the DASL-1.2 Licence.
+
+-- "Forgot password" links. Only sent to verified addresses. `email` is the
+-- address the link went to, so it stops working if the address changes.
+CREATE TABLE password_resets (
+  token_hash TEXT PRIMARY KEY,
+  user_id    TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  email      TEXT NOT NULL,
+  created_at INTEGER NOT NULL,
+  expires_at INTEGER NOT NULL
+);
+
+CREATE INDEX password_resets_user ON password_resets (user_id);
diff --git a/migrations/0006_client_home_urls.sql b/migrations/0006_client_home_urls.sql
new file mode 100644
index 0000000..7cd4746
--- /dev/null
+++ b/migrations/0006_client_home_urls.sql
@@ -0,0 +1,7 @@
+-- migrations/0006_client_home_urls.sql
+-- Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+-- Licensed under the DASL-1.2 Licence.
+
+-- Where an application lives, for the "Your apps" page. Apps without one
+-- still sign people in; they just aren't listed there.
+ALTER TABLE clients ADD COLUMN home_url TEXT;
diff --git a/package.json b/package.json
index 2c83b05..ca74ab8 100644
--- a/package.json
+++ b/package.json
@@ -6,23 +6,28 @@
   "private": true,
   "scripts": {
     "dev": "wrangler dev",
+    "build": "vite build",
     "deploy": "wrangler deploy",
     "db:migrate:local": "wrangler d1 migrations apply auth-server --local",
     "db:migrate:remote": "wrangler d1 migrations apply auth-server --remote",
     "cf-typegen": "wrangler types --env-interface Env",
-    "typecheck": "tsc --noEmit"
+    "typecheck": "node node_modules/@typescript/native/bin/tsc --noEmit && svelte-check --tsgo --tsconfig ./web/tsconfig.json"
   },
   "dependencies": {
     "@simplewebauthn/server": "^14.0.2",
     "hono": "^4.13.8",
     "jose": "^6.2.12",
-    "pixelarticons": "^2.4.1",
     "uqr": "^0.1.3"
   },
   "devDependencies": {
     "@cloudflare/workers-types": "^5.20260916.1",
-    "@types/react": "^19.3.0",
-    "typescript": "^7.0.2",
+    "@lucide/svelte": "^1.63.0",
+    "@sveltejs/vite-plugin-svelte": "^7.3.1",
+    "@typescript/native": "npm:typescript@7",
+    "svelte": "^5.57.3",
+    "svelte-check": "^4.7.7",
+    "typescript": "~6",
+    "vite": "^8.3.5",
     "wrangler": "^4.132.0"
   }
 }
diff --git a/public/_headers b/public/_headers
deleted file mode 100644
index 7766872..0000000
--- a/public/_headers
+++ /dev/null
@@ -1,3 +0,0 @@
-/static/*
-  X-Content-Type-Options: nosniff
-  Cache-Control: public, max-age=3600
diff --git a/public/static/app.js b/public/static/app.js
deleted file mode 100644
index 8be602c..0000000
--- a/public/static/app.js
+++ /dev/null
@@ -1,250 +0,0 @@
-/* public/static/app.js
- * 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.
- */
-
-"use strict";
-
-// --- base64url <-> ArrayBuffer, for browsers without the WebAuthn JSON helpers --
-
-function toBuffer(b64url) {
-  const b64 = b64url.replace(/-/g, "+").replace(/_/g, "/");
-  const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
-  const out = new Uint8Array(bin.length);
-  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
-  return out.buffer;
-}
-
-function toB64url(buffer) {
-  if (!buffer) return undefined;
-  const bytes = new Uint8Array(buffer);
-  let bin = "";
-  for (const b of bytes) bin += String.fromCharCode(b);
-  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
-}
-
-function creationOptions(json) {
-  if (PublicKeyCredential.parseCreationOptionsFromJSON) {
-    return PublicKeyCredential.parseCreationOptionsFromJSON(json);
-  }
-  return {
-    ...json,
-    challenge: toBuffer(json.challenge),
-    user: { ...json.user, id: toBuffer(json.user.id) },
-    excludeCredentials: (json.excludeCredentials || []).map((c) => ({ ...c, id: toBuffer(c.id) })),
-  };
-}
-
-function requestOptions(json) {
-  if (PublicKeyCredential.parseRequestOptionsFromJSON) {
-    return PublicKeyCredential.parseRequestOptionsFromJSON(json);
-  }
-  return {
-    ...json,
-    challenge: toBuffer(json.challenge),
-    allowCredentials: (json.allowCredentials || []).map((c) => ({ ...c, id: toBuffer(c.id) })),
-  };
-}
-
-function credentialJSON(cred) {
-  try {
-    if (typeof cred.toJSON === "function") return cred.toJSON();
-  } catch {
-    // Some password managers return objects whose toJSON throws; build it by hand.
-  }
-  const r = cred.response;
-  const response = { clientDataJSON: toB64url(r.clientDataJSON) };
-  if (r.attestationObject) {
-    response.attestationObject = toB64url(r.attestationObject);
-    response.transports = typeof r.getTransports === "function" ? r.getTransports() : [];
-  } else {
-    response.authenticatorData = toB64url(r.authenticatorData);
-    response.signature = toB64url(r.signature);
-    response.userHandle = toB64url(r.userHandle);
-  }
-  return {
-    id: cred.id,
-    rawId: toB64url(cred.rawId),
-    type: cred.type,
-    authenticatorAttachment: cred.authenticatorAttachment || undefined,
-    clientExtensionResults: cred.getClientExtensionResults(),
-    response,
-  };
-}
-
-async function postJSON(url, body) {
-  const headers = { "Content-Type": "application/json" };
-  const csrf = document.body.dataset.csrf;
-  if (csrf) headers["X-CSRF-Token"] = csrf;
-  const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(body || {}), credentials: "same-origin" });
-  let data = {};
-  try {
-    data = await res.json();
-  } catch {
-    // non-JSON error page
-  }
-  if (!res.ok) throw new Error(data.error || "Something went wrong. Please try again.");
-  return data;
-}
-
-function showError(message) {
-  const el = document.getElementById("passkey-error");
-  if (!el) return;
-  el.textContent = message;
-  el.classList.toggle("hidden", !message);
-}
-
-function webauthnMessage(err) {
-  if (!err) return "Something went wrong. Please try again.";
-  if (err.name === "NotAllowedError" || err.name === "AbortError") return "";
-  if (err.name === "InvalidStateError") return "That passkey is already registered to your account.";
-  if (err.name === "SecurityError") return "Passkeys can't be used on this address.";
-  return err.message || "Something went wrong. Please try again.";
-}
-
-// --- sign in ---------------------------------------------------------------------
-
-function initLogin() {
-  const root = document.getElementById("login");
-  const button = document.getElementById("passkey-signin");
-  if (!root || !button) return;
-
-  if (!window.PublicKeyCredential) {
-    button.disabled = true;
-    button.textContent = "Passkeys aren't supported in this browser";
-    return;
-  }
-
-  const returnTo = root.dataset.return || "/account";
-  let conditional = null;
-
-  async function signIn(mediation) {
-    const { id, options } = await postJSON("/login/passkey/options");
-    const request = { publicKey: requestOptions(options) };
-    if (mediation === "conditional") {
-      conditional = new AbortController();
-      request.mediation = "conditional";
-      request.signal = conditional.signal;
-    }
-    const cred = await navigator.credentials.get(request);
-    if (!cred) return;
-    showError("");
-    const result = await postJSON("/login/passkey/verify", { id, response: credentialJSON(cred), return: returnTo });
-    window.location.href = result.redirect;
-  }
-
-  button.addEventListener("click", async () => {
-    if (conditional) conditional.abort();
-    button.disabled = true;
-    try {
-      await signIn("modal");
-    } catch (err) {
-      showError(webauthnMessage(err));
-    } finally {
-      button.disabled = false;
-      startConditional();
-    }
-  });
-
-  // Offer saved passkeys straight from the username field's autofill.
-  async function startConditional() {
-    if (!PublicKeyCredential.isConditionalMediationAvailable) return;
-    if (!(await PublicKeyCredential.isConditionalMediationAvailable())) return;
-    try {
-      await signIn("conditional");
-    } catch (err) {
-      if (err && err.name !== "AbortError") showError(webauthnMessage(err));
-    }
-  }
-  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() {
-  const formEl = document.getElementById("passkey-add");
-  if (!formEl) return;
-  const button = formEl.querySelector("button");
-
-  if (!window.PublicKeyCredential) {
-    button.disabled = true;
-    button.textContent = "Passkeys aren't supported in this browser";
-    return;
-  }
-
-  formEl.addEventListener("submit", async (ev) => {
-    ev.preventDefault();
-    showError("");
-    button.disabled = true;
-    try {
-      const name = formEl.querySelector('input[name="name"]').value.trim();
-      const { id, options } = await postJSON("/account/passkeys/options");
-      const cred = await navigator.credentials.create({ publicKey: creationOptions(options) });
-      if (!cred) return;
-      const result = await postJSON("/account/passkeys/verify", { id, response: credentialJSON(cred), name });
-      window.location.href = result.redirect;
-    } catch (err) {
-      showError(webauthnMessage(err));
-    } finally {
-      button.disabled = false;
-    }
-  });
-}
-
-// --- shared --------------------------------------------------------------------------
-
-document.addEventListener("submit", (ev) => {
-  const message = ev.target.dataset && ev.target.dataset.confirm;
-  if (message && !window.confirm(message)) ev.preventDefault();
-});
-
-document.addEventListener("click", async (ev) => {
-  const button = ev.target.closest && ev.target.closest("[data-copy]");
-  if (!button) return;
-  try {
-    await navigator.clipboard.writeText(button.dataset.copy);
-    const label = button.textContent;
-    button.textContent = "Copied";
-    setTimeout(() => (button.textContent = label), 1500);
-  } catch {
-    const input = button.parentElement.querySelector("input");
-    if (input) input.select();
-  }
-});
-
-document.addEventListener("DOMContentLoaded", () => {
-  const page = document.body.dataset.page;
-  if (page === "login") initLogin();
-  if (page === "mfa") initMfa();
-  if (page === "account") initAccount();
-});
diff --git a/src/api/account.ts b/src/api/account.ts
new file mode 100644
index 0000000..209db1f
--- /dev/null
+++ b/src/api/account.ts
@@ -0,0 +1,338 @@
+/* src/api/account.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 { Hono } from "hono";
+import { renderSVG } from "uqr";
+import type { RegistrationResponseJSON } from "@simplewebauthn/server";
+import { ADMIN_GROUP, siteName, type AppContext, type AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { decrypt, encrypt } from "../lib/crypto";
+import { amrLabel, describeAgent } from "../lib/format";
+import { isRecentAuth, requireCsrf, requireRecentAuth, requireUser } from "../lib/guards";
+import { body, fail, readJson, str } from "../lib/http";
+import { hashPassword, passwordProblem, verifyPassword } from "../lib/password";
+import { attempt } from "../lib/ratelimit";
+import { generateTotpSecret, otpauthUri, verifyTotp } from "../lib/totp";
+import { cleanText, emailProblem, pictureProblem } from "../lib/validate";
+import {
+  countPasskeys,
+  deletePasskey,
+  finishRegistration,
+  listPasskeys,
+  registrationOptions,
+  renamePasskey,
+} from "../data/passkeys";
+import { notify, notifyAccountDeleted, signOutDevice } from "../data/notices";
+import { endSession, listSessions, revokeOtherSessions } from "../data/sessions";
+import {
+  claimTotpStep,
+  deleteUser,
+  disableTotp,
+  enableTotp,
+  getUser,
+  setPasswordHash,
+  setTotpPending,
+  updateProfile,
+  type UserRow,
+} from "../data/users";
+import { sendVerificationEmail } from "../data/verifications";
+import { TOTP_USER_LIMIT } from "./login";
+
+export const account = new Hono<AppEnv>();
+
+account.use("/api/account", requireUser);
+account.use("/api/account/*", requireUser, requireCsrf);
+// Anything that changes how the account signs in, or deletes it.
+for (const path of [
+  "/api/account/passkeys/options",
+  "/api/account/passkeys/verify",
+  "/api/account/passkeys/:id/delete",
+  "/api/account/password",
+  "/api/account/password/remove",
+  "/api/account/totp/*",
+  "/api/account/delete",
+]) {
+  account.post(path, requireRecentAuth);
+}
+
+async function me(c: AppContext): Promise<UserRow> {
+  const user = await getUser(c.env, c.get("user")!.id);
+  if (!user) throw new Error("session user vanished");
+  return user;
+}
+
+/** Everything the account page shows. Secrets never leave: only whether they're set. */
+account.get("/api/account", async (c) => {
+  const user = await me(c);
+  const session = c.get("session")!;
+  const [passkeys, sessions] = await Promise.all([listPasskeys(c.env, user.id), listSessions(c.env, user.id)]);
+  return c.json({
+    username: user.username,
+    name: user.name,
+    email: user.email,
+    emailVerified: Boolean(user.email_verified),
+    picture: user.picture,
+    hasPassword: Boolean(user.password_hash),
+    totp: Boolean(user.totp_secret),
+    recentAuth: isRecentAuth(session.authTime),
+    passkeys: passkeys.map((p) => ({
+      id: p.id,
+      name: p.name,
+      synced: p.device_type === "multiDevice",
+      createdAt: p.created_at,
+      lastUsedAt: p.last_used_at,
+    })),
+    sessions: sessions.map((s) => ({
+      id: s.id_hash,
+      current: s.id_hash === session.idHash,
+      device: describeAgent(s.user_agent),
+      ip: s.ip,
+      method: amrLabel(JSON.parse(s.amr) as string[]),
+      createdAt: s.created_at,
+      lastSeenAt: s.last_seen_at,
+    })),
+  });
+});
+
+account.post("/api/account/profile", async (c) => {
+  const b = await body(c);
+  const update = {
+    name: cleanText(str(b.name), 100),
+    email: cleanText(str(b.email), 254),
+    picture: cleanText(str(b.picture), 2048),
+  };
+  const problem = emailProblem(update.email) ?? pictureProblem(update.picture);
+  if (problem) return fail(c, problem);
+
+  const user = await me(c);
+  const emailChanged = update.email !== user.email;
+  // The email address receives security notices, so swapping it is as
+  // sensitive as changing the password.
+  if (emailChanged && !isRecentAuth(c.get("session")!.authTime)) {
+    return fail(c, "For your security, confirm it's you before changing your email address.", 401, { reauth: true });
+  }
+  await updateProfile(c.env, user, update);
+  await audit(c, "account.profile");
+
+  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 && emailChanged) {
+    const sent = await sendVerificationEmail(c.env, user.id, update.email);
+    return c.json({ message: sent === "sent" ? "verify-sent" : "verify-failed" });
+  }
+  return c.json({ message: "profile-saved" });
+});
+
+account.post("/api/account/email/verify", async (c) => {
+  const user = await me(c);
+  if (!user.email || user.email_verified) return c.json({ message: null });
+  const sent = await sendVerificationEmail(c.env, user.id, user.email);
+  return c.json({ message: sent === "sent" ? "verify-sent" : "verify-failed" });
+});
+
+// --- passkeys --------------------------------------------------------------------
+
+account.post("/api/account/passkeys/options", async (c) => {
+  return c.json(await registrationOptions(c.env, await me(c)));
+});
+
+account.post("/api/account/passkeys/verify", async (c) => {
+  const b = await readJson<{ id?: string; response?: RegistrationResponseJSON; name?: string }>(c);
+  if (!b?.id || !b.response) return fail(c, "Malformed request.");
+
+  const name = cleanText(str(b.name), 60) ?? "Passkey";
+  const result = await finishRegistration(c.env, await me(c), b.id, b.response, name);
+  if (!result.ok) return fail(c, result.error);
+
+  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({ message: "passkey-added" });
+});
+
+account.post("/api/account/passkeys/:id/rename", async (c) => {
+  const name = cleanText(str((await body(c)).name), 60);
+  if (!name) return fail(c, "Passkeys need a name.");
+  await renamePasskey(c.env, c.get("user")!.id, c.req.param("id"), name);
+  return c.json({ message: "passkey-renamed" });
+});
+
+account.post("/api/account/passkeys/:id/delete", async (c) => {
+  const user = await me(c);
+  if (!user.password_hash && (await countPasskeys(c.env, user.id)) <= 1) {
+    return fail(c, "That's your only way to sign in. Add another passkey or a password before removing it.");
+  }
+  const name = await deletePasskey(c.env, user.id, c.req.param("id"));
+  if (name) {
+    await audit(c, "account.passkey_removed", { detail: name });
+    notify(c, user.id, {
+      subject: "A passkey was removed",
+      summary: `The passkey "${name}" was removed from your account.`,
+      by: "self",
+    });
+  }
+  return c.json({ message: "passkey-removed" });
+});
+
+// --- password ------------------------------------------------------------------
+
+account.post("/api/account/password", async (c) => {
+  const user = await me(c);
+  const b = await body(c);
+  const password = str(b.password);
+  const problem =
+    passwordProblem(password, user.username) ?? (password !== str(b.confirm) ? "The two passwords don't match." : null);
+  if (problem) return fail(c, problem);
+
+  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.json({ message: "password-set" });
+});
+
+account.post("/api/account/password/remove", async (c) => {
+  const user = await me(c);
+  if ((await countPasskeys(c.env, user.id)) === 0) return fail(c, "Add a passkey before removing your password.");
+  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.json({ message: "password-removed" });
+});
+
+// --- TOTP ----------------------------------------------------------------------
+
+/** Starts (or restarts) setup and returns what the authenticator app needs. */
+account.post("/api/account/totp/start", async (c) => {
+  const user = await me(c);
+  if (!user.password_hash) return fail(c, "Set a password first.");
+  if (user.totp_secret) return fail(c, "Two-factor codes are already on.", 409);
+
+  const secret = generateTotpSecret();
+  await setTotpPending(c.env, user.id, await encrypt(c.env.KEY_ENCRYPTION_KEY, secret));
+  const uri = otpauthUri(secret, siteName(c.env), user.username);
+  return c.json({
+    qr: `data:image/svg+xml,${encodeURIComponent(renderSVG(uri, { border: 2 }))}`,
+    secret: secret.match(/.{1,4}/g)?.join(" ") ?? secret,
+  });
+});
+
+account.post("/api/account/totp/confirm", async (c) => {
+  const user = await me(c);
+  if (!user.totp_pending) return fail(c, "Setup expired. Start again.", 409);
+
+  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_pending);
+  const step = await verifyTotp(secret, str((await body(c)).code), 0);
+  if (step === null) return fail(c, "That code didn't match. Check your device's clock and try the next one.");
+
+  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.json({ message: "totp-enabled" });
+});
+
+account.post("/api/account/totp/disable", async (c) => {
+  const user = await me(c);
+  if (!user.totp_secret) return c.json({ message: "totp-disabled" });
+
+  if (!(await attempt(c.env, `totp-user:${user.id}`, TOTP_USER_LIMIT, 15 * 60))) {
+    return fail(c, "Too many codes tried. Wait a few minutes and try again.", 429);
+  }
+  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_secret);
+  const step = await verifyTotp(secret, str((await body(c)).code), user.totp_last_step);
+  if (step === null || !(await claimTotpStep(c.env, user.id, step))) {
+    return fail(c, "That code didn't work, so two-factor codes are still on.");
+  }
+  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.json({ message: "totp-disabled" });
+});
+
+// --- sessions ------------------------------------------------------------------
+
+account.post("/api/account/sessions/revoke-others", async (c) => {
+  await revokeOtherSessions(c.env, c.get("user")!.id, c.get("session")!.idHash);
+  await audit(c, "account.sessions_revoked");
+  return c.json({ message: "sessions-revoked" });
+});
+
+account.post("/api/account/sessions/:id/revoke", async (c) => {
+  const id = c.req.param("id");
+  if (id === c.get("session")!.idHash) {
+    await endSession(c);
+    return c.json({ redirect: "/login?m=signed-out" });
+  }
+  await signOutDevice(c.env, c.get("user")!.id, id);
+  await audit(c, "account.session_revoked");
+  return c.json({ message: "session-revoked" });
+});
+
+// --- deletion --------------------------------------------------------------------
+
+account.post("/api/account/delete", async (c) => {
+  const user = await me(c);
+  const b = await body(c);
+
+  if (str(b.confirm).trim().toLowerCase() !== user.username.toLowerCase()) {
+    return fail(c, "Type your username exactly to delete your account.");
+  }
+  if (user.password_hash && !(await verifyPassword(str(b.password).slice(0, 512), user.password_hash))) {
+    return fail(c, "That password isn't right, so your account wasn't deleted.");
+  }
+  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 fail(c, `You're the only admin. Add another member to ${ADMIN_GROUP} before deleting your account.`);
+    }
+  }
+
+  // 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.json({ redirect: "/login?m=account-deleted" });
+});
diff --git a/src/api/admin.ts b/src/api/admin.ts
new file mode 100644
index 0000000..584a01d
--- /dev/null
+++ b/src/api/admin.ts
@@ -0,0 +1,494 @@
+/* src/api/admin.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 { Hono } from "hono";
+import { ADMIN_GROUP, issuer, type AppContext, type AppEnv } from "../env";
+import { audit, recentAudit } from "../lib/audit";
+import { requireAdmin, requireCsrf, requireUser } from "../lib/guards";
+import { body, fail, lines, str, strings } from "../lib/http";
+import {
+  cleanText,
+  clientIdProblem,
+  homeUrlProblem,
+  emailProblem,
+  groupProblem,
+  normaliseUsername,
+  pictureProblem,
+  redirectUriProblem,
+  subjectProblem,
+  usernameProblem,
+} from "../lib/validate";
+import {
+  createClient,
+  deleteClient,
+  getClient,
+  listClients,
+  makeClientPublic,
+  rotateClientSecret,
+  updateClient,
+  type Client,
+  type ClientInput,
+} from "../data/clients";
+import { createGroup, deleteGroup, listGroups, updateGroup } from "../data/groups";
+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 { builtinReserved, listReserved, lookalikeOf, reserveUsername, unreserveUsername } from "../data/reserved";
+import { listSessions } from "../data/sessions";
+import {
+  adminUpdateUser,
+  createUser,
+  deleteUser,
+  disableTotp,
+  getUser,
+  groupsFor,
+  listUsers,
+  revokeAllStatements,
+  setDisabled,
+  setPasswordHash,
+  setUserGroups,
+} from "../data/users";
+
+export const admin = new Hono<AppEnv>();
+
+admin.use("/api/admin/*", requireUser, requireAdmin, requireCsrf);
+
+/** Admins may hand out reserved names, but not ones that pass for another account. */
+async function lookalikeProblem(c: AppContext, username: string, exceptId: string | null = null): Promise<string | null> {
+  const other = await lookalikeOf(c.env, username, exceptId);
+  if (!other) return null;
+  return other === username ? "That username is already taken." : `That username looks too much like @${other}.`;
+}
+
+const notFound = (c: AppContext, what: string) => fail(c, `That ${what} doesn't exist.`, 404);
+const ok = (c: AppContext, message: string) => c.json({ message });
+
+// --- users -----------------------------------------------------------------------
+
+admin.get("/api/admin/users", async (c) => {
+  const users = await listUsers(c.env);
+  return c.json(
+    users.map((u) => ({
+      id: u.id,
+      username: u.username,
+      name: u.name,
+      disabled: Boolean(u.disabled),
+      groups: u.groups,
+      passkeys: u.passkey_count,
+      hasPassword: Boolean(u.password_hash),
+      totp: Boolean(u.totp_secret),
+      lastLoginAt: u.last_login_at,
+    })),
+  );
+});
+
+admin.post("/api/admin/users", async (c) => {
+  const b = await body(c);
+  const username = normaliseUsername(str(b.username));
+  const email = cleanText(str(b.email), 254);
+  const subject = cleanText(str(b.subject), 64);
+  const problem =
+    usernameProblem(username) ??
+    emailProblem(email) ??
+    (subject ? subjectProblem(subject) : null) ??
+    (await lookalikeProblem(c, username));
+  if (problem) return fail(c, problem);
+
+  const result = await createUser(c.env, {
+    id: subject ?? undefined,
+    username,
+    name: cleanText(str(b.name), 100),
+    email,
+    emailVerified: b.emailVerified === true,
+  });
+  if (!result.ok) return fail(c, result.error, 409);
+
+  const groups = strings(b.groups);
+  await setUserGroups(c.env, result.id, groups);
+  await audit(c, "admin.user_created", { target: username, detail: groups.join(",") });
+  return c.json({ id: result.id, message: "user-created" });
+});
+
+admin.get("/api/admin/users/:id", async (c) => {
+  const id = c.req.param("id");
+  const user = await getUser(c.env, id);
+  if (!user) return notFound(c, "user");
+  const [groups, passkeys, sessions, openLink] = await Promise.all([
+    groupsFor(c.env, id),
+    listPasskeys(c.env, id),
+    listSessions(c.env, id),
+    hasOpenLoginLink(c.env, id),
+  ]);
+  return c.json({
+    id: user.id,
+    username: user.username,
+    name: user.name,
+    email: user.email,
+    emailVerified: Boolean(user.email_verified),
+    picture: user.picture,
+    disabled: Boolean(user.disabled),
+    createdAt: user.created_at,
+    lastLoginAt: user.last_login_at,
+    hasPassword: Boolean(user.password_hash),
+    totp: Boolean(user.totp_secret),
+    groups,
+    passkeys: passkeys.map((p) => ({ id: p.id, name: p.name, createdAt: p.created_at, lastUsedAt: p.last_used_at })),
+    sessionCount: sessions.length,
+    openLinkExpiresAt: openLink,
+    self: c.get("user")!.id === id,
+  });
+});
+
+admin.post("/api/admin/users/:id/profile", async (c) => {
+  const id = c.req.param("id");
+  const b = await body(c);
+  const update = {
+    username: normaliseUsername(str(b.username)),
+    name: cleanText(str(b.name), 100),
+    email: cleanText(str(b.email), 254),
+    picture: cleanText(str(b.picture), 2048),
+    emailVerified: b.emailVerified === true,
+  };
+  const problem =
+    usernameProblem(update.username) ??
+    emailProblem(update.email) ??
+    pictureProblem(update.picture) ??
+    (await lookalikeProblem(c, update.username, id));
+  if (problem) return fail(c, problem);
+
+  const before = await getUser(c.env, id);
+  if (!before) return notFound(c, "user");
+  const error = await adminUpdateUser(c.env, id, update);
+  if (error) return fail(c, error, 409);
+  await audit(c, "admin.user_updated", { target: id });
+
+  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 ok(c, "user-saved");
+});
+
+admin.post("/api/admin/users/:id/groups", async (c) => {
+  const id = c.req.param("id");
+  const groups = strings((await body(c)).groups);
+  if (id === c.get("user")!.id && !groups.includes(ADMIN_GROUP)) {
+    return fail(c, `You can't remove yourself from ${ADMIN_GROUP}. Ask another admin.`);
+  }
+  await setUserGroups(c.env, id, groups);
+  await audit(c, "admin.user_groups", { target: id, detail: groups.join(",") });
+  return ok(c, "groups-saved");
+});
+
+const LINK_TTLS = new Set([900, 3600, 86400, 604800]);
+
+/** Returns the link itself: shown once, never stored in plaintext. */
+admin.post("/api/admin/users/:id/link", async (c) => {
+  const id = c.req.param("id");
+  const user = await getUser(c.env, id);
+  if (!user) return notFound(c, "user");
+  if (user.disabled) return fail(c, "Enable the account before sending a sign-in link.");
+
+  const asked = Number((await body(c)).ttl);
+  const ttl = LINK_TTLS.has(asked) ? asked : 3600;
+  const link = await createLoginLink(c.env, id, c.get("user")!.id, ttl);
+  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 c.json(link);
+});
+
+admin.post("/api/admin/users/:id/link/revoke", async (c) => {
+  const id = c.req.param("id");
+  await revokeLoginLinks(c.env, id);
+  await audit(c, "admin.link_revoked", { target: id });
+  return ok(c, "link-revoked");
+});
+
+admin.post("/api/admin/users/:id/passkeys/:pid/delete", async (c) => {
+  const id = c.req.param("id");
+  const name = await deletePasskey(c.env, id, c.req.param("pid"));
+  if (name) {
+    await audit(c, "admin.passkey_removed", { target: id, detail: name });
+    notify(c, id, { subject: "A passkey was removed", summary: `An administrator removed your passkey "${name}".`, by: "admin" });
+  }
+  return ok(c, "credential-removed");
+});
+
+admin.post("/api/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 ok(c, "credential-removed");
+});
+
+admin.post("/api/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 ok(c, "credential-removed");
+});
+
+admin.post("/api/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.json({ redirect: "/login?m=signed-out" });
+  return ok(c, "user-signed-out");
+});
+
+admin.post("/api/admin/users/:id/disable", async (c) => {
+  const id = c.req.param("id");
+  if (id === c.get("user")!.id) return fail(c, "You can't disable your own account.");
+  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 ok(c, "user-disabled");
+});
+
+admin.post("/api/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 ok(c, "user-enabled");
+});
+
+admin.post("/api/admin/users/:id/delete", async (c) => {
+  const id = c.req.param("id");
+  const user = await getUser(c.env, id);
+  if (!user) return notFound(c, "user");
+  if (id === c.get("user")!.id) return fail(c, "You can't delete your own account.");
+  if (normaliseUsername(str((await body(c)).confirm)) !== user.username) {
+    return fail(c, "Type the username exactly to delete the account.");
+  }
+  await deleteUser(c.env, id);
+  await audit(c, "admin.user_deleted", { target: `${user.username} (${id})` });
+  return ok(c, "user-deleted");
+});
+
+// --- groups ----------------------------------------------------------------------
+
+admin.get("/api/admin/groups", async (c) => {
+  const groups = await listGroups(c.env);
+  return c.json(groups.map((g) => ({ name: g.name, description: g.description, members: g.member_count })));
+});
+
+admin.post("/api/admin/groups", async (c) => {
+  const b = await body(c);
+  const name = str(b.name).trim().toLowerCase();
+  const problem = groupProblem(name);
+  if (problem) return fail(c, problem);
+  if (!(await createGroup(c.env, name, cleanText(str(b.description), 200) ?? ""))) {
+    return fail(c, "A group with that name already exists.", 409);
+  }
+  await audit(c, "admin.group_created", { target: name });
+  return ok(c, "group-created");
+});
+
+admin.post("/api/admin/groups/:name", async (c) => {
+  const name = c.req.param("name");
+  await updateGroup(c.env, name, cleanText(str((await body(c)).description), 200) ?? "");
+  await audit(c, "admin.group_updated", { target: name });
+  return ok(c, "group-saved");
+});
+
+admin.post("/api/admin/groups/:name/delete", async (c) => {
+  const name = c.req.param("name");
+  if (name === ADMIN_GROUP) return fail(c, `${ADMIN_GROUP} can't be deleted.`);
+  await deleteGroup(c.env, name);
+  await audit(c, "admin.group_deleted", { target: name });
+  return ok(c, "group-deleted");
+});
+
+// --- reserved usernames ------------------------------------------------------------
+
+admin.get("/api/admin/reserved", async (c) => {
+  const reserved = await listReserved(c.env);
+  return c.json({
+    reserved: reserved.map((r) => ({ username: r.username, note: r.note, createdAt: r.created_at })),
+    builtin: builtinReserved(),
+  });
+});
+
+admin.post("/api/admin/reserved", async (c) => {
+  const b = await body(c);
+  const username = normaliseUsername(str(b.username));
+  const problem = usernameProblem(username);
+  if (problem) return fail(c, problem);
+  if (!(await reserveUsername(c.env, username, cleanText(str(b.note), 200) ?? ""))) {
+    return fail(c, "That name is already reserved.", 409);
+  }
+  await audit(c, "admin.username_reserved", { target: username });
+  return ok(c, "name-reserved");
+});
+
+admin.post("/api/admin/reserved/:name/delete", async (c) => {
+  const name = c.req.param("name");
+  await unreserveUsername(c.env, name);
+  await audit(c, "admin.username_released", { target: name });
+  return ok(c, "name-released");
+});
+
+// --- clients -----------------------------------------------------------------------
+
+async function readClient(c: AppContext, b: Record<string, unknown>): Promise<ClientInput | string> {
+  const known = new Set((await listGroups(c.env)).map((g) => g.name));
+  const name = cleanText(str(b.name), 100);
+  const homeUrl = cleanText(str(b.homeUrl), 2048);
+  const redirectUris = lines(str(b.redirectUris));
+  const postLogoutRedirectUris = lines(str(b.postLogoutRedirectUris));
+
+  if (!name) return "Applications need a name.";
+  const urlProblem = homeUrlProblem(homeUrl);
+  if (urlProblem) return urlProblem;
+  if (redirectUris.length === 0) return "Add at least one redirect URI.";
+  if (redirectUris.length + postLogoutRedirectUris.length > 40) return "That's too many URIs.";
+  for (const uri of [...redirectUris, ...postLogoutRedirectUris]) {
+    const problem = redirectUriProblem(uri);
+    if (problem) return problem;
+  }
+  return {
+    name,
+    homeUrl,
+    redirectUris: [...new Set(redirectUris)],
+    postLogoutRedirectUris: [...new Set(postLogoutRedirectUris)],
+    allowedGroups: strings(b.allowedGroups).filter((g) => known.has(g)),
+  };
+}
+
+function clientJson(c: AppContext, client: Client) {
+  const iss = issuer(c.env);
+  return {
+    id: client.id,
+    name: client.name,
+    homeUrl: client.homeUrl,
+    isPublic: client.isPublic,
+    redirectUris: client.redirectUris,
+    postLogoutRedirectUris: client.postLogoutRedirectUris,
+    allowedGroups: client.allowedGroups,
+    issuer: iss,
+    discovery: `${iss}/.well-known/openid-configuration`,
+  };
+}
+
+admin.get("/api/admin/clients", async (c) => {
+  const clients = await listClients(c.env);
+  return c.json(clients.map((cl) => clientJson(c, cl)));
+});
+
+/** Confidential clients get their secret back here, exactly once. */
+admin.post("/api/admin/clients", async (c) => {
+  const b = await body(c);
+  const input = await readClient(c, b);
+  if (typeof input === "string") return fail(c, input);
+
+  const id = cleanText(str(b.clientId), 128) ?? crypto.randomUUID();
+  const idProblem = clientIdProblem(id);
+  if (idProblem) return fail(c, idProblem);
+
+  const result = await createClient(c.env, id, b.type !== "public", input);
+  if (!result.ok) return fail(c, result.error, 409);
+  await audit(c, "admin.client_created", { target: id });
+  return c.json({ id, secret: result.secret });
+});
+
+admin.get("/api/admin/clients/:id", async (c) => {
+  const client = await getClient(c.env, c.req.param("id"));
+  if (!client) return notFound(c, "application");
+  return c.json(clientJson(c, client));
+});
+
+admin.post("/api/admin/clients/:id", async (c) => {
+  const id = c.req.param("id");
+  if (!(await getClient(c.env, id))) return notFound(c, "application");
+  const input = await readClient(c, await body(c));
+  if (typeof input === "string") return fail(c, input);
+  await updateClient(c.env, id, input);
+  await audit(c, "admin.client_updated", { target: id });
+  return ok(c, "client-saved");
+});
+
+admin.post("/api/admin/clients/:id/secret", async (c) => {
+  const id = c.req.param("id");
+  if (!(await getClient(c.env, id))) return notFound(c, "application");
+  const secret = await rotateClientSecret(c.env, id);
+  await audit(c, "admin.client_secret_rotated", { target: id });
+  return c.json({ secret });
+});
+
+admin.post("/api/admin/clients/:id/public", async (c) => {
+  const id = c.req.param("id");
+  await makeClientPublic(c.env, id);
+  await audit(c, "admin.client_made_public", { target: id });
+  return ok(c, "client-public");
+});
+
+admin.post("/api/admin/clients/:id/delete", async (c) => {
+  const id = c.req.param("id");
+  await deleteClient(c.env, id);
+  await audit(c, "admin.client_deleted", { target: id });
+  return ok(c, "client-deleted");
+});
+
+// --- keys + audit ------------------------------------------------------------------
+
+admin.get("/api/admin/keys", async (c) => {
+  const keys = await listKeys(c.env);
+  return c.json(keys.map((k) => ({ kid: k.kid, alg: k.alg, createdAt: k.created_at, retiredAt: k.retired_at })));
+});
+
+admin.post("/api/admin/keys/rotate", async (c) => {
+  const kid = await rotateKeys(c.env);
+  await audit(c, "admin.keys_rotated", { target: kid });
+  return ok(c, "keys-rotated");
+});
+
+admin.get("/api/admin/audit", async (c) => {
+  const entries = await recentAudit(c);
+  return c.json(
+    entries.map((e) => ({
+      id: e.id,
+      at: e.at,
+      actor: e.actor_username,
+      action: e.action,
+      target: e.target,
+      ip: e.ip,
+      detail: e.detail,
+    })),
+  );
+});
diff --git a/src/api/apps.ts b/src/api/apps.ts
new file mode 100644
index 0000000..6081180
--- /dev/null
+++ b/src/api/apps.ts
@@ -0,0 +1,26 @@
+/* src/api/apps.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 { Hono } from "hono";
+import type { AppEnv } from "../env";
+import { requireUser } from "../lib/guards";
+import { clientAllows, listClients } from "../data/clients";
+
+export const apps = new Hono<AppEnv>();
+
+/**
+ * The apps this account may sign in to, for the "Your apps" page: the same
+ * group check /authorize makes, limited to apps that have a website to open.
+ */
+apps.get("/api/apps", requireUser, async (c) => {
+  const groups = c.get("user")!.groups;
+  const clients = await listClients(c.env);
+  return c.json(
+    clients
+      .filter((cl) => cl.homeUrl && clientAllows(cl, groups))
+      .map((cl) => ({ id: cl.id, name: cl.name, url: cl.homeUrl })),
+  );
+});
diff --git a/src/api/emailed.ts b/src/api/emailed.ts
new file mode 100644
index 0000000..b434737
--- /dev/null
+++ b/src/api/emailed.ts
@@ -0,0 +1,129 @@
+/* src/api/emailed.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.
+ *
+ * The links we email: verify an address, "wasn't me" sign-outs, and password
+ * resets. They work without signing in. Mail scanners follow GETs, so a GET
+ * only looks a link up; using it always takes a POST from the page.
+ */
+
+import { Hono } from "hono";
+import type { AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { body, clientIp, fail, str } from "../lib/http";
+import { hashPassword, passwordProblem } from "../lib/password";
+import { attempt } from "../lib/ratelimit";
+import { notify, peekSignoutLink, signOutDevice, signOutEverywhere } from "../data/notices";
+import { consumePasswordReset, peekPasswordReset, resetCandidates, sendPasswordReset } from "../data/resets";
+import { endSession } from "../data/sessions";
+import { consumeEmailVerification, peekEmailVerification } from "../data/verifications";
+
+export const emailed = new Hono<AppEnv>();
+
+const TOO_MANY = "Too many attempts. Wait a few minutes and try again.";
+
+// --- email verification ------------------------------------------------------------
+
+emailed.get("/api/verify-email/:token", async (c) => {
+  const email = await peekEmailVerification(c.env, c.req.param("token"));
+  if (!email) return fail(c, "This link has expired, was already used, or a newer one was sent.", 410);
+  return c.json({ email });
+});
+
+emailed.post("/api/verify-email/:token", async (c) => {
+  if (!(await attempt(c.env, `verify-ip:${clientIp(c)}`, 30, 15 * 60))) return fail(c, TOO_MANY, 429);
+  const userId = await consumeEmailVerification(c.env, c.req.param("token"));
+  if (!userId) return fail(c, "This link has expired, was already used, or a newer one was sent.", 410);
+
+  await audit(c, "account.email_verified", { actor: userId, target: userId });
+  return c.json({ signedIn: c.get("user")?.id === userId });
+});
+
+// --- "wasn't me" sign-out links ------------------------------------------------------
+
+const SIGNOUT_EXPIRED =
+  "This link has expired. Sign in to see and sign out your sessions. If you can't sign in, ask an admin to sign you out everywhere.";
+
+emailed.get("/api/security/:token", async (c) => {
+  const target = await peekSignoutLink(c.env, c.req.param("token"));
+  if (!target) return fail(c, SIGNOUT_EXPIRED, 410);
+  return c.json({ username: target.username, sessionLive: Boolean(target.session_live) });
+});
+
+emailed.post("/api/security/:token", async (c) => {
+  if (!(await attempt(c.env, `signout-ip:${clientIp(c)}`, 30, 15 * 60))) return fail(c, TOO_MANY, 429);
+  const target = await peekSignoutLink(c.env, c.req.param("token"));
+  if (!target) return fail(c, SIGNOUT_EXPIRED, 410);
+
+  const everywhere = str((await body(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 c.json({ everywhere });
+});
+
+// --- forgot password ---------------------------------------------------------------
+
+emailed.post("/api/forgot", async (c) => {
+  if (!(await attempt(c.env, `forgot-ip:${clientIp(c)}`, 10, 60 * 60))) {
+    return fail(c, "Too many requests from here. Try again later.", 429);
+  }
+  const input = str((await body(c)).account).slice(0, 254);
+
+  // Looked up and sent in the background, so the response is the same, and
+  // takes the same time, whether or not the account exists.
+  const task = (async () => {
+    for (const user of await resetCandidates(c.env, input)) {
+      await sendPasswordReset(c.env, user);
+      await audit(c, "account.reset_requested", { actor: null, target: user.id });
+    }
+  })().catch((err) => console.error("[reset] couldn't send", err));
+  try {
+    c.executionCtx.waitUntil(task);
+  } catch {
+    // No execution context (local tools): the promise still runs.
+  }
+  return c.json({ sent: true });
+});
+
+const RESET_EXPIRED = "This link has expired, was already used, or a newer one was sent.";
+
+emailed.get("/api/reset/:token", async (c) => {
+  const target = await peekPasswordReset(c.env, c.req.param("token"));
+  if (!target) return fail(c, RESET_EXPIRED, 410);
+  return c.json({ username: target.username });
+});
+
+emailed.post("/api/reset/:token", async (c) => {
+  if (!(await attempt(c.env, `reset-ip:${clientIp(c)}`, 30, 15 * 60))) return fail(c, TOO_MANY, 429);
+  const token = c.req.param("token");
+  const target = await peekPasswordReset(c.env, token);
+  if (!target) return fail(c, RESET_EXPIRED, 410);
+
+  const b = await body(c);
+  const password = str(b.password);
+  const problem =
+    passwordProblem(password, target.username) ?? (password !== str(b.confirm) ? "The two passwords don't match." : null);
+  if (problem) return fail(c, problem);
+
+  const userId = await consumePasswordReset(c.env, token, await hashPassword(password));
+  if (!userId) return fail(c, RESET_EXPIRED, 410);
+
+  // This browser may be signed in as someone else; start clean either way.
+  await endSession(c);
+  await audit(c, "account.password_reset", { actor: userId, target: userId });
+  notify(c, userId, {
+    subject: "Your password was reset",
+    summary: "Your password was reset with a link sent to this address, and every browser and app was signed out.",
+    by: "self",
+    sessionHash: null,
+  });
+  return c.json({ redirect: "/login?m=password-reset" });
+});
diff --git a/src/api/login.ts b/src/api/login.ts
new file mode 100644
index 0000000..bfa4476
--- /dev/null
+++ b/src/api/login.ts
@@ -0,0 +1,231 @@
+/* src/api/login.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 { Hono } from "hono";
+import type { AuthenticationResponseJSON } from "@simplewebauthn/server";
+import type { AppContext, AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { decrypt } from "../lib/crypto";
+import { csrfOk, staleCsrf } from "../lib/guards";
+import { body, clientIp, fail, readJson, safeReturn, str } from "../lib/http";
+import { burnPasswordCheck, hashPassword, needsRehash, verifyPassword } from "../lib/password";
+import { attempt, clearAttempts } from "../lib/ratelimit";
+import { verifyTotp } from "../lib/totp";
+import { normaliseUsername } from "../lib/validate";
+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, getUser, getUserByUsername, setPasswordHash, type UserRow } from "../data/users";
+
+const WINDOW = 15 * 60;
+const USER_LIMIT = 10;
+const IP_LIMIT = 50;
+const TOTP_ATTEMPTS = 5;
+/** Code guesses per account per window, across every pending login. */
+export const TOTP_USER_LIMIT = 10;
+const GENERIC_FAILURE = "That username and password don't match.";
+const TOO_MANY = "Too many sign-in attempts. Wait a few minutes and try again.";
+const EXPIRED = "This sign-in expired. Start over.";
+
+export const login = new Hono<AppEnv>();
+
+login.post("/api/login/password", async (c) => {
+  const b = await body(c);
+  const returnTo = safeReturn(b.return);
+  const username = normaliseUsername(str(b.username)).slice(0, 64);
+  const password = str(b.password).slice(0, 512);
+
+  const ipOk = await attempt(c.env, `login-ip:${clientIp(c)}`, IP_LIMIT, WINDOW);
+  const userOk = await attempt(c.env, `login-user:${username}`, USER_LIMIT, WINDOW);
+  if (!ipOk || !userOk) {
+    await audit(c, "login.rate_limited", { actor: null, target: username });
+    return fail(c, TOO_MANY, 429);
+  }
+
+  const user = username ? await getUserByUsername(c.env, username) : null;
+  if (!user || !user.password_hash || user.disabled) {
+    await burnPasswordCheck(password);
+    await audit(c, "login.failed", { actor: null, target: username, detail: "password" });
+    return fail(c, GENERIC_FAILURE, 401);
+  }
+
+  if (!(await verifyPassword(password, user.password_hash))) {
+    await audit(c, "login.failed", { actor: user.id, target: user.username, detail: "password" });
+    return fail(c, GENERIC_FAILURE, 401);
+  }
+
+  await clearAttempts(c.env, `login-user:${username}`);
+  if (needsRehash(user.password_hash)) {
+    await setPasswordHash(c.env, user.id, await hashPassword(password));
+  }
+
+  // Accounts with a passkey or two-factor codes need one of them as well.
+  const step = await secondStepFor(c, user);
+  if (step) {
+    await startPendingLogin(c, user.id, returnTo);
+    return c.json({ mfa: step });
+  }
+
+  await startSession(c, user.id, ["pwd"]);
+  await audit(c, "login.password", { actor: user.id, target: user.username });
+  return c.json({ redirect: returnTo });
+});
+
+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;
+}
+
+/** 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 };
+}
+
+/** What the second-step page should offer. */
+login.get("/api/login/mfa", async (c) => {
+  const found = await pendingUser(c);
+  if (!found) return fail(c, EXPIRED, 401, { restart: true });
+  return c.json(found.step);
+});
+
+login.post("/api/login/mfa", async (c) => {
+  const b = await body(c);
+  const pending = await spendPendingAttempt(c, TOTP_ATTEMPTS);
+  if (!pending) return fail(c, EXPIRED, 401, { restart: true });
+
+  const user = await getUser(c.env, pending.user_id);
+  const step = user && !user.disabled ? await secondStepFor(c, user) : null;
+  if (!user || !step || !user.totp_secret) {
+    await finishPendingLogin(c, pending.id_hash);
+    return fail(c, EXPIRED, 401, { restart: true });
+  }
+
+  // Per account, not per pending login: a correct password starts a fresh
+  // pending login (and clears login-user), so without this anyone holding the
+  // password could keep guessing codes five at a time.
+  if (!(await attempt(c.env, `totp-user:${user.id}`, TOTP_USER_LIMIT, WINDOW))) {
+    await audit(c, "login.rate_limited", { actor: user.id, target: user.username, detail: "totp" });
+    return fail(c, "Too many codes tried. Wait a few minutes and try again.", 429);
+  }
+
+  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_secret);
+  const totpStep = await verifyTotp(secret, str(b.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 fail(c, "That code didn't work, and that was the last try. Start over.", 401, { restart: true });
+    }
+    return fail(c, `That code didn't work. ${left} ${left === 1 ? "try" : "tries"} left.`, 401);
+  }
+
+  await finishPendingLogin(c, pending.id_hash);
+  await startSession(c, user.id, ["pwd", "otp", "mfa"]);
+  await audit(c, "login.password_totp", { actor: user.id, target: user.username });
+  return c.json({ redirect: safeReturn(pending.return_to) });
+});
+
+login.post("/api/login/mfa/passkey/options", async (c) => {
+  if (!(await attempt(c.env, `passkey-ip:${clientIp(c)}`, 120, WINDOW))) return fail(c, TOO_MANY, 429);
+  const found = await pendingUser(c);
+  if (!found?.step.passkey) return fail(c, EXPIRED, 401, { restart: true });
+  return c.json(await authenticationOptions(c.env, found.user.id));
+});
+
+login.post("/api/login/mfa/passkey/verify", async (c) => {
+  const b = await readJson<{ id?: string; response?: AuthenticationResponseJSON }>(c);
+  if (!b?.id || !b.response) return fail(c, "Malformed request.");
+  const found = await pendingUser(c);
+  if (!found) return fail(c, EXPIRED, 401, { restart: true });
+  const { pending, user } = found;
+
+  const result = await finishAuthentication(c.env, b.id, b.response, user.id);
+  if (!result.ok) {
+    await audit(c, "login.failed", { actor: user.id, target: user.username, detail: "passkey (second step)" });
+    return fail(c, 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("/api/login/passkey/options", async (c) => {
+  if (!(await attempt(c.env, `passkey-ip:${clientIp(c)}`, 120, WINDOW))) return fail(c, TOO_MANY, 429);
+  return c.json(await authenticationOptions(c.env));
+});
+
+login.post("/api/login/passkey/verify", async (c) => {
+  const b = await readJson<{ id?: string; response?: AuthenticationResponseJSON; return?: string }>(c);
+  if (!b?.id || !b.response) return fail(c, "Malformed request.");
+
+  const result = await finishAuthentication(c.env, b.id, b.response);
+  if (!result.ok) {
+    await audit(c, "login.failed", { actor: null, detail: "passkey" });
+    return fail(c, result.error, 401);
+  }
+
+  const user = await getUser(c.env, result.userId);
+  if (!user || user.disabled) return fail(c, "This account is disabled.", 403);
+
+  await startSession(c, user.id, result.amr);
+  await audit(c, "login.passkey", { actor: user.id, target: user.username });
+  return c.json({ redirect: safeReturn(b.return) });
+});
+
+// One-time links from an admin. Link scanners follow GETs, so looking one up
+// never uses it; the page posts to use it.
+login.get("/api/login/link/:token", async (c) => {
+  const target = await peekLoginLink(c.env, c.req.param("token"));
+  if (!target) return fail(c, "This link has expired, was already used, or was replaced by a newer one.", 410);
+  return c.json({ userId: target.user_id, username: target.username, name: target.name });
+});
+
+login.post("/api/login/link/:token", async (c) => {
+  if (!(await attempt(c.env, `link-ip:${clientIp(c)}`, 30, WINDOW))) {
+    return fail(c, "Too many attempts. Wait a few minutes and try again.", 429);
+  }
+  const userId = await consumeLoginLink(c.env, c.req.param("token"));
+  if (!userId) return fail(c, "This link has expired, was already used, or was replaced by a newer one.", 410);
+
+  await startSession(c, userId, ["link"]);
+  await audit(c, "login.link", { actor: userId, target: userId });
+  return c.json({ redirect: "/settings?m=link-welcome" });
+});
+
+login.post("/api/logout", async (c) => {
+  // Already signed out (expired, or another tab) is fine: there's nothing to protect.
+  if (c.get("session")) {
+    if (!csrfOk(c)) return staleCsrf(c);
+    await audit(c, "logout");
+    await endSession(c);
+  }
+  return c.json({ redirect: "/login?m=signed-out" });
+});
diff --git a/src/api/session.ts b/src/api/session.ts
new file mode 100644
index 0000000..9bb16a2
--- /dev/null
+++ b/src/api/session.ts
@@ -0,0 +1,34 @@
+/* src/api/session.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 { Hono } from "hono";
+import { siteName, type AppEnv } from "../env";
+import { isRecentAuth } from "../lib/guards";
+import { countUsers } from "../data/users";
+
+export const session = new Hono<AppEnv>();
+
+/** Everything the page needs before it can draw anything: who's signed in, and how this server is set up. */
+session.get("/api/session", async (c) => {
+  const user = c.get("user");
+  const current = c.get("session");
+  return c.json({
+    site: siteName(c.env),
+    registration: c.env.REGISTRATION === "open",
+    contact: c.env.CONTACT_EMAIL || null,
+    needsSetup: user ? false : (await countUsers(c.env)) === 0,
+    user: user && {
+      id: user.id,
+      username: user.username,
+      name: user.name,
+      email: user.email,
+      picture: user.picture,
+      isAdmin: user.isAdmin,
+    },
+    csrf: current?.csrf ?? null,
+    recentAuth: current ? isRecentAuth(current.authTime) : false,
+  });
+});
diff --git a/src/api/signup.ts b/src/api/signup.ts
new file mode 100644
index 0000000..082889a
--- /dev/null
+++ b/src/api/signup.ts
@@ -0,0 +1,106 @@
+/* src/api/signup.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.
+ *
+ * Creating accounts without an admin: open registration, and /setup for the
+ * very first (admin) account.
+ */
+
+import { Hono } from "hono";
+import type { AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { timingSafeEqualStr } from "../lib/crypto";
+import { body, clientIp, fail, safeReturn, str } from "../lib/http";
+import { PASSWORD_MAX, hashPassword, passwordProblem } from "../lib/password";
+import { attempt } from "../lib/ratelimit";
+import { cleanText, emailProblem, normaliseUsername, usernameProblem } from "../lib/validate";
+import { isReserved, lookalikeOf } from "../data/reserved";
+import { startSession } from "../data/sessions";
+import { countUsers, createFirstAdmin, createUser } from "../data/users";
+import { sendVerificationEmail } from "../data/verifications";
+
+// Reserved, taken and look-alike names get the same answer, so the form
+// can't be used to find out which names are reserved.
+const UNAVAILABLE = "That username isn't available.";
+
+export const signup = new Hono<AppEnv>();
+
+signup.post("/api/register", async (c) => {
+  if (c.env.REGISTRATION !== "open") return fail(c, "Sign-ups are closed. Accounts on this server are created by an admin.", 403);
+  if (c.get("user")) return c.json({ redirect: "/apps" });
+  if ((await countUsers(c.env)) === 0) return c.json({ redirect: "/setup" });
+
+  if (!(await attempt(c.env, `register-ip:${clientIp(c)}`, 10, 60 * 60))) {
+    await audit(c, "register.rate_limited", { actor: null });
+    return fail(c, "Too many sign-ups from here. Try again later.", 429);
+  }
+
+  const b = await body(c);
+  const returnTo = safeReturn(b.return);
+  const username = normaliseUsername(str(b.username));
+  const password = str(b.password).slice(0, PASSWORD_MAX);
+  const email = cleanText(str(b.email), 254);
+
+  const problem =
+    usernameProblem(username) ??
+    ((await isReserved(c.env, username)) || (await lookalikeOf(c.env, username)) ? UNAVAILABLE : null) ??
+    (email === null ? "Enter your email address." : emailProblem(email)) ??
+    passwordProblem(password, username) ??
+    (password !== str(b.confirm) ? "The passwords don't match." : null);
+  if (problem || email === null) return fail(c, problem ?? "Enter your email address.");
+
+  const result = await createUser(c.env, {
+    username,
+    name: cleanText(str(b.name), 100),
+    email,
+    emailVerified: false,
+    passwordHash: await hashPassword(password),
+  });
+  if (!result.ok) return fail(c, UNAVAILABLE);
+
+  const sent = await sendVerificationEmail(c.env, result.id, email);
+  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 !== "/apps") return c.json({ redirect: returnTo });
+  return c.json({ redirect: `/settings?m=${sent === "sent" ? "welcome-verify" : "verify-failed"}` });
+});
+
+/** "open", "done" (there are accounts), or "unconfigured" (no SETUP_TOKEN secret). */
+signup.get("/api/setup", async (c) => {
+  if ((await countUsers(c.env)) > 0) return c.json({ state: "done" });
+  return c.json({ state: c.env.SETUP_TOKEN ? "open" : "unconfigured" });
+});
+
+signup.post("/api/setup", async (c) => {
+  const done = () => fail(c, "This server already has accounts.", 409, { done: true });
+  if ((await countUsers(c.env)) > 0 || !c.env.SETUP_TOKEN) return done();
+
+  if (!(await attempt(c.env, `setup-ip:${clientIp(c)}`, 10, 60 * 60))) {
+    return fail(c, "Too many attempts. Try again later.", 429);
+  }
+
+  const b = await body(c);
+  if (!timingSafeEqualStr(str(b.token), c.env.SETUP_TOKEN)) {
+    await audit(c, "setup.bad_token", { actor: null });
+    return fail(c, "That setup token is wrong.", 403);
+  }
+
+  const username = normaliseUsername(str(b.username));
+  const email = cleanText(str(b.email), 254);
+  const problem = usernameProblem(username) ?? emailProblem(email);
+  if (problem) return fail(c, problem);
+
+  const id = await createFirstAdmin(c.env, {
+    username,
+    name: cleanText(str(b.name), 100),
+    email,
+    emailVerified: false,
+  });
+  if (!id) return done();
+
+  await startSession(c, id, ["setup"], { alert: false });
+  await audit(c, "setup.complete", { actor: id, target: username });
+  return c.json({ redirect: "/settings?m=setup-done" });
+});
diff --git a/src/data/cleanup.ts b/src/data/cleanup.ts
index fa09230..5ffbd42 100644
--- a/src/data/cleanup.ts
+++ b/src/data/cleanup.ts
@@ -18,6 +18,7 @@ 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 password_resets 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),
diff --git a/src/data/clients.ts b/src/data/clients.ts
index 99c5f9e..70445d0 100644
--- a/src/data/clients.ts
+++ b/src/data/clients.ts
@@ -10,6 +10,7 @@ import { randomToken, sha256Hex, timingSafeEqualStr } from "../lib/crypto";
 interface ClientRow {
   id: string;
   name: string;
+  home_url: string | null;
   secret_hash: string | null;
   redirect_uris: string;
   post_logout_redirect_uris: string;
@@ -21,6 +22,8 @@ interface ClientRow {
 export interface Client {
   id: string;
   name: string;
+  /** The app's own website, linked from "Your apps". */
+  homeUrl: string | null;
   secretHash: string | null;
   isPublic: boolean;
   redirectUris: string[];
@@ -34,6 +37,7 @@ function toClient(row: ClientRow): Client {
   return {
     id: row.id,
     name: row.name,
+    homeUrl: row.home_url,
     secretHash: row.secret_hash,
     isPublic: row.secret_hash === null,
     redirectUris: JSON.parse(row.redirect_uris) as string[],
@@ -56,6 +60,7 @@ export async function listClients(env: Env): Promise<Client[]> {
 
 export interface ClientInput {
   name: string;
+  homeUrl: string | null;
   redirectUris: string[];
   postLogoutRedirectUris: string[];
   allowedGroups: string[];
@@ -76,12 +81,13 @@ export async function createClient(
   const ts = now();
   try {
     await env.DB.prepare(
-      `INSERT INTO clients (id, name, secret_hash, redirect_uris, post_logout_redirect_uris, allowed_groups, created_at, updated_at)
-       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+      `INSERT INTO clients (id, name, home_url, secret_hash, redirect_uris, post_logout_redirect_uris, allowed_groups, created_at, updated_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
     )
       .bind(
         id,
         input.name,
+        input.homeUrl,
         secret ? await sha256Hex(secret) : null,
         JSON.stringify(input.redirectUris),
         JSON.stringify(input.postLogoutRedirectUris),
@@ -99,11 +105,12 @@ export async function createClient(
 
 export async function updateClient(env: Env, id: string, input: ClientInput): Promise<void> {
   await env.DB.prepare(
-    `UPDATE clients SET name = ?, redirect_uris = ?, post_logout_redirect_uris = ?, allowed_groups = ?, updated_at = ?
+    `UPDATE clients SET name = ?, home_url = ?, redirect_uris = ?, post_logout_redirect_uris = ?, allowed_groups = ?, updated_at = ?
      WHERE id = ?`,
   )
     .bind(
       input.name,
+      input.homeUrl,
       JSON.stringify(input.redirectUris),
       JSON.stringify(input.postLogoutRedirectUris),
       JSON.stringify(input.allowedGroups),
diff --git a/src/data/notices.ts b/src/data/notices.ts
index 2fc2e88..96e8264 100644
--- a/src/data/notices.ts
+++ b/src/data/notices.ts
@@ -8,7 +8,7 @@ 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 { date, describeAgent } from "../lib/format";
 import { getUser, revokeAllStatements, type UserRow } from "./users";
 
 export interface Notice {
@@ -65,7 +65,7 @@ async function sendNotice(env: Env, userId: string, notice: Notice, origin: Orig
   if (!to) return;
 
   const site = siteName(env);
-  const accountUrl = `${issuer(env)}/account`;
+  const accountUrl = `${issuer(env)}/settings`;
   const link = notice.by === "self" ? await createSignoutLink(env, userId, notice.sessionHash ?? null) : null;
 
   const details: [string, string][] =
diff --git a/src/data/reserved.ts b/src/data/reserved.ts
index 4a7ad44..03bbc03 100644
--- a/src/data/reserved.ts
+++ b/src/data/reserved.ts
@@ -1,53 +1,93 @@
+/* src/data/reserved.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 { now, type Env } from "../env";
 
+// Usernames that read the same count as the same name: separators are dropped
+// and look-alike characters folded, so c.love, c_love and cl0ve all match clove, and adm1n matches admin.
+// Applied in this order, by both canonicalUsername and canonicalSql.
+const FOLDS: [string, string][] = [
+  [".", ""],
+  ["_", ""],
+  ["-", ""],
+  ["0", "o"],
+  ["1", "l"],
+  ["i", "l"],
+  ["rn", "m"],
+  ["vv", "w"],
+];
+
 const BUILTIN = new Set([
-    "admin", "administrator", "root", "system", "support", "help", "security",
-    "abuse", "postmaster", "hostmaster", "webmaster", "noreply", "mail",
-    "auth", "sso", "login", "logout", "register", "setup", "account", "api",
-    "www", "null", "undefined", "doughmination", "ctf", "universalcredit",
-    "sandrone", "aria",
-])
+  "admin", "administrator", "root", "system", "support", "help", "security",
+  "abuse", "postmaster", "hostmaster", "webmaster", "noreply", "mail",
+  "auth", "sso", "login", "logout", "register", "setup", "account", "api",
+  "www", "null", "undefined", "doughmination", "ctf", "universalcredit",
+  "sandrone", "aria",
+].map(canonicalUsername));
 
 export function canonicalUsername(username: string): string {
-    return username.replace(/[._-]/g, "");
+  return FOLDS.reduce((s, [from, to]) => s.replaceAll(from, to), username.toLowerCase());
+}
+
+/** canonicalUsername as a SQL expression over `column`. */
+function canonicalSql(column: string): string {
+  return FOLDS.reduce((expr, [from, to]) => `replace(${expr}, '${from}', '${to}')`, `lower(${column})`);
 }
 
 export async function isReserved(env: Env, username: string): Promise<boolean> {
-    const key = canonicalUsername(username);
-    if (BUILTIN.has(key)) return true;
-    const row = await env.DB.prepare("SELECT 1 FROM reserved_usernames WHERE username = ?").bind(key).first();
-    return row !== null
+  const key = canonicalUsername(username);
+  if (BUILTIN.has(key)) return true;
+  // Stored keys are re-folded, so rows saved before a fold was added still match.
+  const row = await env.DB.prepare(`SELECT 1 FROM reserved_usernames WHERE ${canonicalSql("username")} = ?`)
+    .bind(key)
+    .first();
+  return row !== null;
+}
+
+/**
+ * Another account whose username reads the same as this one, if any.
+ * `exceptId` skips the account being renamed.
+ */
+export async function lookalikeOf(env: Env, username: string, exceptId: string | null = null): Promise<string | null> {
+  const row = await env.DB.prepare(
+    `SELECT username FROM users WHERE ${canonicalSql("username")} = ? AND id IS NOT ? LIMIT 1`,
+  )
+    .bind(canonicalUsername(username), exceptId)
+    .first<{ username: string }>();
+  return row?.username ?? null;
 }
 
 export interface ReservedRow {
-    username: string;
-    note: string;
-    created_at: number;
+  username: string;
+  note: string;
+  created_at: number;
 }
 
 export async function listReserved(env: Env): Promise<ReservedRow[]> {
-    const { results } = await env.DB.prepare(
-        "SELECT * FROM reserved_usernames ORDER BY username",
-    ).all<ReservedRow>();
-    return results;
+  const { results } = await env.DB.prepare("SELECT * FROM reserved_usernames ORDER BY username").all<ReservedRow>();
+  return results;
 }
 
 /** False if it was already reserved. */
 export async function reserveUsername(env: Env, username: string, note: string): Promise<boolean> {
-    const result = await env.DB.prepare(
-        "INSERT OR IGNORE INTO reserved_usernames (username, note, created_at) VALUES (?, ?, ?)",
-    )
-        .bind(canonicalUsername(username), note, now())
-        .run();
-    return result.meta.changes === 1;
+  if (await isReserved(env, username)) return false;
+  const result = await env.DB.prepare(
+    "INSERT OR IGNORE INTO reserved_usernames (username, note, created_at) VALUES (?, ?, ?)",
+  )
+    .bind(canonicalUsername(username), note, now())
+    .run();
+  return result.meta.changes === 1;
 }
 
 export async function unreserveUsername(env: Env, username: string): Promise<void> {
-    await env.DB.prepare("DELETE FROM reserved_usernames WHERE username = ?")
-        .bind(canonicalUsername(username))
-        .run();
+  await env.DB.prepare(`DELETE FROM reserved_usernames WHERE ${canonicalSql("username")} = ?`)
+    .bind(canonicalUsername(username))
+    .run();
 }
 
 export function builtinReserved(): string[] {
-    return [...BUILTIN].sort();
-}
\ No newline at end of file
+  return [...BUILTIN].sort();
+}
diff --git a/src/data/resets.ts b/src/data/resets.ts
new file mode 100644
index 0000000..505ba6c
--- /dev/null
+++ b/src/data/resets.ts
@@ -0,0 +1,107 @@
+/* src/data/resets.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 Env } from "../env";
+import { randomToken, sha256Hex } from "../lib/crypto";
+import { sendMail } from "../lib/mail";
+import { attempt } from "../lib/ratelimit";
+import { revokeAllStatements, type UserRow } from "./users";
+
+/**
+ * The accounts a "forgot password" request could be about: one username, or
+ * every account with that verified address (addresses aren't unique).
+ */
+export async function resetCandidates(env: Env, input: string): Promise<UserRow[]> {
+  const value = input.trim();
+  if (!value) return [];
+  const { results } = await env.DB.prepare(
+    value.includes("@")
+      ? "SELECT * FROM users WHERE email = ? COLLATE NOCASE AND email_verified = 1 AND disabled = 0 LIMIT 10"
+      : "SELECT * FROM users WHERE username = ? AND email IS NOT NULL AND email_verified = 1 AND disabled = 0",
+  )
+    .bind(value.toLowerCase())
+    .all<UserRow>();
+  return results;
+}
+
+/** Emails a reset link to the account's verified address. Rate limited per account. */
+export async function sendPasswordReset(env: Env, user: UserRow): Promise<void> {
+  if (!user.email || !user.email_verified || user.disabled) return;
+  if (!(await attempt(env, `reset-mail:${user.id}`, 3, 60 * 60))) return;
+
+  const token = randomToken(32);
+  const ts = now();
+  await env.DB.batch([
+    // Only the newest link for an account stays valid.
+    env.DB.prepare("DELETE FROM password_resets WHERE user_id = ?").bind(user.id),
+    env.DB.prepare(
+      "INSERT INTO password_resets (token_hash, user_id, email, created_at, expires_at) VALUES (?, ?, ?, ?, ?)",
+    ).bind(await sha256Hex(token), user.id, user.email, ts, ts + TTL.passwordReset),
+  ]);
+
+  // The username is limited to [a-z0-9._-] and the rest is our own config, so
+  // nothing here needs HTML escaping.
+  const url = `${issuer(env)}/reset/${token}`;
+  const site = siteName(env);
+  await sendMail(env, {
+    to: user.email,
+    subject: `Reset your password for ${site}`,
+    text:
+      `Someone asked to reset the password for @${user.username} on ${site}.\n\n` +
+      `Open this link to choose a new one:\n\n${url}\n\n` +
+      `It works for one hour. If you didn't ask for this, ignore this email: your password hasn't changed.`,
+    html:
+      `<p>Someone asked to reset the password for <strong>@${user.username}</strong> on ${site}.</p>` +
+      `<p><a href="${url}">Choose a new password</a></p>` +
+      `<p>It works for one hour. If you didn't ask for this, ignore this email: your password hasn't changed.</p>`,
+  });
+}
+
+export interface ResetTarget {
+  user_id: string;
+  username: string;
+}
+
+/** The account a link would reset, without using it (the form page). */
+export async function peekPasswordReset(env: Env, token: string): Promise<ResetTarget | null> {
+  return env.DB.prepare(
+    `SELECT r.user_id, u.username FROM password_resets r JOIN users u ON u.id = r.user_id
+     WHERE r.token_hash = ? AND r.expires_at > ? AND u.disabled = 0
+       AND u.email = r.email AND u.email_verified = 1`,
+  )
+    .bind(await sha256Hex(token), now())
+    .first<ResetTarget>();
+}
+
+/**
+ * Uses a link up: sets the new password and signs the account out of every
+ * browser and app, since whoever had the old password may still be signed in.
+ * Two-factor codes and passkeys stay, so a password sign-in still needs them.
+ */
+export async function consumePasswordReset(env: Env, token: string, passwordHash: string): Promise<string | null> {
+  const row = await env.DB.prepare(
+    "DELETE FROM password_resets WHERE token_hash = ? RETURNING user_id, email, expires_at",
+  )
+    .bind(await sha256Hex(token))
+    .first<{ user_id: string; email: string; expires_at: number }>();
+  if (!row || row.expires_at <= now()) return null;
+
+  // Only if the account still has the address the link went to.
+  const updated = await env.DB.prepare(
+    `UPDATE users SET password_hash = ?, updated_at = ?
+     WHERE id = ? AND email = ? AND email_verified = 1 AND disabled = 0
+     RETURNING username`,
+  )
+    .bind(passwordHash, now(), row.user_id, row.email)
+    .first<{ username: string }>();
+  if (!updated) return null;
+
+  await env.DB.batch([
+    ...revokeAllStatements(env, row.user_id),
+    env.DB.prepare("DELETE FROM rate_limits WHERE key = ?").bind(`login-user:${updated.username}`),
+  ]);
+  return row.user_id;
+}
diff --git a/src/data/sessions.ts b/src/data/sessions.ts
index 4c4fd52..310d975 100644
--- a/src/data/sessions.ts
+++ b/src/data/sessions.ts
@@ -8,7 +8,7 @@ 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 { amrLabel } from "../lib/format";
 import { notify } from "./notices";
 import { groupsFor, markLogin } from "./users";
 
diff --git a/src/env.ts b/src/env.ts
index 179458a..3dc7dc0 100644
--- a/src/env.ts
+++ b/src/env.ts
@@ -8,6 +8,8 @@ import type { Context } from "hono";
 
 export interface Env {
   DB: D1Database;
+  /** The built Svelte app (dist/). */
+  ASSETS: Fetcher;
   ISSUER: string;
   SITE_NAME: string;
   KEY_ENCRYPTION_KEY: string;
@@ -61,6 +63,8 @@ export const TTL = {
   refreshToken: 60 * 60 * 24 * 30,
   /** Email verification links. */
   emailVerification: 60 * 60 * 24,
+  /** "Forgot password" links. */
+  passwordReset: 60 * 60,
   /** 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. */
diff --git a/src/lib/format.ts b/src/lib/format.ts
new file mode 100644
index 0000000..b67d387
--- /dev/null
+++ b/src/lib/format.ts
@@ -0,0 +1,43 @@
+/* src/lib/format.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.
+ *
+ * Wording shared by security emails and the session lists the API returns.
+ */
+
+export function date(ts: number | null | undefined): string {
+  if (!ts) return "never";
+  return new Date(ts * 1000).toISOString().slice(0, 16).replace("T", " ") + " UTC";
+}
+
+/** 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";
+  const browser =
+    /Edg\//.test(ua) ? "Edge" :
+    /Firefox\//.test(ua) ? "Firefox" :
+    /Chrome\//.test(ua) ? "Chrome" :
+    /Safari\//.test(ua) ? "Safari" :
+    "Browser";
+  const os =
+    /Windows/.test(ua) ? "Windows" :
+    /iPhone|iPad/.test(ua) ? "iOS" :
+    /Mac OS X/.test(ua) ? "macOS" :
+    /Android/.test(ua) ? "Android" :
+    /Linux/.test(ua) ? "Linux" :
+    "unknown OS";
+  return `${browser} on ${os}`;
+}
diff --git a/src/lib/guards.ts b/src/lib/guards.ts
new file mode 100644
index 0000000..3df83fb
--- /dev/null
+++ b/src/lib/guards.ts
@@ -0,0 +1,60 @@
+/* src/lib/guards.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 { createMiddleware } from "hono/factory";
+import { now, type AppContext, type AppEnv } from "../env";
+import { timingSafeEqualStr } from "./crypto";
+import { fail } from "./http";
+
+// The page reacts to these flags: `signin` and `reauth` send it to /login,
+// `stale` asks for a reload to pick up a fresh CSRF token.
+
+export const requireUser = createMiddleware<AppEnv>(async (c, next) => {
+  if (!c.get("user")) return fail(c, "Your session ended. Sign in again.", 401, { signin: true });
+  await next();
+});
+
+export const requireAdmin = createMiddleware<AppEnv>(async (c, next) => {
+  if (!c.get("user")?.isAdmin) return fail(c, "Your account isn't in the admin group for this server.", 403);
+  await next();
+});
+
+/** How long after signing in a session may change how the account signs in. */
+export const RECENT_AUTH = 15 * 60;
+
+export function isRecentAuth(authTime: number): boolean {
+  return now() - authTime <= RECENT_AUTH;
+}
+
+/**
+ * Changes that could lock the owner out (password, passkeys, two-factor,
+ * email, deletion) need a recent sign-in, so a stolen session cookie alone
+ * can't take the account over. Older sessions are sent to confirm it's them.
+ */
+export const requireRecentAuth = createMiddleware<AppEnv>(async (c, next) => {
+  const session = c.get("session");
+  if (!session || !isRecentAuth(session.authTime)) {
+    return fail(c, "For your security, confirm it's you first.", 401, { reauth: true });
+  }
+  await next();
+});
+
+/** True when the request carries this session's CSRF token in `x-csrf-token`. */
+export function csrfOk(c: AppContext): boolean {
+  const session = c.get("session");
+  const sent = c.req.header("x-csrf-token");
+  return Boolean(session && sent && timingSafeEqualStr(sent, session.csrf));
+}
+
+export function staleCsrf(c: AppContext) {
+  return fail(c, "This page is out of date. Reload and try again.", 403, { stale: true });
+}
+
+/** Every state-changing request from a signed-in page carries the session's CSRF token. */
+export const requireCsrf = createMiddleware<AppEnv>(async (c, next) => {
+  if (c.req.method !== "GET" && c.req.method !== "HEAD" && !csrfOk(c)) return staleCsrf(c);
+  await next();
+});
diff --git a/src/lib/guards.tsx b/src/lib/guards.tsx
deleted file mode 100644
index cbeec0c..0000000
--- a/src/lib/guards.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-/* src/lib/guards.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 { createMiddleware } from "hono/factory";
-import { issuerOrigin, type AppContext, type AppEnv } from "../env";
-import { timingSafeEqualStr } from "./crypto";
-import { form, safeReturn } from "./http";
-import { ArrowLeft } from "pixelarticons/react";
-import { render } from "../views/layout";
-
-function wantsJson(c: AppContext): boolean {
-  return (c.req.header("content-type") ?? "").includes("application/json");
-}
-
-function loginUrl(returnTo: string): string {
-  return `/login?${new URLSearchParams({ return: returnTo })}`;
-}
-
-/** Where to come back to after signing in: the page, or for a POST, the page it came from. */
-function returnTarget(c: AppContext, fallback: string): string {
-  if (c.req.method === "GET") {
-    const url = new URL(c.req.url);
-    return url.pathname + url.search;
-  }
-  // Referrer-Policy is same-origin, so a Referer here is one of our own pages.
-  try {
-    const referer = new URL(c.req.header("referer") ?? "");
-    if (referer.origin === issuerOrigin(c.env)) return safeReturn(referer.pathname + referer.search, fallback);
-  } catch {
-    // no usable referer
-  }
-  return fallback;
-}
-
-export const requireUser = createMiddleware<AppEnv>(async (c, next) => {
-  if (!c.get("user")) {
-    if (wantsJson(c)) return c.json({ error: "Your session ended. Sign in again." }, 401);
-    return c.redirect(loginUrl(returnTarget(c, "/account")));
-  }
-  await next();
-});
-
-export const requireAdmin = createMiddleware<AppEnv>(async (c, next) => {
-  if (!c.get("user")?.isAdmin) {
-    return render(
-      c,
-      { title: "Not allowed", narrow: true, status: 403 },
-      <div class="card">
-        <h1>Admins only</h1>
-        <p class="muted">Your account isn't in the admin group for this server.</p>
-        <p>
-          <a class="btn primary" href="/account">
-            <ArrowLeft class="icon" aria-hidden="true" />
-            Back to your account
-          </a>
-        </p>
-      </div>,
-    );
-  }
-  await next();
-});
-
-/**
- * Every state-changing request from a signed-in page carries the session's
- * CSRF token, either as a `_csrf` form field or an `x-csrf-token` header.
- */
-export const requireCsrf = createMiddleware<AppEnv>(async (c, next) => {
-  if (c.req.method === "POST") {
-    const session = c.get("session");
-    const sent = wantsJson(c) ? c.req.header("x-csrf-token") : (await form(c))._csrf;
-    if (!session || !sent || !timingSafeEqualStr(sent, session.csrf)) {
-      if (wantsJson(c)) return c.json({ error: "This page is out of date. Reload and try again." }, 403);
-      return c.text("This form is out of date. Go back, reload the page and try again.", 403);
-    }
-  }
-  await next();
-});
-
diff --git a/src/lib/http.ts b/src/lib/http.ts
index 89d1ad3..ad2e66e 100644
Binary files a/src/lib/http.ts and b/src/lib/http.ts differ
diff --git a/src/lib/validate.ts b/src/lib/validate.ts
index 74a8650..15e9503 100644
--- a/src/lib/validate.ts
+++ b/src/lib/validate.ts
@@ -71,6 +71,21 @@ function isLoopback(hostname: string): boolean {
   return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
 }
 
+/** An app's website: an absolute https URL (plain http only for loopback). */
+export function homeUrlProblem(url: string | null): string | null {
+  if (url === null) return null;
+  let parsed: URL;
+  try {
+    parsed = new URL(url);
+  } catch {
+    return "The website isn't a valid URL.";
+  }
+  if (url.length > 2048) return "The website URL is too long.";
+  if (parsed.protocol === "https:") return null;
+  if (parsed.protocol === "http:" && isLoopback(parsed.hostname)) return null;
+  return "The website must use https (http is only allowed for localhost).";
+}
+
 /**
  * Redirect URIs are matched exactly, so validation only has to make sure they
  * are absolute, have no fragment, and use https (plain http only for loopback).
diff --git a/src/main.ts b/src/main.ts
index ceba677..79f3f53 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -2,6 +2,10 @@
  * 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.
+ *
+ * The Worker is the OpenID Connect provider plus a JSON API under /api. Every
+ * page is the Svelte app in web/, built into dist/ and served from here so it
+ * gets the same host check and security headers as everything else.
  */
 
 import { Hono } from "hono";
@@ -9,14 +13,13 @@ import { isSecure, issuerOrigin, type AppEnv, type Env } from "./env";
 import { loadSession } from "./data/sessions";
 import { sweepExpired } from "./data/cleanup";
 import { oidc } from "./oidc/endpoints";
-import { login } from "./routes/login";
-import { setup } from "./routes/setup";
-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";
+import { session } from "./api/session";
+import { login } from "./api/login";
+import { signup } from "./api/signup";
+import { emailed } from "./api/emailed";
+import { account } from "./api/account";
+import { admin } from "./api/admin";
+import { apps } from "./api/apps";
 
 const app = new Hono<AppEnv>();
 
@@ -39,7 +42,7 @@ app.use("*", async (c, next) => {
 
   // CSRF, layer one: browsers label every cross-site request with Origin or
   // Sec-Fetch-Site, so state-changing requests from elsewhere are refused.
-  // Session-bound forms additionally carry a CSRF token (lib/guards).
+  // Session-bound API calls additionally carry a CSRF token (lib/guards).
   const safe = c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS";
   if (!safe && !CROSS_ORIGIN_POSTS.has(url.pathname)) {
     const sentOrigin = c.req.header("origin");
@@ -49,13 +52,14 @@ app.use("*", async (c, next) => {
     }
   }
 
-  await loadSession(c);
+  // Static files don't need to know who's signed in.
+  if (!url.pathname.startsWith("/assets/") && !url.pathname.startsWith("/static/")) await loadSession(c);
   await next();
 
   const h = c.res.headers;
   h.set(
     "Content-Security-Policy",
-    "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' https: data:; font-src https://m.doughmination.gay; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'",
+    "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' https: data:; font-src https://m.doughmination.gay; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
   );
   h.set("X-Frame-Options", "DENY");
   h.set("X-Content-Type-Options", "nosniff");
@@ -66,22 +70,38 @@ app.use("*", async (c, next) => {
   if (!h.has("Cache-Control")) h.set("Cache-Control", "no-store");
 });
 
-app.get("/", (c) => c.redirect(c.get("user") ? "/account" : "/login"));
-
 app.route("/", oidc);
+app.route("/", session);
 app.route("/", login);
-app.route("/", register);
-app.route("/", verify);
-app.route("/", security);
-app.route("/", legal);
-app.route("/", setup);
+app.route("/", signup);
+app.route("/", emailed);
 app.route("/", account);
 app.route("/", admin);
+app.route("/", apps);
+
+app.all("/api/*", (c) => c.json({ error: "Not found" }, 404));
+
+// Everything else is the Svelte app: its files, or index.html for any page URL
+// (wrangler.jsonc sets not_found_handling to single-page-application).
+app.get("*", async (c) => {
+  const asset = await c.env.ASSETS.fetch(c.req.raw);
+  // Responses from fetch() have immutable headers; copy so the middleware can add its own.
+  const res = new Response(asset.body, asset);
+  const path = new URL(c.req.url).pathname;
+  // Vite puts a content hash in every file name under /assets, so they never change.
+  if (path.startsWith("/assets/")) res.headers.set("Cache-Control", "public, max-age=31536000, immutable");
+  else if (path.startsWith("/static/")) res.headers.set("Cache-Control", "public, max-age=3600");
+  else res.headers.set("Cache-Control", "no-cache");
+  return res;
+});
 
 app.notFound((c) => c.text("Not found", 404));
 
 app.onError((err, c) => {
   console.error("[error]", c.req.method, new URL(c.req.url).pathname, err);
+  if (new URL(c.req.url).pathname.startsWith("/api/")) {
+    return c.json({ error: "Something went wrong on our side. Please try again." }, 500);
+  }
   return c.text("Something went wrong on our side. Please try again.", 500);
 });
 
diff --git a/src/oidc/endpoints.tsx b/src/oidc/endpoints.ts
similarity index 66%
rename from src/oidc/endpoints.tsx
rename to src/oidc/endpoints.ts
index f88eb49..9d3c046 100644
--- a/src/oidc/endpoints.tsx
+++ b/src/oidc/endpoints.ts
@@ -1,4 +1,4 @@
-/* src/oidc/endpoints.tsx
+/* src/oidc/endpoints.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.
@@ -6,17 +6,15 @@
 
 import { Hono } from "hono";
 import { cors } from "hono/cors";
-import { Logout } from "pixelarticons/react";
 import { TTL, issuer, now, type AppContext, type AppEnv } from "../env";
 import { audit } from "../lib/audit";
 import { b64url, randomToken, sha256, sha256Hex, timingSafeEqualStr } from "../lib/crypto";
-import { form } from "../lib/http";
+import { csrfOk, staleCsrf } from "../lib/guards";
+import { body, fail, form, str } from "../lib/http";
 import { clientAllows, getClient, verifyClientSecret, type Client } from "../data/clients";
 import { publicJwks } from "../data/keys";
 import { endSession } from "../data/sessions";
-import { getUser, groupsFor } from "../data/users";
-import { render } from "../views/layout";
-import { Csrf } from "../views/ui";
+import { getUser, groupsFor, type UserRow } from "../data/users";
 import {
   SUPPORTED_CLAIMS,
   SUPPORTED_SCOPES,
@@ -29,6 +27,9 @@ import {
 
 export const oidc = new Hono<AppEnv>();
 
+/** How long a /login round trip may take and still satisfy prompt=login / max_age. */
+const FRESH_WINDOW = 30 * 60;
+
 // Machine-to-machine endpoints are called from other origins (including SPAs),
 // carry no cookies, and so are safe to open to any origin.
 const openCors = cors({
@@ -80,188 +81,193 @@ oidc.get("/.well-known/jwks.json", async (c) => {
 });
 
 // --- authorize ------------------------------------------------------------------------
-
-function errorPage(c: AppContext, title: string, text: string, status: 400 | 403 = 400) {
-  return render(
-    c,
-    { title, narrow: true, status },
-    <div class="card">
-      <h1>{title}</h1>
-      <p class="muted">{text}</p>
-    </div>,
-  );
+//
+// /authorize itself only ever redirects. When there's something to explain
+// (the app isn't allowed, the email isn't verified), it sends the browser to
+// the /authorize/notice page with the same query, which asks
+// /api/authorize/notice what to show. Problems that can't be sent back to the
+// app go to /error?code=…, which shows a fixed message for each code.
+
+/** Ends the request by showing a fixed error; never an open redirect. */
+function errorPage(c: AppContext, code: string) {
+  return c.redirect(`/error?code=${encodeURIComponent(code)}`);
 }
 
-async function authorizeParams(c: AppContext): Promise<Record<string, string>> {
-  if (c.req.method === "POST") return form(c);
+function authorizeParams(c: AppContext, posted: Record<string, string> | null): Record<string, string> {
+  if (posted) return posted;
   const out: Record<string, string> = {};
   for (const [k, v] of new URL(c.req.url).searchParams) if (!(k in out)) out[k] = v;
   return out;
 }
 
-async function authorize(c: AppContext) {
-  const params = await authorizeParams(c);
+type Decision =
+  /** Can't trust the client or redirect_uri, so show our own error. */
+  | { kind: "error"; code: string }
+  /** Send the browser here: an error back to the app, or a bounce through /login. */
+  | { kind: "redirect"; url: string }
+  /** Signed in, but this account may not use the app. */
+  | { kind: "denied"; client: Client; user: UserRow; back: string }
+  /** Signed in, but apps need a verified email first. */
+  | { kind: "verify-email"; client: Client; user: UserRow }
+  /** Good to go: issue a code. */
+  | { kind: "issue"; client: Client; user: UserRow; scopes: string[]; challenge: string | null; back: (v: Record<string, string>) => string };
+
+async function decide(c: AppContext, params: Record<string, string>): Promise<Decision> {
   const iss = issuer(c.env);
 
   // Until client and redirect_uri are both trusted, errors can only be shown
   // here: redirecting to an unverified URI would make this an open redirector.
-  if (!params.client_id || !params.redirect_uri) {
-    return errorPage(c, "Incomplete sign-in request", "The app didn't say who it is or where to send you back to.");
-  }
+  if (!params.client_id || !params.redirect_uri) return { kind: "error", code: "incomplete_request" };
   const client = await getClient(c.env, params.client_id);
-  if (!client) {
-    return errorPage(c, "Unknown application", "The app that sent you here isn't registered with this server.");
-  }
-  if (!client.redirectUris.includes(params.redirect_uri)) {
-    return errorPage(c, "Unregistered redirect", `${client.name} asked to send you somewhere it isn't allowed to.`);
-  }
+  if (!client) return { kind: "error", code: "unknown_client" };
+  if (!client.redirectUris.includes(params.redirect_uri)) return { kind: "error", code: "unregistered_redirect" };
 
   const back = (values: Record<string, string>) => {
     const url = new URL(params.redirect_uri!);
     for (const [k, v] of Object.entries(values)) url.searchParams.set(k, v);
     if (params.state !== undefined) url.searchParams.set("state", params.state);
     url.searchParams.set("iss", iss);
-    return c.redirect(url.toString());
+    return url.toString();
   };
-  const fail = (error: string, description: string) => back({ error, error_description: description });
+  const toApp = (error: string, description: string): Decision => ({
+    kind: "redirect",
+    url: back({ error, error_description: description }),
+  });
 
   if (params.request || params.request_uri) {
-    return fail(params.request ? "request_not_supported" : "request_uri_not_supported", "Request objects aren't supported.");
+    return toApp(params.request ? "request_not_supported" : "request_uri_not_supported", "Request objects aren't supported.");
   }
-  if (params.response_type !== "code") return fail("unsupported_response_type", "Only response_type=code is supported.");
+  if (params.response_type !== "code") return toApp("unsupported_response_type", "Only response_type=code is supported.");
   if (params.response_mode && params.response_mode !== "query") {
-    return fail("invalid_request", "Only response_mode=query is supported.");
+    return toApp("invalid_request", "Only response_mode=query is supported.");
   }
 
   const scopes = parseScope(params.scope);
-  if (!scopes.includes("openid")) return fail("invalid_scope", "The openid scope is required.");
+  if (!scopes.includes("openid")) return toApp("invalid_scope", "The openid scope is required.");
 
   const challenge = params.code_challenge;
   if (challenge) {
-    if (params.code_challenge_method !== "S256") return fail("invalid_request", "code_challenge_method must be S256.");
-    if (!/^[A-Za-z0-9_-]{43}$/.test(challenge)) return fail("invalid_request", "Malformed code_challenge.");
+    if (params.code_challenge_method !== "S256") return toApp("invalid_request", "code_challenge_method must be S256.");
+    if (!/^[A-Za-z0-9_-]{43}$/.test(challenge)) return toApp("invalid_request", "Malformed code_challenge.");
   } else if (client.isPublic) {
-    return fail("invalid_request", "Public clients must use PKCE (S256).");
+    return toApp("invalid_request", "Public clients must use PKCE (S256).");
   }
-  if (params.nonce && params.nonce.length > 512) return fail("invalid_request", "nonce is too long.");
+  if (params.nonce && params.nonce.length > 512) return toApp("invalid_request", "nonce is too long.");
 
   const prompts = (params.prompt ?? "").split(" ").filter(Boolean);
   if (prompts.includes("none") && prompts.length > 1) {
-    return fail("invalid_request", "prompt=none can't be combined with other values.");
+    return toApp("invalid_request", "prompt=none can't be combined with other values.");
   }
   let maxAge: number | null = null;
   if (params.max_age !== undefined) {
     maxAge = Number(params.max_age);
-    if (!Number.isInteger(maxAge) || maxAge < 0) return fail("invalid_request", "max_age must be a non-negative integer.");
+    if (!Number.isInteger(maxAge) || maxAge < 0) return toApp("invalid_request", "max_age must be a non-negative integer.");
   }
 
   // `_fresh` is added by us when bouncing through /login: a session that
   // authenticated at or after that moment satisfies prompt=login / max_age.
+  // Anyone can type `_fresh=1` into a URL, so only a recent one counts.
   const session = c.get("session");
   const fresh = Number(params._fresh) || 0;
+  const freshValid = fresh > 0 && fresh <= now() && now() - fresh <= FRESH_WINDOW;
   let needLogin = !session;
-  if (session && !(fresh && session.authTime >= fresh)) {
+  if (session && !(freshValid && session.authTime >= fresh)) {
     if (prompts.includes("login")) needLogin = true;
     if (maxAge !== null && now() - session.authTime > maxAge) needLogin = true;
   }
 
   if (needLogin) {
-    if (prompts.includes("none")) return fail("login_required", "The user isn't signed in.");
+    if (prompts.includes("none")) return toApp("login_required", "The user isn't signed in.");
     const again = new URLSearchParams(params);
     again.set("_fresh", String(now()));
     const loginParams = new URLSearchParams({ return: `/authorize?${again}` });
     if (session) loginParams.set("reauth", "1");
-    return c.redirect(`/login?${loginParams}`);
+    return { kind: "redirect", url: `/login?${loginParams}` };
   }
 
   const user = await getUser(c.env, session!.userId);
   if (!user || user.disabled) {
     await endSession(c);
-    return fail("login_required", "The user isn't signed in.");
+    return toApp("login_required", "The user isn't signed in.");
   }
 
   if (!clientAllows(client, await groupsFor(c.env, user.id))) {
-    await audit(c, "oidc.access_denied", { target: client.id });
-    if (prompts.includes("none")) return fail("access_denied", "This account isn't allowed to use this application.");
-    const denied = new URL(params.redirect_uri);
-    denied.searchParams.set("error", "access_denied");
-    if (params.state !== undefined) denied.searchParams.set("state", params.state);
-    denied.searchParams.set("iss", iss);
-    return render(
-      c,
-      { title: "No access", narrow: true, status: 403 },
-      <div class="card">
-        <h1>No access to {client.name}</h1>
-        <p class="muted">
-          You're signed in as <strong>@{user.username}</strong>, which isn't allowed to use {client.name}. If you think it should be, ask an admin.
-        </p>
-        <form method="post" action="/logout" class="stack">
-          <Csrf token={session!.csrf} />
-          <button type="submit" class="wide">Sign in as someone else</button>
-        </form>
-        <p class="small">
-          <a class="btn wide" href={denied.toString()}>Back to {client.name}</a>
-        </p>
-      </div>,
-    );
+    if (prompts.includes("none")) return toApp("access_denied", "This account isn't allowed to use this application.");
+    return { kind: "denied", client, user, back: back({ error: "access_denied" }) };
   }
 
   // Apps may trust the email claim, so every account needs a verified address.
   if (!user.email_verified) {
-    if (prompts.includes("none")) return fail("interaction_required", "The user hasn't verified their email address.");
-    return render(
-      c,
-      { title: "Verify your email", narrow: true, status: 403 },
-      <div class="card">
-        <h1>Verify your email first</h1>
-        <p class="muted">
-          {user.email ? (
-            <>
-              We sent a link to <strong>{user.email}</strong>. Open it, then come back here.
-            </>
-          ) : (
-            <>Add an email address on your account page and verify it to use {client.name}.</>
-          )}
-        </p>
-        <p>
-          <a class="btn primary wide" href={`/authorize?${new URLSearchParams(params)}`}>
-            I've verified it, continue
-          </a>
-        </p>
-        <p>
-          <a class="btn wide" href="/account">
-            Your account (resend the link)
-          </a>
-        </p>
-      </div>,
-    );
+    if (prompts.includes("none")) return toApp("interaction_required", "The user hasn't verified their email address.");
+    return { kind: "verify-email", client, user };
   }
 
-  const code = randomToken(32);
-  await c.env.DB.prepare(
-    `INSERT INTO auth_codes (code_hash, client_id, user_id, redirect_uri, scope, nonce, code_challenge, auth_time, amr, expires_at)
-     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
-  )
-    .bind(
-      await sha256Hex(code),
-      client.id,
-      user.id,
-      params.redirect_uri,
-      scopes.join(" "),
-      params.nonce ?? null,
-      challenge ?? null,
-      session!.authTime,
-      JSON.stringify(session!.amr),
-      now() + TTL.authCode,
-    )
-    .run();
+  return { kind: "issue", client, user, scopes, challenge: challenge ?? null, back };
+}
 
-  return back({ code });
+async function authorize(c: AppContext) {
+  const params = authorizeParams(c, c.req.method === "POST" ? await form(c) : null);
+  const decision = await decide(c, params);
+  switch (decision.kind) {
+    case "error":
+      return errorPage(c, decision.code);
+    case "redirect":
+      return c.redirect(decision.url);
+    case "denied":
+      await audit(c, "oidc.access_denied", { target: decision.client.id });
+      return c.redirect(`/authorize/notice?${new URLSearchParams(params)}`);
+    case "verify-email":
+      return c.redirect(`/authorize/notice?${new URLSearchParams(params)}`);
+    case "issue": {
+      const session = c.get("session")!;
+      const code = randomToken(32);
+      await c.env.DB.prepare(
+        `INSERT INTO auth_codes (code_hash, client_id, user_id, redirect_uri, scope, nonce, code_challenge, auth_time, amr, expires_at)
+         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+      )
+        .bind(
+          await sha256Hex(code),
+          decision.client.id,
+          decision.user.id,
+          params.redirect_uri,
+          decision.scopes.join(" "),
+          params.nonce ?? null,
+          decision.challenge,
+          session.authTime,
+          JSON.stringify(session.amr),
+          now() + TTL.authCode,
+        )
+        .run();
+      return c.redirect(decision.back({ code }));
+    }
+  }
 }
 
 oidc.get("/authorize", authorize);
 oidc.post("/authorize", authorize);
 
+/**
+ * What the /authorize/notice page should show for these parameters. Read-only:
+ * if the request can now go ahead, the page is just told to retry /authorize.
+ */
+oidc.get("/api/authorize/notice", async (c) => {
+  const params = authorizeParams(c, null);
+  const decision = await decide(c, params);
+  const retry = `/authorize?${new URLSearchParams(params)}`;
+  switch (decision.kind) {
+    case "error":
+      return c.json({ kind: "error", code: decision.code });
+    case "redirect":
+      return c.json({ kind: "redirect", url: decision.url });
+    case "issue":
+      return c.json({ kind: "redirect", url: retry });
+    case "denied":
+      return c.json({ kind: "denied", client: decision.client.name, username: decision.user.username, back: decision.back });
+    case "verify-email":
+      return c.json({ kind: "verify-email", client: decision.client.name, email: decision.user.email, retry });
+  }
+});
+
 // --- token --------------------------------------------------------------------------
 
 function tokenError(c: AppContext, error: string, description: string, status: 400 | 401 = 400) {
@@ -485,18 +491,13 @@ oidc.post("/revoke", async (c) => {
 
 // --- RP-initiated logout ------------------------------------------------------------
 
-type LogoutTarget = { ok: true; client: Client | null; returnTo: string | null } | { ok: false; response: Promise<Response> };
+type LogoutTarget = { ok: true; client: Client | null; returnTo: string | null } | { ok: false; code: string };
 
 /** Validates client_id / post_logout_redirect_uri exactly against the registration. */
 async function logoutTarget(c: AppContext, clientId: string | undefined, uri: string | undefined, state: string | undefined): Promise<LogoutTarget> {
   const client = clientId ? await getClient(c.env, clientId) : null;
   if (!uri) return { ok: true, client, returnTo: null };
-  if (!client || !client.postLogoutRedirectUris.includes(uri)) {
-    return {
-      ok: false,
-      response: errorPage(c, "Sign-out failed", "The app asked to send you somewhere it isn't allowed to after signing out."),
-    };
-  }
+  if (!client || !client.postLogoutRedirectUris.includes(uri)) return { ok: false, code: "logout_bad_redirect" };
   const url = new URL(uri);
   if (state) url.searchParams.set("state", state);
   return { ok: true, client, returnTo: url.toString() };
@@ -506,79 +507,62 @@ async function endSessionRequest(c: AppContext) {
   const params = c.req.method === "POST" ? await form(c) : Object.fromEntries(new URL(c.req.url).searchParams);
 
   const hint = params.id_token_hint ? await verifyIdTokenHint(c.env, params.id_token_hint) : null;
-  if (params.id_token_hint && !hint) {
-    return errorPage(c, "Sign-out failed", "The app sent a sign-out request this server couldn't verify.");
-  }
+  if (params.id_token_hint && !hint) return errorPage(c, "logout_unverified");
 
   let clientId = params.client_id;
   if (hint) {
-    if (clientId && !hint.aud.includes(clientId)) {
-      return errorPage(c, "Sign-out failed", "The sign-out request doesn't match the app that sent it.");
-    }
+    if (clientId && !hint.aud.includes(clientId)) return errorPage(c, "logout_mismatch");
     clientId ??= hint.aud[0];
   }
 
   const target = await logoutTarget(c, clientId, params.post_logout_redirect_uri, params.state);
-  if (!target.ok) return target.response;
-  const { client, returnTo } = target;
+  if (!target.ok) return errorPage(c, target.code);
 
   const session = c.get("session");
   const user = c.get("user");
   // A logout request without proof it came from the app is just a link anyone
   // could send, so it gets a confirmation step instead of acting straight away.
   if (session && user && !(hint && hint.sub === user.id)) {
-    return render(
-      c,
-      { title: "Sign out", narrow: true },
-      <div class="card">
-        <h1>Sign out?</h1>
-        <p class="muted">
-          {client ? `${client.name} wants to sign you out` : "Sign out"} of @{user.username} on this server.
-        </p>
-        <form method="post" action="/end-session/confirm" class="stack">
-          <Csrf token={session.csrf} />
-          <input type="hidden" name="client_id" value={clientId ?? ""} />
-          <input type="hidden" name="post_logout_redirect_uri" value={params.post_logout_redirect_uri ?? ""} />
-          <input type="hidden" name="state" value={params.state ?? ""} />
-          <button type="submit" class="primary wide">
-            <Logout class="icon" aria-hidden="true" />
-            Sign out
-          </button>
-        </form>
-        {returnTo && (
-          <p class="small">
-            <a class="btn wide" href={returnTo}>Stay signed in and go back</a>
-          </p>
-        )}
-      </div>,
-    );
+    const confirm = new URLSearchParams();
+    if (clientId) confirm.set("client_id", clientId);
+    if (params.post_logout_redirect_uri) confirm.set("post_logout_redirect_uri", params.post_logout_redirect_uri);
+    if (params.state) confirm.set("state", params.state);
+    return c.redirect(`/end-session/confirm?${confirm}`);
   }
 
   if (session) {
-    await audit(c, "logout.rp", { target: client?.id ?? null });
+    await audit(c, "logout.rp", { target: target.client?.id ?? null });
     await endSession(c);
   }
-  return c.redirect(returnTo ?? "/login?m=signed-out");
+  return c.redirect(target.returnTo ?? "/login?m=signed-out");
 }
 
 oidc.get("/end-session", endSessionRequest);
 oidc.post("/end-session", endSessionRequest);
 
-oidc.post("/end-session/confirm", async (c) => {
+/** What the sign-out confirmation page shows. */
+oidc.get("/api/end-session", async (c) => {
+  const q = new URL(c.req.url).searchParams;
+  const target = await logoutTarget(c, q.get("client_id") || undefined, q.get("post_logout_redirect_uri") || undefined, q.get("state") || undefined);
+  if (!target.ok) return fail(c, "The app asked to send you somewhere it isn't allowed to after signing out.", 400, { code: target.code });
+  return c.json({
+    client: target.client?.name ?? null,
+    username: c.get("user")?.username ?? null,
+    returnTo: target.returnTo,
+  });
+});
+
+oidc.post("/api/end-session", async (c) => {
   const session = c.get("session");
-  const body = await form(c);
-  if (session) {
-    if (!body._csrf || !timingSafeEqualStr(body._csrf, session.csrf)) {
-      return c.text("This form is out of date. Go back, reload the page and try again.", 403);
-    }
-  }
+  if (session && !csrfOk(c)) return staleCsrf(c);
 
-  const target = await logoutTarget(c, body.client_id || undefined, body.post_logout_redirect_uri || undefined, body.state || undefined);
-  if (!target.ok) return target.response;
+  const b = await body(c);
+  const target = await logoutTarget(c, str(b.client_id) || undefined, str(b.post_logout_redirect_uri) || undefined, str(b.state) || undefined);
+  if (!target.ok) return fail(c, "The app asked to send you somewhere it isn't allowed to after signing out.", 400, { code: target.code });
 
   if (session) {
     await audit(c, "logout.rp", { target: target.client?.id ?? null });
     await endSession(c);
   }
-  return c.redirect(target.returnTo ?? "/login?m=signed-out");
+  return c.json({ redirect: target.returnTo ?? "/login?m=signed-out" });
 });
diff --git a/src/oidc/tokens.ts b/src/oidc/tokens.ts
index 1e9c9f1..5be9d17 100644
--- a/src/oidc/tokens.ts
+++ b/src/oidc/tokens.ts
@@ -191,7 +191,12 @@ export async function verifyAccessToken(env: Env, token: string): Promise<Access
  */
 export async function verifyIdTokenHint(env: Env, token: string): Promise<{ sub: string; aud: string[] } | null> {
   try {
-    const { payload } = await withKeys(env, (keys) => compactVerify(token, keys, { algorithms: [ALG] }));
+    const { payload, protectedHeader } = await withKeys(env, (keys) =>
+      compactVerify(token, keys, { algorithms: [ALG] }),
+    );
+    // Access tokens are signed with the same key and also carry sub and aud;
+    // anyone they were handed to (an API) mustn't be able to sign the user out.
+    if (protectedHeader.typ === "at+jwt") return null;
     const claims = JSON.parse(new TextDecoder().decode(payload)) as JWTPayload;
     if (claims.iss !== issuer(env) || typeof claims.sub !== "string") return null;
     const aud = Array.isArray(claims.aud) ? claims.aud : claims.aud ? [claims.aud] : [];
diff --git a/src/routes/account.tsx b/src/routes/account.tsx
deleted file mode 100644
index 9894889..0000000
--- a/src/routes/account.tsx
+++ /dev/null
@@ -1,534 +0,0 @@
-/* src/routes/account.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 { Key, Save, Shield } from "pixelarticons/react";
-import { renderSVG } from "uqr";
-import type { RegistrationResponseJSON } from "@simplewebauthn/server";
-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, verifyPassword } from "../lib/password";
-import { generateTotpSecret, otpauthUri, verifyTotp } from "../lib/totp";
-import { cleanText, emailProblem, pictureProblem } from "../lib/validate";
-import {
-  countPasskeys,
-  deletePasskey,
-  finishRegistration,
-  listPasskeys,
-  registrationOptions,
-  renamePasskey,
-} from "../data/passkeys";
-import { notify, notifyAccountDeleted, signOutDevice } from "../data/notices";
-import { endSession, listSessions, revokeOtherSessions } from "../data/sessions";
-import {
-  claimTotpStep,
-  deleteUser,
-  disableTotp,
-  enableTotp,
-  getUser,
-  setPasswordHash,
-  setTotpPending,
-  updateProfile,
-  type UserRow,
-} from "../data/users";
-import { sendVerificationEmail } from "../data/verifications";
-import { render } from "../views/layout";
-import { Csrf, ErrorNote, Field, Flash, Section, amrLabel, date, describeAgent, relative } from "../views/ui";
-
-export const account = new Hono<AppEnv>();
-
-account.use("/account", requireUser);
-account.use("/account/*", requireUser, requireCsrf);
-
-async function me(c: AppContext): Promise<UserRow> {
-  const user = await getUser(c.env, c.get("user")!.id);
-  if (!user) throw new Error("session user vanished");
-  return user;
-}
-
-async function accountPage(c: AppContext, opts: { error?: string; status?: 400 } = {}) {
-  const user = await me(c);
-  const session = c.get("session")!;
-  const [passkeys, sessions] = await Promise.all([listPasskeys(c.env, user.id), listSessions(c.env, user.id)]);
-  const csrf = session.csrf;
-
-  return render(
-    c,
-    { title: "Your account", page: "account", status: opts.status },
-    <>
-      <h1>Hi, {user.name ?? user.username}</h1>
-      <Flash code={c.req.query("m")} />
-      <ErrorNote error={opts.error} />
-      <p class="notice error hidden" id="passkey-error" role="alert"></p>
-
-      <Section title="Profile" description="Shared with the apps you sign in to.">
-        <form method="post" action="/account/profile" class="stack">
-          <Csrf token={csrf} />
-          <label class="field">
-            <span>Username</span>
-            <input type="text" value={user.username} disabled />
-            <small class="muted">Only an admin can change this.</small>
-          </label>
-          <Field label="Display name" name="name" value={user.name} autocomplete="name" maxlength={100} />
-          <Field
-            label="Email"
-            name="email"
-            type="email"
-            value={user.email}
-            autocomplete="email"
-            maxlength={254}
-            hint={user.email ? (user.email_verified ? "Verified." : "Not verified.") : undefined}
-          />
-          <Field label="Picture URL" name="picture" type="url" value={user.picture} maxlength={2048} placeholder="https://…" />
-          <div>
-            <button type="submit">
-              <Save class="icon" aria-hidden="true" />
-              Save profile
-            </button>
-          </div>
-        </form>
-        {user.email && !user.email_verified && (
-          <form method="post" action="/account/email/verify" class="inline-edit">
-            <Csrf token={csrf} />
-            <small class="muted">{user.email} isn't verified yet.</small>
-            <button type="submit" class="small">Resend verification email</button>
-          </form>
-        )}
-      </Section>
-
-      <Section title="Passkeys" description="The quickest and safest way to sign in: your device unlocks with a fingerprint, face or PIN.">
-        {passkeys.length === 0 ? (
-          <p class="muted">No passkeys yet.</p>
-        ) : (
-          <ul class="rows">
-            {passkeys.map((p) => (
-              <li>
-                <div class="grow">
-                  <form method="post" action={`/account/passkeys/${encodeURIComponent(p.id)}/rename`} class="inline-edit">
-                    <Csrf token={csrf} />
-                    <input type="text" name="name" value={p.name} maxlength={60} aria-label="Passkey name" required />
-                    <button type="submit" class="small">Rename</button>
-                  </form>
-                  <small class="muted">
-                    {p.device_type === "multiDevice" ? "Synced" : "This device only"} · added {date(p.created_at)} · last used{" "}
-                    {relative(p.last_used_at)}
-                  </small>
-                </div>
-                <form
-                  method="post"
-                  action={`/account/passkeys/${encodeURIComponent(p.id)}/delete`}
-                  data-confirm={`Remove the passkey "${p.name}"?`}
-                >
-                  <Csrf token={csrf} />
-                  <button type="submit" class="danger small">Remove</button>
-                </form>
-              </li>
-            ))}
-          </ul>
-        )}
-        <form id="passkey-add" class="inline-edit">
-          <input type="text" name="name" placeholder="Name, e.g. Phone" maxlength={60} aria-label="New passkey name" />
-          <button type="submit" class="primary">
-            <Key class="icon" aria-hidden="true" />
-            Add a passkey
-          </button>
-        </form>
-      </Section>
-
-      <Section title="Password">
-        <p class="muted">
-          {user.password_hash
-            ? "You can sign in with a password."
-            : "No password set. Add one as a fallback for devices without your passkeys."}
-        </p>
-        <form method="post" action="/account/password" class="stack">
-          <Csrf token={csrf} />
-          <input type="text" name="username" value={user.username} autocomplete="username" hidden />
-          <Field
-            label={user.password_hash ? "New password" : "Password"}
-            name="password"
-            type="password"
-            required
-            autocomplete="new-password"
-            maxlength={512}
-            hint={`At least ${PASSWORD_MIN} characters. A long phrase beats a short tricky one.`}
-          />
-          <Field label="Confirm password" name="confirm" type="password" required autocomplete="new-password" maxlength={512} />
-          <div>
-            <button type="submit">{user.password_hash ? "Change password" : "Set password"}</button>
-          </div>
-        </form>
-        {user.password_hash && (
-          <form method="post" action="/account/password/remove" data-confirm="Remove your password? You'll only be able to sign in with a passkey.">
-            <Csrf token={csrf} />
-            <button type="submit" class="danger small" disabled={passkeys.length === 0}>
-              Remove password
-            </button>
-            {passkeys.length === 0 && <small class="muted"> Add a passkey first.</small>}
-          </form>
-        )}
-      </Section>
-
-      <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 ? (
-          <form method="post" action="/account/totp/disable" class="inline-edit">
-            <Csrf token={csrf} />
-            <span class="badge ok">On</span>
-            <input
-              type="text"
-              name="code"
-              placeholder="Current code"
-              inputmode="numeric"
-              autocomplete="one-time-code"
-              maxlength={7}
-              required
-              aria-label="Current code"
-            />
-            <button type="submit" class="danger">Turn off</button>
-          </form>
-        ) : (
-          <form method="post" action="/account/totp/start">
-            <Csrf token={csrf} />
-            <button type="submit">Set up an authenticator app</button>
-          </form>
-        )}
-      </Section>
-
-      <Section title="Sessions" description="Browsers signed in to this server. Apps you've signed in to keep their own sessions.">
-        <ul class="rows">
-          {sessions.map((s) => (
-            <li>
-              <div class="grow">
-                <strong>{describeAgent(s.user_agent)}</strong>
-                {s.id_hash === session.idHash && <span class="badge">This browser</span>}
-                <br />
-                <small class="muted">
-                  {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`}>
-                <Csrf token={csrf} />
-                <button type="submit" class="small">Sign out</button>
-              </form>
-            </li>
-          ))}
-        </ul>
-        {sessions.length > 1 && (
-          <form method="post" action="/account/sessions/revoke-others">
-            <Csrf token={csrf} />
-            <button type="submit" class="danger small">Sign out everywhere else</button>
-          </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>
-    </>,
-  );
-}
-
-account.get("/account", (c) => accountPage(c));
-
-account.post("/account/profile", async (c) => {
-  const body = await form(c);
-  const update = {
-    name: cleanText(body.name, 100),
-    email: cleanText(body.email, 254),
-    picture: cleanText(body.picture, 2048),
-  };
-  const problem = emailProblem(update.email) ?? pictureProblem(update.picture);
-  if (problem) return accountPage(c, { error: problem, status: 400 });
-
-  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"}`);
-  }
-  return c.redirect("/account?m=profile-saved");
-});
-
-account.post("/account/email/verify", async (c) => {
-  const user = await me(c);
-  if (!user.email || user.email_verified) return c.redirect("/account");
-  const sent = await sendVerificationEmail(c.env, user.id, user.email);
-  return c.redirect(`/account?m=${sent === "sent" ? "verify-sent" : "verify-failed"}`);
-});
-
-// --- passkeys --------------------------------------------------------------------
-
-account.post("/account/passkeys/options", async (c) => {
-  return c.json(await registrationOptions(c.env, await me(c)));
-});
-
-account.post("/account/passkeys/verify", async (c) => {
-  const body = await readJson<{ id?: string; response?: RegistrationResponseJSON; name?: string }>(c);
-  if (!body?.id || !body.response) return c.json({ error: "Malformed request." }, 400);
-
-  const name = cleanText(body.name, 60) ?? "Passkey";
-  const result = await finishRegistration(c.env, await me(c), body.id, body.response, name);
-  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" });
-});
-
-account.post("/account/passkeys/:id/rename", async (c) => {
-  const body = await form(c);
-  const name = cleanText(body.name, 60);
-  if (!name) return accountPage(c, { error: "Passkeys need a name.", status: 400 });
-  await renamePasskey(c.env, c.get("user")!.id, c.req.param("id"), name);
-  return c.redirect("/account?m=passkey-renamed");
-});
-
-account.post("/account/passkeys/:id/delete", async (c) => {
-  const user = await me(c);
-  if (!user.password_hash && (await countPasskeys(c.env, user.id)) <= 1) {
-    return accountPage(c, {
-      error: "That's your only way to sign in. Add another passkey or a password before removing it.",
-      status: 400,
-    });
-  }
-  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");
-});
-
-// --- password ------------------------------------------------------------------
-
-account.post("/account/password", async (c) => {
-  const user = await me(c);
-  const body = await form(c);
-  const password = body.password ?? "";
-  const problem =
-    passwordProblem(password, user.username) ??
-    (password !== body.confirm ? "The two passwords don't match." : null);
-  if (problem) return accountPage(c, { error: problem, status: 400 });
-
-  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");
-});
-
-account.post("/account/password/remove", async (c) => {
-  const user = await me(c);
-  if ((await countPasskeys(c.env, user.id)) === 0) {
-    return accountPage(c, { error: "Add a passkey before removing your password.", status: 400 });
-  }
-  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");
-});
-
-// --- TOTP ----------------------------------------------------------------------
-
-account.post("/account/totp/start", async (c) => {
-  const user = await me(c);
-  if (!user.password_hash) return c.redirect("/account");
-  if (user.totp_secret) return c.redirect("/account");
-  await setTotpPending(c.env, user.id, await encrypt(c.env.KEY_ENCRYPTION_KEY, generateTotpSecret()));
-  return c.redirect("/account/totp");
-});
-
-async function totpSetupPage(c: AppContext, error?: string) {
-  const user = await me(c);
-  if (!user.totp_pending || user.totp_secret) return c.redirect("/account");
-
-  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_pending);
-  const uri = otpauthUri(secret, siteName(c.env), user.username);
-  const svg = renderSVG(uri, { border: 2 });
-  const qr = `data:image/svg+xml,${encodeURIComponent(svg)}`;
-
-  return render(
-    c,
-    { title: "Set up two-factor codes", narrow: true, status: error ? 400 : 200 },
-    <div class="card">
-      <h1>Scan this code</h1>
-      <p class="muted">Use any authenticator app (1Password, Aegis, Google Authenticator…), then enter the code it shows.</p>
-      <ErrorNote error={error} />
-      <img class="qr" src={qr} alt="QR code for your authenticator app" width="220" height="220" />
-      <details>
-        <summary>Can't scan it?</summary>
-        <p>Enter this key instead:</p>
-        <p class="secret">
-          <code>{secret.match(/.{1,4}/g)?.join(" ")}</code>
-        </p>
-      </details>
-      <form method="post" action="/account/totp/confirm" class="stack">
-        <Csrf token={c.get("session")!.csrf} />
-        <Field label="Code" name="code" required inputmode="numeric" autocomplete="one-time-code" maxlength={7} autofocus />
-        <button type="submit" class="primary wide">
-          <Shield class="icon" aria-hidden="true" />
-          Turn on
-        </button>
-      </form>
-      <p class="small">
-        <a class="btn wide" href="/account">Cancel</a>
-      </p>
-    </div>,
-  );
-}
-
-account.get("/account/totp", (c) => totpSetupPage(c));
-
-account.post("/account/totp/confirm", async (c) => {
-  const user = await me(c);
-  if (!user.totp_pending) return c.redirect("/account");
-
-  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_pending);
-  const step = await verifyTotp(secret, (await form(c)).code ?? "", 0);
-  if (step === null) return totpSetupPage(c, "That code didn't match. Check your device's clock and try the next one.");
-
-  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");
-});
-
-account.post("/account/totp/disable", async (c) => {
-  const user = await me(c);
-  if (!user.totp_secret) return c.redirect("/account");
-
-  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_secret);
-  const step = await verifyTotp(secret, (await form(c)).code ?? "", user.totp_last_step);
-  if (step === null || !(await claimTotpStep(c.env, user.id, step))) {
-    return accountPage(c, { error: "That code didn't work, so two-factor codes are still on.", status: 400 });
-  }
-  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");
-});
-
-// --- sessions ------------------------------------------------------------------
-
-account.post("/account/sessions/revoke-others", async (c) => {
-  await revokeOtherSessions(c.env, c.get("user")!.id, c.get("session")!.idHash);
-  await audit(c, "account.sessions_revoked");
-  return c.redirect("/account?m=sessions-revoked");
-});
-
-account.post("/account/sessions/:id/revoke", async (c) => {
-  const id = c.req.param("id");
-  if (id === c.get("session")!.idHash) {
-    await endSession(c);
-    return c.redirect("/login?m=signed-out");
-  }
-  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
deleted file mode 100644
index c75ae85..0000000
--- a/src/routes/admin.tsx
+++ /dev/null
@@ -1,1100 +0,0 @@
-/* src/routes/admin.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 type { Child } from "hono/jsx";
-import { AppWindows, Link, Save, UserPlus, Users } from "pixelarticons/react";
-import { ADMIN_GROUP, issuer, type AppContext, type AppEnv } from "../env";
-import { audit, recentAudit } from "../lib/audit";
-import { form, formAll, lines } from "../lib/http";
-import { requireAdmin, requireCsrf, requireUser } from "../lib/guards";
-import {
-  cleanText,
-  clientIdProblem,
-  emailProblem,
-  groupProblem,
-  normaliseUsername,
-  pictureProblem,
-  redirectUriProblem,
-  subjectProblem,
-  usernameProblem,
-} from "../lib/validate";
-import {
-  createClient,
-  deleteClient,
-  getClient,
-  listClients,
-  makeClientPublic,
-  rotateClientSecret,
-  updateClient,
-  type Client,
-  type ClientInput,
-} from "../data/clients";
-import { createGroup, deleteGroup, listGroups, updateGroup, type GroupRow } from "../data/groups";
-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,
-  createUser,
-  deleteUser,
-  disableTotp,
-  getUser,
-  groupsFor,
-  listUsers,
-  revokeAllStatements,
-  setDisabled,
-  setPasswordHash,
-  setUserGroups,
-} from "../data/users";
-import { render } from "../views/layout";
-import { Csrf, ErrorNote, Field, Flash, Section, date, relative } from "../views/ui";
-import { builtinReserved, listReserved, reserveUsername, unreserveUsername } from "../data/reserved";
-
-export const admin = new Hono<AppEnv>();
-
-admin.use("/admin", requireUser, requireAdmin);
-admin.use("/admin/*", requireUser, requireAdmin, requireCsrf);
-
-admin.get("/admin", (c) => c.redirect("/admin/users"));
-
-const TABS = [
-  ["/admin/users", "Users"],
-  ["/admin/groups", "Groups"],
-  ["/admin/clients", "Applications"],
-  ["/admin/keys", "Signing keys"],
-  ["/admin/audit", "Audit log"],
-  ["/admin/reserved", "Reserved Names"],
-] as const;
-
-function adminPage(
-  c: AppContext,
-  opts: { title: string; tab: string; error?: string | null; status?: 400 | 404 },
-  body: Child,
-) {
-  return render(
-    c,
-    { title: opts.title, page: "admin", status: opts.status },
-    <>
-      <nav class="tabs">
-        {TABS.map(([href, label]) => (
-          <a href={href} class={opts.tab === href ? "active" : undefined}>
-            {label}
-          </a>
-        ))}
-      </nav>
-      <Flash code={c.req.query("m")} />
-      <ErrorNote error={opts.error} />
-      {body}
-    </>,
-  );
-}
-
-function csrf(c: AppContext): string {
-  return c.get("session")!.csrf;
-}
-
-function GroupChecks(props: { groups: GroupRow[]; selected: string[]; name?: string }) {
-  if (props.groups.length === 0) return <p class="muted">No groups yet.</p>;
-  return (
-    <div class="checks">
-      {props.groups.map((g) => (
-        <label class="check">
-          <input type="checkbox" name={props.name ?? "groups"} value={g.name} checked={props.selected.includes(g.name)} />
-          <span>
-            {g.name}
-            {g.description && <small class="muted"> — {g.description}</small>}
-          </span>
-        </label>
-      ))}
-    </div>
-  );
-}
-
-function notFound(c: AppContext, what: string) {
-  return adminPage(
-    c,
-    { title: "Not found", tab: "", status: 404 },
-    <p>
-      That {what} doesn't exist. <a class="btn small" href="/admin">Back</a>
-    </p>,
-  );
-}
-
-// --- users -----------------------------------------------------------------------
-
-async function usersPage(c: AppContext, error?: string, values: Record<string, string> = {}, chosen: string[] = []) {
-  const [users, groups] = await Promise.all([listUsers(c.env), listGroups(c.env)]);
-  return adminPage(
-    c,
-    { title: "Users", tab: "/admin/users", error, status: error ? 400 : undefined },
-    <>
-      <Section title={`Users (${users.length})`}>
-        <div class="table-wrap">
-          <table>
-            <thead>
-              <tr>
-                <th>User</th>
-                <th>Groups</th>
-                <th>Sign-in methods</th>
-                <th>Last sign-in</th>
-              </tr>
-            </thead>
-            <tbody>
-              {users.map((u) => (
-                <tr>
-                  <td>
-                    <a class="btn small" href={`/admin/users/${encodeURIComponent(u.id)}`}>
-                      {u.name ?? u.username}
-                    </a>
-                    <br />
-                    <small class="muted">@{u.username}</small>
-                    {u.disabled ? <span class="badge danger">disabled</span> : null}
-                  </td>
-                  <td>{u.groups.length ? u.groups.map((g) => <span class="badge">{g}</span>) : <span class="muted">—</span>}</td>
-                  <td>
-                    {u.passkey_count > 0 && <span class="badge">{u.passkey_count} passkey{u.passkey_count === 1 ? "" : "s"}</span>}
-                    {u.password_hash && <span class="badge">password{u.totp_secret ? " + 2FA" : ""}</span>}
-                    {!u.passkey_count && !u.password_hash && <span class="muted">none</span>}
-                  </td>
-                  <td>{relative(u.last_login_at)}</td>
-                </tr>
-              ))}
-            </tbody>
-          </table>
-        </div>
-      </Section>
-
-      <Section title="Add a user" description="They'll need a sign-in link from their page to set up a passkey or password.">
-        <form method="post" action="/admin/users" class="stack">
-          <Csrf token={csrf(c)} />
-          <div class="grid2">
-            <Field label="Username" name="username" value={values.username} required maxlength={32} autocomplete="off" />
-            <Field label="Display name" name="name" value={values.name} maxlength={100} autocomplete="off" />
-            <Field label="Email" name="email" type="email" value={values.email} maxlength={254} autocomplete="off" />
-            <label class="check">
-              <input type="checkbox" name="email_verified" value="1" checked={values.email_verified === "1"} />
-              <span>Email is verified</span>
-            </label>
-          </div>
-          <fieldset>
-            <legend>Groups</legend>
-            <GroupChecks groups={groups} selected={chosen} />
-          </fieldset>
-          <details>
-            <summary>Advanced</summary>
-            <Field
-              label="Subject id"
-              name="subject"
-              value={values.subject}
-              maxlength={64}
-              autocomplete="off"
-              hint="The permanent `sub` apps see. Leave blank for a random UUID. Set it to carry an account over from another identity provider without apps treating it as a new person."
-            />
-          </details>
-          <div>
-            <button type="submit" class="primary">
-              <UserPlus class="icon" aria-hidden="true" />
-              Create user
-            </button>
-          </div>
-        </form>
-      </Section>
-    </>,
-  );
-}
-
-admin.get("/admin/users", (c) => usersPage(c));
-
-admin.post("/admin/users", async (c) => {
-  const body = await form(c);
-  const groups = await formAll(c, "groups");
-  const username = normaliseUsername(body.username);
-  const email = cleanText(body.email, 254);
-  const subject = cleanText(body.subject, 64);
-  const problem =
-    usernameProblem(username) ?? emailProblem(email) ?? (subject ? subjectProblem(subject) : null);
-  if (problem) return usersPage(c, problem, body, groups);
-
-  const result = await createUser(c.env, {
-    id: subject ?? undefined,
-    username,
-    name: cleanText(body.name, 100),
-    email,
-    emailVerified: body.email_verified === "1",
-  });
-  if (!result.ok) return usersPage(c, result.error, body, groups);
-
-  await setUserGroups(c.env, result.id, groups);
-  await audit(c, "admin.user_created", { target: username, detail: groups.join(",") });
-  return c.redirect(`/admin/users/${encodeURIComponent(result.id)}?m=user-created`);
-});
-
-async function userPage(
-  c: AppContext,
-  id: string,
-  opts: { error?: string; link?: { url: string; expiresAt: number } } = {},
-) {
-  const user = await getUser(c.env, id);
-  if (!user) return notFound(c, "user");
-
-  const [groups, allGroups, passkeys, sessions, openLink] = await Promise.all([
-    groupsFor(c.env, id),
-    listGroups(c.env),
-    listPasskeys(c.env, id),
-    listSessions(c.env, id),
-    hasOpenLoginLink(c.env, id),
-  ]);
-  const base = `/admin/users/${encodeURIComponent(id)}`;
-  const token = csrf(c);
-  const self = c.get("user")!.id === id;
-
-  return adminPage(
-    c,
-    { title: `@${user.username}`, tab: "/admin/users", error: opts.error, status: opts.error ? 400 : undefined },
-    <>
-      <p>
-        <a class="btn small" href="/admin/users">← All users</a>
-      </p>
-      <h1>
-        {user.name ?? user.username} <small class="muted">@{user.username}</small>
-        {user.disabled ? <span class="badge danger">disabled</span> : null}
-      </h1>
-      <p class="muted">
-        Subject <code>{user.id}</code> · created {date(user.created_at)} · last sign-in {relative(user.last_login_at)}
-      </p>
-
-      {opts.link && (
-        <div class="notice ok">
-          <p>
-            <strong>Sign-in link</strong> — send this to @{user.username}. It works once and expires{" "}
-            {relative(opts.link.expiresAt)}. It won't be shown again.
-          </p>
-          <p class="copyrow">
-            <input type="text" readonly value={opts.link.url} aria-label="Sign-in link" />
-            <button type="button" data-copy={opts.link.url}>Copy</button>
-          </p>
-        </div>
-      )}
-
-      <Section title="Profile">
-        <form method="post" action={`${base}/profile`} class="stack">
-          <Csrf token={token} />
-          <div class="grid2">
-            <Field label="Username" name="username" value={user.username} required maxlength={32} autocomplete="off" hint="Apps may use this as a mailbox or URL; changing it can break things there." />
-            <Field label="Display name" name="name" value={user.name} maxlength={100} autocomplete="off" />
-            <Field label="Email" name="email" type="email" value={user.email} maxlength={254} autocomplete="off" />
-            <Field label="Picture URL" name="picture" type="url" value={user.picture} maxlength={2048} autocomplete="off" />
-            <label class="check">
-              <input type="checkbox" name="email_verified" value="1" checked={user.email_verified === 1} />
-              <span>Email is verified</span>
-            </label>
-          </div>
-          <div>
-            <button type="submit">
-              <Save class="icon" aria-hidden="true" />
-              Save profile
-            </button>
-          </div>
-        </form>
-      </Section>
-
-      <Section title="Groups" description="Sent to apps in the `groups` claim, and used to limit who can open each application.">
-        <form method="post" action={`${base}/groups`} class="stack">
-          <Csrf token={token} />
-          <GroupChecks groups={allGroups} selected={groups} />
-          <div>
-            <button type="submit">
-              <Save class="icon" aria-hidden="true" />
-              Save groups
-            </button>
-          </div>
-        </form>
-      </Section>
-
-      <Section title="Sign-in link" description="A one-time link that signs this person in so they can add a passkey or password. Use it for new accounts and lost devices.">
-        {openLink && (
-          <form method="post" action={`${base}/link/revoke`} class="inline-edit">
-            <Csrf token={token} />
-            <span>An unused link expires {relative(openLink)}.</span>
-            <button type="submit" class="small">Revoke it</button>
-          </form>
-        )}
-        <form method="post" action={`${base}/link`} class="inline-edit">
-          <Csrf token={token} />
-          <label>
-            Valid for{" "}
-            <select name="ttl">
-              <option value="900">15 minutes</option>
-              <option value="3600" selected>1 hour</option>
-              <option value="86400">1 day</option>
-              <option value="604800">7 days</option>
-            </select>
-          </label>
-          <button type="submit" class="primary">
-            <Link class="icon" aria-hidden="true" />
-            {openLink ? "Replace link" : "Create link"}
-          </button>
-        </form>
-      </Section>
-
-      <Section title="Sign-in methods">
-        <ul class="rows">
-          {passkeys.map((p) => (
-            <li>
-              <div class="grow">
-                <strong>Passkey: {p.name}</strong>
-                <br />
-                <small class="muted">added {date(p.created_at)} · last used {relative(p.last_used_at)}</small>
-              </div>
-              <form method="post" action={`${base}/passkeys/${encodeURIComponent(p.id)}/delete`} data-confirm={`Remove the passkey "${p.name}"?`}>
-                <Csrf token={token} />
-                <button type="submit" class="danger small">Remove</button>
-              </form>
-            </li>
-          ))}
-          {user.password_hash && (
-            <li>
-              <div class="grow">
-                <strong>Password</strong>
-              </div>
-              <form method="post" action={`${base}/password/remove`} data-confirm="Remove this password (and any two-factor setup)?">
-                <Csrf token={token} />
-                <button type="submit" class="danger small">Remove</button>
-              </form>
-            </li>
-          )}
-          {user.totp_secret && (
-            <li>
-              <div class="grow">
-                <strong>Two-factor codes</strong>
-              </div>
-              <form method="post" action={`${base}/totp/reset`} data-confirm="Turn off two-factor codes for this account?">
-                <Csrf token={token} />
-                <button type="submit" class="danger small">Turn off</button>
-              </form>
-            </li>
-          )}
-          {!passkeys.length && !user.password_hash && <li class="muted">None. Send a sign-in link so they can add one.</li>}
-        </ul>
-      </Section>
-
-      <Section title="Access">
-        <p class="muted">
-          {sessions.length} active browser session{sessions.length === 1 ? "" : "s"} on this server.
-        </p>
-        <div class="buttons">
-          <form method="post" action={`${base}/signout`} data-confirm="Sign this account out of every browser and application?">
-            <Csrf token={token} />
-            <button type="submit">Sign out everywhere</button>
-          </form>
-          {!self &&
-            (user.disabled ? (
-              <form method="post" action={`${base}/enable`}>
-                <Csrf token={token} />
-                <button type="submit">Enable account</button>
-              </form>
-            ) : (
-              <form method="post" action={`${base}/disable`} data-confirm="Disable this account? They'll be signed out everywhere.">
-                <Csrf token={token} />
-                <button type="submit" class="danger">Disable account</button>
-              </form>
-            ))}
-        </div>
-      </Section>
-
-      {!self && (
-        <Section title="Delete account" description="Permanent. Apps keep whatever they stored about this person; a new account will get a new subject id.">
-          <form method="post" action={`${base}/delete`} class="inline-edit">
-            <Csrf token={token} />
-            <input type="text" name="confirm" placeholder={`Type ${user.username} to confirm`} required autocomplete="off" aria-label="Confirm username" />
-            <button type="submit" class="danger">Delete</button>
-          </form>
-        </Section>
-      )}
-    </>,
-  );
-}
-
-admin.get("/admin/users/:id", (c) => userPage(c, c.req.param("id")));
-
-admin.post("/admin/users/:id/profile", async (c) => {
-  const id = c.req.param("id");
-  const body = await form(c);
-  const update = {
-    username: normaliseUsername(body.username),
-    name: cleanText(body.name, 100),
-    email: cleanText(body.email, 254),
-    picture: cleanText(body.picture, 2048),
-    emailVerified: body.email_verified === "1",
-  };
-  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`);
-});
-
-admin.post("/admin/users/:id/groups", async (c) => {
-  const id = c.req.param("id");
-  const groups = await formAll(c, "groups");
-  if (id === c.get("user")!.id && !groups.includes(ADMIN_GROUP)) {
-    return userPage(c, id, { error: `You can't remove yourself from ${ADMIN_GROUP}. Ask another admin.` });
-  }
-  await setUserGroups(c.env, id, groups);
-  await audit(c, "admin.user_groups", { target: id, detail: groups.join(",") });
-  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=groups-saved`);
-});
-
-const LINK_TTLS = new Set([900, 3600, 86400, 604800]);
-
-admin.post("/admin/users/:id/link", async (c) => {
-  const id = c.req.param("id");
-  const user = await getUser(c.env, id);
-  if (!user) return notFound(c, "user");
-  if (user.disabled) return userPage(c, id, { error: "Enable the account before sending a sign-in link." });
-
-  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 });
-});
-
-admin.post("/admin/users/:id/link/revoke", async (c) => {
-  const id = c.req.param("id");
-  await revokeLoginLinks(c.env, id);
-  await audit(c, "admin.link_revoked", { target: id });
-  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=link-revoked`);
-});
-
-admin.post("/admin/users/:id/passkeys/:pid/delete", async (c) => {
-  const id = c.req.param("id");
-  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`);
-});
-
-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`);
-});
-
-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`);
-});
-
-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`);
-});
-
-admin.post("/admin/users/:id/disable", async (c) => {
-  const id = c.req.param("id");
-  if (id === c.get("user")!.id) return userPage(c, id, { error: "You can't disable your own account." });
-  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`);
-});
-
-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`);
-});
-
-admin.post("/admin/users/:id/delete", async (c) => {
-  const id = c.req.param("id");
-  const user = await getUser(c.env, id);
-  if (!user) return notFound(c, "user");
-  if (id === c.get("user")!.id) return userPage(c, id, { error: "You can't delete your own account." });
-  if (normaliseUsername((await form(c)).confirm) !== user.username) {
-    return userPage(c, id, { error: "Type the username exactly to delete the account." });
-  }
-  await deleteUser(c.env, id);
-  await audit(c, "admin.user_deleted", { target: `${user.username} (${id})` });
-  return c.redirect("/admin/users?m=user-deleted");
-});
-
-// --- groups ----------------------------------------------------------------------
-
-async function groupsPage(c: AppContext, error?: string) {
-  const groups = await listGroups(c.env);
-  const token = csrf(c);
-  return adminPage(
-    c,
-    { title: "Groups", tab: "/admin/groups", error, status: error ? 400 : undefined },
-    <>
-      <Section title="Groups" description="Apps receive group names in the `groups` claim. Name them after what they allow, e.g. system-owner or inbox-admin.">
-        <ul class="rows">
-          {groups.map((g) => (
-            <li>
-              <div class="grow">
-                <strong>{g.name}</strong> <small class="muted">{g.member_count} member{g.member_count === 1 ? "" : "s"}</small>
-                <form method="post" action={`/admin/groups/${encodeURIComponent(g.name)}`} class="inline-edit">
-                  <Csrf token={token} />
-                  <input type="text" name="description" value={g.description} maxlength={200} placeholder="Description" aria-label={`Description of ${g.name}`} />
-                  <button type="submit" class="small">
-                    <Save class="icon" aria-hidden="true" />
-                    Save
-                  </button>
-                </form>
-              </div>
-              {g.name !== ADMIN_GROUP && (
-                <form method="post" action={`/admin/groups/${encodeURIComponent(g.name)}/delete`} data-confirm={`Delete the group "${g.name}"? Members lose it immediately.`}>
-                  <Csrf token={token} />
-                  <button type="submit" class="danger small">Delete</button>
-                </form>
-              )}
-            </li>
-          ))}
-        </ul>
-      </Section>
-      <Section title="New group">
-        <form method="post" action="/admin/groups" class="stack">
-          <Csrf token={token} />
-          <div class="grid2">
-            <Field label="Name" name="name" required maxlength={64} autocomplete="off" />
-            <Field label="Description" name="description" maxlength={200} autocomplete="off" />
-          </div>
-          <div>
-            <button type="submit" class="primary">
-              <Users class="icon" aria-hidden="true" />
-              Create group
-            </button>
-          </div>
-        </form>
-      </Section>
-    </>,
-  );
-}
-
-admin.get("/admin/groups", (c) => groupsPage(c));
-
-admin.post("/admin/groups", async (c) => {
-  const body = await form(c);
-  const name = (body.name ?? "").trim().toLowerCase();
-  const problem = groupProblem(name);
-  if (problem) return groupsPage(c, problem);
-  if (!(await createGroup(c.env, name, cleanText(body.description, 200) ?? ""))) {
-    return groupsPage(c, "A group with that name already exists.");
-  }
-  await audit(c, "admin.group_created", { target: name });
-  return c.redirect("/admin/groups?m=group-created");
-});
-
-admin.post("/admin/groups/:name", async (c) => {
-  const body = await form(c);
-  await updateGroup(c.env, c.req.param("name"), cleanText(body.description, 200) ?? "");
-  return c.redirect("/admin/groups?m=group-saved");
-});
-
-admin.post("/admin/groups/:name/delete", async (c) => {
-  const name = c.req.param("name");
-  if (name === ADMIN_GROUP) return groupsPage(c, `${ADMIN_GROUP} can't be deleted.`);
-  await deleteGroup(c.env, name);
-  await audit(c, "admin.group_deleted", { target: name });
-  return c.redirect("/admin/groups?m=group-deleted");
-});
-
-// --- reserved usernames ------------------------------------------------------------
-
-async function reservedPage(c: AppContext, error?: string) {
-  const reserved = await listReserved(c.env);
-  const token = csrf(c);
-  return adminPage(
-    c,
-    { title: "Reserved names", tab: "/admin/reserved", error, status: error ? 400 : undefined },
-    <>
-      <Section title="Reserved names" description="Nobody can sign up with these. Dots, dashes and underscores are
-  ignored when matching, so reserving noreply also blocks no-reply and no.reply. Admins can still create accounts
-  with them.">
-        <ul class="rows">
-          {reserved.map((r) => (
-            <li>
-              <div class="grow">
-                <strong>{r.username}</strong> {r.note && <small class="muted">{r.note}</small>}
-              </div>
-              <form method="post" action={`/admin/reserved/${encodeURIComponent(r.username)}/delete`}
-                data-confirm={`Release "${r.username}"? Anyone can then sign up with it.`}>
-                <Csrf token={token} />
-                <button type="submit" class="danger small">Release</button>
-              </form>
-            </li>
-          ))}
-        </ul>
-      </Section>
-      <Section title="Reserve a name">
-        <form method="post" action="/admin/reserved" class="stack">
-          <Csrf token={token} />
-          <div class="grid2">
-            <Field label="Username" name="username" required maxlength={32} autocomplete="off" />
-            <Field label="Note" name="note" maxlength={200} autocomplete="off" hint="Why, or who it's held for."
-            />
-          </div>
-          <div>
-            <button type="submit" class="primary">
-              <Save class="icon" aria-hidden="true" />
-              Reserve
-            </button>
-          </div>
-        </form>
-      </Section>
-      <Section title="Always reserved" description="Built into the code (src/data/reserved.ts).">
-        <p class="muted small">{builtinReserved().join(", ")}</p>
-      </Section>
-    </>,
-  );
-}
-
-admin.get("/admin/reserved", (c) => reservedPage(c));
-
-admin.post("/admin/reserved", async (c) => {
-  const body = await form(c);
-  const username = normaliseUsername(body.username);
-  const problem = usernameProblem(username);
-  if (problem) return reservedPage(c, problem);
-  if (!(await reserveUsername(c.env, username, cleanText(body.note, 200) ?? ""))) {
-    return reservedPage(c, "That name is already reserved.");
-  }
-  await audit(c, "admin.username_reserved", { target: username });
-  return c.redirect("/admin/reserved?m=name-reserved");
-});
-
-admin.post("/admin/reserved/:name/delete", async (c) => {
-  const name = c.req.param("name");
-  await unreserveUsername(c.env, name);
-  await audit(c, "admin.username_released", { target: name });
-  return c.redirect("/admin/reserved?m=name-released");
-});
-
-// --- clients -----------------------------------------------------------------------
-
-interface ClientForm {
-  input: ClientInput;
-  raw: Record<string, string>;
-}
-
-async function readClientForm(c: AppContext): Promise<ClientForm | { error: string; raw: Record<string, string>; groups: string[] }> {
-  const raw = await form(c);
-  const chosen = await formAll(c, "allowed_groups");
-  const known = new Set((await listGroups(c.env)).map((g) => g.name));
-  const name = cleanText(raw.name, 100);
-  const redirectUris = lines(raw.redirect_uris);
-  const postLogoutRedirectUris = lines(raw.post_logout_redirect_uris);
-
-  const fail = (error: string) => ({ error, raw, groups: chosen });
-  if (!name) return fail("Applications need a name.");
-  if (redirectUris.length === 0) return fail("Add at least one redirect URI.");
-  if (redirectUris.length + postLogoutRedirectUris.length > 40) return fail("That's too many URIs.");
-  for (const uri of [...redirectUris, ...postLogoutRedirectUris]) {
-    const problem = redirectUriProblem(uri);
-    if (problem) return fail(problem);
-  }
-  return {
-    raw,
-    input: {
-      name,
-      redirectUris: [...new Set(redirectUris)],
-      postLogoutRedirectUris: [...new Set(postLogoutRedirectUris)],
-      allowedGroups: chosen.filter((g) => known.has(g)),
-    },
-  };
-}
-
-function ClientFields(props: { groups: GroupRow[]; name?: string; redirects?: string; postLogout?: string; allowed: string[] }) {
-  return (
-    <>
-      <Field label="Name" name="name" value={props.name} required maxlength={100} autocomplete="off" hint="Shown to people when they're asked to sign in." />
-      <label class="field">
-        <span>Redirect URIs</span>
-        <textarea name="redirect_uris" rows={3} required placeholder="https://app.example.com/auth/callback">
-          {props.redirects ?? ""}
-        </textarea>
-        <small class="muted">One per line, matched exactly.</small>
-      </label>
-      <label class="field">
-        <span>Post-logout redirect URIs</span>
-        <textarea name="post_logout_redirect_uris" rows={2} placeholder="https://app.example.com/">
-          {props.postLogout ?? ""}
-        </textarea>
-        <small class="muted">Optional. Where the app may send people after signing out here.</small>
-      </label>
-      <fieldset>
-        <legend>Who can use it</legend>
-        <p class="muted small">Leave everything unticked to allow every account.</p>
-        <GroupChecks groups={props.groups} selected={props.allowed} name="allowed_groups" />
-      </fieldset>
-    </>
-  );
-}
-
-async function clientsPage(c: AppContext, error?: string, raw: Record<string, string> = {}, allowed: string[] = []) {
-  const [clients, groups] = await Promise.all([listClients(c.env), listGroups(c.env)]);
-  return adminPage(
-    c,
-    { title: "Applications", tab: "/admin/clients", error, status: error ? 400 : undefined },
-    <>
-      <Section title="Applications" description="Each app that signs people in through this server is an OpenID Connect client.">
-        {clients.length === 0 ? (
-          <p class="muted">No applications yet.</p>
-        ) : (
-          <div class="table-wrap">
-            <table>
-              <thead>
-                <tr>
-                  <th>Name</th>
-                  <th>Client id</th>
-                  <th>Type</th>
-                  <th>Allowed</th>
-                </tr>
-              </thead>
-              <tbody>
-                {clients.map((cl) => (
-                  <tr>
-                    <td>
-                      <a class="btn small" href={`/admin/clients/${encodeURIComponent(cl.id)}`}>
-                        {cl.name}
-                      </a>
-                    </td>
-                    <td>
-                      <code>{cl.id}</code>
-                    </td>
-                    <td>{cl.isPublic ? "public (PKCE)" : "confidential"}</td>
-                    <td>{cl.allowedGroups.length ? cl.allowedGroups.map((g) => <span class="badge">{g}</span>) : "everyone"}</td>
-                  </tr>
-                ))}
-              </tbody>
-            </table>
-          </div>
-        )}
-      </Section>
-
-      <Section title="Add an application">
-        <form method="post" action="/admin/clients" class="stack">
-          <Csrf token={csrf(c)} />
-          <ClientFields groups={groups} name={raw.name} redirects={raw.redirect_uris} postLogout={raw.post_logout_redirect_uris} allowed={allowed} />
-          <fieldset>
-            <legend>Type</legend>
-            <label class="check">
-              <input type="radio" name="type" value="confidential" checked={raw.type !== "public"} />
-              <span>
-                Confidential <small class="muted">— has a server that can keep a client secret (dough-git, inbox).</small>
-              </span>
-            </label>
-            <label class="check">
-              <input type="radio" name="type" value="public" checked={raw.type === "public"} />
-              <span>
-                Public <small class="muted">— runs entirely in the browser or on a device; uses PKCE and no secret.</small>
-              </span>
-            </label>
-          </fieldset>
-          <details>
-            <summary>Advanced</summary>
-            <Field
-              label="Client id"
-              name="client_id"
-              value={raw.client_id}
-              maxlength={128}
-              autocomplete="off"
-              hint="Leave blank for a random id. Set it to keep an app's existing client id when moving it over from another provider."
-            />
-          </details>
-          <div>
-            <button type="submit" class="primary">
-              <AppWindows class="icon" aria-hidden="true" />
-              Create application
-            </button>
-          </div>
-        </form>
-      </Section>
-    </>,
-  );
-}
-
-admin.get("/admin/clients", (c) => clientsPage(c));
-
-admin.post("/admin/clients", async (c) => {
-  const parsed = await readClientForm(c);
-  if ("error" in parsed) return clientsPage(c, parsed.error, parsed.raw, parsed.groups);
-
-  const id = cleanText(parsed.raw.client_id, 128) ?? crypto.randomUUID();
-  const idProblem = clientIdProblem(id);
-  if (idProblem) return clientsPage(c, idProblem, parsed.raw, parsed.input.allowedGroups);
-
-  const result = await createClient(c.env, id, parsed.raw.type !== "public", parsed.input);
-  if (!result.ok) return clientsPage(c, result.error, parsed.raw, parsed.input.allowedGroups);
-
-  await audit(c, "admin.client_created", { target: id });
-  return clientPage(c, id, { secret: result.secret });
-});
-
-function Integration(props: { c: AppContext; client: Client }) {
-  const iss = issuer(props.c.env);
-  const rows: [string, string][] = [
-    ["Issuer", iss],
-    ["Discovery", `${iss}/.well-known/openid-configuration`],
-    ["Client id", props.client.id],
-    ["Token auth", props.client.isPublic ? "none (PKCE)" : "client_secret_basic or client_secret_post"],
-    ["Scopes", "openid profile email groups (+ offline_access for refresh tokens)"],
-  ];
-  return (
-    <dl class="kv">
-      {rows.map(([k, v]) => (
-        <>
-          <dt>{k}</dt>
-          <dd>
-            <code>{v}</code>
-          </dd>
-        </>
-      ))}
-    </dl>
-  );
-}
-
-async function clientPage(c: AppContext, id: string, opts: { error?: string; secret?: string | null } = {}) {
-  const client = await getClient(c.env, id);
-  if (!client) return notFound(c, "application");
-  const groups = await listGroups(c.env);
-  const base = `/admin/clients/${encodeURIComponent(id)}`;
-  const token = csrf(c);
-
-  return adminPage(
-    c,
-    { title: client.name, tab: "/admin/clients", error: opts.error, status: opts.error ? 400 : undefined },
-    <>
-      <p>
-        <a class="btn small" href="/admin/clients">← All applications</a>
-      </p>
-      <h1>{client.name}</h1>
-
-      {opts.secret && (
-        <div class="notice ok">
-          <p>
-            <strong>Client secret</strong> — copy it into the app's configuration now. It won't be shown again.
-          </p>
-          <p class="copyrow">
-            <input type="text" readonly value={opts.secret} aria-label="Client secret" />
-            <button type="button" data-copy={opts.secret}>Copy</button>
-          </p>
-        </div>
-      )}
-
-      <Section title="Connecting the app">
-        <Integration c={c} client={client} />
-      </Section>
-
-      <Section title="Settings">
-        <form method="post" action={base} class="stack">
-          <Csrf token={token} />
-          <ClientFields
-            groups={groups}
-            name={client.name}
-            redirects={client.redirectUris.join("\n")}
-            postLogout={client.postLogoutRedirectUris.join("\n")}
-            allowed={client.allowedGroups}
-          />
-          <div>
-            <button type="submit">
-              <Save class="icon" aria-hidden="true" />
-              Save
-            </button>
-          </div>
-        </form>
-      </Section>
-
-      <Section title="Client secret">
-        <p class="muted">
-          {client.isPublic
-            ? "This is a public client: it has no secret and must use PKCE."
-            : "Rotating the secret breaks the app until it's given the new one."}
-        </p>
-        <div class="buttons">
-          <form method="post" action={`${base}/secret`} data-confirm={client.isPublic ? "Give this app a secret and make it confidential?" : "Replace the secret? The old one stops working immediately."}>
-            <Csrf token={token} />
-            <button type="submit">{client.isPublic ? "Create a secret" : "Rotate secret"}</button>
-          </form>
-          {!client.isPublic && (
-            <form method="post" action={`${base}/public`} data-confirm="Remove the secret and make this a public PKCE client?">
-              <Csrf token={token} />
-              <button type="submit" class="danger">Make public</button>
-            </form>
-          )}
-        </div>
-      </Section>
-
-      <Section title="Delete application" description="Its refresh tokens stop working immediately; issued access tokens are refused by /userinfo.">
-        <form method="post" action={`${base}/delete`} data-confirm={`Delete ${client.name}? People won't be able to sign in to it.`}>
-          <Csrf token={token} />
-          <button type="submit" class="danger">Delete</button>
-        </form>
-      </Section>
-    </>,
-  );
-}
-
-admin.get("/admin/clients/:id", (c) => clientPage(c, c.req.param("id")));
-
-admin.post("/admin/clients/:id", async (c) => {
-  const id = c.req.param("id");
-  if (!(await getClient(c.env, id))) return notFound(c, "application");
-  const parsed = await readClientForm(c);
-  if ("error" in parsed) return clientPage(c, id, { error: parsed.error });
-  await updateClient(c.env, id, parsed.input);
-  await audit(c, "admin.client_updated", { target: id });
-  return c.redirect(`/admin/clients/${encodeURIComponent(id)}?m=client-saved`);
-});
-
-admin.post("/admin/clients/:id/secret", async (c) => {
-  const id = c.req.param("id");
-  if (!(await getClient(c.env, id))) return notFound(c, "application");
-  const secret = await rotateClientSecret(c.env, id);
-  await audit(c, "admin.client_secret_rotated", { target: id });
-  return clientPage(c, id, { secret });
-});
-
-admin.post("/admin/clients/:id/public", async (c) => {
-  const id = c.req.param("id");
-  await makeClientPublic(c.env, id);
-  await audit(c, "admin.client_made_public", { target: id });
-  return c.redirect(`/admin/clients/${encodeURIComponent(id)}?m=client-public`);
-});
-
-admin.post("/admin/clients/:id/delete", async (c) => {
-  const id = c.req.param("id");
-  await deleteClient(c.env, id);
-  await audit(c, "admin.client_deleted", { target: id });
-  return c.redirect("/admin/clients?m=client-deleted");
-});
-
-// --- keys + audit ------------------------------------------------------------------
-
-admin.get("/admin/keys", async (c) => {
-  const keys = await listKeys(c.env);
-  return adminPage(
-    c,
-    { title: "Signing keys", tab: "/admin/keys" },
-    <Section title="Signing keys" description="Tokens are signed with the newest active key. Apps pick up new keys from the JWKS automatically. A key is created on first use.">
-      <ul class="rows">
-        {keys.map((k) => (
-          <li>
-            <div class="grow">
-              <code>{k.kid}</code> <span class={`badge ${k.retired_at ? "" : "ok"}`}>{k.retired_at ? "retired" : "active"}</span>
-              <br />
-              <small class="muted">
-                {k.alg} · created {date(k.created_at)}
-                {k.retired_at ? ` · retired ${date(k.retired_at)}` : ""}
-              </small>
-            </div>
-          </li>
-        ))}
-      </ul>
-      <form method="post" action="/admin/keys/rotate" data-confirm="Rotate the signing key?">
-        <Csrf token={csrf(c)} />
-        <button type="submit">Rotate now</button>
-      </form>
-    </Section>,
-  );
-});
-
-admin.post("/admin/keys/rotate", async (c) => {
-  const kid = await rotateKeys(c.env);
-  await audit(c, "admin.keys_rotated", { target: kid });
-  return c.redirect("/admin/keys?m=keys-rotated");
-});
-
-admin.get("/admin/audit", async (c) => {
-  const entries = await recentAudit(c);
-  return adminPage(
-    c,
-    { title: "Audit log", tab: "/admin/audit" },
-    <Section title="Recent activity" description="The latest 200 events. Kept for 180 days.">
-      <div class="table-wrap">
-        <table class="compact">
-          <thead>
-            <tr>
-              <th>When</th>
-              <th>Who</th>
-              <th>What</th>
-              <th>Target</th>
-              <th>IP</th>
-            </tr>
-          </thead>
-          <tbody>
-            {entries.map((e) => (
-              <tr>
-                <td title={date(e.at)}>{relative(e.at)}</td>
-                <td>{e.actor_username ? `@${e.actor_username}` : <span class="muted">—</span>}</td>
-                <td>
-                  <code>{e.action}</code>
-                  {e.detail && <small class="muted"> {e.detail}</small>}
-                </td>
-                <td>{e.target ?? ""}</td>
-                <td>{e.ip ?? ""}</td>
-              </tr>
-            ))}
-          </tbody>
-        </table>
-      </div>
-    </Section>,
-  );
-});
diff --git a/src/routes/legal.tsx b/src/routes/legal.tsx
deleted file mode 100644
index 77ec43c..0000000
--- a/src/routes/legal.tsx
+++ /dev/null
@@ -1,204 +0,0 @@
-/* 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
deleted file mode 100644
index b468791..0000000
--- a/src/routes/login.tsx
+++ /dev/null
@@ -1,391 +0,0 @@
-/* src/routes/login.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 { Key, Login } from "pixelarticons/react";
-import type { AuthenticationResponseJSON } from "@simplewebauthn/server";
-import type { AppContext, AppEnv } from "../env";
-import { audit } from "../lib/audit";
-import { decrypt, timingSafeEqualStr } from "../lib/crypto";
-import { clientIp, form, readJson, safeReturn } from "../lib/http";
-import { burnPasswordCheck, hashPassword, needsRehash, verifyPassword } from "../lib/password";
-import { attempt, clearAttempts } from "../lib/ratelimit";
-import { verifyTotp } from "../lib/totp";
-import { normaliseUsername } from "../lib/validate";
-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, type UserRow } from "../data/users";
-import { render } from "../views/layout";
-import { ErrorNote, Field, Flash } from "../views/ui";
-
-const WINDOW = 15 * 60;
-const USER_LIMIT = 10;
-const IP_LIMIT = 50;
-const TOTP_ATTEMPTS = 5;
-const GENERIC_FAILURE = "That username and password don't match.";
-
-export const login = new Hono<AppEnv>();
-
-interface LoginPageOptions {
-  returnTo: string;
-  reauth: boolean;
-  username?: string;
-  error?: string;
-  message?: string;
-  status?: 401 | 429;
-}
-
-function loginPage(c: AppContext, opts: LoginPageOptions) {
-  const user = c.get("user");
-  const username = opts.username ?? (opts.reauth ? user?.username : undefined);
-  return render(
-    c,
-    { title: "Sign in", page: "login", narrow: true, status: opts.status },
-    <div class="card" id="login" data-return={opts.returnTo}>
-      <h1>{opts.reauth ? "Confirm it's you" : "Sign in"}</h1>
-      {opts.reauth && (
-        <p class="muted">This needs a fresh sign-in. It only takes a moment.</p>
-      )}
-      <Flash code={opts.message} />
-      <ErrorNote error={opts.error} />
-      <p class="notice error hidden" id="passkey-error" role="alert"></p>
-
-      <button type="button" class="primary wide" id="passkey-signin">
-        <Key class="icon" aria-hidden="true" />
-        Sign in with a passkey
-      </button>
-
-      <div class="divider">
-        <span>or use a password</span>
-      </div>
-
-      <form method="post" action="/login/password" class="stack">
-        <input type="hidden" name="return" value={opts.returnTo} />
-        {opts.reauth && <input type="hidden" name="reauth" value="1" />}
-        <Field
-          label="Username"
-          name="username"
-          value={username}
-          required
-          autocomplete="username webauthn"
-          autofocus={!username}
-          maxlength={64}
-        />
-        <Field
-          label="Password"
-          name="password"
-          type="password"
-          required
-          autocomplete="current-password"
-          autofocus={Boolean(username)}
-          maxlength={512}
-        />
-        <button type="submit" class="wide">
-          Sign in
-        </button>
-      </form>
-      {!opts.reauth && c.env.REGISTRATION === "open" && (
-        <p class="muted small">
-          New here? <a href={`/register?return=${encodeURIComponent(opts.returnTo)}`}>Create an account</a>
-        </p>
-      )}
-    </div>,
-  );
-}
-
-login.get("/login", async (c) => {
-  const returnTo = safeReturn(c.req.query("return"));
-  const reauth = c.req.query("reauth") === "1";
-  if (c.get("user") && !reauth) return c.redirect(returnTo);
-  if ((await countUsers(c.env)) === 0) return c.redirect("/setup");
-  return loginPage(c, { returnTo, reauth, message: c.req.query("m") });
-});
-
-login.post("/login/password", async (c) => {
-  const body = await form(c);
-  const returnTo = safeReturn(body.return);
-  const reauth = body.reauth === "1";
-  const username = normaliseUsername(body.username).slice(0, 64);
-  const password = (body.password ?? "").slice(0, 512);
-
-  const ipOk = await attempt(c.env, `login-ip:${clientIp(c)}`, IP_LIMIT, WINDOW);
-  const userOk = await attempt(c.env, `login-user:${username}`, USER_LIMIT, WINDOW);
-  if (!ipOk || !userOk) {
-    await audit(c, "login.rate_limited", { actor: null, target: username });
-    return loginPage(c, {
-      returnTo,
-      reauth,
-      username,
-      status: 429,
-      error: "Too many sign-in attempts. Wait a few minutes and try again.",
-    });
-  }
-
-  const user = username ? await getUserByUsername(c.env, username) : null;
-  if (!user || !user.password_hash || user.disabled) {
-    await burnPasswordCheck(password);
-    await audit(c, "login.failed", { actor: null, target: username, detail: "password" });
-    return loginPage(c, { returnTo, reauth, username, status: 401, error: GENERIC_FAILURE });
-  }
-
-  if (!(await verifyPassword(password, user.password_hash))) {
-    await audit(c, "login.failed", { actor: user.id, target: user.username, detail: "password" });
-    return loginPage(c, { returnTo, reauth, username, status: 401, error: GENERIC_FAILURE });
-  }
-
-  await clearAttempts(c.env, `login-user:${username}`);
-  if (needsRehash(user.password_hash)) {
-    await setPasswordHash(c.env, user.id, await hashPassword(password));
-  }
-
-  // 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/mfa");
-  }
-
-  await startSession(c, user.id, ["pwd"]);
-  await audit(c, "login.password", { actor: user.id, target: user.username });
-  return c.redirect(returnTo);
-});
-
-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: "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} />
-      <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>
-      )}
-
-      {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>
-      </p>
-    </div>,
-  );
-}
-
-/** 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/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);
-  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 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 secondStepPage(c, step, `That code didn't work. ${left} ${left === 1 ? "try" : "tries"} left.`);
-  }
-
-  await finishPendingLogin(c, pending.id_hash);
-  await startSession(c, user.id, ["pwd", "otp", "mfa"]);
-  await audit(c, "login.password_totp", { actor: user.id, target: user.username });
-  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);
-  }
-  return c.json(await authenticationOptions(c.env));
-});
-
-login.post("/login/passkey/verify", async (c) => {
-  const body = await readJson<{ id?: string; response?: AuthenticationResponseJSON; return?: string }>(c);
-  if (!body?.id || !body.response) return c.json({ error: "Malformed request." }, 400);
-
-  const result = await finishAuthentication(c.env, body.id, body.response);
-  if (!result.ok) {
-    await audit(c, "login.failed", { actor: null, detail: "passkey" });
-    return c.json({ error: result.error }, 401);
-  }
-
-  const user = await getUser(c.env, result.userId);
-  if (!user || user.disabled) return c.json({ error: "This account is disabled." }, 403);
-
-  await startSession(c, user.id, result.amr);
-  await audit(c, "login.passkey", { actor: user.id, target: user.username });
-  return c.json({ redirect: safeReturn(body.return) });
-});
-
-login.get("/login/link/:token", async (c) => {
-  const target = await peekLoginLink(c.env, c.req.param("token"));
-  if (!target) {
-    return render(
-      c,
-      { title: "Link expired", narrow: true, status: 410 },
-      <div class="card">
-        <h1>This link can't be used</h1>
-        <p class="muted">It has expired, was already used, or was replaced by a newer one. Ask an admin for a new link.</p>
-      </div>,
-    );
-  }
-
-  const current = c.get("user");
-  // Link scanners follow GETs, so using the link takes a deliberate POST.
-  return render(
-    c,
-    { title: "Sign in", narrow: true },
-    <div class="card">
-      <h1>Sign in as {target.name ?? target.username}</h1>
-      <p class="muted">
-        This one-time link signs you in as <strong>@{target.username}</strong>. It stops working once it's used.
-      </p>
-      {current && current.id !== target.user_id && (
-        <p class="notice">You'll be signed out of @{current.username} on this browser.</p>
-      )}
-      <form method="post" action={`/login/link/${c.req.param("token")}`}>
-        <button type="submit" class="primary wide">
-          <Login class="icon" aria-hidden="true" />
-          Continue
-        </button>
-      </form>
-    </div>,
-  );
-});
-
-login.post("/login/link/:token", async (c) => {
-  if (!(await attempt(c.env, `link-ip:${clientIp(c)}`, 30, WINDOW))) {
-    return c.text("Too many attempts. Wait a few minutes and try again.", 429);
-  }
-  const userId = await consumeLoginLink(c.env, c.req.param("token"));
-  if (!userId) return c.redirect(`/login/link/${encodeURIComponent(c.req.param("token"))}`);
-
-  await startSession(c, userId, ["link"]);
-  await audit(c, "login.link", { actor: userId, target: userId });
-  return c.redirect("/account?m=link-welcome");
-});
-
-login.post("/logout", async (c) => {
-  const session = c.get("session");
-  if (session) {
-    const body = await form(c);
-    if (!body._csrf || !timingSafeEqualStr(body._csrf, session.csrf)) {
-      return c.text("This form is out of date. Go back, reload the page and try again.", 403);
-    }
-    await audit(c, "logout");
-    await endSession(c);
-  }
-  return c.redirect("/login?m=signed-out");
-});
diff --git a/src/routes/register.tsx b/src/routes/register.tsx
deleted file mode 100644
index b1e5b56..0000000
--- a/src/routes/register.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-/* src/routes/register.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, UserPlus } from "pixelarticons/react";
-import type { AppContext, AppEnv } from "../env";
-import { audit } from "../lib/audit";
-import { clientIp, form, safeReturn } from "../lib/http";
-import { PASSWORD_MAX, PASSWORD_MIN, hashPassword, passwordProblem } from "../lib/password";
-import { attempt } from "../lib/ratelimit";
-import { cleanText, emailProblem, normaliseUsername, usernameProblem } from "../lib/validate";
-import { isReserved } from "../data/reserved";
-import { startSession } from "../data/sessions";
-import { countUsers, createUser } from "../data/users";
-import { sendVerificationEmail } from "../data/verifications";
-import { render } from "../views/layout";
-import { ErrorNote, Field } from "../views/ui";
-
-// Reserved and taken names get the same answer, so the form can't be used to
-// find out which names are reserved.
-const UNAVAILABLE = "That username isn't available.";
-
-export const register = new Hono<AppEnv>();
-
-function isOpen(c: AppContext): boolean {
-    return c.env.REGISTRATION === "open";
-}
-
-function closed(c: AppContext) {
-    return render(
-        c,
-        { title: "Sign up", narrow: true, status: 404 },
-        <div class="card">
-            <h1>Sign-ups are closed</h1>
-            <p class="muted">Accounts on this server are created by an admin.</p>
-            <p>
-                <a class="btn primary" href="/login">
-                    <Login class="icon" aria-hidden="true" />
-                    Sign in
-                </a>
-            </p>
-        </div>,
-    );
-}
-
-interface RegisterValues {
-    returnTo: string;
-    username?: string;
-    name?: string;
-    email?: string;
-}
-
-function registerPage(c: AppContext, values: RegisterValues, error?: string) {
-    return render(
-        c,
-        { title: "Create an account", narrow: true, status: error ? 400 : 200 },
-        <div class="card">
-            <h1>Create an account</h1>
-            <p class="muted">You can add a passkey straight after.</p>
-            <ErrorNote error={error} />
-            <form method="post" action="/register" class="stack">
-                <input type="hidden" name="return" value={values.returnTo} />
-                <Field
-                    label="Username"
-                    name="username"
-                    value={values.username}
-                    required
-                    autocomplete="username"
-                    maxlength={32}
-                    autofocus
-                    hint="Lowercase letters, digits, dots, dashes or underscores. You can't change it later."
-                />
-                <Field label="Display name" name="name" value={values.name} autocomplete="name" maxlength={100} />
-                <Field
-                    label="Email"
-                    name="email"
-                    type="email"
-                    value={values.email}
-                    required
-                    autocomplete="email"
-                    maxlength={254}
-                    hint="We'll send a link to verify it."
-                />
-                <Field
-                    label="Password"
-                    name="password"
-                    type="password"
-                    required
-                    autocomplete="new-password"
-                    maxlength={PASSWORD_MAX}
-                    hint={`At least ${PASSWORD_MIN} characters.`}
-                />
-                <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
-                </button>
-            </form>
-            <p class="muted small">
-                Already have an account? <a href={`/login?return=${encodeURIComponent(values.returnTo)}`}>Sign in</a>
-            </p>
-        </div>,
-    );
-}
-
-register.get("/register", async (c) => {
-    if (!isOpen(c)) return closed(c);
-    const returnTo = safeReturn(c.req.query("return"));
-    if (c.get("user")) return c.redirect(returnTo);
-    if ((await countUsers(c.env)) === 0) return c.redirect("/setup");
-    return registerPage(c, { returnTo });
-});
-
-register.post("/register", async (c) => {
-    if (!isOpen(c)) return closed(c);
-    if (c.get("user")) return c.redirect("/account");
-
-    if (!(await attempt(c.env, `register-ip:${clientIp(c)}`, 10, 60 * 60))) {
-        await audit(c, "register.rate_limited", { actor: null });
-        return c.text("Too many sign-ups from here. Try again later.", 429);
-    }
-
-    const body = await form(c);
-    const returnTo = safeReturn(body.return);
-    const username = normaliseUsername(body.username);
-    const password = (body.password ?? "").slice(0, PASSWORD_MAX);
-    const email = cleanText(body.email, 254);
-    // Never echo the password back into the form.
-    const values = { returnTo, username, name: body.name ?? "", email: email ?? "" };
-
-    const problem =
-        usernameProblem(username) ??
-        ((await isReserved(c.env, username)) ? UNAVAILABLE : null) ??
-        (email === null ? "Enter your email address." : emailProblem(email)) ??
-        passwordProblem(password, username) ??
-        (password !== body.confirm ? "The passwords don't match." : null);
-    if (problem || email === null) return registerPage(c, values, problem ?? "Enter your email address.");
-
-    const result = await createUser(c.env, {
-        username,
-        name: cleanText(body.name, 100),
-        email,
-        emailVerified: false,
-        passwordHash: await hashPassword(password),
-    });
-    if (!result.ok) return registerPage(c, values, UNAVAILABLE);
-
-    const sent = await sendVerificationEmail(c.env, result.id, email);
-    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);
-    return c.redirect(`/account?m=${sent === "sent" ? "welcome-verify" : "verify-failed"}`);
-});
\ No newline at end of file
diff --git a/src/routes/security.tsx b/src/routes/security.tsx
deleted file mode 100644
index d5f50ae..0000000
--- a/src/routes/security.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-/* 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
deleted file mode 100644
index 7dec9f5..0000000
--- a/src/routes/setup.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-/* src/routes/setup.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, UserPlus } from "pixelarticons/react";
-import type { AppContext, AppEnv } from "../env";
-import { audit } from "../lib/audit";
-import { timingSafeEqualStr } from "../lib/crypto";
-import { clientIp, form } from "../lib/http";
-import { attempt } from "../lib/ratelimit";
-import { cleanText, emailProblem, normaliseUsername, usernameProblem } from "../lib/validate";
-import { startSession } from "../data/sessions";
-import { countUsers, createFirstAdmin } from "../data/users";
-import { render } from "../views/layout";
-import { ErrorNote, Field } from "../views/ui";
-
-export const setup = new Hono<AppEnv>();
-
-function closed(c: AppContext) {
-  return render(
-    c,
-    { title: "Setup", narrow: true, status: 404 },
-    <div class="card">
-      <h1>Setup is done</h1>
-      <p class="muted">This server already has accounts.</p>
-      <p>
-        <a class="btn primary" href="/login">
-          <Login class="icon" aria-hidden="true" />
-          Sign in
-        </a>
-      </p>
-    </div>,
-  );
-}
-
-function setupPage(c: AppContext, values: Record<string, string> = {}, error?: string) {
-  if (!c.env.SETUP_TOKEN) {
-    return render(
-      c,
-      { title: "Setup", narrow: true, status: 503 },
-      <div class="card">
-        <h1>Almost there</h1>
-        <p>
-          Set a <code>SETUP_TOKEN</code> secret (<code>wrangler secret put SETUP_TOKEN</code>, or{" "}
-          <code>.dev.vars</code> locally), then reload this page to create the first admin.
-        </p>
-      </div>,
-    );
-  }
-  return render(
-    c,
-    { title: "Setup", narrow: true, status: error ? 400 : 200 },
-    <div class="card">
-      <h1>Create the first admin</h1>
-      <p class="muted">
-        This page only works while the server has no accounts. You'll add a passkey or password straight after.
-      </p>
-      <ErrorNote error={error} />
-      <form method="post" action="/setup" class="stack">
-        <Field label="Setup token" name="token" type="password" required autocomplete="off" hint="The SETUP_TOKEN secret." />
-        <Field label="Username" name="username" value={values.username} required autocomplete="username" maxlength={32} />
-        <Field label="Display name" name="name" value={values.name} autocomplete="name" maxlength={100} />
-        <Field label="Email" name="email" type="email" value={values.email} autocomplete="email" maxlength={254} />
-        <button type="submit" class="primary wide">
-          <UserPlus class="icon" aria-hidden="true" />
-          Create admin account
-        </button>
-      </form>
-    </div>,
-  );
-}
-
-setup.get("/setup", async (c) => {
-  if ((await countUsers(c.env)) > 0) return closed(c);
-  return setupPage(c);
-});
-
-setup.post("/setup", async (c) => {
-  if ((await countUsers(c.env)) > 0 || !c.env.SETUP_TOKEN) return closed(c);
-
-  if (!(await attempt(c.env, `setup-ip:${clientIp(c)}`, 10, 60 * 60))) {
-    return c.text("Too many attempts. Try again later.", 429);
-  }
-
-  const body = await form(c);
-  if (!timingSafeEqualStr(body.token ?? "", c.env.SETUP_TOKEN)) {
-    await audit(c, "setup.bad_token", { actor: null });
-    return setupPage(c, body, "That setup token is wrong.");
-  }
-
-  const username = normaliseUsername(body.username);
-  const email = cleanText(body.email, 254);
-  const problem = usernameProblem(username) ?? emailProblem(email);
-  if (problem) return setupPage(c, body, problem);
-
-  const id = await createFirstAdmin(c.env, {
-    username,
-    name: cleanText(body.name, 100),
-    email,
-    emailVerified: false,
-  });
-  if (!id) return closed(c);
-
-  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/routes/verify.tsx b/src/routes/verify.tsx
deleted file mode 100644
index 2123f88..0000000
--- a/src/routes/verify.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-/* src/routes/verify.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 { Check, Login } from "pixelarticons/react";
-import type { AppContext, AppEnv } from "../env";
-import { audit } from "../lib/audit";
-import { clientIp } from "../lib/http";
-import { attempt } from "../lib/ratelimit";
-import { consumeEmailVerification, peekEmailVerification } from "../data/verifications";
-import { render } from "../views/layout";
-
-export const verify = new Hono<AppEnv>();
-
-function unusable(c: AppContext) {
-  return render(
-    c,
-    { title: "Link expired", narrow: true, status: 410 },
-    <div class="card">
-      <h1>This link can't be used</h1>
-      <p class="muted">
-        It has expired, was already used, or a newer one was sent. You can send a new one from your account page.
-      </p>
-      <p>
-        <a class="btn primary" href="/account">
-          Your account
-        </a>
-      </p>
-    </div>,
-  );
-}
-
-// Mail scanners follow GETs, so verifying takes a deliberate POST.
-verify.get("/verify-email/:token", async (c) => {
-  const email = await peekEmailVerification(c.env, c.req.param("token"));
-  if (!email) return unusable(c);
-  return render(
-    c,
-    { title: "Verify your email", narrow: true },
-    <div class="card">
-      <h1>Verify your email</h1>
-      <p class="muted">
-        Confirm that <strong>{email}</strong> is yours.
-      </p>
-      <form method="post" action={`/verify-email/${c.req.param("token")}`}>
-        <button type="submit" class="primary wide">
-          <Check class="icon" aria-hidden="true" />
-          Verify
-        </button>
-      </form>
-    </div>,
-  );
-});
-
-verify.post("/verify-email/:token", async (c) => {
-  if (!(await attempt(c.env, `verify-ip:${clientIp(c)}`, 30, 15 * 60))) {
-    return c.text("Too many attempts. Wait a few minutes and try again.", 429);
-  }
-  const userId = await consumeEmailVerification(c.env, c.req.param("token"));
-  if (!userId) return unusable(c);
-
-  await audit(c, "account.email_verified", { actor: userId, target: userId });
-  if (c.get("user")?.id === userId) return c.redirect("/account?m=email-verified");
-  return render(
-    c,
-    { title: "Email verified", narrow: true },
-    <div class="card">
-      <h1>Email verified</h1>
-      <p class="muted">Thanks! You can close this tab, or sign in.</p>
-      <p>
-        <a class="btn primary" href="/login">
-          <Login class="icon" aria-hidden="true" />
-          Sign in
-        </a>
-      </p>
-    </div>,
-  );
-});
diff --git a/src/types/pixelarticons-react.ts b/src/types/pixelarticons-react.ts
deleted file mode 100644
index 0b5da53..0000000
--- a/src/types/pixelarticons-react.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/* src/types/pixelarticons-react.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.
- *
- * Type-checking stand-in for `pixelarticons/react`. Its real .d.ts types each
- * icon as a React component; tsconfig.json points the "pixelarticons/react"
- * specifier here instead so tsc checks against what these actually are at
- * runtime under the `react` -> `hono/jsx` alias in wrangler.jsonc. Add a line
- * here whenever a new icon from the package is imported.
- */
-
-type Icon = (props: Record<string, unknown>) => any;
-
-export declare const AppWindows: Icon;
-export declare const ArrowLeft: Icon;
-export declare const Check: Icon;
-export declare const Key: Icon;
-export declare const Link: Icon;
-export declare const Login: Icon;
-export declare const Logout: Icon;
-export declare const Save: Icon;
-export declare const Shield: Icon;
-export declare const User: Icon;
-export declare const UserPlus: Icon;
-export declare const Users: Icon;
diff --git a/src/views/layout.tsx b/src/views/layout.tsx
deleted file mode 100644
index d757a04..0000000
--- a/src/views/layout.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-/* src/views/layout.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 type { Child } from "hono/jsx";
-import type { ContentfulStatusCode } from "hono/utils/http-status";
-import { Logout, Shield, User } from "pixelarticons/react";
-import { siteName, type AppContext } from "../env";
-
-interface PageOptions {
-  title: string;
-  /** Picks the behaviour in /static/app.js. */
-  page?: string;
-  /** Centered card layout for sign-in screens. */
-  narrow?: boolean;
-  status?: ContentfulStatusCode;
-}
-
-export async function render(c: AppContext, opts: PageOptions, body: Child): Promise<Response> {
-  const site = siteName(c.env);
-  const user = c.get("user");
-  const session = c.get("session");
-
-  const html = (
-    <html lang="en">
-      <head>
-        <meta charset="utf-8" />
-        <meta name="viewport" content="width=device-width, initial-scale=1" />
-        <meta name="color-scheme" content="dark" />
-        <meta name="robots" content="noindex" />
-        <title>{`${opts.title} · ${site}`}</title>
-        <link rel="icon" type="image/svg+xml" href="/static/favicon.svg" />
-        <link rel="stylesheet" href="/static/style.css" />
-        <script src="/static/app.js" defer></script>
-      </head>
-      <body data-page={opts.page ?? ""} data-csrf={session?.csrf ?? ""}>
-        <header class="topbar">
-          <a class="brand" href={user ? "/account" : "/login"}>
-            {site}
-          </a>
-          {user && (
-            <nav>
-              <a class="btn small" href="/account">
-                <User class="icon" aria-hidden="true" />
-                Account
-              </a>
-              {user.isAdmin && (
-                <a class="btn small" href="/admin">
-                  <Shield class="icon" aria-hidden="true" />
-                  Admin
-                </a>
-              )}
-              <form method="post" action="/logout" class="inline">
-                <input type="hidden" name="_csrf" value={session?.csrf ?? ""} />
-                <button type="submit" class="small">
-                  <Logout class="icon" aria-hidden="true" />
-                  Sign out
-                </button>
-              </form>
-            </nav>
-          )}
-        </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>
-  );
-
-  return c.html(`<!doctype html>${await html}`, opts.status ?? 200);
-}
diff --git a/src/views/ui.tsx b/src/views/ui.tsx
deleted file mode 100644
index a6153ea..0000000
--- a/src/views/ui.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-/* src/views/ui.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 type { Child } from "hono/jsx";
-
-// Flash messages travel as a fixed code in `?m=`, never as free text, so a
-// 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.",
-  "verify-sent": "Verification email sent. Check your inbox (and spam).",
-  "verify-failed": "We couldn't send a verification email right now. Try again later.",
-  "email-verified": "Email verified.",
-  "profile-saved": "Profile saved.",
-  "passkey-added": "Passkey added.",
-  "passkey-renamed": "Passkey renamed.",
-  "passkey-removed": "Passkey removed.",
-  "password-set": "Password saved. Your other sessions were signed out.",
-  "password-removed": "Password removed. Sign in with a passkey from now on.",
-  "totp-enabled": "Two-factor codes are on for password sign-ins.",
-  "totp-disabled": "Two-factor codes are off.",
-  "session-revoked": "Session signed out.",
-  "sessions-revoked": "All other sessions are signed out.",
-  "user-created": "User created.",
-  "user-saved": "User saved.",
-  "user-deleted": "User deleted.",
-  "groups-saved": "Groups saved.",
-  "group-created": "Group created.",
-  "group-saved": "Group saved.",
-  "group-deleted": "Group deleted.",
-  "client-saved": "Application saved.",
-  "client-deleted": "Application deleted.",
-  "client-public": "Secret removed. The application is now a public (PKCE) client.",
-  "keys-rotated": "Signing key rotated. The old key stays published for two days.",
-  "credential-removed": "Sign-in method removed.",
-  "user-disabled": "Account disabled and signed out everywhere.",
-  "user-enabled": "Account enabled.",
-  "user-signed-out": "Signed out of every session and application.",
-  "link-revoked": "Sign-in link revoked.",
-  "name-reserved": "Name reserved.",
-  "name-released": "Name released.",
-  "welcome": "Welcome! Add a passkey below too, so you have a second way to sign in.",
-};
-
-export function Flash(props: { code?: string | undefined }) {
-  const text = props.code ? MESSAGES[props.code] : undefined;
-  return text ? <p class="notice ok">{text}</p> : null;
-}
-
-export function ErrorNote(props: { error?: string | null | undefined }) {
-  return props.error ? (
-    <p class="notice error" role="alert">
-      {props.error}
-    </p>
-  ) : null;
-}
-
-export function Csrf(props: { token: string }) {
-  return <input type="hidden" name="_csrf" value={props.token} />;
-}
-
-export function Section(props: { title: string; children?: Child; id?: string; description?: string }) {
-  return (
-    <section class="panel" id={props.id}>
-      <h2>{props.title}</h2>
-      {props.description && <p class="muted">{props.description}</p>}
-      {props.children}
-    </section>
-  );
-}
-
-export function Field(props: {
-  label: string;
-  name: string;
-  type?: string;
-  value?: string | null;
-  required?: boolean;
-  autocomplete?: string;
-  hint?: string;
-  placeholder?: string;
-  maxlength?: number;
-  inputmode?: string;
-  pattern?: string;
-  autofocus?: boolean;
-}) {
-  return (
-    <label class="field">
-      <span>{props.label}</span>
-      <input
-        type={props.type ?? "text"}
-        name={props.name}
-        value={props.value ?? ""}
-        required={props.required}
-        autocomplete={props.autocomplete}
-        placeholder={props.placeholder}
-        maxlength={props.maxlength}
-        inputmode={props.inputmode as "numeric" | undefined}
-        pattern={props.pattern}
-        autofocus={props.autofocus}
-      />
-      {props.hint && <small class="muted">{props.hint}</small>}
-    </label>
-  );
-}
-
-export function date(ts: number | null | undefined): string {
-  if (!ts) return "never";
-  return new Date(ts * 1000).toISOString().slice(0, 16).replace("T", " ") + " UTC";
-}
-
-export function relative(ts: number | null | undefined): string {
-  if (!ts) return "never";
-  const diff = Math.floor(Date.now() / 1000) - ts;
-  const future = diff < 0;
-  const abs = Math.abs(diff);
-  const unit =
-    abs < 60 ? [abs, "second"] :
-    abs < 3600 ? [Math.floor(abs / 60), "minute"] :
-    abs < 86400 ? [Math.floor(abs / 3600), "hour"] :
-    [Math.floor(abs / 86400), "day"];
-  const [n, word] = unit as [number, string];
-  const text = `${n} ${word}${n === 1 ? "" : "s"}`;
-  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";
-  const browser =
-    /Edg\//.test(ua) ? "Edge" :
-    /Firefox\//.test(ua) ? "Firefox" :
-    /Chrome\//.test(ua) ? "Chrome" :
-    /Safari\//.test(ua) ? "Safari" :
-    "Browser";
-  const os =
-    /Windows/.test(ua) ? "Windows" :
-    /iPhone|iPad/.test(ua) ? "iOS" :
-    /Mac OS X/.test(ua) ? "macOS" :
-    /Android/.test(ua) ? "Android" :
-    /Linux/.test(ua) ? "Linux" :
-    "unknown OS";
-  return `${browser} on ${os}`;
-}
diff --git a/tsconfig.build.json b/tsconfig.build.json
deleted file mode 100644
index 66a3485..0000000
--- a/tsconfig.build.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
-  // Used by wrangler (see the top-level "tsconfig" field in wrangler.jsonc)
-  // to bundle the actual Worker. It must NOT carry the "paths" override from
-  // tsconfig.json: that's a type-checking-only stand-in for
-  // "pixelarticons/react", and esbuild (wrangler's bundler) honours tsconfig
-  // "paths" for real module resolution too, so leaving it in here would
-  // literally replace the icon package with the type stub at runtime.
-  "extends": "./tsconfig.json",
-  "compilerOptions": {
-    "paths": {}
-  }
-}
diff --git a/tsconfig.json b/tsconfig.json
index 0a768c1..194fdfe 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -10,14 +10,6 @@
     "jsx": "react-jsx",
     "jsxImportSource": "hono/jsx",
 
-    // pixelarticons/react's own .d.ts types its components against real React
-    // (SVGProps, React.JSX.Element). wrangler.jsonc aliases that package's
-    // `react` import to `hono/jsx` at runtime, so this repo actually gets
-    // hono/jsx elements back; this stub tells tsc that instead.
-    "paths": {
-      "pixelarticons/react": ["./src/types/pixelarticons-react.ts"]
-    },
-
     "allowImportingTsExtensions": true,
     "verbatimModuleSyntax": true,
     "resolveJsonModule": true,
diff --git a/vite.config.ts b/vite.config.ts
new file mode 100644
index 0000000..3a98c16
--- /dev/null
+++ b/vite.config.ts
@@ -0,0 +1,21 @@
+/* vite.config.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.
+ *
+ * Builds the Svelte app in web/ into dist/, which the Worker serves.
+ */
+
+import { defineConfig } from "vite";
+import { svelte } from "@sveltejs/vite-plugin-svelte";
+
+export default defineConfig({
+  root: "web",
+  plugins: [svelte()],
+  build: {
+    outDir: "../dist",
+    emptyOutDir: true,
+    // The CSP allows no inline code, so every asset must be a real file.
+    assetsInlineLimit: 0,
+  },
+});
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..fa6664a
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <meta name="color-scheme" content="dark" />
+    <meta name="robots" content="noindex" />
+    <title>Sign in</title>
+    <link rel="icon" type="image/svg+xml" href="/static/favicon.svg" />
+    <script type="module" src="/src/main.ts"></script>
+  </head>
+  <body>
+    <div id="app"></div>
+  </body>
+</html>
diff --git a/public/static/background.avif b/web/public/static/background.avif
similarity index 100%
rename from public/static/background.avif
rename to web/public/static/background.avif
diff --git a/public/static/favicon.svg b/web/public/static/favicon.svg
similarity index 100%
rename from public/static/favicon.svg
rename to web/public/static/favicon.svg
diff --git a/web/src/App.svelte b/web/src/App.svelte
new file mode 100644
index 0000000..ab35777
--- /dev/null
+++ b/web/src/App.svelte
@@ -0,0 +1,157 @@
+<script lang="ts">
+  import type { Component } from "svelte";
+  import { ArrowLeft, LayoutGrid, LogOut, Settings as SettingsIcon, Shield } from "@lucide/svelte";
+  import { api, errorText } from "./lib/api";
+  import { here, navigate, reload, route } from "./lib/router.svelte";
+  import { session } from "./lib/session.svelte";
+  import Card from "./components/Card.svelte";
+
+  import Login from "./pages/Login.svelte";
+  import Mfa from "./pages/Mfa.svelte";
+  import LoginLink from "./pages/LoginLink.svelte";
+  import Register from "./pages/Register.svelte";
+  import Setup from "./pages/Setup.svelte";
+  import Forgot from "./pages/Forgot.svelte";
+  import Reset from "./pages/Reset.svelte";
+  import VerifyEmail from "./pages/VerifyEmail.svelte";
+  import Security from "./pages/Security.svelte";
+  import Apps from "./pages/Apps.svelte";
+  import Settings from "./pages/Settings.svelte";
+  import TotpSetup from "./pages/TotpSetup.svelte";
+  import Privacy from "./pages/Privacy.svelte";
+  import Terms from "./pages/Terms.svelte";
+  import AuthorizeNotice from "./pages/AuthorizeNotice.svelte";
+  import EndSession from "./pages/EndSession.svelte";
+  import ErrorPage from "./pages/ErrorPage.svelte";
+  import NotFound from "./pages/NotFound.svelte";
+  import Users from "./pages/admin/Users.svelte";
+  import UserDetail from "./pages/admin/UserDetail.svelte";
+  import Groups from "./pages/admin/Groups.svelte";
+  import Clients from "./pages/admin/Clients.svelte";
+  import ClientDetail from "./pages/admin/ClientDetail.svelte";
+  import Keys from "./pages/admin/Keys.svelte";
+  import Audit from "./pages/admin/Audit.svelte";
+  import Reserved from "./pages/admin/Reserved.svelte";
+
+  type Page = Component<{ params: Record<string, string> }>;
+
+  interface Route {
+    pattern: string;
+    page: Page;
+    /** Centered card layout for sign-in screens. */
+    narrow?: boolean;
+    access?: "user" | "admin";
+  }
+
+  // These paths are also the links in our emails (verify-email, security,
+  // reset, login/link), so they mustn't change.
+  const ROUTES: Route[] = [
+    { pattern: "/login", page: Login, narrow: true },
+    { pattern: "/login/mfa", page: Mfa, narrow: true },
+    { pattern: "/login/link/:token", page: LoginLink, narrow: true },
+    { pattern: "/register", page: Register, narrow: true },
+    { pattern: "/setup", page: Setup, narrow: true },
+    { pattern: "/forgot", page: Forgot, narrow: true },
+    { pattern: "/reset/:token", page: Reset, narrow: true },
+    { pattern: "/verify-email/:token", page: VerifyEmail, narrow: true },
+    { pattern: "/security/:token", page: Security, narrow: true },
+    { pattern: "/apps", page: Apps, access: "user" },
+    { pattern: "/settings", page: Settings, access: "user" },
+    { pattern: "/settings/totp", page: TotpSetup, narrow: true, access: "user" },
+    { pattern: "/admin/users", page: Users, access: "admin" },
+    { pattern: "/admin/users/:id", page: UserDetail, access: "admin" },
+    { pattern: "/admin/groups", page: Groups, access: "admin" },
+    { pattern: "/admin/clients", page: Clients, access: "admin" },
+    { pattern: "/admin/clients/:id", page: ClientDetail, access: "admin" },
+    { pattern: "/admin/keys", page: Keys, access: "admin" },
+    { pattern: "/admin/audit", page: Audit, access: "admin" },
+    { pattern: "/admin/reserved", page: Reserved, access: "admin" },
+    { pattern: "/privacy", page: Privacy },
+    { pattern: "/terms", page: Terms },
+    { pattern: "/authorize/notice", page: AuthorizeNotice, narrow: true },
+    { pattern: "/end-session/confirm", page: EndSession, narrow: true },
+    { pattern: "/error", page: ErrorPage, narrow: true },
+  ];
+
+  const REDIRECTS: Record<string, () => string> = {
+    "/": () => (session.user ? "/apps" : "/login"),
+    "/admin": () => "/admin/users",
+    // The old name for /settings, still linked from emails sent before the rename.
+    "/account": () => "/settings" + route.search,
+  };
+
+  function match(path: string): { route: Route; params: Record<string, string> } {
+    const parts = path.replace(/\/+$/, "").split("/");
+    for (const r of ROUTES) {
+      const want = r.pattern.split("/");
+      if (want.length !== parts.length) continue;
+      const params: Record<string, string> = {};
+      if (want.every((w, i) => (w.startsWith(":") ? (params[w.slice(1)] = decodeURIComponent(parts[i]!)) : w === parts[i]))) {
+        return { route: r, params };
+      }
+    }
+    return { route: { pattern: "*", page: NotFound, narrow: true }, params: {} };
+  }
+
+  $effect(() => {
+    const to = REDIRECTS[route.path];
+    if (to) navigate(to(), { replace: true });
+  });
+
+  const current = $derived(match(route.path));
+  const needsSignIn = $derived(current.route.access !== undefined && !session.user);
+  const forbidden = $derived(current.route.access === "admin" && session.user !== null && !session.user.isAdmin);
+
+  $effect(() => {
+    if (needsSignIn) reload(`/login?${new URLSearchParams({ return: here() })}`);
+  });
+
+  let signOutError = $state("");
+  async function signOut() {
+    try {
+      const { redirect } = await api<{ redirect: string }>("/api/logout", {});
+      reload(redirect);
+    } catch (err) {
+      signOutError = errorText(err);
+    }
+  }
+</script>
+
+<header class="topbar">
+  <a class="brand" href={session.user ? "/apps" : "/login"}>{session.site}</a>
+  {#if session.user}
+    <nav>
+      <a class="btn small" href="/apps"><LayoutGrid class="icon" aria-hidden="true" /> Apps</a>
+      <a class="btn small" href="/settings"><SettingsIcon class="icon" aria-hidden="true" /> Settings</a>
+      {#if session.user.isAdmin}
+        <a class="btn small" href="/admin/users"><Shield class="icon" aria-hidden="true" /> Admin</a>
+      {/if}
+      <button type="button" class="small" onclick={signOut}>
+        <LogOut class="icon" aria-hidden="true" /> Sign out
+      </button>
+    </nav>
+  {/if}
+</header>
+
+<main class={current.route.narrow || forbidden ? "narrow" : "wide"}>
+  {#if signOutError}<p class="notice error" role="alert">{signOutError}</p>{/if}
+  {#if needsSignIn || REDIRECTS[route.path]}
+    <!-- on its way somewhere else -->
+  {:else if forbidden}
+    <Card title="Admins only" lead="Your account isn't in the admin group for this server.">
+      <p>
+        <a class="btn primary" href="/apps"><ArrowLeft class="icon" aria-hidden="true" /> Back to your apps</a>
+      </p>
+    </Card>
+  {:else}
+    {#key route.path}
+      {@const Page = current.route.page}
+      <Page params={current.params} />
+    {/key}
+  {/if}
+</main>
+
+<footer class="site-footer">
+  <a href="/privacy">Privacy</a>
+  <a href="/terms">Terms</a>
+</footer>
diff --git a/public/static/style.css b/web/src/app.css
similarity index 92%
rename from public/static/style.css
rename to web/src/app.css
index 441a333..27669ed 100644
--- a/public/static/style.css
+++ b/web/src/app.css
@@ -1,4 +1,4 @@
-/* public/static/style.css
+/* web/src/app.css
  * 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.
@@ -707,6 +707,61 @@ table.compact td {
   margin: 0.35rem 0;
 }
 
+/* "Your apps": one tile per application, linking to its website. */
+.apps {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
+  gap: 0.75rem;
+  margin: 1rem 0 0;
+  padding: 0;
+  list-style: none;
+}
+
+.app-tile {
+  display: flex;
+  align-items: center;
+  gap: 0.75rem;
+  height: 100%;
+  padding: 0.9rem 1rem;
+  border: 1px solid var(--line);
+  border-radius: 14px;
+  background: var(--panel);
+  color: var(--text);
+  text-decoration: none;
+  backdrop-filter: blur(12px);
+}
+
+.app-tile:hover {
+  border-color: var(--accent-line);
+  box-shadow: 0 0 0 4px var(--accent-dim);
+  color: var(--text);
+}
+
+.app-mark {
+  display: grid;
+  place-items: center;
+  flex-shrink: 0;
+  width: 2.5rem;
+  height: 2.5rem;
+  border-radius: 10px;
+  background: var(--accent-dim);
+  color: var(--accent);
+  font-weight: 700;
+}
+
+.app-text {
+  display: flex;
+  flex-direction: column;
+  flex: 1;
+  min-width: 0;
+}
+
+.app-text small {
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
 .site-footer {
   display: flex;
   justify-content: center;
diff --git a/web/src/components/AdminTabs.svelte b/web/src/components/AdminTabs.svelte
new file mode 100644
index 0000000..7e2bbe1
--- /dev/null
+++ b/web/src/components/AdminTabs.svelte
@@ -0,0 +1,18 @@
+<script lang="ts">
+  import { route } from "../lib/router.svelte";
+
+  const TABS = [
+    ["/admin/users", "Users"],
+    ["/admin/groups", "Groups"],
+    ["/admin/clients", "Applications"],
+    ["/admin/keys", "Signing keys"],
+    ["/admin/audit", "Audit log"],
+    ["/admin/reserved", "Reserved names"],
+  ] as const;
+</script>
+
+<nav class="tabs">
+  {#each TABS as [href, label] (href)}
+    <a {href} class={route.path === href || route.path.startsWith(href + "/") ? "active" : undefined}>{label}</a>
+  {/each}
+</nav>
diff --git a/web/src/components/Card.svelte b/web/src/components/Card.svelte
new file mode 100644
index 0000000..0d77315
--- /dev/null
+++ b/web/src/components/Card.svelte
@@ -0,0 +1,14 @@
+<script lang="ts">
+  // A narrow page's single card: a title, an optional lead paragraph, then content.
+  import type { Snippet } from "svelte";
+  import Title from "./Title.svelte";
+
+  let { title, lead, children }: { title: string; lead?: string; children?: Snippet } = $props();
+</script>
+
+<Title text={title} />
+<div class="card">
+  <h1>{title}</h1>
+  {#if lead}<p class="muted">{lead}</p>{/if}
+  {@render children?.()}
+</div>
diff --git a/web/src/components/ClientFields.svelte b/web/src/components/ClientFields.svelte
new file mode 100644
index 0000000..9e05325
--- /dev/null
+++ b/web/src/components/ClientFields.svelte
@@ -0,0 +1,43 @@
+<script lang="ts" module>
+  export interface ClientValues {
+    name: string;
+    homeUrl: string;
+    redirectUris: string;
+    postLogoutRedirectUris: string;
+    allowedGroups: string[];
+  }
+</script>
+
+<script lang="ts">
+  import Field from "./Field.svelte";
+  import GroupChecks, { type GroupOption } from "./GroupChecks.svelte";
+
+  let { values = $bindable(), groups }: { values: ClientValues; groups: GroupOption[] } = $props();
+</script>
+
+<Field label="Name" name="name" bind:value={values.name} required maxlength={100} autocomplete="off" hint="Shown to people when they're asked to sign in." />
+<Field
+  label="Website"
+  name="homeUrl"
+  type="url"
+  bind:value={values.homeUrl}
+  maxlength={2048}
+  autocomplete="off"
+  placeholder="https://app.example.com/"
+  hint="Optional. Where the app lives: with one, it's listed on everyone's “Your apps” page (if their groups allow it)."
+/>
+<label class="field">
+  <span>Redirect URIs</span>
+  <textarea bind:value={values.redirectUris} rows={3} required placeholder="https://app.example.com/auth/callback"></textarea>
+  <small class="muted">One per line, matched exactly.</small>
+</label>
+<label class="field">
+  <span>Post-logout redirect URIs</span>
+  <textarea bind:value={values.postLogoutRedirectUris} rows={2} placeholder="https://app.example.com/"></textarea>
+  <small class="muted">Optional. Where the app may send people after signing out here.</small>
+</label>
+<fieldset>
+  <legend>Who can use it</legend>
+  <p class="muted small">Leave everything unticked to allow every account.</p>
+  <GroupChecks {groups} bind:selected={values.allowedGroups} />
+</fieldset>
diff --git a/web/src/components/CopyRow.svelte b/web/src/components/CopyRow.svelte
new file mode 100644
index 0000000..b66e04b
--- /dev/null
+++ b/web/src/components/CopyRow.svelte
@@ -0,0 +1,20 @@
+<script lang="ts">
+  let { value, label }: { value: string; label: string } = $props();
+  let input: HTMLInputElement;
+  let copied = $state(false);
+
+  async function copy() {
+    try {
+      await navigator.clipboard.writeText(value);
+      copied = true;
+      setTimeout(() => (copied = false), 1500);
+    } catch {
+      input.select();
+    }
+  }
+</script>
+
+<p class="copyrow">
+  <input bind:this={input} type="text" readonly {value} aria-label={label} />
+  <button type="button" onclick={copy}>{copied ? "Copied" : "Copy"}</button>
+</p>
diff --git a/web/src/components/Field.svelte b/web/src/components/Field.svelte
new file mode 100644
index 0000000..987a4cf
--- /dev/null
+++ b/web/src/components/Field.svelte
@@ -0,0 +1,33 @@
+<script lang="ts">
+  import { focus } from "../lib/action.svelte";
+
+  let {
+    label,
+    name,
+    value = $bindable(""),
+    type = "text",
+    hint,
+    autofocus = false,
+    ...rest
+  }: {
+    label: string;
+    name: string;
+    value?: string | null;
+    type?: string;
+    hint?: string;
+    autofocus?: boolean;
+    required?: boolean;
+    autocomplete?: HTMLInputElement["autocomplete"] | null;
+    placeholder?: string;
+    maxlength?: number;
+    inputmode?: "numeric" | "email" | "text";
+    pattern?: string;
+    disabled?: boolean;
+  } = $props();
+</script>
+
+<label class="field">
+  <span>{label}</span>
+  <input {type} {name} bind:value {...rest} use:focus={autofocus} />
+  {#if hint}<small class="muted">{hint}</small>{/if}
+</label>
diff --git a/web/src/components/Flash.svelte b/web/src/components/Flash.svelte
new file mode 100644
index 0000000..0756117
--- /dev/null
+++ b/web/src/components/Flash.svelte
@@ -0,0 +1,9 @@
+<script lang="ts">
+  // A success note named by `?m=` in the URL (fixed codes only, see lib/messages).
+  import { MESSAGES } from "../lib/messages";
+  import { query } from "../lib/router.svelte";
+
+  const text = $derived(MESSAGES[query().get("m") ?? ""] ?? "");
+</script>
+
+{#if text}<p class="notice ok" role="status">{text}</p>{/if}
diff --git a/web/src/components/GroupChecks.svelte b/web/src/components/GroupChecks.svelte
new file mode 100644
index 0000000..203a4d5
--- /dev/null
+++ b/web/src/components/GroupChecks.svelte
@@ -0,0 +1,26 @@
+<script lang="ts" module>
+  export interface GroupOption {
+    name: string;
+    description: string;
+  }
+</script>
+
+<script lang="ts">
+  let { groups, selected = $bindable([]) }: { groups: GroupOption[]; selected?: string[] } = $props();
+</script>
+
+{#if groups.length === 0}
+  <p class="muted">No groups yet.</p>
+{:else}
+  <div class="checks">
+    {#each groups as g (g.name)}
+      <label class="check">
+        <input type="checkbox" value={g.name} bind:group={selected} />
+        <span>
+          {g.name}
+          {#if g.description}<small class="muted"> — {g.description}</small>{/if}
+        </span>
+      </label>
+    {/each}
+  </div>
+{/if}
diff --git a/web/src/components/Notes.svelte b/web/src/components/Notes.svelte
new file mode 100644
index 0000000..e5c89b5
--- /dev/null
+++ b/web/src/components/Notes.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+  // The success note and/or error for an action. Errors are announced to screen readers.
+  let { ok = "", error = "" }: { ok?: string | null; error?: string | null } = $props();
+</script>
+
+{#if ok}<p class="notice ok" role="status">{ok}</p>{/if}
+{#if error}<p class="notice error" role="alert">{error}</p>{/if}
diff --git a/web/src/components/Section.svelte b/web/src/components/Section.svelte
new file mode 100644
index 0000000..adc9a25
--- /dev/null
+++ b/web/src/components/Section.svelte
@@ -0,0 +1,11 @@
+<script lang="ts">
+  import type { Snippet } from "svelte";
+
+  let { title, description, children }: { title: string; description?: string; children: Snippet } = $props();
+</script>
+
+<section class="panel">
+  <h2>{title}</h2>
+  {#if description}<p class="muted">{description}</p>{/if}
+  {@render children()}
+</section>
diff --git a/web/src/components/Title.svelte b/web/src/components/Title.svelte
new file mode 100644
index 0000000..3619def
--- /dev/null
+++ b/web/src/components/Title.svelte
@@ -0,0 +1,9 @@
+<script lang="ts">
+  import { session } from "../lib/session.svelte";
+
+  let { text }: { text: string } = $props();
+</script>
+
+<svelte:head>
+  <title>{text} · {session.site}</title>
+</svelte:head>
diff --git a/web/src/lib/action.svelte.ts b/web/src/lib/action.svelte.ts
new file mode 100644
index 0000000..0fe9ce0
--- /dev/null
+++ b/web/src/lib/action.svelte.ts
@@ -0,0 +1,41 @@
+/* web/src/lib/action.svelte.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 { errorText } from "./api";
+import { MESSAGES } from "./messages";
+
+/**
+ * The state behind a form or button: busy while it runs, then either a
+ * success note (from a message code) or the error to show.
+ */
+export class Action {
+  busy = $state(false);
+  error = $state("");
+  message = $state("");
+
+  /** Runs `fn`; if it returns a message code (or `{ message }`), that's shown as the success note. */
+  run = async (fn: () => Promise<unknown>): Promise<boolean> => {
+    this.busy = true;
+    this.error = "";
+    this.message = "";
+    try {
+      const result = await fn();
+      const code = typeof result === "string" ? result : (result as { message?: unknown } | undefined)?.message;
+      if (typeof code === "string") this.message = MESSAGES[code] ?? "";
+      return true;
+    } catch (err) {
+      this.error = errorText(err);
+      return false;
+    } finally {
+      this.busy = false;
+    }
+  };
+}
+
+/** Focuses an element when it appears (instead of `autofocus`, which only works on first load). */
+export function focus(node: HTMLElement, enabled: boolean | undefined = true) {
+  if (enabled) queueMicrotask(() => node.focus());
+}
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
new file mode 100644
index 0000000..df94e40
--- /dev/null
+++ b/web/src/lib/api.ts
@@ -0,0 +1,69 @@
+/* web/src/lib/api.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 { here, reload } from "./router.svelte";
+import { session } from "./session.svelte";
+
+export class ApiError extends Error {
+  constructor(
+    message: string,
+    readonly status: number,
+    readonly data: Record<string, unknown>,
+  ) {
+    super(message);
+  }
+}
+
+const FALLBACK = "Something went wrong. Please try again.";
+
+/**
+ * Calls the Worker's JSON API. Sends the session's CSRF token, and handles the
+ * answers every page would handle the same way: a lost session or a needed
+ * re-sign-in goes to /login and comes back here afterwards.
+ */
+export async function api<T = Record<string, unknown>>(path: string, body?: unknown): Promise<T> {
+  const headers: Record<string, string> = {};
+  if (body !== undefined) headers["Content-Type"] = "application/json";
+  if (session.csrf) headers["X-CSRF-Token"] = session.csrf;
+
+  let res: Response;
+  try {
+    res = await fetch(path, {
+      method: body === undefined ? "GET" : "POST",
+      headers,
+      body: body === undefined ? undefined : JSON.stringify(body),
+      credentials: "same-origin",
+    });
+  } catch {
+    throw new ApiError("Couldn't reach the server. Check your connection and try again.", 0, {});
+  }
+
+  let data: Record<string, unknown> = {};
+  try {
+    data = await res.json();
+  } catch {
+    // not JSON (a proxy error page, say)
+  }
+
+  if (!res.ok) {
+    if (data.signin) reload(`/login?${new URLSearchParams({ return: here() })}`);
+    else if (data.reauth) reload(`/login?${new URLSearchParams({ return: here(), reauth: "1" })}`);
+    throw new ApiError(typeof data.error === "string" ? data.error : FALLBACK, res.status, data);
+  }
+  return data as T;
+}
+
+/** The message to show for anything thrown by api() or WebAuthn. */
+export function errorText(err: unknown): string {
+  if (err instanceof ApiError) return err.message;
+  if (err instanceof Error && err.message) return err.message;
+  return FALLBACK;
+}
+
+/** Shorthand for a confirmation prompt before something destructive. */
+export function confirmed(message: string): boolean {
+  return window.confirm(message);
+}
diff --git a/web/src/lib/format.ts b/web/src/lib/format.ts
new file mode 100644
index 0000000..30823d2
--- /dev/null
+++ b/web/src/lib/format.ts
@@ -0,0 +1,27 @@
+/* web/src/lib/format.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.
+ */
+
+export function date(ts: number | null | undefined): string {
+  if (!ts) return "never";
+  return new Date(ts * 1000).toISOString().slice(0, 16).replace("T", " ") + " UTC";
+}
+
+export function relative(ts: number | null | undefined): string {
+  if (!ts) return "never";
+  const diff = Math.floor(Date.now() / 1000) - ts;
+  const abs = Math.abs(diff);
+  const [n, word] =
+    abs < 60 ? [abs, "second"] :
+    abs < 3600 ? [Math.floor(abs / 60), "minute"] :
+    abs < 86400 ? [Math.floor(abs / 3600), "hour"] :
+    [Math.floor(abs / 86400), "day"];
+  const text = `${n} ${word}${n === 1 ? "" : "s"}`;
+  return diff < 0 ? `in ${text}` : `${text} ago`;
+}
+
+export function plural(n: number, word: string): string {
+  return `${n} ${word}${n === 1 ? "" : "s"}`;
+}
diff --git a/web/src/lib/legal.ts b/web/src/lib/legal.ts
new file mode 100644
index 0000000..b9bb44a
--- /dev/null
+++ b/web/src/lib/legal.ts
@@ -0,0 +1,9 @@
+/* web/src/lib/legal.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.
+ */
+
+/** Bump when either page changes in substance. */
+export const UPDATED = "28 October 2026";
+export const OPERATOR = "Clove Nytrix Doughmination Twilight";
diff --git a/web/src/lib/messages.ts b/web/src/lib/messages.ts
new file mode 100644
index 0000000..25857c1
--- /dev/null
+++ b/web/src/lib/messages.ts
@@ -0,0 +1,77 @@
+/* web/src/lib/messages.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.
+ *
+ * Messages that arrive in a URL travel as fixed codes, never as free text, so
+ * a crafted link can't put words in this site's mouth.
+ */
+
+/** Success notes, from `?m=` or an API answer's `message`. */
+export 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.",
+  "verify-sent": "Verification email sent. Check your inbox (and spam).",
+  "verify-failed": "We couldn't send a verification email right now. Try again later.",
+  "email-verified": "Email verified.",
+  "profile-saved": "Profile saved.",
+  "passkey-added": "Passkey added.",
+  "passkey-renamed": "Passkey renamed.",
+  "passkey-removed": "Passkey removed.",
+  "password-set": "Password saved. Your other sessions were signed out.",
+  "password-reset": "Password changed, and every device was signed out. Sign in with your new password.",
+  "password-removed": "Password removed. Sign in with a passkey from now on.",
+  "totp-enabled": "Two-factor codes are on for password sign-ins.",
+  "totp-disabled": "Two-factor codes are off.",
+  "session-revoked": "Session signed out.",
+  "sessions-revoked": "All other sessions are signed out.",
+  "user-created": "User created.",
+  "user-saved": "User saved.",
+  "user-deleted": "User deleted.",
+  "groups-saved": "Groups saved.",
+  "group-created": "Group created.",
+  "group-saved": "Group saved.",
+  "group-deleted": "Group deleted.",
+  "client-saved": "Application saved.",
+  "client-deleted": "Application deleted.",
+  "client-public": "Secret removed. The application is now a public (PKCE) client.",
+  "keys-rotated": "Signing key rotated. The old key stays published for two days.",
+  "credential-removed": "Sign-in method removed.",
+  "user-disabled": "Account disabled and signed out everywhere.",
+  "user-enabled": "Account enabled.",
+  "user-signed-out": "Signed out of every session and application.",
+  "link-revoked": "Sign-in link revoked.",
+  "name-reserved": "Name reserved.",
+  "name-released": "Name released.",
+};
+
+/** Problems the Worker can't send back to an app, from /error?code=. */
+export const ERRORS: Record<string, { title: string; text: string }> = {
+  incomplete_request: {
+    title: "Incomplete sign-in request",
+    text: "The app didn't say who it is or where to send you back to.",
+  },
+  unknown_client: {
+    title: "Unknown application",
+    text: "The app that sent you here isn't registered with this server.",
+  },
+  unregistered_redirect: {
+    title: "Unregistered redirect",
+    text: "The app asked to send you somewhere it isn't allowed to.",
+  },
+  logout_unverified: {
+    title: "Sign-out failed",
+    text: "The app sent a sign-out request this server couldn't verify.",
+  },
+  logout_mismatch: {
+    title: "Sign-out failed",
+    text: "The sign-out request doesn't match the app that sent it.",
+  },
+  logout_bad_redirect: {
+    title: "Sign-out failed",
+    text: "The app asked to send you somewhere it isn't allowed to after signing out.",
+  },
+};
diff --git a/web/src/lib/router.svelte.ts b/web/src/lib/router.svelte.ts
new file mode 100644
index 0000000..87edb50
--- /dev/null
+++ b/web/src/lib/router.svelte.ts
@@ -0,0 +1,66 @@
+/* web/src/lib/router.svelte.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.
+ *
+ * A small History API router. Same-origin links are handled in the page,
+ * except the ones the Worker answers itself (OIDC endpoints), which always
+ * get a real navigation.
+ */
+
+/** Paths the Worker handles; links to them must leave the app. */
+const SERVER_PATHS = [/^\/authorize$/, /^\/end-session$/, /^\/\.well-known\//, /^\/api\//, /^\/token$/, /^\/userinfo$/];
+
+function current() {
+  return { path: location.pathname, search: location.search };
+}
+
+export const route = $state(current());
+
+/** The current query string, parsed. */
+export function query(): URLSearchParams {
+  return new URLSearchParams(route.search);
+}
+
+/** Where we are, for `?return=` parameters. */
+export function here(): string {
+  return route.path + route.search;
+}
+
+export function isServerPath(path: string): boolean {
+  return SERVER_PATHS.some((re) => re.test(path));
+}
+
+/** Moves within the app; anything the Worker owns gets a real navigation. */
+export function navigate(url: string, opts: { replace?: boolean } = {}): void {
+  const target = new URL(url, location.href);
+  if (target.origin !== location.origin || isServerPath(target.pathname)) {
+    location.assign(target.href);
+    return;
+  }
+  const next = target.pathname + target.search;
+  if (opts.replace) history.replaceState(null, "", next);
+  else history.pushState(null, "", next);
+  Object.assign(route, current());
+  window.scrollTo(0, 0);
+}
+
+/**
+ * A full page load. Used after signing in or out (or anything else that
+ * changes the session), so the whole app starts again from the new state.
+ */
+export function reload(url: string): void {
+  location.assign(url);
+}
+
+addEventListener("popstate", () => Object.assign(route, current()));
+
+document.addEventListener("click", (ev) => {
+  if (ev.defaultPrevented || ev.button !== 0 || ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
+  const a = (ev.target as Element | null)?.closest?.("a");
+  if (!a || !a.href || a.target || a.hasAttribute("download") || a.dataset.reload !== undefined) return;
+  const url = new URL(a.href);
+  if (url.origin !== location.origin || isServerPath(url.pathname)) return;
+  ev.preventDefault();
+  navigate(url.pathname + url.search);
+});
diff --git a/web/src/lib/session.svelte.ts b/web/src/lib/session.svelte.ts
new file mode 100644
index 0000000..b9d6ff8
--- /dev/null
+++ b/web/src/lib/session.svelte.ts
@@ -0,0 +1,47 @@
+/* web/src/lib/session.svelte.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.
+ */
+
+export interface SessionUser {
+  id: string;
+  username: string;
+  name: string | null;
+  email: string | null;
+  picture: string | null;
+  isAdmin: boolean;
+}
+
+interface SessionState {
+  ready: boolean;
+  site: string;
+  registration: boolean;
+  contact: string | null;
+  needsSetup: boolean;
+  user: SessionUser | null;
+  csrf: string | null;
+  recentAuth: boolean;
+}
+
+/**
+ * Who's signed in and how the server is set up, from /api/session. Loaded once
+ * per page load: anything that signs in or out does a full navigation, so
+ * this never goes stale.
+ */
+export const session = $state<SessionState>({
+  ready: false,
+  site: "Sign in",
+  registration: false,
+  contact: null,
+  needsSetup: false,
+  user: null,
+  csrf: null,
+  recentAuth: false,
+});
+
+export async function loadSession(): Promise<void> {
+  const res = await fetch("/api/session", { credentials: "same-origin" });
+  if (!res.ok) throw new Error(`session ${res.status}`);
+  Object.assign(session, await res.json(), { ready: true });
+}
diff --git a/web/src/lib/webauthn.ts b/web/src/lib/webauthn.ts
new file mode 100644
index 0000000..2bf7c05
--- /dev/null
+++ b/web/src/lib/webauthn.ts
@@ -0,0 +1,124 @@
+/* web/src/lib/webauthn.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.
+ *
+ * Passkey ceremonies. The server speaks the WebAuthn JSON format
+ * (@simplewebauthn/server); browsers without the JSON helpers get it
+ * converted by hand.
+ */
+
+import { api } from "./api";
+
+type Json = Record<string, any>;
+
+export function passkeysSupported(): boolean {
+  return typeof window.PublicKeyCredential === "function";
+}
+
+function toBuffer(b64url: string): ArrayBuffer {
+  const b64 = b64url.replace(/-/g, "+").replace(/_/g, "/");
+  const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
+  const out = new Uint8Array(bin.length);
+  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+  return out.buffer;
+}
+
+function toB64url(buffer: ArrayBuffer | null | undefined): string | undefined {
+  if (!buffer) return undefined;
+  let bin = "";
+  for (const b of new Uint8Array(buffer)) bin += String.fromCharCode(b);
+  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+function creationOptions(json: Json): PublicKeyCredentialCreationOptions {
+  const PKC = PublicKeyCredential as any;
+  if (PKC.parseCreationOptionsFromJSON) return PKC.parseCreationOptionsFromJSON(json);
+  return {
+    ...json,
+    challenge: toBuffer(json.challenge),
+    user: { ...json.user, id: toBuffer(json.user.id) },
+    excludeCredentials: (json.excludeCredentials || []).map((c: Json) => ({ ...c, id: toBuffer(c.id) })),
+  } as PublicKeyCredentialCreationOptions;
+}
+
+function requestOptions(json: Json): PublicKeyCredentialRequestOptions {
+  const PKC = PublicKeyCredential as any;
+  if (PKC.parseRequestOptionsFromJSON) return PKC.parseRequestOptionsFromJSON(json);
+  return {
+    ...json,
+    challenge: toBuffer(json.challenge),
+    allowCredentials: (json.allowCredentials || []).map((c: Json) => ({ ...c, id: toBuffer(c.id) })),
+  } as PublicKeyCredentialRequestOptions;
+}
+
+function credentialJSON(cred: PublicKeyCredential): Json {
+  try {
+    if (typeof (cred as any).toJSON === "function") return (cred as any).toJSON();
+  } catch {
+    // Some password managers return objects whose toJSON throws; build it by hand.
+  }
+  const r = cred.response as any;
+  const response: Json = { clientDataJSON: toB64url(r.clientDataJSON) };
+  if (r.attestationObject) {
+    response.attestationObject = toB64url(r.attestationObject);
+    response.transports = typeof r.getTransports === "function" ? r.getTransports() : [];
+  } else {
+    response.authenticatorData = toB64url(r.authenticatorData);
+    response.signature = toB64url(r.signature);
+    response.userHandle = toB64url(r.userHandle);
+  }
+  return {
+    id: cred.id,
+    rawId: toB64url(cred.rawId),
+    type: cred.type,
+    authenticatorAttachment: cred.authenticatorAttachment || undefined,
+    clientExtensionResults: cred.getClientExtensionResults(),
+    response,
+  };
+}
+
+/** A friendly message, or "" when the person simply cancelled. */
+export function passkeyMessage(err: unknown): string {
+  const e = err as { name?: string; message?: string } | null;
+  if (!e) return "Something went wrong. Please try again.";
+  if (e.name === "NotAllowedError" || e.name === "AbortError") return "";
+  if (e.name === "InvalidStateError") return "That passkey is already registered to your account.";
+  if (e.name === "SecurityError") return "Passkeys can't be used on this address.";
+  return e.message || "Something went wrong. Please try again.";
+}
+
+/**
+ * Signs in with a passkey: options from `base/options`, the result to
+ * `base/verify`. Returns where to go next, or null if the browser gave nothing.
+ */
+export async function getPasskey(
+  base: string,
+  extra: Json = {},
+  opts: { conditional?: AbortSignal } = {},
+): Promise<string | null> {
+  const { id, options } = await api<{ id: string; options: Json }>(`${base}/options`, {});
+  const request: CredentialRequestOptions = { publicKey: requestOptions(options) };
+  if (opts.conditional) {
+    (request as any).mediation = "conditional";
+    request.signal = opts.conditional;
+  }
+  const cred = (await navigator.credentials.get(request)) as PublicKeyCredential | null;
+  if (!cred) return null;
+  const result = await api<{ redirect: string }>(`${base}/verify`, { id, response: credentialJSON(cred), ...extra });
+  return result.redirect;
+}
+
+/** Adds a passkey to the signed-in account. Returns false if the browser gave nothing. */
+export async function createPasskey(name: string): Promise<boolean> {
+  const { id, options } = await api<{ id: string; options: Json }>("/api/account/passkeys/options", {});
+  const cred = (await navigator.credentials.create({ publicKey: creationOptions(options) })) as PublicKeyCredential | null;
+  if (!cred) return false;
+  await api("/api/account/passkeys/verify", { id, response: credentialJSON(cred), name });
+  return true;
+}
+
+export async function conditionalAvailable(): Promise<boolean> {
+  const PKC = window.PublicKeyCredential as any;
+  return Boolean(PKC?.isConditionalMediationAvailable && (await PKC.isConditionalMediationAvailable()));
+}
diff --git a/web/src/main.ts b/web/src/main.ts
new file mode 100644
index 0000000..d71744e
--- /dev/null
+++ b/web/src/main.ts
@@ -0,0 +1,19 @@
+/* web/src/main.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 { mount } from "svelte";
+import "./app.css";
+import App from "./App.svelte";
+import { loadSession } from "./lib/session.svelte";
+
+const target = document.getElementById("app")!;
+
+loadSession()
+  .then(() => mount(App, { target }))
+  .catch(() => {
+    target.innerHTML =
+      '<main class="narrow"><div class="card"><h1>Can\'t reach the server</h1><p class="muted">Check your connection, then reload the page.</p></div></main>';
+  });
diff --git a/web/src/pages/Apps.svelte b/web/src/pages/Apps.svelte
new file mode 100644
index 0000000..b4ad4c2
--- /dev/null
+++ b/web/src/pages/Apps.svelte
@@ -0,0 +1,62 @@
+<script lang="ts">
+  import { ExternalLink } from "@lucide/svelte";
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { session } from "../lib/session.svelte";
+  import Flash from "../components/Flash.svelte";
+  import Notes from "../components/Notes.svelte";
+  import Title from "../components/Title.svelte";
+
+  interface App {
+    id: string;
+    name: string;
+    url: string;
+  }
+
+  let apps = $state<App[] | null>(null);
+  const load = new Action();
+  load.run(async () => (apps = await api<App[]>("/api/apps")));
+
+  function host(url: string): string {
+    try {
+      return new URL(url).host;
+    } catch {
+      return url;
+    }
+  }
+</script>
+
+<Title text="Your apps" />
+<h1>Hi, {session.user?.name ?? session.user?.username}</h1>
+<Flash />
+<Notes error={load.error} />
+
+{#if apps}
+  {#if apps.length === 0}
+    <section class="panel">
+      <h2>No apps yet</h2>
+      <p class="muted">
+        Apps you can sign in to with this account will show up here.
+        {#if session.user?.isAdmin}
+          Give an application a website in <a href="/admin/clients">Admin → Applications</a> to list it.
+        {/if}
+      </p>
+    </section>
+  {:else}
+    <p class="muted">Everything you can sign in to with @{session.user?.username}.</p>
+    <ul class="apps">
+      {#each apps as app (app.id)}
+        <li>
+          <a class="app-tile" href={app.url} rel="noopener">
+            <span class="app-mark" aria-hidden="true">{app.name.slice(0, 1).toUpperCase()}</span>
+            <span class="app-text">
+              <strong>{app.name}</strong>
+              <small class="muted">{host(app.url)}</small>
+            </span>
+            <ExternalLink class="icon" aria-hidden="true" />
+          </a>
+        </li>
+      {/each}
+    </ul>
+  {/if}
+{/if}
diff --git a/web/src/pages/AuthorizeNotice.svelte b/web/src/pages/AuthorizeNotice.svelte
new file mode 100644
index 0000000..3a34bbe
--- /dev/null
+++ b/web/src/pages/AuthorizeNotice.svelte
@@ -0,0 +1,59 @@
+<script lang="ts">
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { navigate, reload, route } from "../lib/router.svelte";
+  import Card from "../components/Card.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  // /authorize sends people here (with its own query) when it has something to
+  // explain. Asking the API again keeps the decision on the server.
+  type Notice =
+    | { kind: "error"; code: string }
+    | { kind: "redirect"; url: string }
+    | { kind: "denied"; client: string; username: string; back: string }
+    | { kind: "verify-email"; client: string; email: string | null; retry: string };
+
+  let notice = $state<Notice | null>(null);
+  const load = new Action();
+  const signOut = new Action();
+
+  load.run(async () => {
+    const n = await api<Notice>(`/api/authorize/notice${route.search}`);
+    if (n.kind === "redirect") reload(n.url);
+    else if (n.kind === "error") navigate(`/error?code=${encodeURIComponent(n.code)}`, { replace: true });
+    else notice = n;
+  });
+
+  async function switchAccount() {
+    // Sign out, then sign in again and pick up this same request.
+    await signOut.run(async () => {
+      await api("/api/logout", {});
+      reload(`/login?${new URLSearchParams({ return: `/authorize${route.search}` })}`);
+    });
+  }
+</script>
+
+<Notes error={load.error} />
+{#if notice?.kind === "denied"}
+  <Card title={`No access to ${notice.client}`}>
+    <p class="muted">
+      You're signed in as <strong>@{notice.username}</strong>, which isn't allowed to use {notice.client}. If you think
+      it should be, ask an admin.
+    </p>
+    <Notes error={signOut.error} />
+    <button type="button" class="wide" onclick={switchAccount} disabled={signOut.busy}>Sign in as someone else</button>
+    <p class="small"><a class="btn wide" href={notice.back}>Back to {notice.client}</a></p>
+  </Card>
+{:else if notice?.kind === "verify-email"}
+  <Card title="Verify your email first">
+    <p class="muted">
+      {#if notice.email}
+        We sent a link to <strong>{notice.email}</strong>. Open it, then come back here.
+      {:else}
+        Add an email address in your settings and verify it to use {notice.client}.
+      {/if}
+    </p>
+    <p><a class="btn primary wide" href={notice.retry}>I've verified it, continue</a></p>
+    <p><a class="btn wide" href="/settings">Settings (resend the link)</a></p>
+  </Card>
+{/if}
diff --git a/web/src/pages/Contact.svelte b/web/src/pages/Contact.svelte
new file mode 100644
index 0000000..e531cc1
--- /dev/null
+++ b/web/src/pages/Contact.svelte
@@ -0,0 +1,5 @@
+<script lang="ts">
+  import { session } from "../lib/session.svelte";
+</script>
+
+{#if session.contact}<a href={`mailto:${session.contact}`}>{session.contact}</a>{:else}the administrator of this server{/if}
diff --git a/web/src/pages/EndSession.svelte b/web/src/pages/EndSession.svelte
new file mode 100644
index 0000000..2797a55
--- /dev/null
+++ b/web/src/pages/EndSession.svelte
@@ -0,0 +1,49 @@
+<script lang="ts">
+  import { LogOut } from "@lucide/svelte";
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { navigate, query, reload, route } from "../lib/router.svelte";
+  import Card from "../components/Card.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  // RP-initiated logout without proof it came from the app: confirm first.
+  const q = query();
+  const request = {
+    client_id: q.get("client_id") ?? "",
+    post_logout_redirect_uri: q.get("post_logout_redirect_uri") ?? "",
+    state: q.get("state") ?? "",
+  };
+
+  let info = $state<{ client: string | null; username: string | null; returnTo: string | null } | null>(null);
+  const load = new Action();
+  const act = new Action();
+
+  load.run(async () => {
+    try {
+      info = await api(`/api/end-session${route.search}`);
+    } catch (err) {
+      navigate("/error?code=logout_bad_redirect", { replace: true });
+      throw err;
+    }
+  });
+
+  async function signOut() {
+    await act.run(async () => reload((await api<{ redirect: string }>("/api/end-session", request)).redirect));
+  }
+</script>
+
+{#if info}
+  <Card title="Sign out?">
+    <p class="muted">
+      {info.client ? `${info.client} wants to sign you out` : "Sign out"}{info.username ? ` of @${info.username}` : ""} on this server.
+    </p>
+    <Notes error={act.error} />
+    <button type="button" class="primary wide" onclick={signOut} disabled={act.busy}>
+      <LogOut class="icon" aria-hidden="true" />
+      Sign out
+    </button>
+    {#if info.returnTo}
+      <p class="small"><a class="btn wide" href={info.returnTo}>Stay signed in and go back</a></p>
+    {/if}
+  </Card>
+{/if}
diff --git a/web/src/pages/ErrorPage.svelte b/web/src/pages/ErrorPage.svelte
new file mode 100644
index 0000000..a29fa59
--- /dev/null
+++ b/web/src/pages/ErrorPage.svelte
@@ -0,0 +1,13 @@
+<script lang="ts">
+  import { ERRORS } from "../lib/messages";
+  import { query } from "../lib/router.svelte";
+  import Card from "../components/Card.svelte";
+
+  // Fixed messages only: the code picks one, so a crafted link can't write the text.
+  const error = ERRORS[query().get("code") ?? ""] ?? {
+    title: "Something went wrong",
+    text: "That request couldn't be completed. Go back to the app and try again.",
+  };
+</script>
+
+<Card title={error.title} lead={error.text} />
diff --git a/web/src/pages/Forgot.svelte b/web/src/pages/Forgot.svelte
new file mode 100644
index 0000000..e82d15f
--- /dev/null
+++ b/web/src/pages/Forgot.svelte
@@ -0,0 +1,40 @@
+<script lang="ts">
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import Card from "../components/Card.svelte";
+  import Field from "../components/Field.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  let account = $state("");
+  let sent = $state(false);
+  const form = new Action();
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    // The answer is the same whether or not the account exists.
+    await form.run(async () => {
+      await api("/api/forgot", { account });
+      sent = true;
+    });
+  }
+</script>
+
+<Card title="Forgot your password?">
+  {#if sent}
+    <p class="notice ok" role="status">
+      If that matches an account with a verified email address, we've sent it a link. Check your inbox (and spam).
+    </p>
+    <p class="muted">No email? Ask an admin for a sign-in link.</p>
+  {:else}
+    <p class="muted">
+      Enter your username or email address. We'll email a link to choose a new password, if the account has a verified
+      address.
+    </p>
+    <form class="stack" onsubmit={submit}>
+      <Notes error={form.error} />
+      <Field label="Username or email" name="account" bind:value={account} required autocomplete="username" maxlength={254} autofocus />
+      <button type="submit" class="primary wide" disabled={form.busy}>Send reset link</button>
+    </form>
+  {/if}
+  <p class="muted small"><a href="/login">Back to sign in</a></p>
+</Card>
diff --git a/web/src/pages/Login.svelte b/web/src/pages/Login.svelte
new file mode 100644
index 0000000..0f0586f
--- /dev/null
+++ b/web/src/pages/Login.svelte
@@ -0,0 +1,109 @@
+<script lang="ts">
+  import { KeyRound } from "@lucide/svelte";
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { navigate, query, reload } from "../lib/router.svelte";
+  import { session } from "../lib/session.svelte";
+  import { conditionalAvailable, getPasskey, passkeyMessage, passkeysSupported } from "../lib/webauthn";
+  import Card from "../components/Card.svelte";
+  import Field from "../components/Field.svelte";
+  import Flash from "../components/Flash.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  const q = query();
+  const returnTo = safeReturn(q.get("return"));
+  const reauth = q.get("reauth") === "1";
+
+  /** Same rule as the server: only paths on this site. */
+  function safeReturn(raw: string | null): string {
+    if (!raw || !raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return "/apps";
+    return raw;
+  }
+
+  let username = $state(reauth ? (session.user?.username ?? "") : "");
+  let password = $state("");
+  const form = new Action();
+  let passkeyError = $state("");
+  let passkeyBusy = $state(false);
+  const supported = passkeysSupported();
+
+  // Already signed in (and not confirming it's you): straight on.
+  if (session.user && !reauth) reload(returnTo);
+  else if (session.needsSetup) navigate("/setup", { replace: true });
+
+  // Saved passkeys are offered straight from the username field's autofill.
+  // Cancelled when the page goes away or the button is used instead.
+  let conditional: AbortController | null = null;
+  async function startConditional() {
+    if (!supported || !(await conditionalAvailable())) return;
+    conditional = new AbortController();
+    try {
+      const to = await getPasskey("/api/login/passkey", { return: returnTo }, { conditional: conditional.signal });
+      if (to) reload(to);
+    } catch (err) {
+      if ((err as { name?: string })?.name !== "AbortError") passkeyError = passkeyMessage(err);
+    }
+  }
+  $effect(() => {
+    if (session.user && !reauth) return;
+    startConditional();
+    return () => conditional?.abort();
+  });
+
+  async function passkeySignIn() {
+    conditional?.abort();
+    passkeyBusy = true;
+    passkeyError = "";
+    try {
+      const to = await getPasskey("/api/login/passkey", { return: returnTo });
+      if (to) reload(to);
+    } catch (err) {
+      passkeyError = passkeyMessage(err);
+    } finally {
+      passkeyBusy = false;
+      startConditional();
+    }
+  }
+
+  async function passwordSignIn(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      const res = await api<{ redirect?: string; mfa?: object }>("/api/login/password", {
+        username,
+        password,
+        return: returnTo,
+      });
+      password = "";
+      if (res.mfa) navigate("/login/mfa");
+      else if (res.redirect) reload(res.redirect);
+    });
+  }
+</script>
+
+<Card title={reauth ? "Confirm it's you" : "Sign in"} lead={reauth ? "This needs a fresh sign-in. It only takes a moment." : undefined}>
+  <Flash />
+  <Notes error={passkeyError} />
+
+  <button type="button" class="primary wide" onclick={passkeySignIn} disabled={!supported || passkeyBusy}>
+    <KeyRound class="icon" aria-hidden="true" />
+    {supported ? "Sign in with a passkey" : "Passkeys aren't supported in this browser"}
+  </button>
+
+  <div class="divider"><span>or use a password</span></div>
+
+  <form class="stack" onsubmit={passwordSignIn}>
+    <Notes error={form.error} />
+    <Field label="Username" name="username" bind:value={username} required autocomplete="username webauthn" maxlength={64} autofocus={!username} />
+    <Field label="Password" name="password" type="password" bind:value={password} required autocomplete="current-password" maxlength={512} autofocus={Boolean(username)} />
+    <button type="submit" class="wide" disabled={form.busy}>Sign in</button>
+  </form>
+
+  {#if !reauth}
+    <p class="muted small"><a href="/forgot">Forgot your password?</a></p>
+    {#if session.registration}
+      <p class="muted small">
+        New here? <a href={`/register?${new URLSearchParams({ return: returnTo })}`}>Create an account</a>
+      </p>
+    {/if}
+  {/if}
+</Card>
diff --git a/web/src/pages/LoginLink.svelte b/web/src/pages/LoginLink.svelte
new file mode 100644
index 0000000..2082eac
--- /dev/null
+++ b/web/src/pages/LoginLink.svelte
@@ -0,0 +1,40 @@
+<script lang="ts">
+  import { LogIn } from "@lucide/svelte";
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { reload } from "../lib/router.svelte";
+  import { session } from "../lib/session.svelte";
+  import Card from "../components/Card.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  let { params }: { params: Record<string, string> } = $props();
+  const path = $derived(`/api/login/link/${encodeURIComponent(params.token ?? "")}`);
+
+  let target = $state<{ userId: string; username: string; name: string | null } | null>(null);
+  const load = new Action();
+  const use = new Action();
+  load.run(async () => (target = await api(path)));
+
+  // Link scanners follow GETs, so using the link takes a deliberate click.
+  async function signIn() {
+    await use.run(async () => reload((await api<{ redirect: string }>(path, {})).redirect));
+  }
+</script>
+
+{#if load.error}
+  <Card title="This link can't be used" lead="It has expired, was already used, or was replaced by a newer one. Ask an admin for a new link." />
+{:else if target}
+  <Card title={`Sign in as ${target.name ?? target.username}`}>
+    <p class="muted">
+      This one-time link signs you in as <strong>@{target.username}</strong>. It stops working once it's used.
+    </p>
+    {#if session.user && session.user.id !== target.userId}
+      <p class="notice">You'll be signed out of @{session.user.username} on this browser.</p>
+    {/if}
+    <Notes error={use.error} />
+    <button type="button" class="primary wide" onclick={signIn} disabled={use.busy}>
+      <LogIn class="icon" aria-hidden="true" />
+      Continue
+    </button>
+  </Card>
+{/if}
diff --git a/web/src/pages/Mfa.svelte b/web/src/pages/Mfa.svelte
new file mode 100644
index 0000000..7c0cade
--- /dev/null
+++ b/web/src/pages/Mfa.svelte
@@ -0,0 +1,87 @@
+<script lang="ts">
+  import { KeyRound, LogIn } from "@lucide/svelte";
+  import { ApiError, api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { navigate, reload } from "../lib/router.svelte";
+  import { getPasskey, passkeyMessage, passkeysSupported } from "../lib/webauthn";
+  import Card from "../components/Card.svelte";
+  import Field from "../components/Field.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  let step = $state<{ totp: boolean; passkey: boolean } | null>(null);
+  let code = $state("");
+  const form = new Action();
+  let passkeyError = $state("");
+  let passkeyBusy = $state(false);
+  const supported = passkeysSupported();
+
+  /** The half-finished sign-in is gone (expired, or too many tries): back to the start. */
+  function restartIfNeeded(err: unknown) {
+    if (err instanceof ApiError && err.data.restart) navigate("/login", { replace: true });
+  }
+
+  api<{ totp: boolean; passkey: boolean }>("/api/login/mfa").then((s) => (step = s), restartIfNeeded);
+
+  async function submitCode(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      try {
+        const { redirect } = await api<{ redirect: string }>("/api/login/mfa", { code });
+        reload(redirect);
+      } catch (err) {
+        code = "";
+        restartIfNeeded(err);
+        throw err;
+      }
+    });
+  }
+
+  async function usePasskey() {
+    passkeyBusy = true;
+    passkeyError = "";
+    try {
+      const to = await getPasskey("/api/login/mfa/passkey");
+      if (to) reload(to);
+    } catch (err) {
+      restartIfNeeded(err);
+      passkeyError = passkeyMessage(err);
+    } finally {
+      passkeyBusy = false;
+    }
+  }
+</script>
+
+<Card
+  title="One more step"
+  lead={!step
+    ? undefined
+    : 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."}
+>
+  {#if step}
+    <Notes error={passkeyError} />
+    {#if step.passkey}
+      <button type="button" class={step.totp ? "wide" : "primary wide"} onclick={usePasskey} disabled={!supported || passkeyBusy}>
+        <KeyRound class="icon" aria-hidden="true" />
+        {supported ? "Use a passkey" : "Passkeys aren't supported in this browser"}
+      </button>
+    {/if}
+    {#if step.passkey && step.totp}
+      <div class="divider"><span>or enter a code</span></div>
+    {/if}
+    {#if step.totp}
+      <form class="stack" onsubmit={submitCode}>
+        <Notes error={form.error} />
+        <Field label="Code" name="code" bind:value={code} required autocomplete="one-time-code" inputmode="numeric" pattern={"[0-9 ]{6,7}"} maxlength={7} autofocus />
+        <button type="submit" class="primary wide" disabled={form.busy}>
+          <LogIn class="icon" aria-hidden="true" />
+          Continue
+        </button>
+      </form>
+    {/if}
+  {/if}
+  <p class="muted small"><a class="btn wide" href="/login">Start over</a></p>
+</Card>
diff --git a/web/src/pages/NotFound.svelte b/web/src/pages/NotFound.svelte
new file mode 100644
index 0000000..ef04215
--- /dev/null
+++ b/web/src/pages/NotFound.svelte
@@ -0,0 +1,8 @@
+<script lang="ts">
+  import { session } from "../lib/session.svelte";
+  import Card from "../components/Card.svelte";
+</script>
+
+<Card title="Page not found" lead="There's nothing at this address.">
+  <p><a class="btn primary" href={session.user ? "/apps" : "/login"}>{session.user ? "Your apps" : "Sign in"}</a></p>
+</Card>
diff --git a/web/src/pages/Privacy.svelte b/web/src/pages/Privacy.svelte
new file mode 100644
index 0000000..365594d
--- /dev/null
+++ b/web/src/pages/Privacy.svelte
@@ -0,0 +1,106 @@
+<script lang="ts">
+  import { session } from "../lib/session.svelte";
+  import Title from "../components/Title.svelte";
+  import Contact from "./Contact.svelte";
+  import { OPERATOR, UPDATED } from "../lib/legal";
+</script>
+
+<Title text="Privacy policy" />
+<article class="legal">
+  <p class="eyebrow">Last updated {UPDATED}</p>
+  <h1>Privacy policy</h1>
+  <p>
+    {session.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 />.
+  </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 (password reset, verification, sign-out): an hour 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 />. 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>
diff --git a/web/src/pages/Register.svelte b/web/src/pages/Register.svelte
new file mode 100644
index 0000000..2148314
--- /dev/null
+++ b/web/src/pages/Register.svelte
@@ -0,0 +1,58 @@
+<script lang="ts">
+  import { LogIn, UserPlus } from "@lucide/svelte";
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { navigate, query, reload } from "../lib/router.svelte";
+  import { session } from "../lib/session.svelte";
+  import Card from "../components/Card.svelte";
+  import Field from "../components/Field.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  const PASSWORD_MIN = 10;
+  const returnTo = query().get("return") ?? "/apps";
+
+  if (session.user) reload(returnTo.startsWith("/") && !returnTo.startsWith("//") ? returnTo : "/apps");
+  else if (session.needsSetup) navigate("/setup", { replace: true });
+
+  const values = $state({ username: "", name: "", email: "", password: "", confirm: "" });
+  const form = new Action();
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      try {
+        reload((await api<{ redirect: string }>("/api/register", { ...values, return: returnTo })).redirect);
+      } finally {
+        // Never keep the password around after a failed attempt.
+        values.password = values.confirm = "";
+      }
+    });
+  }
+</script>
+
+{#if !session.registration}
+  <Card title="Sign-ups are closed" lead="Accounts on this server are created by an admin.">
+    <p><a class="btn primary" href="/login"><LogIn class="icon" aria-hidden="true" /> Sign in</a></p>
+  </Card>
+{:else}
+  <Card title="Create an account" lead="You can add a passkey straight after.">
+    <form class="stack" onsubmit={submit}>
+      <Notes error={form.error} />
+      <Field label="Username" name="username" bind:value={values.username} required autocomplete="username" maxlength={32} autofocus hint="Lowercase letters, digits, dots, dashes or underscores. You can't change it later." />
+      <Field label="Display name" name="name" bind:value={values.name} autocomplete="name" maxlength={100} />
+      <Field label="Email" name="email" type="email" bind:value={values.email} required autocomplete="email" maxlength={254} hint="We'll send a link to verify it." />
+      <Field label="Password" name="password" type="password" bind:value={values.password} required autocomplete="new-password" maxlength={512} hint={`At least ${PASSWORD_MIN} characters.`} />
+      <Field label="Confirm password" name="confirm" type="password" bind:value={values.confirm} required autocomplete="new-password" maxlength={512} />
+      <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" disabled={form.busy}>
+        <UserPlus class="icon" aria-hidden="true" />
+        Create account
+      </button>
+    </form>
+    <p class="muted small">
+      Already have an account? <a href={`/login?${new URLSearchParams({ return: returnTo })}`}>Sign in</a>
+    </p>
+  </Card>
+{/if}
diff --git a/web/src/pages/Reset.svelte b/web/src/pages/Reset.svelte
new file mode 100644
index 0000000..3a997c9
--- /dev/null
+++ b/web/src/pages/Reset.svelte
@@ -0,0 +1,51 @@
+<script lang="ts">
+  import { KeyRound } from "@lucide/svelte";
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { reload } from "../lib/router.svelte";
+  import Card from "../components/Card.svelte";
+  import Field from "../components/Field.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  let { params }: { params: Record<string, string> } = $props();
+  const path = $derived(`/api/reset/${encodeURIComponent(params.token ?? "")}`);
+
+  let username = $state<string | null>(null);
+  let password = $state("");
+  let confirm = $state("");
+  const load = new Action();
+  const form = new Action();
+  load.run(async () => (username = (await api<{ username: string }>(path)).username));
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      try {
+        reload((await api<{ redirect: string }>(path, { password, confirm })).redirect);
+      } finally {
+        password = confirm = "";
+      }
+    });
+  }
+</script>
+
+{#if load.error}
+  <Card title="This link can't be used" lead="It has expired, was already used, or a newer one was sent.">
+    <p><a class="btn primary" href="/forgot">Send a new link</a></p>
+  </Card>
+{:else if username}
+  <Card title="Choose a new password">
+    <p class="muted">For <strong>@{username}</strong>. Every browser and app signed in to this account will be signed out.</p>
+    <form class="stack" onsubmit={submit}>
+      <Notes error={form.error} />
+      <!-- Lets password managers save the new password against the right account. -->
+      <input type="text" name="username" value={username} autocomplete="username" hidden />
+      <Field label="New password" name="password" type="password" bind:value={password} required autocomplete="new-password" maxlength={512} hint="At least 10 characters." autofocus />
+      <Field label="Confirm password" name="confirm" type="password" bind:value={confirm} required autocomplete="new-password" maxlength={512} />
+      <button type="submit" class="primary wide" disabled={form.busy}>
+        <KeyRound class="icon" aria-hidden="true" />
+        Set password
+      </button>
+    </form>
+  </Card>
+{/if}
diff --git a/web/src/pages/Security.svelte b/web/src/pages/Security.svelte
new file mode 100644
index 0000000..227b1f4
--- /dev/null
+++ b/web/src/pages/Security.svelte
@@ -0,0 +1,57 @@
+<script lang="ts">
+  import { LogIn, LogOut } from "@lucide/svelte";
+  import { api, confirmed } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import Card from "../components/Card.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  // The "wasn't me" links in security emails. They work without signing in.
+  let { params }: { params: Record<string, string> } = $props();
+  const path = $derived(`/api/security/${encodeURIComponent(params.token ?? "")}`);
+
+  let target = $state<{ username: string; sessionLive: boolean } | null>(null);
+  let result = $state<{ everywhere: boolean } | null>(null);
+  const load = new Action();
+  const act = new Action();
+  load.run(async () => (target = await api(path)));
+
+  async function signOut(scope: "device" | "all") {
+    if (scope === "all" && !confirmed("Sign out every browser and app, including this one?")) return;
+    await act.run(async () => (result = await api(path, { scope })));
+  }
+</script>
+
+{#if result}
+  <Card
+    title={result.everywhere ? "Signed out everywhere" : "That device is signed out"}
+    lead="Now sign in, change your password, and check your passkeys and two-factor settings for anything you didn't add."
+  >
+    <p><a class="btn primary" href="/login?return=%2Fsettings" data-reload><LogIn class="icon" aria-hidden="true" /> Sign in</a></p>
+  </Card>
+{:else if load.error}
+  <Card title="This link has expired" lead="Sign in to see and sign out your sessions in Settings. If you can't sign in, ask an admin to sign you out everywhere.">
+    <p><a class="btn primary" href="/login"><LogIn class="icon" aria-hidden="true" /> Sign in</a></p>
+  </Card>
+{:else if target}
+  <Card title="Wasn't you?">
+    <p class="muted">
+      Sign the device out of <strong>@{target.username}</strong>. Then sign in yourself and change your password.
+    </p>
+    <Notes error={act.error} />
+    <div class="stack">
+      {#if target.sessionLive}
+        <button type="button" class="primary wide" onclick={() => signOut("device")} disabled={act.busy}>
+          <LogOut class="icon" aria-hidden="true" />
+          Sign out that device
+        </button>
+      {:else}
+        <p class="notice">That device's session has already ended.</p>
+      {/if}
+      <button type="button" class="danger wide" onclick={() => signOut("all")} disabled={act.busy}>
+        <LogOut class="icon" aria-hidden="true" />
+        Sign out everywhere
+      </button>
+    </div>
+    <p class="muted small">"Everywhere" also signs out the apps you use with this account.</p>
+  </Card>
+{/if}
diff --git a/web/src/pages/Settings.svelte b/web/src/pages/Settings.svelte
new file mode 100644
index 0000000..9ea10a1
--- /dev/null
+++ b/web/src/pages/Settings.svelte
@@ -0,0 +1,333 @@
+<script lang="ts">
+  import { KeyRound, Save } from "@lucide/svelte";
+  import { api, confirmed } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { date, relative } from "../lib/format";
+  import { navigate, reload } from "../lib/router.svelte";
+  import { createPasskey, passkeyMessage, passkeysSupported } from "../lib/webauthn";
+  import Field from "../components/Field.svelte";
+  import Flash from "../components/Flash.svelte";
+  import Notes from "../components/Notes.svelte";
+  import Section from "../components/Section.svelte";
+  import Title from "../components/Title.svelte";
+
+  interface AccountData {
+    username: string;
+    name: string | null;
+    email: string | null;
+    emailVerified: boolean;
+    picture: string | null;
+    hasPassword: boolean;
+    totp: boolean;
+    recentAuth: boolean;
+    passkeys: { id: string; name: string; synced: boolean; createdAt: number; lastUsedAt: number | null }[];
+    sessions: {
+      id: string;
+      current: boolean;
+      device: string;
+      ip: string | null;
+      method: string;
+      createdAt: number;
+      lastSeenAt: number;
+    }[];
+  }
+
+  const PASSWORD_MIN = 10;
+
+  let data = $state<AccountData | null>(null);
+  const profile = $state({ name: "", email: "", picture: "" });
+  const passwords = $state({ password: "", confirm: "" });
+  const removal = $state({ confirm: "", password: "" });
+  let newPasskeyName = $state("");
+  let totpCode = $state("");
+  let renames = $state<Record<string, string>>({});
+
+  // One Action per section, so each shows its own result next to its form.
+  const load = new Action();
+  const profileAction = new Action();
+  const passkeyAction = new Action();
+  const passwordAction = new Action();
+  const totpAction = new Action();
+  const sessionAction = new Action();
+  const deleteAction = new Action();
+
+  async function refresh() {
+    const d = await api<AccountData>("/api/account");
+    data = d;
+    Object.assign(profile, { name: d.name ?? "", email: d.email ?? "", picture: d.picture ?? "" });
+    renames = Object.fromEntries(d.passkeys.map((p) => [p.id, p.name]));
+  }
+  load.run(refresh);
+
+  /** Runs `call` in a section; on success shows its message and reloads the page's data. */
+  async function act(section: Action, call: () => Promise<{ message?: string | null; redirect?: string }>) {
+    await section.run(async () => {
+      const res = await call();
+      if (res.redirect) return reload(res.redirect);
+      await refresh();
+      return res;
+    });
+  }
+
+  const post = (path: string, body: object = {}) => api<{ message?: string; redirect?: string }>(path, body);
+
+  function saveProfile(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(profileAction, () => post("/api/account/profile", profile));
+  }
+
+  async function addPasskey(ev: SubmitEvent) {
+    ev.preventDefault();
+    passkeyAction.busy = true;
+    passkeyAction.error = "";
+    passkeyAction.message = "";
+    try {
+      if (await createPasskey(newPasskeyName.trim())) {
+        newPasskeyName = "";
+        await refresh();
+        passkeyAction.message = "Passkey added.";
+      }
+    } catch (err) {
+      passkeyAction.error = passkeyMessage(err);
+    } finally {
+      passkeyAction.busy = false;
+    }
+  }
+
+  function renamePasskey(ev: SubmitEvent, id: string) {
+    ev.preventDefault();
+    act(passkeyAction, () => post(`/api/account/passkeys/${encodeURIComponent(id)}/rename`, { name: renames[id] }));
+  }
+
+  function removePasskey(id: string, name: string) {
+    if (!confirmed(`Remove the passkey "${name}"?`)) return;
+    act(passkeyAction, () => post(`/api/account/passkeys/${encodeURIComponent(id)}/delete`));
+  }
+
+  function setPassword(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(passwordAction, async () => {
+      try {
+        return await post("/api/account/password", passwords);
+      } finally {
+        passwords.password = passwords.confirm = "";
+      }
+    });
+  }
+
+  function removePassword() {
+    if (!confirmed("Remove your password? You'll only be able to sign in with a passkey.")) return;
+    act(passwordAction, () => post("/api/account/password/remove"));
+  }
+
+  function disableTotp(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(totpAction, async () => {
+      try {
+        return await post("/api/account/totp/disable", { code: totpCode });
+      } finally {
+        totpCode = "";
+      }
+    });
+  }
+
+  function resendVerification() {
+    act(profileAction, () => post("/api/account/email/verify"));
+  }
+
+  function revokeSession(id: string) {
+    act(sessionAction, () => post(`/api/account/sessions/${encodeURIComponent(id)}/revoke`));
+  }
+
+  function revokeOthers() {
+    act(sessionAction, () => post("/api/account/sessions/revoke-others"));
+  }
+
+  function deleteAccount(ev: SubmitEvent) {
+    ev.preventDefault();
+    if (!confirmed("Delete your account for good? This can't be undone.")) return;
+    act(deleteAction, () => post("/api/account/delete", removal));
+  }
+
+  const supported = passkeysSupported();
+</script>
+
+<Title text="Settings" />
+
+{#if load.error}
+  <Notes error={load.error} />
+{:else if data}
+  <h1>Settings</h1>
+  <Flash />
+  {#if !data.recentAuth}
+    <p class="notice">
+      Changing your password, passkeys, two-factor codes or email asks you to
+      <a href={`/login?${new URLSearchParams({ return: "/settings", reauth: "1" })}`} data-reload>confirm it's you</a> first.
+    </p>
+  {/if}
+
+  <Section title="Profile" description="Shared with the apps you sign in to.">
+    <Notes ok={profileAction.message} error={profileAction.error} />
+    <form class="stack" onsubmit={saveProfile}>
+      <label class="field">
+        <span>Username</span>
+        <input type="text" value={data.username} disabled />
+        <small class="muted">Only an admin can change this.</small>
+      </label>
+      <Field label="Display name" name="name" bind:value={profile.name} autocomplete="name" maxlength={100} />
+      <Field
+        label="Email"
+        name="email"
+        type="email"
+        bind:value={profile.email}
+        autocomplete="email"
+        maxlength={254}
+        hint={data.email ? (data.emailVerified ? "Verified." : "Not verified.") : undefined}
+      />
+      <Field label="Picture URL" name="picture" type="url" bind:value={profile.picture} maxlength={2048} placeholder="https://…" />
+      <div>
+        <button type="submit" disabled={profileAction.busy}><Save class="icon" aria-hidden="true" /> Save profile</button>
+      </div>
+    </form>
+    {#if data.email && !data.emailVerified}
+      <div class="inline-edit">
+        <small class="muted">{data.email} isn't verified yet.</small>
+        <button type="button" class="small" onclick={resendVerification} disabled={profileAction.busy}>
+          Resend verification email
+        </button>
+      </div>
+    {/if}
+  </Section>
+
+  <Section title="Passkeys" description="The quickest and safest way to sign in: your device unlocks with a fingerprint, face or PIN.">
+    <Notes ok={passkeyAction.message} error={passkeyAction.error} />
+    {#if data.passkeys.length === 0}
+      <p class="muted">No passkeys yet.</p>
+    {:else}
+      <ul class="rows">
+        {#each data.passkeys as p (p.id)}
+          <li>
+            <div class="grow">
+              <form class="inline-edit" onsubmit={(ev) => renamePasskey(ev, p.id)}>
+                <input type="text" bind:value={renames[p.id]} maxlength={60} aria-label="Passkey name" required />
+                <button type="submit" class="small" disabled={passkeyAction.busy}>Rename</button>
+              </form>
+              <small class="muted">
+                {p.synced ? "Synced" : "This device only"} · added {date(p.createdAt)} · last used {relative(p.lastUsedAt)}
+              </small>
+            </div>
+            <button type="button" class="danger small" onclick={() => removePasskey(p.id, p.name)} disabled={passkeyAction.busy}>
+              Remove
+            </button>
+          </li>
+        {/each}
+      </ul>
+    {/if}
+    <form class="inline-edit" onsubmit={addPasskey}>
+      <input type="text" bind:value={newPasskeyName} placeholder="Name, e.g. Phone" maxlength={60} aria-label="New passkey name" />
+      <button type="submit" class="primary" disabled={!supported || passkeyAction.busy}>
+        <KeyRound class="icon" aria-hidden="true" />
+        {supported ? "Add a passkey" : "Passkeys aren't supported in this browser"}
+      </button>
+    </form>
+  </Section>
+
+  <Section title="Password">
+    <Notes ok={passwordAction.message} error={passwordAction.error} />
+    <p class="muted">
+      {data.hasPassword
+        ? "You can sign in with a password."
+        : "No password set. Add one as a fallback for devices without your passkeys."}
+    </p>
+    <form class="stack" onsubmit={setPassword}>
+      <input type="text" name="username" value={data.username} autocomplete="username" hidden />
+      <Field
+        label={data.hasPassword ? "New password" : "Password"}
+        name="password"
+        type="password"
+        bind:value={passwords.password}
+        required
+        autocomplete="new-password"
+        maxlength={512}
+        hint={`At least ${PASSWORD_MIN} characters. A long phrase beats a short tricky one.`}
+      />
+      <Field label="Confirm password" name="confirm" type="password" bind:value={passwords.confirm} required autocomplete="new-password" maxlength={512} />
+      <div>
+        <button type="submit" disabled={passwordAction.busy}>{data.hasPassword ? "Change password" : "Set password"}</button>
+      </div>
+    </form>
+    {#if data.hasPassword}
+      <p>
+        <button type="button" class="danger small" onclick={removePassword} disabled={data.passkeys.length === 0 || passwordAction.busy}>
+          Remove password
+        </button>
+        {#if data.passkeys.length === 0}<small class="muted"> Add a passkey first.</small>{/if}
+      </p>
+    {/if}
+  </Section>
+
+  <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."
+  >
+    <Notes ok={totpAction.message} error={totpAction.error} />
+    {#if !data.hasPassword}
+      <p class="muted">Set a password first.</p>
+    {:else if data.totp}
+      <form class="inline-edit" onsubmit={disableTotp}>
+        <span class="badge ok">On</span>
+        <input
+          type="text"
+          bind:value={totpCode}
+          placeholder="Current code"
+          inputmode="numeric"
+          autocomplete="one-time-code"
+          maxlength={7}
+          required
+          aria-label="Current code"
+        />
+        <button type="submit" class="danger" disabled={totpAction.busy}>Turn off</button>
+      </form>
+    {:else}
+      <button type="button" onclick={() => navigate("/settings/totp")}>Set up an authenticator app</button>
+    {/if}
+  </Section>
+
+  <Section title="Sessions" description="Browsers signed in to this server. Apps you've signed in to keep their own sessions.">
+    <Notes ok={sessionAction.message} error={sessionAction.error} />
+    <ul class="rows">
+      {#each data.sessions as s (s.id)}
+        <li>
+          <div class="grow">
+            <strong>{s.device}</strong>
+            {#if s.current}<span class="badge">This browser</span>{/if}
+            <br />
+            <small class="muted">
+              {s.ip ?? "unknown IP"} · via {s.method} · signed in {date(s.createdAt)} · active {relative(s.lastSeenAt)}
+            </small>
+          </div>
+          <button type="button" class="small" onclick={() => revokeSession(s.id)} disabled={sessionAction.busy}>Sign out</button>
+        </li>
+      {/each}
+    </ul>
+    {#if data.sessions.length > 1}
+      <button type="button" class="danger small" onclick={revokeOthers} disabled={sessionAction.busy}>Sign out everywhere else</button>
+    {/if}
+  </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."
+  >
+    <Notes error={deleteAction.error} />
+    <form class="stack" onsubmit={deleteAccount}>
+      <Field label={`Type your username (${data.username}) to confirm`} name="confirm" bind:value={removal.confirm} required autocomplete="off" maxlength={64} />
+      {#if data.hasPassword}
+        <Field label="Password" name="password" type="password" bind:value={removal.password} required autocomplete="current-password" maxlength={512} />
+      {/if}
+      <div>
+        <button type="submit" class="danger" disabled={deleteAction.busy}>Delete my account</button>
+      </div>
+    </form>
+  </Section>
+{/if}
diff --git a/web/src/pages/Setup.svelte b/web/src/pages/Setup.svelte
new file mode 100644
index 0000000..655d5a7
--- /dev/null
+++ b/web/src/pages/Setup.svelte
@@ -0,0 +1,54 @@
+<script lang="ts">
+  import { LogIn, UserPlus } from "@lucide/svelte";
+  import { ApiError, api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { reload } from "../lib/router.svelte";
+  import Card from "../components/Card.svelte";
+  import Field from "../components/Field.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  let status = $state<"open" | "done" | "unconfigured" | null>(null);
+  const values = $state({ token: "", username: "", name: "", email: "" });
+  const form = new Action();
+
+  api<{ state: "open" | "done" | "unconfigured" }>("/api/setup").then((r) => (status = r.state));
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await form.run(async () => {
+      try {
+        reload((await api<{ redirect: string }>("/api/setup", values)).redirect);
+      } catch (err) {
+        if (err instanceof ApiError && err.data.done) status = "done";
+        throw err;
+      }
+    });
+  }
+</script>
+
+{#if status === "done"}
+  <Card title="Setup is done" lead="This server already has accounts.">
+    <p><a class="btn primary" href="/login"><LogIn class="icon" aria-hidden="true" /> Sign in</a></p>
+  </Card>
+{:else if status === "unconfigured"}
+  <Card title="Almost there">
+    <p>
+      Set a <code>SETUP_TOKEN</code> secret (<code>wrangler secret put SETUP_TOKEN</code>, or <code>.dev.vars</code>
+      locally), then reload this page to create the first admin.
+    </p>
+  </Card>
+{:else if status === "open"}
+  <Card title="Create the first admin" lead="This page only works while the server has no accounts. You'll add a passkey or password straight after.">
+    <form class="stack" onsubmit={submit}>
+      <Notes error={form.error} />
+      <Field label="Setup token" name="token" type="password" bind:value={values.token} required autocomplete="off" hint="The SETUP_TOKEN secret." autofocus />
+      <Field label="Username" name="username" bind:value={values.username} required autocomplete="username" maxlength={32} />
+      <Field label="Display name" name="name" bind:value={values.name} autocomplete="name" maxlength={100} />
+      <Field label="Email" name="email" type="email" bind:value={values.email} autocomplete="email" maxlength={254} />
+      <button type="submit" class="primary wide" disabled={form.busy}>
+        <UserPlus class="icon" aria-hidden="true" />
+        Create admin account
+      </button>
+    </form>
+  </Card>
+{/if}
diff --git a/web/src/pages/Terms.svelte b/web/src/pages/Terms.svelte
new file mode 100644
index 0000000..4962aec
--- /dev/null
+++ b/web/src/pages/Terms.svelte
@@ -0,0 +1,69 @@
+<script lang="ts">
+  import { session } from "../lib/session.svelte";
+  import Title from "../components/Title.svelte";
+  import Contact from "./Contact.svelte";
+  import { OPERATOR, UPDATED } from "../lib/legal";
+</script>
+
+<Title text="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 {session.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>
+    {session.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>
+    {session.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 /></p>
+</article>
diff --git a/web/src/pages/TotpSetup.svelte b/web/src/pages/TotpSetup.svelte
new file mode 100644
index 0000000..3b58779
--- /dev/null
+++ b/web/src/pages/TotpSetup.svelte
@@ -0,0 +1,44 @@
+<script lang="ts">
+  import { Shield } from "@lucide/svelte";
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { navigate } from "../lib/router.svelte";
+  import Card from "../components/Card.svelte";
+  import Field from "../components/Field.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  let setup = $state<{ qr: string; secret: string } | null>(null);
+  let code = $state("");
+  const start = new Action();
+  const form = new Action();
+
+  // Each visit makes a fresh secret; it only takes effect once a code from it is confirmed.
+  start.run(async () => (setup = await api("/api/account/totp/start", {})));
+
+  async function confirm(ev: SubmitEvent) {
+    ev.preventDefault();
+    const done = await form.run(() => api("/api/account/totp/confirm", { code }));
+    if (done) navigate("/settings?m=totp-enabled");
+    else code = "";
+  }
+</script>
+
+<Card title="Scan this code" lead="Use any authenticator app (1Password, Aegis, Google Authenticator…), then enter the code it shows.">
+  <Notes error={start.error || form.error} />
+  {#if setup}
+    <img class="qr" src={setup.qr} alt="QR code for your authenticator app" width="220" height="220" />
+    <details>
+      <summary>Can't scan it?</summary>
+      <p>Enter this key instead:</p>
+      <p class="secret"><code>{setup.secret}</code></p>
+    </details>
+    <form class="stack" onsubmit={confirm}>
+      <Field label="Code" name="code" bind:value={code} required inputmode="numeric" autocomplete="one-time-code" maxlength={7} autofocus />
+      <button type="submit" class="primary wide" disabled={form.busy}>
+        <Shield class="icon" aria-hidden="true" />
+        Turn on
+      </button>
+    </form>
+  {/if}
+  <p class="small"><a class="btn wide" href="/settings">Cancel</a></p>
+</Card>
diff --git a/web/src/pages/VerifyEmail.svelte b/web/src/pages/VerifyEmail.svelte
new file mode 100644
index 0000000..a8ede30
--- /dev/null
+++ b/web/src/pages/VerifyEmail.svelte
@@ -0,0 +1,45 @@
+<script lang="ts">
+  import { Check, LogIn } from "@lucide/svelte";
+  import { api } from "../lib/api";
+  import { Action } from "../lib/action.svelte";
+  import { reload } from "../lib/router.svelte";
+  import Card from "../components/Card.svelte";
+  import Notes from "../components/Notes.svelte";
+
+  let { params }: { params: Record<string, string> } = $props();
+  const path = $derived(`/api/verify-email/${encodeURIComponent(params.token ?? "")}`);
+
+  let email = $state<string | null>(null);
+  let done = $state(false);
+  const load = new Action();
+  const verify = new Action();
+  load.run(async () => (email = (await api<{ email: string }>(path)).email));
+
+  // Mail scanners follow GETs, so verifying takes a deliberate click.
+  async function confirm() {
+    await verify.run(async () => {
+      const { signedIn } = await api<{ signedIn: boolean }>(path, {});
+      if (signedIn) reload("/settings?m=email-verified");
+      else done = true;
+    });
+  }
+</script>
+
+{#if done}
+  <Card title="Email verified" lead="Thanks! You can close this tab, or sign in.">
+    <p><a class="btn primary" href="/login"><LogIn class="icon" aria-hidden="true" /> Sign in</a></p>
+  </Card>
+{:else if load.error || verify.error}
+  <Card title="This link can't be used" lead="It has expired, was already used, or a newer one was sent. You can send a new one from your settings.">
+    <Notes error={verify.error && !verify.error.startsWith("This link") ? verify.error : ""} />
+    <p><a class="btn primary" href="/settings">Settings</a></p>
+  </Card>
+{:else if email}
+  <Card title="Verify your email">
+    <p class="muted">Confirm that <strong>{email}</strong> is yours.</p>
+    <button type="button" class="primary wide" onclick={confirm} disabled={verify.busy}>
+      <Check class="icon" aria-hidden="true" />
+      Verify
+    </button>
+  </Card>
+{/if}
diff --git a/web/src/pages/admin/Audit.svelte b/web/src/pages/admin/Audit.svelte
new file mode 100644
index 0000000..7ead7d8
--- /dev/null
+++ b/web/src/pages/admin/Audit.svelte
@@ -0,0 +1,46 @@
+<script lang="ts">
+  import { api } from "../../lib/api";
+  import { Action } from "../../lib/action.svelte";
+  import { date, relative } from "../../lib/format";
+  import AdminTabs from "../../components/AdminTabs.svelte";
+  import Notes from "../../components/Notes.svelte";
+  import Section from "../../components/Section.svelte";
+  import Title from "../../components/Title.svelte";
+
+  interface Entry {
+    id: number;
+    at: number;
+    actor: string | null;
+    action: string;
+    target: string | null;
+    ip: string | null;
+    detail: string | null;
+  }
+
+  let entries = $state<Entry[]>([]);
+  const load = new Action();
+  load.run(async () => (entries = await api<Entry[]>("/api/admin/audit")));
+</script>
+
+<Title text="Audit log" />
+<AdminTabs />
+<Notes error={load.error} />
+
+<Section title="Recent activity" description="The latest 200 events. Kept for 180 days.">
+  <div class="table-wrap">
+    <table class="compact">
+      <thead><tr><th>When</th><th>Who</th><th>What</th><th>Target</th><th>IP</th></tr></thead>
+      <tbody>
+        {#each entries as e (e.id)}
+          <tr>
+            <td title={date(e.at)}>{relative(e.at)}</td>
+            <td>{#if e.actor}@{e.actor}{:else}<span class="muted">—</span>{/if}</td>
+            <td><code>{e.action}</code>{#if e.detail}<small class="muted"> {e.detail}</small>{/if}</td>
+            <td>{e.target ?? ""}</td>
+            <td>{e.ip ?? ""}</td>
+          </tr>
+        {/each}
+      </tbody>
+    </table>
+  </div>
+</Section>
diff --git a/web/src/pages/admin/ClientDetail.svelte b/web/src/pages/admin/ClientDetail.svelte
new file mode 100644
index 0000000..4f539c4
--- /dev/null
+++ b/web/src/pages/admin/ClientDetail.svelte
@@ -0,0 +1,147 @@
+<script lang="ts">
+  import { untrack } from "svelte";
+  import { Save } from "@lucide/svelte";
+  import { api, confirmed } from "../../lib/api";
+  import { Action } from "../../lib/action.svelte";
+  import { navigate } from "../../lib/router.svelte";
+  import AdminTabs from "../../components/AdminTabs.svelte";
+  import ClientFields, { type ClientValues } from "../../components/ClientFields.svelte";
+  import CopyRow from "../../components/CopyRow.svelte";
+  import type { GroupOption } from "../../components/GroupChecks.svelte";
+  import Notes from "../../components/Notes.svelte";
+  import Section from "../../components/Section.svelte";
+  import Title from "../../components/Title.svelte";
+  import { newSecrets, type ClientData } from "./Clients.svelte";
+
+  let { params }: { params: Record<string, string> } = $props();
+  const base = $derived(`/api/admin/clients/${encodeURIComponent(params.id ?? "")}`);
+
+  let client = $state<ClientData | null>(null);
+  let groups = $state<GroupOption[]>([]);
+  let values = $state<ClientValues>({ name: "", homeUrl: "", redirectUris: "", postLogoutRedirectUris: "", allowedGroups: [] });
+  // A secret just created on the previous page (taken, so it's only ever shown
+  // once), or one from rotating it here.
+  let secret = $state<string | null>(
+    untrack(() => {
+      const created = newSecrets.get(params.id ?? "") ?? null;
+      newSecrets.delete(params.id ?? "");
+      return created;
+    }),
+  );
+
+  const load = new Action();
+  const settings = new Action();
+  const secretAction = new Action();
+  const deleteAction = new Action();
+
+  async function refresh() {
+    const [c, g] = await Promise.all([api<ClientData>(base), api<GroupOption[]>("/api/admin/groups")]);
+    client = c;
+    groups = g;
+    values = {
+      name: c.name,
+      homeUrl: c.homeUrl ?? "",
+      redirectUris: c.redirectUris.join("\n"),
+      postLogoutRedirectUris: c.postLogoutRedirectUris.join("\n"),
+      allowedGroups: [...c.allowedGroups],
+    };
+  }
+  load.run(refresh);
+
+  async function save(ev: SubmitEvent) {
+    ev.preventDefault();
+    await settings.run(async () => {
+      const res = await api(base, values);
+      await refresh();
+      return res;
+    });
+  }
+
+  async function rotate() {
+    const message = client!.isPublic
+      ? "Give this app a secret and make it confidential?"
+      : "Replace the secret? The old one stops working immediately.";
+    if (!confirmed(message)) return;
+    await secretAction.run(async () => {
+      secret = (await api<{ secret: string }>(`${base}/secret`, {})).secret;
+      await refresh();
+    });
+  }
+
+  async function makePublic() {
+    if (!confirmed("Remove the secret and make this a public PKCE client?")) return;
+    await secretAction.run(async () => {
+      const res = await api(`${base}/public`, {});
+      secret = null;
+      await refresh();
+      return res;
+    });
+  }
+
+  async function remove() {
+    if (!confirmed(`Delete ${client!.name}? People won't be able to sign in to it.`)) return;
+    const done = await deleteAction.run(() => api(`${base}/delete`, {}));
+    if (done) navigate("/admin/clients?m=client-deleted");
+  }
+</script>
+
+<Title text={client?.name ?? "Application"} />
+<AdminTabs />
+<p><a class="btn small" href="/admin/clients">← All applications</a></p>
+<Notes error={load.error} />
+
+{#if client}
+  <h1>{client.name}</h1>
+
+  {#if secret}
+    <div class="notice ok">
+      <p><strong>Client secret</strong> — copy it into the app's configuration now. It won't be shown again.</p>
+      <CopyRow value={secret} label="Client secret" />
+    </div>
+  {/if}
+
+  <Section title="Connecting the app">
+    <dl class="kv">
+      {#each [
+        ["Issuer", client.issuer],
+        ["Discovery", client.discovery],
+        ["Client id", client.id],
+        ["Token auth", client.isPublic ? "none (PKCE)" : "client_secret_basic or client_secret_post"],
+        ["Scopes", "openid profile email groups (+ offline_access for refresh tokens)"],
+      ] as [k, v] (k)}
+        <dt>{k}</dt>
+        <dd><code>{v}</code></dd>
+      {/each}
+    </dl>
+  </Section>
+
+  <Section title="Settings">
+    <form class="stack" onsubmit={save}>
+      <Notes ok={settings.message} error={settings.error} />
+      <ClientFields bind:values {groups} />
+      <div>
+        <button type="submit" disabled={settings.busy}><Save class="icon" aria-hidden="true" /> Save</button>
+      </div>
+    </form>
+  </Section>
+
+  <Section title="Client secret">
+    <Notes ok={secretAction.message} error={secretAction.error} />
+    <p class="muted">
+      {client.isPublic
+        ? "This is a public client: it has no secret and must use PKCE."
+        : "Rotating the secret breaks the app until it's given the new one."}
+    </p>
+    <div class="buttons">
+      <button type="button" onclick={rotate} disabled={secretAction.busy}>{client.isPublic ? "Create a secret" : "Rotate secret"}</button>
+      {#if !client.isPublic}
+        <button type="button" class="danger" onclick={makePublic} disabled={secretAction.busy}>Make public</button>
+      {/if}
+    </div>
+  </Section>
+
+  <Section title="Delete application" description="Its refresh tokens stop working immediately; issued access tokens are refused by /userinfo.">
+    <Notes error={deleteAction.error} />
+    <button type="button" class="danger" onclick={remove} disabled={deleteAction.busy}>Delete</button>
+  </Section>
+{/if}
diff --git a/web/src/pages/admin/Clients.svelte b/web/src/pages/admin/Clients.svelte
new file mode 100644
index 0000000..958098a
--- /dev/null
+++ b/web/src/pages/admin/Clients.svelte
@@ -0,0 +1,117 @@
+<script lang="ts" module>
+  export interface ClientData {
+    id: string;
+    name: string;
+    homeUrl: string | null;
+    isPublic: boolean;
+    redirectUris: string[];
+    postLogoutRedirectUris: string[];
+    allowedGroups: string[];
+    issuer: string;
+    discovery: string;
+  }
+
+  /** Shown once, on the page the app is opened on after creating it. Never kept beyond this tab. */
+  export const newSecrets = new Map<string, string>();
+</script>
+
+<script lang="ts">
+  import { AppWindow } from "@lucide/svelte";
+  import { api } from "../../lib/api";
+  import { Action } from "../../lib/action.svelte";
+  import { navigate } from "../../lib/router.svelte";
+  import AdminTabs from "../../components/AdminTabs.svelte";
+  import ClientFields, { type ClientValues } from "../../components/ClientFields.svelte";
+  import Field from "../../components/Field.svelte";
+  import Flash from "../../components/Flash.svelte";
+  import type { GroupOption } from "../../components/GroupChecks.svelte";
+  import Notes from "../../components/Notes.svelte";
+  import Section from "../../components/Section.svelte";
+  import Title from "../../components/Title.svelte";
+
+  let clients = $state<ClientData[]>([]);
+  let groups = $state<GroupOption[]>([]);
+  let values = $state<ClientValues>({ name: "", homeUrl: "", redirectUris: "", postLogoutRedirectUris: "", allowedGroups: [] });
+  let type = $state<"confidential" | "public">("confidential");
+  let clientId = $state("");
+  const load = new Action();
+  const create = new Action();
+
+  load.run(async () => {
+    [clients, groups] = await Promise.all([api<ClientData[]>("/api/admin/clients"), api<GroupOption[]>("/api/admin/groups")]);
+  });
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await create.run(async () => {
+      const { id, secret } = await api<{ id: string; secret: string | null }>("/api/admin/clients", { ...values, type, clientId });
+      if (secret) newSecrets.set(id, secret);
+      navigate(`/admin/clients/${encodeURIComponent(id)}`);
+    });
+  }
+</script>
+
+<Title text="Applications" />
+<AdminTabs />
+<Flash />
+<Notes error={load.error} />
+
+<Section title="Applications" description="Each app that signs people in through this server is an OpenID Connect client.">
+  {#if clients.length === 0}
+    <p class="muted">No applications yet.</p>
+  {:else}
+    <div class="table-wrap">
+      <table>
+        <thead><tr><th>Name</th><th>Client id</th><th>Type</th><th>Allowed</th></tr></thead>
+        <tbody>
+          {#each clients as cl (cl.id)}
+            <tr>
+              <td>
+                <a class="btn small" href={`/admin/clients/${encodeURIComponent(cl.id)}`}>{cl.name}</a>
+                {#if !cl.homeUrl}<br /><small class="muted">not on “Your apps”</small>{/if}
+              </td>
+              <td><code>{cl.id}</code></td>
+              <td>{cl.isPublic ? "public (PKCE)" : "confidential"}</td>
+              <td>{#each cl.allowedGroups as g (g)}<span class="badge">{g}</span>{:else}everyone{/each}</td>
+            </tr>
+          {/each}
+        </tbody>
+      </table>
+    </div>
+  {/if}
+</Section>
+
+<Section title="Add an application">
+  <form class="stack" onsubmit={submit}>
+    <Notes error={create.error} />
+    <ClientFields bind:values {groups} />
+    <fieldset>
+      <legend>Type</legend>
+      <label class="check">
+        <input type="radio" value="confidential" bind:group={type} />
+        <span>Confidential <small class="muted">— has a server that can keep a client secret (dough-git, inbox).</small></span>
+      </label>
+      <label class="check">
+        <input type="radio" value="public" bind:group={type} />
+        <span>Public <small class="muted">— runs entirely in the browser or on a device; uses PKCE and no secret.</small></span>
+      </label>
+    </fieldset>
+    <details>
+      <summary>Advanced</summary>
+      <Field
+        label="Client id"
+        name="client_id"
+        bind:value={clientId}
+        maxlength={128}
+        autocomplete="off"
+        hint="Leave blank for a random id. Set it to keep an app's existing client id when moving it over from another provider."
+      />
+    </details>
+    <div>
+      <button type="submit" class="primary" disabled={create.busy}>
+        <AppWindow class="icon" aria-hidden="true" />
+        Create application
+      </button>
+    </div>
+  </form>
+</Section>
diff --git a/web/src/pages/admin/Groups.svelte b/web/src/pages/admin/Groups.svelte
new file mode 100644
index 0000000..73e3e25
--- /dev/null
+++ b/web/src/pages/admin/Groups.svelte
@@ -0,0 +1,94 @@
+<script lang="ts">
+  import { Save, Users } from "@lucide/svelte";
+  import { api, confirmed } from "../../lib/api";
+  import { Action } from "../../lib/action.svelte";
+  import { plural } from "../../lib/format";
+  import AdminTabs from "../../components/AdminTabs.svelte";
+  import Field from "../../components/Field.svelte";
+  import Notes from "../../components/Notes.svelte";
+  import Section from "../../components/Section.svelte";
+  import Title from "../../components/Title.svelte";
+
+  const ADMIN_GROUP = "auth-admin";
+
+  interface Group {
+    name: string;
+    description: string;
+    members: number;
+  }
+
+  let groups = $state<Group[]>([]);
+  let descriptions = $state<Record<string, string>>({});
+  const values = $state({ name: "", description: "" });
+  const load = new Action();
+  const list = new Action();
+  const create = new Action();
+
+  async function refresh() {
+    groups = await api<Group[]>("/api/admin/groups");
+    descriptions = Object.fromEntries(groups.map((g) => [g.name, g.description]));
+  }
+  load.run(refresh);
+
+  async function act(section: Action, path: string, body: object = {}) {
+    await section.run(async () => {
+      const res = await api(path, body);
+      await refresh();
+      return res;
+    });
+  }
+
+  function save(ev: SubmitEvent, name: string) {
+    ev.preventDefault();
+    act(list, `/api/admin/groups/${encodeURIComponent(name)}`, { description: descriptions[name] });
+  }
+
+  function remove(name: string) {
+    if (confirmed(`Delete the group "${name}"? Members lose it immediately.`)) {
+      act(list, `/api/admin/groups/${encodeURIComponent(name)}/delete`);
+    }
+  }
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await act(create, "/api/admin/groups", values);
+    if (!create.error) Object.assign(values, { name: "", description: "" });
+  }
+</script>
+
+<Title text="Groups" />
+<AdminTabs />
+<Notes error={load.error} />
+
+<Section title="Groups" description="Apps receive group names in the `groups` claim. Name them after what they allow, e.g. system-owner or inbox-admin.">
+  <Notes ok={list.message} error={list.error} />
+  <ul class="rows">
+    {#each groups as g (g.name)}
+      <li>
+        <div class="grow">
+          <strong>{g.name}</strong> <small class="muted">{plural(g.members, "member")}</small>
+          <form class="inline-edit" onsubmit={(ev) => save(ev, g.name)}>
+            <input type="text" bind:value={descriptions[g.name]} maxlength={200} placeholder="Description" aria-label={`Description of ${g.name}`} />
+            <button type="submit" class="small" disabled={list.busy}><Save class="icon" aria-hidden="true" /> Save</button>
+          </form>
+        </div>
+        {#if g.name !== ADMIN_GROUP}
+          <button type="button" class="danger small" onclick={() => remove(g.name)} disabled={list.busy}>Delete</button>
+        {/if}
+      </li>
+    {/each}
+  </ul>
+</Section>
+
+<Section title="New group">
+  <form class="stack" onsubmit={submit}>
+    <Notes ok={create.message} error={create.error} />
+    <div class="grid2">
+      <Field label="Name" name="name" bind:value={values.name} required maxlength={64} autocomplete="off" />
+      <Field label="Description" name="description" bind:value={values.description} maxlength={200} autocomplete="off" />
+    </div>
+    <div>
+      <button type="submit" class="primary" disabled={create.busy}><Users class="icon" aria-hidden="true" /> Create group</button>
+    </div>
+  </form>
+</Section>
diff --git a/web/src/pages/admin/Keys.svelte b/web/src/pages/admin/Keys.svelte
new file mode 100644
index 0000000..12e7c45
--- /dev/null
+++ b/web/src/pages/admin/Keys.svelte
@@ -0,0 +1,45 @@
+<script lang="ts">
+  import { api, confirmed } from "../../lib/api";
+  import { Action } from "../../lib/action.svelte";
+  import { date } from "../../lib/format";
+  import AdminTabs from "../../components/AdminTabs.svelte";
+  import Notes from "../../components/Notes.svelte";
+  import Section from "../../components/Section.svelte";
+  import Title from "../../components/Title.svelte";
+
+  let keys = $state<{ kid: string; alg: string; createdAt: number; retiredAt: number | null }[]>([]);
+  const load = new Action();
+  const rotate = new Action();
+
+  const refresh = async () => void (keys = await api("/api/admin/keys"));
+  load.run(refresh);
+
+  async function rotateNow() {
+    if (!confirmed("Rotate the signing key?")) return;
+    await rotate.run(async () => {
+      const res = await api("/api/admin/keys/rotate", {});
+      await refresh();
+      return res;
+    });
+  }
+</script>
+
+<Title text="Signing keys" />
+<AdminTabs />
+<Notes error={load.error} />
+
+<Section title="Signing keys" description="Tokens are signed with the newest active key. Apps pick up new keys from the JWKS automatically. A key is created on first use.">
+  <Notes ok={rotate.message} error={rotate.error} />
+  <ul class="rows">
+    {#each keys as k (k.kid)}
+      <li>
+        <div class="grow">
+          <code>{k.kid}</code> <span class={`badge ${k.retiredAt ? "" : "ok"}`}>{k.retiredAt ? "retired" : "active"}</span>
+          <br />
+          <small class="muted">{k.alg} · created {date(k.createdAt)}{k.retiredAt ? ` · retired ${date(k.retiredAt)}` : ""}</small>
+        </div>
+      </li>
+    {/each}
+  </ul>
+  <button type="button" onclick={rotateNow} disabled={rotate.busy}>Rotate now</button>
+</Section>
diff --git a/web/src/pages/admin/Reserved.svelte b/web/src/pages/admin/Reserved.svelte
new file mode 100644
index 0000000..5af77d8
--- /dev/null
+++ b/web/src/pages/admin/Reserved.svelte
@@ -0,0 +1,78 @@
+<script lang="ts">
+  import { Save } from "@lucide/svelte";
+  import { api, confirmed } from "../../lib/api";
+  import { Action } from "../../lib/action.svelte";
+  import AdminTabs from "../../components/AdminTabs.svelte";
+  import Field from "../../components/Field.svelte";
+  import Notes from "../../components/Notes.svelte";
+  import Section from "../../components/Section.svelte";
+  import Title from "../../components/Title.svelte";
+
+  let reserved = $state<{ username: string; note: string }[]>([]);
+  let builtin = $state<string[]>([]);
+  const values = $state({ username: "", note: "" });
+  const load = new Action();
+  const list = new Action();
+  const create = new Action();
+
+  async function refresh() {
+    ({ reserved, builtin } = await api<{ reserved: { username: string; note: string }[]; builtin: string[] }>("/api/admin/reserved"));
+  }
+  load.run(refresh);
+
+  async function act(section: Action, path: string, body: object = {}) {
+    await section.run(async () => {
+      const res = await api(path, body);
+      await refresh();
+      return res;
+    });
+  }
+
+  function release(name: string) {
+    if (confirmed(`Release "${name}"? Anyone can then sign up with it.`)) {
+      act(list, `/api/admin/reserved/${encodeURIComponent(name)}/delete`);
+    }
+  }
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await act(create, "/api/admin/reserved", values);
+    if (!create.error) Object.assign(values, { username: "", note: "" });
+  }
+</script>
+
+<Title text="Reserved names" />
+<AdminTabs />
+<Notes error={load.error} />
+
+<Section
+  title="Reserved names"
+  description="Nobody can sign up with these, or with anything that reads the same: dots, dashes and underscores are ignored, and look-alikes such as 0 for o or 1 for l are folded, so reserving noreply also blocks no-reply and n0reply. Admins can still create accounts with them."
+>
+  <Notes ok={list.message} error={list.error} />
+  <ul class="rows">
+    {#each reserved as r (r.username)}
+      <li>
+        <div class="grow"><strong>{r.username}</strong> {#if r.note}<small class="muted">{r.note}</small>{/if}</div>
+        <button type="button" class="danger small" onclick={() => release(r.username)} disabled={list.busy}>Release</button>
+      </li>
+    {/each}
+  </ul>
+</Section>
+
+<Section title="Reserve a name">
+  <form class="stack" onsubmit={submit}>
+    <Notes ok={create.message} error={create.error} />
+    <div class="grid2">
+      <Field label="Username" name="username" bind:value={values.username} required maxlength={32} autocomplete="off" />
+      <Field label="Note" name="note" bind:value={values.note} maxlength={200} autocomplete="off" hint="Why, or who it's held for." />
+    </div>
+    <div>
+      <button type="submit" class="primary" disabled={create.busy}><Save class="icon" aria-hidden="true" /> Reserve</button>
+    </div>
+  </form>
+</Section>
+
+<Section title="Always reserved" description="Built into the code (src/data/reserved.ts).">
+  <p class="muted small">{builtin.join(", ")}</p>
+</Section>
diff --git a/web/src/pages/admin/UserDetail.svelte b/web/src/pages/admin/UserDetail.svelte
new file mode 100644
index 0000000..42c1db9
--- /dev/null
+++ b/web/src/pages/admin/UserDetail.svelte
@@ -0,0 +1,277 @@
+<script lang="ts">
+  import { Link, Save } from "@lucide/svelte";
+  import { api, confirmed } from "../../lib/api";
+  import { Action } from "../../lib/action.svelte";
+  import { date, plural, relative } from "../../lib/format";
+  import { navigate, reload } from "../../lib/router.svelte";
+  import AdminTabs from "../../components/AdminTabs.svelte";
+  import CopyRow from "../../components/CopyRow.svelte";
+  import Field from "../../components/Field.svelte";
+  import Flash from "../../components/Flash.svelte";
+  import GroupChecks, { type GroupOption } from "../../components/GroupChecks.svelte";
+  import Notes from "../../components/Notes.svelte";
+  import Section from "../../components/Section.svelte";
+  import Title from "../../components/Title.svelte";
+
+  interface UserData {
+    id: string;
+    username: string;
+    name: string | null;
+    email: string | null;
+    emailVerified: boolean;
+    picture: string | null;
+    disabled: boolean;
+    createdAt: number;
+    lastLoginAt: number | null;
+    hasPassword: boolean;
+    totp: boolean;
+    groups: string[];
+    passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];
+    sessionCount: number;
+    openLinkExpiresAt: number | null;
+    self: boolean;
+  }
+
+  let { params }: { params: Record<string, string> } = $props();
+  const base = $derived(`/api/admin/users/${encodeURIComponent(params.id ?? "")}`);
+
+  let user = $state<UserData | null>(null);
+  let allGroups = $state<GroupOption[]>([]);
+  const profile = $state({ username: "", name: "", email: "", picture: "", emailVerified: false });
+  let groups = $state<string[]>([]);
+  let ttl = $state("3600");
+  let link = $state<{ url: string; expiresAt: number } | null>(null);
+  let deleteConfirm = $state("");
+
+  const load = new Action();
+  const profileAction = new Action();
+  const groupsAction = new Action();
+  const linkAction = new Action();
+  const methodsAction = new Action();
+  const accessAction = new Action();
+  const deleteAction = new Action();
+
+  async function refresh() {
+    const [u, g] = await Promise.all([api<UserData>(base), api<GroupOption[]>("/api/admin/groups")]);
+    user = u;
+    allGroups = g;
+    Object.assign(profile, {
+      username: u.username,
+      name: u.name ?? "",
+      email: u.email ?? "",
+      picture: u.picture ?? "",
+      emailVerified: u.emailVerified,
+    });
+    groups = [...u.groups];
+  }
+  load.run(refresh);
+
+  /** Posts to `base + path`; on success shows the message and reloads this user. */
+  async function act(section: Action, path: string, body: object = {}) {
+    await section.run(async () => {
+      const res = await api<{ message?: string; redirect?: string }>(base + path, body);
+      if (res.redirect) return reload(res.redirect);
+      await refresh();
+      return res;
+    });
+  }
+
+  function saveProfile(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(profileAction, "/profile", profile);
+  }
+
+  function saveGroups(ev: SubmitEvent) {
+    ev.preventDefault();
+    act(groupsAction, "/groups", { groups });
+  }
+
+  async function createLink(ev: SubmitEvent) {
+    ev.preventDefault();
+    await linkAction.run(async () => {
+      link = await api(base + "/link", { ttl: Number(ttl) });
+      await refresh();
+    });
+  }
+
+  function confirmThen(message: string, section: Action, path: string) {
+    if (confirmed(message)) act(section, path);
+  }
+
+  async function remove(ev: SubmitEvent) {
+    ev.preventDefault();
+    const done = await deleteAction.run(() => api(base + "/delete", { confirm: deleteConfirm }));
+    if (done) navigate("/admin/users?m=user-deleted");
+  }
+</script>
+
+<Title text={user ? `@${user.username}` : "User"} />
+<AdminTabs />
+<p><a class="btn small" href="/admin/users">← All users</a></p>
+<Flash />
+<Notes error={load.error} />
+
+{#if user}
+  <h1>
+    {user.name ?? user.username} <small class="muted">@{user.username}</small>
+    {#if user.disabled}<span class="badge danger">disabled</span>{/if}
+  </h1>
+  <p class="muted">
+    Subject <code>{user.id}</code> · created {date(user.createdAt)} · last sign-in {relative(user.lastLoginAt)}
+  </p>
+
+  <Section title="Profile">
+    <Notes ok={profileAction.message} error={profileAction.error} />
+    <form class="stack" onsubmit={saveProfile}>
+      <div class="grid2">
+        <Field label="Username" name="username" bind:value={profile.username} required maxlength={32} autocomplete="off" hint="Apps may use this as a mailbox or URL; changing it can break things there." />
+        <Field label="Display name" name="name" bind:value={profile.name} maxlength={100} autocomplete="off" />
+        <Field label="Email" name="email" type="email" bind:value={profile.email} maxlength={254} autocomplete="off" />
+        <Field label="Picture URL" name="picture" type="url" bind:value={profile.picture} maxlength={2048} autocomplete="off" />
+        <label class="check">
+          <input type="checkbox" bind:checked={profile.emailVerified} />
+          <span>Email is verified</span>
+        </label>
+      </div>
+      <div>
+        <button type="submit" disabled={profileAction.busy}><Save class="icon" aria-hidden="true" /> Save profile</button>
+      </div>
+    </form>
+  </Section>
+
+  <Section title="Groups" description="Sent to apps in the `groups` claim, and used to limit who can open each application.">
+    <Notes ok={groupsAction.message} error={groupsAction.error} />
+    <form class="stack" onsubmit={saveGroups}>
+      <GroupChecks groups={allGroups} bind:selected={groups} />
+      <div>
+        <button type="submit" disabled={groupsAction.busy}><Save class="icon" aria-hidden="true" /> Save groups</button>
+      </div>
+    </form>
+  </Section>
+
+  <Section title="Sign-in link" description="A one-time link that signs this person in so they can add a passkey or password. Use it for new accounts and lost devices.">
+    <Notes ok={linkAction.message} error={linkAction.error} />
+    {#if link}
+      <div class="notice ok">
+        <p>
+          <strong>Sign-in link</strong> — send this to @{user.username}. It works once and expires {relative(link.expiresAt)}.
+          It won't be shown again.
+        </p>
+        <CopyRow value={link.url} label="Sign-in link" />
+      </div>
+    {/if}
+    {#if user.openLinkExpiresAt}
+      <div class="inline-edit">
+        <span>An unused link expires {relative(user.openLinkExpiresAt)}.</span>
+        <button type="button" class="small" onclick={() => { link = null; act(linkAction, "/link/revoke"); }} disabled={linkAction.busy}>
+          Revoke it
+        </button>
+      </div>
+    {/if}
+    <form class="inline-edit" onsubmit={createLink}>
+      <label>
+        Valid for
+        <select bind:value={ttl}>
+          <option value="900">15 minutes</option>
+          <option value="3600">1 hour</option>
+          <option value="86400">1 day</option>
+          <option value="604800">7 days</option>
+        </select>
+      </label>
+      <button type="submit" class="primary" disabled={linkAction.busy}>
+        <Link class="icon" aria-hidden="true" />
+        {user.openLinkExpiresAt ? "Replace link" : "Create link"}
+      </button>
+    </form>
+  </Section>
+
+  <Section title="Sign-in methods">
+    <Notes ok={methodsAction.message} error={methodsAction.error} />
+    <ul class="rows">
+      {#each user.passkeys as p (p.id)}
+        <li>
+          <div class="grow">
+            <strong>Passkey: {p.name}</strong>
+            <br />
+            <small class="muted">added {date(p.createdAt)} · last used {relative(p.lastUsedAt)}</small>
+          </div>
+          <button
+            type="button"
+            class="danger small"
+            disabled={methodsAction.busy}
+            onclick={() => confirmThen(`Remove the passkey "${p.name}"?`, methodsAction, `/passkeys/${encodeURIComponent(p.id)}/delete`)}
+          >
+            Remove
+          </button>
+        </li>
+      {/each}
+      {#if user.hasPassword}
+        <li>
+          <div class="grow"><strong>Password</strong></div>
+          <button
+            type="button"
+            class="danger small"
+            disabled={methodsAction.busy}
+            onclick={() => confirmThen("Remove this password (and any two-factor setup)?", methodsAction, "/password/remove")}
+          >
+            Remove
+          </button>
+        </li>
+      {/if}
+      {#if user.totp}
+        <li>
+          <div class="grow"><strong>Two-factor codes</strong></div>
+          <button
+            type="button"
+            class="danger small"
+            disabled={methodsAction.busy}
+            onclick={() => confirmThen("Turn off two-factor codes for this account?", methodsAction, "/totp/reset")}
+          >
+            Turn off
+          </button>
+        </li>
+      {/if}
+      {#if !user.passkeys.length && !user.hasPassword}
+        <li class="muted">None. Send a sign-in link so they can add one.</li>
+      {/if}
+    </ul>
+  </Section>
+
+  <Section title="Access">
+    <Notes ok={accessAction.message} error={accessAction.error} />
+    <p class="muted">{plural(user.sessionCount, "active browser session")} on this server.</p>
+    <div class="buttons">
+      <button
+        type="button"
+        disabled={accessAction.busy}
+        onclick={() => confirmThen("Sign this account out of every browser and application?", accessAction, "/signout")}
+      >
+        Sign out everywhere
+      </button>
+      {#if !user.self}
+        {#if user.disabled}
+          <button type="button" disabled={accessAction.busy} onclick={() => act(accessAction, "/enable")}>Enable account</button>
+        {:else}
+          <button
+            type="button"
+            class="danger"
+            disabled={accessAction.busy}
+            onclick={() => confirmThen("Disable this account? They'll be signed out everywhere.", accessAction, "/disable")}
+          >
+            Disable account
+          </button>
+        {/if}
+      {/if}
+    </div>
+  </Section>
+
+  {#if !user.self}
+    <Section title="Delete account" description="Permanent. Apps keep whatever they stored about this person; a new account will get a new subject id.">
+      <Notes error={deleteAction.error} />
+      <form class="inline-edit" onsubmit={remove}>
+        <input type="text" bind:value={deleteConfirm} placeholder={`Type ${user.username} to confirm`} required autocomplete="off" aria-label="Confirm username" />
+        <button type="submit" class="danger" disabled={deleteAction.busy}>Delete</button>
+      </form>
+    </Section>
+  {/if}
+{/if}
diff --git a/web/src/pages/admin/Users.svelte b/web/src/pages/admin/Users.svelte
new file mode 100644
index 0000000..26f1e5c
--- /dev/null
+++ b/web/src/pages/admin/Users.svelte
@@ -0,0 +1,117 @@
+<script lang="ts">
+  import { UserPlus } from "@lucide/svelte";
+  import { api } from "../../lib/api";
+  import { Action } from "../../lib/action.svelte";
+  import { relative } from "../../lib/format";
+  import { navigate } from "../../lib/router.svelte";
+  import AdminTabs from "../../components/AdminTabs.svelte";
+  import Field from "../../components/Field.svelte";
+  import Flash from "../../components/Flash.svelte";
+  import GroupChecks, { type GroupOption } from "../../components/GroupChecks.svelte";
+  import Notes from "../../components/Notes.svelte";
+  import Section from "../../components/Section.svelte";
+  import Title from "../../components/Title.svelte";
+
+  interface UserRow {
+    id: string;
+    username: string;
+    name: string | null;
+    disabled: boolean;
+    groups: string[];
+    passkeys: number;
+    hasPassword: boolean;
+    totp: boolean;
+    lastLoginAt: number | null;
+  }
+
+  let users = $state<UserRow[]>([]);
+  let groups = $state<GroupOption[]>([]);
+  const fresh = () => ({ username: "", name: "", email: "", emailVerified: false, subject: "", groups: [] as string[] });
+  let values = $state(fresh());
+  const load = new Action();
+  const create = new Action();
+
+  load.run(async () => {
+    [users, groups] = await Promise.all([api<UserRow[]>("/api/admin/users"), api<GroupOption[]>("/api/admin/groups")]);
+  });
+
+  async function submit(ev: SubmitEvent) {
+    ev.preventDefault();
+    await create.run(async () => {
+      const { id } = await api<{ id: string }>("/api/admin/users", values);
+      navigate(`/admin/users/${encodeURIComponent(id)}?m=user-created`);
+    });
+  }
+</script>
+
+<Title text="Users" />
+<AdminTabs />
+<Flash />
+<Notes error={load.error} />
+
+<Section title={`Users (${users.length})`}>
+  <div class="table-wrap">
+    <table>
+      <thead>
+        <tr><th>User</th><th>Groups</th><th>Sign-in methods</th><th>Last sign-in</th></tr>
+      </thead>
+      <tbody>
+        {#each users as u (u.id)}
+          <tr>
+            <td>
+              <a class="btn small" href={`/admin/users/${encodeURIComponent(u.id)}`}>{u.name ?? u.username}</a>
+              <br />
+              <small class="muted">@{u.username}</small>
+              {#if u.disabled}<span class="badge danger">disabled</span>{/if}
+            </td>
+            <td>
+              {#each u.groups as g (g)}<span class="badge">{g}</span>{:else}<span class="muted">—</span>{/each}
+            </td>
+            <td>
+              {#if u.passkeys > 0}<span class="badge">{u.passkeys} passkey{u.passkeys === 1 ? "" : "s"}</span>{/if}
+              {#if u.hasPassword}<span class="badge">password{u.totp ? " + 2FA" : ""}</span>{/if}
+              {#if !u.passkeys && !u.hasPassword}<span class="muted">none</span>{/if}
+            </td>
+            <td>{relative(u.lastLoginAt)}</td>
+          </tr>
+        {/each}
+      </tbody>
+    </table>
+  </div>
+</Section>
+
+<Section title="Add a user" description="They'll need a sign-in link from their page to set up a passkey or password.">
+  <form class="stack" onsubmit={submit}>
+    <Notes error={create.error} />
+    <div class="grid2">
+      <Field label="Username" name="username" bind:value={values.username} required maxlength={32} autocomplete="off" />
+      <Field label="Display name" name="name" bind:value={values.name} maxlength={100} autocomplete="off" />
+      <Field label="Email" name="email" type="email" bind:value={values.email} maxlength={254} autocomplete="off" />
+      <label class="check">
+        <input type="checkbox" bind:checked={values.emailVerified} />
+        <span>Email is verified</span>
+      </label>
+    </div>
+    <fieldset>
+      <legend>Groups</legend>
+      <GroupChecks {groups} bind:selected={values.groups} />
+    </fieldset>
+    <details>
+      <summary>Advanced</summary>
+      <Field
+        label="Subject id"
+        name="subject"
+        bind:value={values.subject}
+        maxlength={64}
+        autocomplete="off"
+        hint="The permanent `sub` apps see. Leave blank for a random UUID. Set it to carry an account over from another identity provider without apps treating it as a new person."
+      />
+    </details>
+    <div>
+      <button type="submit" class="primary" disabled={create.busy}>
+        <UserPlus class="icon" aria-hidden="true" />
+        Add user
+      </button>
+    </div>
+  </form>
+</Section>
diff --git a/web/tsconfig.json b/web/tsconfig.json
new file mode 100644
index 0000000..42e8ec2
--- /dev/null
+++ b/web/tsconfig.json
@@ -0,0 +1,17 @@
+{
+  "compilerOptions": {
+    "target": "ES2022",
+    "lib": ["ES2022", "DOM", "DOM.Iterable"],
+    "module": "ESNext",
+    "moduleResolution": "bundler",
+    "moduleDetection": "force",
+    "types": ["svelte", "vite/client"],
+    "verbatimModuleSyntax": true,
+    "isolatedModules": true,
+    "noEmit": true,
+    "strict": true,
+    "skipLibCheck": true,
+    "noUncheckedIndexedAccess": true
+  },
+  "include": ["src/**/*.ts", "src/**/*.svelte"]
+}
diff --git a/wrangler.jsonc b/wrangler.jsonc
index 60c0b01..1abab35 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -2,7 +2,6 @@
 	"$schema": "node_modules/wrangler/config-schema.json",
 	"name": "auth-server",
 	"main": "src/main.ts",
-	"tsconfig": "tsconfig.build.json",
 	"compatibility_date": "2026-09-01",
 	"compatibility_flags": [
 		"nodejs_compat"
@@ -13,16 +12,19 @@
 			"invocation_logs": true
 		}
 	},
-	// Stylesheet + browser script. Served straight from the edge; public/_headers
-	// gives them the same hardening headers the worker adds to its own responses.
-	"assets": {
-		"directory": "./public"
+	// The Svelte app (web/), built by Vite into dist/ before every dev/deploy.
+	"build": {
+		"command": "bun run build",
+		"watch_dir": "web"
 	},
-	// pixelarticons/react components call React's createElement; this repo
-	// renders with hono/jsx instead, which ships a React-API-compatible
-	// createElement, so the icons work without pulling in real React.
-	"alias": {
-		"react": "hono/jsx"
+	// The worker runs first for every request, so pages get the same host check
+	// and security headers as the API, then hands non-API paths to the assets.
+	// Unknown paths get index.html: the app's router shows the page (or a 404).
+	"assets": {
+		"directory": "./dist",
+		"binding": "ASSETS",
+		"run_worker_first": true,
+		"not_found_handling": "single-page-application"
 	},
 	"d1_databases": [
 		{