Dough Git

commit

Remove the plural system API

commit
3ce40877d9c3e13b2e9d64840e8ab672bf550dab
author
Clove Twilight <[email protected]>
date
2026-11-14 23:38
It now lives on the system site (doughmination.co.uk/api). Deletes the
plural routes, services, models, SSO and bot-token code, the /v2/plural
forward and every plural mention in the docs and pages. The Hub
entrypoint keeps broadcast() for live updates on /v2/ws, and guestbook
moderation checks admin tokens against the site.

Co-Authored-By: Sandrone <[email protected]>

diff --git a/README.md b/README.md
index 123454e..12a7bb1 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
 # Doughmination API
 
-A combined Discord **presence** (Lanyard-style) and **profile/badges** (dstn.to-style) API on a **single Cloudflare Worker + Durable Objects**, powered by **one Discord bot**. It also carries the Doughmination plural-system API (fronting, members, mental state, devices, guestbook), Minecraft lookups, and merged git contribution heatmaps. Everything returns one unified JSON envelope, and all live updates go over a single WebSocket.
+A combined Discord **presence** (Lanyard-style) and **profile/badges** (dstn.to-style) API on a **single Cloudflare Worker + Durable Objects**, powered by **one Discord bot**. It also carries devices, a guestbook, visit counters, Minecraft lookups, and merged git contribution heatmaps. Everything returns one unified JSON envelope, and all live updates go over a single WebSocket.
 
 - **Live:** https://doughmination.uk · **Docs:** [`/docs`](https://doughmination.uk/docs) · **Abuse & contact:** [`/abuse`](https://doughmination.uk/abuse)
 - **Stack:** Cloudflare Workers, Durable Objects, KV, Hono, Zod, TypeScript, Bun
diff --git a/src/abuse.ts b/src/abuse.ts
index 075fd90..7ea7d78 100644
--- a/src/abuse.ts
+++ b/src/abuse.ts
@@ -76,7 +76,7 @@ export const ABUSE_HTML = `<!doctype html>
 </div>
 
 <h2>What this service is</h2>
-<p>This API serves live Discord presence and public profile data for a small set of tracked users, Minecraft skin lookups, a public guestbook, and the Doughmination plural-system API. It only tracks Discord users who share a server with its bot.</p>
+<p>This API serves live Discord presence and public profile data for a small set of tracked users, Minecraft skin lookups, and a public guestbook. It only tracks Discord users who share a server with its bot.</p>
 
 <h2>Reporting abuse</h2>
 <p>Email <a href="mailto:${ABUSE_CONTACT}">${ABUSE_CONTACT}</a> if you see this service being used for, or serving, any of the following:</p>
diff --git a/src/apidata.ts b/src/apidata.ts
index 313ef7d..19805df 100644
--- a/src/apidata.ts
+++ b/src/apidata.ts
@@ -34,11 +34,9 @@ export const GROUPS: GroupDef[] = [
     id: "auth-overview", name: "Authentication", blurb: "How protected endpoints are secured.",
     endpoints: [
       { m: "GET", path: "Bearer JWT", auth: "jwt",
-        desc: "Most /plural write endpoints need a login token. Get one from POST /plural/login, then send it as 'Authorization: Bearer <token>'. Tokens last 24 hours. Some routes additionally require an admin, owner, or pet role." },
+        desc: "Guestbook moderation accepts a signed-in admin's token from the system site (doughmination.co.uk), sent as 'Authorization: Bearer <token>'." },
       { m: "GET", path: "X-Battery-Key", auth: "key",
         desc: "Reporting or deleting device state (POST/DELETE /devices) needs your device key, sent as the 'X-Battery-Key' header." },
-      { m: "GET", path: "Bot token", auth: "bot",
-        desc: "The /plural/bot/* endpoints are for the companion Discord bot: they need both a 'User-Agent: CloveShortcuts/<version>' header and the bot's token as 'Authorization: Bearer <token>'." },
     ],
   },
   {
@@ -84,137 +82,10 @@ export const GROUPS: GroupDef[] = [
     ],
   },
   {
-    id: "plural-auth", name: "Plural — accounts & auth", blurb: "Login, signup, password reset, and the current user.",
-    endpoints: [
-      { m: "POST", path: "/plural/login", auth: "public",
-        desc: "Log in with your username and password (plus a Turnstile captcha token). Returns an access token to use on protected endpoints.",
-        example: 'POST body: { "username": "admin", "password": "…", "turnstile_token": "…" }  →  { "access_token": "…", "token_type": "bearer", "success": true }' },
-      { m: "POST", path: "/plural/signup", auth: "public",
-        desc: "Create a non-admin account. Body { username, password (≥10 chars), email, display_name?, turnstile_token }. Email is required and unique. The account starts UNCONFIRMED: login is refused until the emailed link is used, and unconfirmed accounts are deleted after 24 hours. The response includes a short-lived correction_token — hold onto it, it's the only way to fix a mistyped address without a password.",
-        example: 'POST body: { "username": "clove", "password": "…", "email": "[email protected]", "turnstile_token": "…" }  →  { "success": true, "email_sent": true, "correction_token": "…", "user": { … } }' },
-      { m: "POST", path: "/plural/verify-email", auth: "public",
-        desc: "Confirm an address using the token from the email. Body { token }. Single use, valid 24 hours. Also applies a pending email change." },
-      { m: "POST", path: "/plural/resend-verification", auth: "public",
-        desc: "Send the confirmation link again. Body { turnstile_token } plus either { correction_token } or { username, password }. Rate limited to one per IP per minute." },
-      { m: "POST", path: "/plural/correct-email", auth: "public",
-        desc: "Fix a mistyped address before confirmation, without a password. Body { correction_token, email, turnstile_token }. The correction token is issued only to the client that signed up, lasts 2 hours, and stops working once the account is confirmed — it is what stops anyone repointing an unconfirmed account at their own inbox." },
-      { m: "GET", path: "/plural/users/check-username?username=", auth: "public",
-        desc: "Check username availability. Returns { username, exists, available }." },
-      { m: "GET", path: "/plural/users/check-email?email=", auth: "public",
-        desc: "Check email availability. Returns { email, exists, available }. Rate limited to 20 lookups per IP per minute." },
-      { m: "POST", path: "/plural/forgot-password", auth: "public",
-        desc: "Request a password-reset link by USERNAME. Body { username, turnstile_token }. The link is emailed to the address on file for that account; the response reports a masked hint so the user knows which inbox to check. Returns 404 for an unknown username and 409 if the account has no email on file. Rate limited to one request per IP per minute.",
-        example: 'POST body: { "username": "clove", "turnstile_token": "…" }  →  { "success": true, "message": "Reset link sent. The link expires in 15 minutes.", "sent_to": "a•••@d•••.win" }' },
-      { m: "POST", path: "/plural/forgot-username", auth: "public",
-        desc: "Recover a forgotten username by EMAIL. Body { email, turnstile_token }. The username is emailed to that address rather than returned, so knowing an address isn't enough to learn the username on it. Returns 404 if the address isn't registered. Rate limited to one request per IP per minute.",
-        example: 'POST body: { "email": "[email protected]", "turnstile_token": "…" }  →  { "success": true, "message": "We\'ve sent your username to that address.", "sent_to": "y•••@e•••.com" }' },
-      { m: "GET", path: "/plural/reset-password/check?token=", auth: "public",
-        desc: "Check whether a reset token is still usable before rendering the form. Returns { valid }." },
-      { m: "POST", path: "/plural/reset-password", auth: "public",
-        desc: "Set a new password using a token from the reset email. Body { token, new_password (≥10 chars), turnstile_token }. Tokens last 15 minutes, are single-use, and requesting a new one revokes the previous.",
-        example: 'POST body: { "token": "…", "new_password": "…", "turnstile_token": "…" }  →  { "success": true, "message": "Your password has been reset. …" }' },
-      { m: "GET", path: "/plural/user_info", auth: "auth",
-        desc: "The current authenticated user (no password hash)." },
-      { m: "GET", path: "/plural/auth/is_admin", auth: "auth", desc: "{ isAdmin } for the current user." },
-      { m: "GET", path: "/plural/auth/is_owner", auth: "auth", desc: "{ isOwner } for the current user." },
-      { m: "GET", path: "/plural/auth/is_pet", auth: "auth", desc: "{ isPet } for the current user." },
-    ],
-  },
-  {
-    id: "plural-system", name: "Plural — system & mental state", blurb: "PluralKit system info and the tracked mental state.",
-    endpoints: [
-      { m: "GET", path: "/plural/system", auth: "public",
-        desc: "PluralKit system info (name, description, tag) with the current mental_state attached." },
-      { m: "GET", path: "/plural/mental-state", auth: "public",
-        desc: "Current mental state: { level, updated_at, notes }." },
-      { m: "POST", path: "/plural/mental-state", auth: "admin",
-        desc: "Update mental state. Body { level, notes? }. Broadcasts a mental_state_update over /ws." },
-    ],
-  },
-  {
-    id: "plural-members", name: "Plural — members & tags", blurb: "System members, their tags and custom status.",
-    endpoints: [
-      { m: "GET", path: "/plural/members", auth: "public",
-        desc: "All members enriched with tags and custom status." },
-      { m: "GET", path: "/plural/member/:member_id", auth: "public",
-        desc: "One member by id OR name (case-insensitive), enriched with tags + status.",
-        params: [["member_id", "PluralKit member id or name."]] },
-      { m: "GET", path: "/plural/member-tags", auth: "admin", desc: "The full member → tags map." },
-      { m: "POST", path: "/plural/member-tags/:member_identifier", auth: "admin",
-        desc: "Replace a member's tag list. Body: string[] (JSON array of tags)." },
-      { m: "POST", path: "/plural/member-tags/:member_identifier/add", auth: "admin",
-        desc: "Add one tag. Body { tag }." },
-      { m: "DELETE", path: "/plural/member-tags/:member_identifier/:tag", auth: "admin",
-        desc: "Remove one tag from a member." },
-      { m: "GET", path: "/plural/members/:member_identifier/status", auth: "public",
-        desc: "A member's custom status ({ text, emoji, updated_at }) or null." },
-      { m: "POST", path: "/plural/members/:member_identifier/status", auth: "admin",
-        desc: "Set/update a member's status. Body { text (≤100 chars), emoji? }." },
-      { m: "DELETE", path: "/plural/members/:member_identifier/status", auth: "admin",
-        desc: "Clear a member's status." },
-    ],
-  },
-  {
-    id: "plural-fronting", name: "Plural — fronting", blurb: "Who is fronting, and switching.",
-    endpoints: [
-      { m: "GET", path: "/plural/fronters", auth: "public",
-        desc: "Current fronters, enriched with tags + status. { members: [...] }." },
-      { m: "POST", path: "/plural/switch", auth: "auth",
-        desc: "Set the front to a list. Body { members: string[] }. Broadcasts fronters_update." },
-      { m: "POST", path: "/plural/switch_front", auth: "auth",
-        desc: "Switch to a single fronter. Body { member_id }." },
-      { m: "POST", path: "/plural/multi_switch", auth: "auth",
-        desc: "Switch to several fronters with detailed feedback. Body { member_ids: string[] }." },
-    ],
-  },
-  {
-    id: "plural-users", name: "Plural — user management", blurb: "Admin CRUD over accounts.",
-    endpoints: [
-      { m: "GET", path: "/plural/users", auth: "admin", desc: "List all users (no password hashes)." },
-      { m: "POST", path: "/plural/users", auth: "admin",
-        desc: "Create a user. Body { username, password, email?, display_name?, is_admin?, is_pet? }. Accounts created here are pre-confirmed — the address is being assigned deliberately — so they can log in immediately and are never touched by the unconfirmed-account sweep." },
-      { m: "PUT", path: "/plural/users/:user_id", auth: "auth",
-        desc: "Update a user (admin, or the user themselves). Body may include display_name, current_password + new_password, avatar_url (an EXTERNAL image URL — uploads were removed), is_admin, is_pet, email. EMAIL RULES: a user may change their own address but must supply current_password, and the new address is held in pending_email until confirmed (the old one keeps working, and gets an alert). The owner may set anyone's address outright. A plain admin may NOT change someone else's." },
-      { m: "DELETE", path: "/plural/users/:user_id", auth: "admin",
-        desc: "Delete a user. Cannot delete yourself or the owner." },
-    ],
-  },
-  {
-    id: "plural-metrics", name: "Plural — metrics", blurb: "Fronting analytics.",
-    endpoints: [
-      { m: "GET", path: "/plural/metrics/fronting-time?days=30", auth: "public",
-        desc: "Per-member fronting time across 24h/48h/5d/7d/30d windows and totals." },
-      { m: "GET", path: "/plural/metrics/switch-frequency?days=30", auth: "public",
-        desc: "Switch counts per window and average switches/day." },
-    ],
-  },
-  {
-    id: "plural-realtime", name: "Plural — realtime & admin", blurb: "The unified WebSocket + broadcast controls.",
+    id: "realtime", name: "Realtime", blurb: "One WebSocket for every live update.",
     endpoints: [
       { m: "WS", path: "/ws", auth: "public",
         desc: "The single realtime socket for ALL live updates. On connect you get a connection_established message. Fronting (fronters_update), mental state (mental_state_update), device/battery (device_update) and force_refresh events are pushed to every client automatically. For live Discord presence, send a subscribe frame — either { \"type\": \"subscribe\", \"all\": true } or { \"type\": \"subscribe\", \"ids\": [\"<user id>\", …] }; you'll get an init_state snapshot immediately and presence_update events thereafter (only for the users you subscribed to). Every message is a { type, data } object. Send 'ping' to get 'pong'." },
-      { m: "POST", path: "/plural/admin/refresh", auth: "admin",
-        desc: "Broadcast a force_refresh to every connected /ws client." },
-    ],
-  },
-  {
-    id: "plural-bot", name: "Plural — bot API", blurb: "For the Discord bot (User-Agent + bot token).",
-    endpoints: [
-      { m: "GET", path: "/plural/bot/health", auth: "bot", desc: "Liveness check." },
-      { m: "GET", path: "/plural/bot/system/info", auth: "bot", desc: "System info wrapped as { success, data }." },
-      { m: "GET", path: "/plural/bot/members", auth: "bot", desc: "Members with tags + status." },
-      { m: "GET", path: "/plural/bot/fronters", auth: "bot", desc: "Current fronters." },
-      { m: "POST", path: "/plural/bot/switch", auth: "bot",
-        desc: "Switch fronters with validation. Body { member_ids: string[] }." },
-      { m: "POST", path: "/plural/bot/token/regenerate", auth: "owner",
-        desc: "No longer available — returns 410. The bot token is now set manually by the server operator." },
-    ],
-  },
-  {
-    id: "plural-seo", name: "Plural — SEO", blurb: "Data-driven crawler files.",
-    endpoints: [
-      { m: "GET", path: "/plural/robots.txt", auth: "public", desc: "robots.txt." },
-      { m: "GET", path: "/plural/sitemap.xml", auth: "public", desc: "Sitemap generated from the member list." },
     ],
   },
   {
diff --git a/src/docs.ts b/src/docs.ts
index 3dc13f4..a712d05 100644
--- a/src/docs.ts
+++ b/src/docs.ts
@@ -23,11 +23,11 @@ export const DOCS_HTML = `<!doctype html>
 <meta property="og:type" content="website" />
 <meta property="og:site_name" content="Doughmination API" />
 <meta property="og:title" content="Doughmination API reference" />
-<meta property="og:description" content="Endpoint reference for the Doughmination API — Discord presence, profiles, plural system and Genshin roster." />
+<meta property="og:description" content="Endpoint reference for the Doughmination API — Discord presence, profiles and Genshin roster." />
 <meta property="og:image" content="https://m.doughmination.gay/img/avatars/favicon.png" />
 <meta name="twitter:card" content="summary" />
 <meta name="twitter:title" content="Doughmination API reference" />
-<meta name="twitter:description" content="Endpoint reference for the Doughmination API — Discord presence, profiles, plural system and Genshin roster." />
+<meta name="twitter:description" content="Endpoint reference for the Doughmination API — Discord presence, profiles and Genshin roster." />
 <meta name="twitter:image" content="https://m.doughmination.gay/img/avatars/favicon.png" />
 <meta name="theme-color" content="#f5a9b8" />
 <style>
@@ -220,7 +220,7 @@ export const DOCS_HTML = `<!doctype html>
 <header>
   <div class="header-text">
     <h1>Doughmination API reference</h1>
-    <p>Universal API: live Discord presence, Discord profiles, Minecraft skins & capes, Genshin roster tracking, the plural system, and misc services. Base URL: <code>https://doughmination.uk/v2</code> · <a class="self" href="/openapi.json">OpenAPI spec</a> · <a class="self" href="/abuse">Abuse</a> · <a class="self" href="/terms">Terms</a> · <a class="self" href="/privacy">Privacy</a></p>
+    <p>Universal API: live Discord presence, Discord profiles, Minecraft skins & capes, Genshin roster tracking, and misc services. Base URL: <code>https://doughmination.uk/v2</code> · <a class="self" href="/openapi.json">OpenAPI spec</a> · <a class="self" href="/abuse">Abuse</a> · <a class="self" href="/terms">Terms</a> · <a class="self" href="/privacy">Privacy</a></p>
     <p class="disclaimer">Not affiliated with, endorsed by, or associated with Mojang/Microsoft.</p>
   </div>
   <button id="navToggle" class="nav-toggle" type="button" aria-expanded="false" aria-controls="nav">
diff --git a/src/index.ts b/src/index.ts
index 2dfafbb..18c6e85 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -7,7 +7,6 @@
  *   /v2/discord/*     — Discord users (profile + badges + presence + equipped
  *                       collectibles, one merged record), guilds, girls, status
  *                       (the old /v2/lanyard/* presence routes now live here)
- *   /v2/plural/*      — Doughmination system API   (SystemState DO)
  *   /v2/devices/*     — device state (battery, etc.) (SystemState DO)
  *   /v2/guestbook/*   — public guestbook            (SystemState DO)
  *   /v2/counter/*     — per-site visit counters    (SystemState DO)
@@ -18,7 +17,7 @@
  * Two Durable Objects:
  *   GATEWAY  — singleton holding the Discord gateway socket (presence). Relays
  *              presence updates to SYSTEM for fan-out; no browser sockets.
- *   SYSTEM   — singleton running the Doughmination API + the single /v2/ws hub.
+ *   SYSTEM   — singleton running devices, guestbook, counters + the single /v2/ws hub.
  * ===================================================================== */
 
 import type {
@@ -53,7 +52,7 @@ import { DOCS_HTML } from "./docs";
 import { ABUSE_HTML, ABUSE_CONTACT, securityTxt } from "./abuse";
 import { LANDING_HTML, TERMS_HTML, PRIVACY_HTML, NOT_FOUND_HTML } from "./pages";
 import { OPENAPI_JSON } from "./openapi";
-import { SystemState, BROADCAST_PATH, EXPORT_PATH } from "./system/do";
+import { SystemState, BROADCAST_PATH } from "./system/do";
 import { WorkerEntrypoint } from "cloudflare:workers";
 
 export { GatewayManager, SystemState };
@@ -70,13 +69,6 @@ export class Hub extends WorkerEntrypoint<Env> {
       body: JSON.stringify(data),
     });
   }
-
-  /** The old SystemState store, every key, for the site's one-time import. */
-  async exportLegacy(): Promise<Record<string, unknown>> {
-    const res = await systemStub(this.env).fetch(`https://do${EXPORT_PATH}`);
-    if (!res.ok) throw new Error(`Legacy export failed: ${res.status}`);
-    return (await res.json()) as Record<string, unknown>;
-  }
 }
 
 const CORS = {
@@ -163,8 +155,6 @@ const ID_RE = /^\d{16,21}$/;
 function isSystemPath(path: string): boolean {
   return (
     path === "/v2/ws" ||
-    path === "/v2/plural" ||
-    path.startsWith("/v2/plural/") ||
     path === "/v2/devices" ||
     path.startsWith("/v2/devices/") ||
     path === "/v2/guestbook" ||
@@ -207,7 +197,7 @@ export default {
 
     const path = url.pathname.replace(/\/+$/, "") || "/";
 
-    // ---- SystemState DO (plural / devices / counter / realtime) ----------
+    // ---- SystemState DO (devices / guestbook / counter / realtime) -------
     // Forwarded first, and untouched, so its Hono CORS + the single realtime
     // WebSocket upgrade (/v2/ws) work end-to-end.
     if (isSystemPath(path)) {
@@ -309,7 +299,7 @@ export default {
         success: true,
         data: {
           service: "Doughmination API",
-          description: "Universal API: live Discord presence + profiles + plural system + Genshin roster tracking.",
+          description: "Universal API: live Discord presence + profiles + Genshin roster tracking.",
           licence: "DASL-1.0",
           repository_url: "https://github.com/doughmination/api",
           docs: "/docs",
diff --git a/src/openapi.ts b/src/openapi.ts
index dcb67d2..9ba51dd 100644
--- a/src/openapi.ts
+++ b/src/openapi.ts
@@ -157,7 +157,7 @@ function buildSpec(): JsonObj {
       title: "Doughmination API",
       version: "2.0.0",
       description:
-        "Combined Discord presence + profile/badges API, Minecraft lookups, git contribution heatmaps, and the Doughmination plural-system API — one Cloudflare Worker.\n\n" +
+        "Combined Discord presence + profile/badges API, Minecraft lookups, git contribution heatmaps, devices, guestbook and counters — one Cloudflare Worker.\n\n" +
         "All JSON responses share one envelope: `{ success, data }` or `{ success: false, error: { code, message } }`.\n\n" +
         "**Realtime:** live updates (presence, fronting, mental state, devices) are pushed over a single WebSocket at `wss://doughmination.uk/v2/ws` — see /docs for the frame protocol. WebSocket endpoints are not listed as paths below.\n\n" +
         "**Terms:** be reasonable with request volume or your IP gets blocked — https://doughmination.uk/terms",
@@ -173,7 +173,7 @@ function buildSpec(): JsonObj {
           type: "http",
           scheme: "bearer",
           description:
-            "JWT from POST /v2/plural/login (24h expiry) for user endpoints; the operator-set bot token (plus a 'User-Agent: CloveShortcuts/<version>' header) for /v2/plural/bot/* endpoints. Some routes additionally require an admin, owner, or pet role.",
+            "A signed-in admin's token from the system site (doughmination.co.uk), for guestbook moderation.",
         },
         batteryKey: {
           type: "apiKey",
diff --git a/src/pages.ts b/src/pages.ts
index 875c032..17cdc67 100644
--- a/src/pages.ts
+++ b/src/pages.ts
@@ -12,7 +12,7 @@ const FOOTER_LINKS = `<a href="/docs">API reference</a> · <a href="/abuse">Abus
 const AVATAR = "https://m.doughmination.gay/img/avatars/favicon.png";
 
 const DEFAULT_OG_DESCRIPTION =
-  "Universal API: live Discord presence, profiles, plural system and Genshin roster tracking.";
+  "Universal API: live Discord presence, profiles and Genshin roster tracking.";
 
 /**
  * Wraps page content in the shared document shell. `body` is trusted HTML.
@@ -100,10 +100,10 @@ ${body}
 
 export const LANDING_HTML = pageShell(
   "Doughmination API",
-  `Universal API — live Discord presence, profiles, plural system and Genshin roster. <a href="/docs">API reference →</a>`,
+  `Universal API — live Discord presence, profiles and Genshin roster. <a href="/docs">API reference →</a>`,
   `
 <div class="card">
-  <strong>Doughmination API</strong> — a universal API for live Discord presence, profiles, the plural system, and Genshin roster tracking.
+  <strong>Doughmination API</strong> — a universal API for live Discord presence, profiles, and Genshin roster tracking.
 </div>
 
 <h2>Start here</h2>
@@ -133,7 +133,7 @@ export const TERMS_HTML = pageShell(
   <li>The public endpoints are free for personal and non-commercial projects. No API key, no signup.</li>
   <li><strong>Be reasonable with requests.</strong> Use the batch endpoints (100 users per call), respect the cache TTLs instead of polling with <code>?fresh</code>, and use the WebSocket (<code>/v2/ws</code>) for live data instead of tight polling loops. Unreasonable traffic — floods, scraping loops, cache-bust spam — gets the source IP blocked at the edge, usually without warning.</li>
   <li>Don't use this API to harass, stalk, or surveil anyone. That's an immediate permanent block and, where relevant, a report to the platform involved.</li>
-  <li>Authenticated endpoints (the plural-system API, devices, admin routes) are for authorised users only. Don't probe them.</li>
+  <li>Authenticated endpoints (devices, admin routes) are for authorised users only. Don't probe them.</li>
 </ul>
 
 <h2>No guarantees</h2>
@@ -165,7 +165,7 @@ export const PRIVACY_HTML = pageShell(
   <li><strong>Guestbook entries.</strong> Name, message, and optional website are public by design. The submitting IP is used transiently for rate limiting (one post per 60 seconds) and spam protection (Cloudflare Turnstile).</li>
   <li><strong>Discord presence & profiles.</strong> The API tracks live presence only for users who share a Discord server with its bot. Presence is held in memory only and never written to storage. Profile data (avatar, badges, connections) is fetched live from Discord on each request and not stored.</li>
   <li><strong>Minecraft data.</strong> Public data fetched from Mojang on request, cached for about 5 minutes. The vanilla-cape catalogue keeps cape textures (not player identities) permanently.</li>
-  <li><strong>Accounts & devices.</strong> Plural-system accounts (username, password hash, display name) and device/battery reports are stored for the people who use them — these are private to the system's own users.</li>
+  <li><strong>Devices.</strong> Device/battery reports are stored for the people who use them — these are private to their owners.</li>
 </ul>
 
 <h2>What's NOT collected</h2>
diff --git a/src/system/app.ts b/src/system/app.ts
index 5bbda79..49686f3 100644
--- a/src/system/app.ts
+++ b/src/system/app.ts
@@ -5,14 +5,12 @@
  */
 
 /**
- * The Doughmination system API as a single Hono app, run inside the
+ * Devices, guestbook and counters as a single Hono app, run inside the
  * SystemState Durable Object. Route groups:
  *
- *   /v2/plural/*        — auth, system, members, fronting, users, metrics,
- *                         admin, member status, bot, SEO (robots/sitemap)
- *   /v2/devices/*       — device state (battery, etc.)  (misc)
- *   /v2/guestbook/*     — public guestbook (post/list/delete)  (misc)
- *   /v2/counter/*       — per-site visit counters (misc)
+ *   /v2/devices/*       — device state (battery, etc.)
+ *   /v2/guestbook/*     — public guestbook (post/list/delete)
+ *   /v2/counter/*       — per-site visit counters
  *
  * The single realtime socket /v2/ws is handled by the DO before the request
  * ever reaches this app (see do.ts).
@@ -24,51 +22,11 @@ import { cors } from "hono/cors";
 import type { Env } from "./hono";
 import { HttpError } from "./errors";
 import { corsOrigins, isLocalhostOrigin } from "./config";
-import { initializeAdminUser } from "./services/users";
 
-import { authRoutes } from "./routes/auth";
-import { systemRoutes } from "./routes/system";
-import { membersRoutes } from "./routes/members";
-import { relationshipsRoutes } from "./routes/relationships";
-import { frontingRoutes } from "./routes/fronting";
-import { usersRoutes } from "./routes/users";
-import { metricsRoutes } from "./routes/metrics";
-import { adminRoutes } from "./routes/admin";
-import { memberStatusRoutes } from "./routes/member_status";
-import { botRoutes } from "./routes/bot";
-import { staticRoutes } from "./routes/static";
 import { deviceRoutes } from "./routes/devices";
 import { guestbookRoutes } from "./routes/guestbook";
 import { counterRoutes } from "./routes/counter";
 
-// One-time owner seed per DO lifetime (there is no startup phase on a Worker).
-let seeded = false;
-async function ensureSeeded(): Promise<void> {
-  if (seeded) return;
-  seeded = true;
-  try {
-    await initializeAdminUser();
-  } catch (err) {
-    seeded = false;
-    console.error(`Admin seed failed: ${String(err)}`);
-  }
-}
-
-// ---- /v2/plural sub-app ----------------------------------------------------
-
-const pluralApp = new Hono<Env>();
-pluralApp.route("/", authRoutes);
-pluralApp.route("/", systemRoutes);
-pluralApp.route("/", membersRoutes);
-pluralApp.route("/", relationshipsRoutes);
-pluralApp.route("/", frontingRoutes);
-pluralApp.route("/", usersRoutes);
-pluralApp.route("/", metricsRoutes);
-pluralApp.route("/", adminRoutes);
-pluralApp.route("/", memberStatusRoutes);
-pluralApp.route("/", botRoutes);
-pluralApp.route("/", staticRoutes);
-
 // ---- Top-level app ---------------------------------------------------------
 
 export const systemApp = new Hono<Env>();
@@ -89,11 +47,6 @@ systemApp.use(
   }),
 );
 
-systemApp.use("*", async (_c, next) => {
-  await ensureSeeded();
-  await next();
-});
-
 systemApp.onError((err, c) => {
   if (err instanceof HttpError) {
     if (err.headers) {
@@ -105,7 +58,6 @@ systemApp.onError((err, c) => {
   return c.json({ detail: "Internal server error" }, 500);
 });
 
-systemApp.route("/v2/plural", pluralApp);
 systemApp.route("/v2/devices", deviceRoutes);
 systemApp.route("/v2/guestbook", guestbookRoutes);
 systemApp.route("/v2/counter", counterRoutes);
diff --git a/src/system/cache.ts b/src/system/cache.ts
deleted file mode 100644
index 130ad6d..0000000
--- a/src/system/cache.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Simple in-memory cache, unchanged from the old backend. It lives in the
- * SystemState DO isolate, so it survives between requests for as long as the
- * DO stays warm and is reset (harmlessly) if the DO is evicted.
- */
-
-interface CacheEntry {
-  value: unknown;
-  expireAt: number;
-}
-
-const cache = new Map<string, CacheEntry>();
-
-export function getFromCache<T = unknown>(key: string): T | undefined {
-  const entry = cache.get(key);
-  if (entry) {
-    if (Date.now() < entry.expireAt) {
-      return entry.value as T;
-    }
-    cache.delete(key);
-  }
-  return undefined;
-}
-
-export function setInCache(key: string, value: unknown, ttlSeconds = 30): void {
-  cache.set(key, { value, expireAt: Date.now() + ttlSeconds * 1000 });
-}
-
-export function clearCache(key?: string): void {
-  if (key) {
-    cache.delete(key);
-  } else {
-    cache.clear();
-  }
-}
diff --git a/src/system/config.ts b/src/system/config.ts
index 43b9a11..c16d6e3 100644
--- a/src/system/config.ts
+++ b/src/system/config.ts
@@ -5,7 +5,7 @@
  */
 
 /**
- * Configuration for the Doughmination system API.
+ * Configuration for the devices / guestbook / counter API.
  *
  * Unlike the old backend (module-level constants read from process.env at
  * import time), these are functions that read `rt().env` lazily. That's
@@ -15,118 +15,11 @@
 
 import { rt } from "./runtime";
 
-// PluralKit
-export const PLURALKIT_BASE_URL = "https://api.pluralkit.me/v2";
-export const JWT_ALGORITHM = "HS256" as const;
-export const ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24; // 24 hours
-
-export function systemToken(): string | undefined {
-  return rt().env.SYSTEM_TOKEN;
-}
-
-export function pluralkitHeaders(): Record<string, string> {
-  const token = systemToken();
-  return {
-    "User-Agent": "doughmination-api/2.0 (+https://doughmination.uk)",
-    ...(token ? { Authorization: token } : {}),
-  };
-}
-
-export function cacheTtl(): number {
-  return Number(rt().env.CACHE_TTL ?? 30);
-}
-
-export function jwtSecret(): string {
-  return rt().env.JWT_SECRET ?? "your-secret-key-for-jwt";
-}
-
 export function turnstileSecret(): string | undefined {
   const env = rt().env;
   return env.TURNSTILE_SECRET ?? env.TURNSILE_SECRET;
 }
 
-export function adminUsername(): string {
-  return rt().env.ADMIN_USERNAME ?? "admin";
-}
-
-export function adminDisplayName(): string {
-  return rt().env.ADMIN_DISPLAY_NAME ?? "Administrator";
-}
-
-// ---------------------------------------------------------------------------
-// Doughmination SSO (OpenID Connect) — the ONLY login method.
-//
-// The API is a confidential OIDC client: it runs the Authorization Code +
-// PKCE flow against the SSO (auth-server), then mints its own JWT (see
-// security.ts) so every existing `requireAuth` route keeps working. Each JWT
-// is tied to an SSO session that is re-checked every few minutes, so accounts
-// disabled on the SSO stop working here too (see services/sso_sessions.ts).
-// ---------------------------------------------------------------------------
-
-/** SSO issuer origin, e.g. https://auth.doughmination.gay. No trailing slash.
- *  `${issuer}/.well-known/openid-configuration` must resolve. */
-export function ssoIssuer(): string {
-  return (rt().env.SSO_ISSUER ?? "").replace(/\/+$/, "");
-}
-
-/** OIDC client id of this API's application on the SSO. */
-export function ssoClientId(): string | undefined {
-  return rt().env.SSO_CLIENT_ID;
-}
-
-/** OIDC client secret. Set via `wrangler secret put SSO_CLIENT_SECRET`. */
-export function ssoClientSecret(): string | undefined {
-  return rt().env.SSO_CLIENT_SECRET;
-}
-
-/** The redirect URI registered on the SSO. Must point back at the API's
- *  callback route. Defaults to `${baseUrl}/v2/plural/auth/sso/callback`. */
-export function ssoRedirectUri(): string {
-  const configured = rt().env.SSO_REDIRECT_URI;
-  if (configured) return configured;
-  return `${baseUrl()}/v2/plural/auth/sso/callback`;
-}
-
-/** Space-separated OIDC scopes. `openid` is mandatory; `profile` gives
- *  preferred_username + name, `email` the address, and `offline_access` the
- *  refresh token sessions are re-checked with. */
-export function ssoScopes(): string {
-  return rt().env.SSO_SCOPES ?? "openid profile email offline_access";
-}
-
-/** Where the callback sends the browser once a JWT has been minted. The token
- *  is appended in the URL fragment (`#token=…`) so it never hits a server log.
- *  Defaults to the frontend's login landing page. */
-export function ssoPostLoginUrl(): string {
-  const configured = rt().env.SSO_POST_LOGIN_URL;
-  if (configured) return configured.replace(/\/+$/, "");
-  return `${frontendUrl()}/user/login/callback`;
-}
-
-/** Where the browser is sent when login fails or is cancelled. */
-export function ssoLoginErrorUrl(): string {
-  return `${frontendUrl()}/user/login`;
-}
-
-/** Where the SSO returns the browser after signing out. Must be registered as
- *  a post-logout redirect URI on the SSO application. */
-export function ssoPostLogoutRedirectUri(): string {
-  const configured = rt().env.SSO_POST_LOGOUT_REDIRECT_URI;
-  if (configured) return configured;
-  return `${frontendUrl()}/`;
-}
-
-/** How long an in-flight authorization request (state + PKCE verifier) stays
- *  valid between /login and /callback. */
-export const OIDC_STATE_TTL_MINUTES = 10;
-
-/** Owner's email. Backfilled onto the owner account on read, so an owner
- *  created before emails existed still gets one without a manual edit. */
-export function adminEmail(): string | undefined {
-  const value = rt().env.ADMIN_EMAIL?.trim().toLowerCase();
-  return value || undefined;
-}
-
 export function baseUrl(): string {
   return (rt().env.BASE_URL ?? "https://doughmination.uk").replace(/\/+$/, "");
 }
diff --git a/src/system/datetime.ts b/src/system/datetime.ts
deleted file mode 100644
index f9a8c43..0000000
--- a/src/system/datetime.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/** Parse an ISO-8601 timestamp, tolerating excess fractional-second digits
- *  and missing offsets (naive input is treated as UTC). Ported verbatim. */
-
-const TIMESTAMP_PATTERN = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d+)?([+-]\d{2}:\d{2})?$/;
-
-export function parseTimestamp(timestampStr: string): Date {
-  let s = timestampStr;
-  const hadExplicitTz = /[zZ]$|[+-]\d{2}:\d{2}$/.test(s);
-
-  if (s.endsWith("Z") || s.endsWith("z")) {
-    s = `${s.slice(0, -1)}+00:00`;
-  }
-
-  const match = s.match(TIMESTAMP_PATTERN);
-  if (match) {
-    const [, base, frac, tz] = match;
-    const fracPart = frac ? frac.slice(0, 4) : "";
-    s = `${base}${fracPart}${tz ?? ""}`;
-  }
-
-  const dt = new Date(s);
-  if (Number.isNaN(dt.getTime())) {
-    throw new Error(`Could not parse timestamp: ${timestampStr}`);
-  }
-
-  if (!hadExplicitTz) {
-    return new Date(
-      Date.UTC(
-        dt.getFullYear(),
-        dt.getMonth(),
-        dt.getDate(),
-        dt.getHours(),
-        dt.getMinutes(),
-        dt.getSeconds(),
-        dt.getMilliseconds(),
-      ),
-    );
-  }
-  return dt;
-}
diff --git a/src/system/do.ts b/src/system/do.ts
index 1078611..406c6c8 100644
--- a/src/system/do.ts
+++ b/src/system/do.ts
@@ -5,10 +5,10 @@
  */
 
 /**
- * SystemState — the Durable Object that IS the old backend "process".
+ * SystemState — the Durable Object behind devices, guestbook and counters.
  *
- *  - Holds all persistent state (users, tags, statuses, battery, mental
- *    state) in DO key-value storage via a small Store adapter.
+ *  - Holds their state (battery levels, guestbook entries) in DO key-value
+ *    storage via a small Store adapter.
  *  - Owns the visit-counter SQLite tables (DO embedded SQLite).
  *  - Is the SINGLE realtime WebSocket hub for the whole API, at /v2/ws,
  *    using the hibernatable WebSocket API so idle sockets don't keep the DO
@@ -53,9 +53,8 @@ class DoStore implements Store {
 const WS_PATH = "/v2/ws";
 /** Internal DO-to-DO path GatewayManager relays presence updates to. */
 const PRESENCE_RELAY_PATH = "/internal/presence";
-/** Internal paths the Hub entrypoint (index.ts) calls for the system site. */
+/** Internal path the Hub entrypoint (index.ts) calls for the system site. */
 export const BROADCAST_PATH = "/internal/broadcast";
-export const EXPORT_PATH = "/internal/export";
 
 /** Per-socket presence subscription, persisted on the hibernatable socket via
  *  serializeAttachment so it survives eviction. Presence events are filtered
@@ -111,12 +110,6 @@ export class SystemState implements DurableObject {
       return new Response(null, { status: 204 });
     }
 
-    // Every stored key, for the system site's one-time import
-    if (url.pathname === EXPORT_PATH && req.method === "GET") {
-      const entries = await this.state.storage.list();
-      return Response.json(Object.fromEntries(entries));
-    }
-
     return systemApp.fetch(req, {} as never);
   }
 
diff --git a/src/system/hono.ts b/src/system/hono.ts
index 523739b..497f66a 100644
--- a/src/system/hono.ts
+++ b/src/system/hono.ts
@@ -5,12 +5,6 @@
  */
 
 import type { Hono } from "hono";
-import type { User } from "./models";
 
-/** Variables carried on the Hono context (set by auth middleware). */
-export type Variables = {
-  user?: User;
-};
-
-export type Env = { Variables: Variables };
+export type Env = Record<string, never>;
 export type App = Hono<Env>;
diff --git a/src/system/html.ts b/src/system/html.ts
deleted file mode 100644
index 87eeef1..0000000
--- a/src/system/html.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-const HEX_PATTERN = /^[0-9a-fA-F]{6}$/;
-
-export function escapeHtml(text: string): string {
-  if (!text) return "";
-  return text
-    .replace(/&/g, "&amp;")
-    .replace(/</g, "&lt;")
-    .replace(/>/g, "&gt;")
-    .replace(/"/g, "&quot;")
-    .replace(/'/g, "&#x27;");
-}
-
-export function normalizeHex(color: string | null | undefined, defaultColor = "#FF69B4"): string {
-  if (typeof color !== "string" || !color) return defaultColor;
-  const c = color.replace(/^#+/, "");
-  if (HEX_PATTERN.test(c)) return `#${c.toUpperCase()}`;
-  return defaultColor;
-}
diff --git a/src/system/middleware/auth.ts b/src/system/middleware/auth.ts
index 0468788..4a7330e 100644
--- a/src/system/middleware/auth.ts
+++ b/src/system/middleware/auth.ts
@@ -5,116 +5,18 @@
  */
 
 /**
- * Auth middleware, ported from the Express dependencies. On success the
- * resolved user is attached with `c.set("user", user)` (the Hono analogue
- * of `req.user`). Failures throw HttpError, translated by app.onError.
+ * Key and admin checks for devices, guestbook and counters. Failures throw
+ * HttpError, translated by app.onError.
+ *
+ * Site accounts live on the system site (doughmination.co.uk) now, so a
+ * bearer token is checked by asking it, over the SITE service binding.
  */
 
 import type { Context, Next } from "hono";
 import type { Env } from "../hono";
-import { decodeAccessToken } from "../security";
 import { HttpError } from "../errors";
-import { getUserByUsername } from "../services/users";
-import { currentSsoSession } from "../services/sso_sessions";
-import { verifyBotToken, verifyBatteryKey, verifyGuestbookKey } from "../services/keys";
-import type { User } from "../models";
-
-function extractBearer(c: Context<Env>): string | undefined {
-  const header = c.req.header("Authorization");
-  if (!header) return undefined;
-  const parts = header.split(" ");
-  if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") return undefined;
-  return parts[1];
-}
-
-async function resolveCurrentUser(c: Context<Env>): Promise<User> {
-  const token = extractBearer(c);
-  if (!token) {
-    throw new HttpError(401, "Not authenticated", { "WWW-Authenticate": "Bearer" });
-  }
-
-  const payload = await decodeAccessToken(token);
-  const username = payload.sub;
-  if (!username || typeof username !== "string") {
-    throw new HttpError(401, "Invalid token", { "WWW-Authenticate": "Bearer" });
-  }
-
-  // Every token belongs to an SSO-backed session: logging out, the session
-  // expiring, or the SSO no longer vouching for the account all end it here.
-  // Tokens from before sessions existed carry no sid and must sign in again.
-  const session = typeof payload.sid === "string" ? await currentSsoSession(payload.sid) : null;
-  if (!session || session.username.toLowerCase() !== username.toLowerCase()) {
-    throw new HttpError(401, "Session ended. Please sign in again.", { "WWW-Authenticate": "Bearer" });
-  }
-
-  const user = await getUserByUsername(username);
-  if (!user) {
-    throw new HttpError(401, "User not found", { "WWW-Authenticate": "Bearer" });
-  }
-  return user;
-}
-
-/** Require an authenticated user. */
-export async function requireAuth(c: Context<Env>, next: Next): Promise<void> {
-  c.set("user", await resolveCurrentUser(c));
-  await next();
-}
-
-/** Attach user if authenticated, otherwise leave undefined. Never rejects. */
-export async function optionalAuth(c: Context<Env>, next: Next): Promise<void> {
-  try {
-    c.set("user", await resolveCurrentUser(c));
-  } catch {
-    // ignore
-  }
-  await next();
-}
-
-export async function requireAdmin(c: Context<Env>, next: Next): Promise<void> {
-  const user = c.get("user") as User | undefined;
-  if (!user?.is_admin) throw new HttpError(403, "Admin privileges required");
-  await next();
-}
-
-export async function requireOwner(c: Context<Env>, next: Next): Promise<void> {
-  const user = c.get("user") as User | undefined;
-  if (!user?.is_owner) throw new HttpError(403, "Owner privileges required");
-  await next();
-}
-
-export async function requirePet(c: Context<Env>, next: Next): Promise<void> {
-  const user = c.get("user") as User | undefined;
-  if (!user?.is_pet) throw new HttpError(403, "Pet privileges required");
-  await next();
-}
-
-/**
- * Verify Discord bot access: `Authorization: Bearer <DOUGH_BOT_TOKEN>` plus a
- * `User-Agent: CloveShortcuts/<version>` header.
- */
-export async function verifyBotAccess(c: Context<Env>, next: Next): Promise<void> {
-  const userAgent = c.req.header("User-Agent");
-  const authorization = c.req.header("Authorization");
-
-  if (!userAgent || !userAgent.startsWith("CloveShortcuts/")) {
-    throw new HttpError(403, "Invalid User-Agent. Expected 'CloveShortcuts/<version>'");
-  }
-  if (!authorization) {
-    throw new HttpError(401, "Missing Authorization header", { "WWW-Authenticate": "Bearer" });
-  }
-
-  const parts = authorization.split(" ");
-  if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") {
-    throw new HttpError(401, "Invalid Authorization header format. Expected 'Bearer <token>'", {
-      "WWW-Authenticate": "Bearer",
-    });
-  }
-
-  if (!verifyBotToken(parts[1])) {
-    throw new HttpError(401, "Invalid bot access token", { "WWW-Authenticate": "Bearer" });
-  }
-  await next();
-}
+import { verifyBatteryKey, verifyGuestbookKey } from "../services/keys";
+import { rt } from "../runtime";
 
 /** Verify battery API access via the X-Battery-Key header. */
 export async function verifyBatteryAccess(c: Context<Env>, next: Next): Promise<void> {
@@ -124,6 +26,17 @@ export async function verifyBatteryAccess(c: Context<Env>, next: Next): Promise<
   await next();
 }
 
+/** True when the site says this bearer token belongs to an admin. */
+async function isSiteAdmin(authorization: string): Promise<boolean> {
+  const res = await rt().env.SITE.fetch("https://doughmination.co.uk/api/plural/auth/is_admin", {
+    headers: { Authorization: authorization },
+  });
+  if (res.status === 401) throw new HttpError(401, "Invalid or expired token", { "WWW-Authenticate": "Bearer" });
+  if (!res.ok) throw new HttpError(502, "Could not check your account with the system site");
+  const body = (await res.json()) as { isAdmin?: boolean };
+  return body.isAdmin === true;
+}
+
 /**
  * Guestbook moderation: either the X-Guestbook-Key header (the website's
  * server, after its own SSO login) or a signed-in admin's bearer token.
@@ -135,8 +48,11 @@ export async function verifyGuestbookAdmin(c: Context<Env>, next: Next): Promise
     await next();
     return;
   }
-  const user = await resolveCurrentUser(c);
-  if (!user.is_admin) throw new HttpError(403, "Admin privileges required");
-  c.set("user", user);
+
+  const authorization = c.req.header("Authorization");
+  if (!authorization?.toLowerCase().startsWith("bearer ")) {
+    throw new HttpError(401, "Not authenticated", { "WWW-Authenticate": "Bearer" });
+  }
+  if (!(await isSiteAdmin(authorization))) throw new HttpError(403, "Admin privileges required");
   await next();
 }
diff --git a/src/system/models.ts b/src/system/models.ts
deleted file mode 100644
index 40a1ef8..0000000
--- a/src/system/models.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * zod models + types. Field names stay snake_case to match the existing
- * data blobs and the frontend wire format. Consolidated from the old
- * models/user.ts + models/index.ts.
- */
-
-import { z } from "zod";
-
-// ============================================================================
-// USER MODELS
-// ============================================================================
-
-/** Emails are stored lowercased and trimmed so uniqueness checks are stable. */
-export const EmailSchema = z
-  .string()
-  .trim()
-  .toLowerCase()
-  .email("Must be a valid email address")
-  .max(254, "Email address is too long");
-
-export const UserSchema = z.object({
-  id: z.string(),
-  username: z.string(),
-  /**
-   * The OIDC subject (`sub`) this account is linked to. The field keeps its
-   * original name so stored records load unchanged: accounts linked before the
-   * move to the Doughmination SSO hold a PocketID subject here.
-   * Optional so the owner seed and pre-link accounts still load.
-   */
-  pocket_id: z.string().nullable().optional(),
-  /**
-   * Issuer that `pocket_id` belongs to. Null/absent = linked before the SSO
-   * move (or never linked), which is what lets the first SSO sign-in adopt the
-   * account by username exactly once.
-   */
-  sso_issuer: z.string().nullable().optional(),
-  /**
-   * Legacy PBKDF2 hash from the retired password login. Kept optional purely
-   * so old stored records still parse; it is never read or written any more.
-   */
-  password_hash: z.string().nullable().optional(),
-  display_name: z.string().nullable().optional(),
-  /** Email address, populated from the SSO `email` claim when available. */
-  email: z.string().nullable().optional(),
-  /** ISO timestamp of account creation. Absent on legacy accounts. */
-  created_at: z.string().nullable().optional(),
-  is_admin: z.boolean().default(false),
-  is_owner: z.boolean().default(false),
-  is_pet: z.boolean().default(false),
-  avatar_url: z.string().nullable().optional(),
-});
-export type User = z.infer<typeof UserSchema>;
-
-export const UserCreateSchema = z.object({
-  username: z.string(),
-  /** Set when an admin pre-provisions an account before its first SSO login
-   *  (the SSO subject id); normally the link is established automatically. */
-  pocket_id: z.string().nullable().optional(),
-  email: EmailSchema.nullable().optional(),
-  display_name: z.string().nullable().optional(),
-  is_admin: z.boolean().default(false),
-  is_pet: z.boolean().default(false),
-});
-export type UserCreate = z.infer<typeof UserCreateSchema>;
-
-export const UserResponseSchema = z.object({
-  id: z.string(),
-  username: z.string(),
-  display_name: z.string().nullable().optional(),
-  email: z.string().nullable().optional(),
-  created_at: z.string().nullable().optional(),
-  is_admin: z.boolean().default(false),
-  is_owner: z.boolean().default(false),
-  is_pet: z.boolean().default(false),
-  avatar_url: z.string().nullable().optional(),
-});
-export type UserResponse = z.infer<typeof UserResponseSchema>;
-
-export const UserUpdateSchema = z.object({
-  display_name: z.string().nullable().optional(),
-  avatar_url: z.string().nullable().optional(),
-  /**
-   * Profile email. Changeable by the account's own user or by an admin/owner.
-   * There is no confirmation step any more — identity is proven by the SSO,
-   * so this field is purely informational/contact metadata.
-   */
-  email: EmailSchema.nullable().optional(),
-  is_admin: z.boolean().nullable().optional(),
-  is_pet: z.boolean().nullable().optional(),
-});
-export type UserUpdate = z.infer<typeof UserUpdateSchema>;
-
-/** Strip internal-only fields for public-facing responses. */
-export function toUserResponse(user: User): UserResponse {
-  const { password_hash: _pw, pocket_id: _sub, sso_issuer: _iss, ...rest } = user;
-  return rest;
-}
-
-// ============================================================================
-// SYSTEM / MENTAL STATE
-// ============================================================================
-
-export const MentalStateSchema = z.object({
-  level: z.string(),
-  updated_at: z.coerce.date().default(() => new Date()),
-  notes: z.string().nullable().optional(),
-});
-export type MentalState = z.infer<typeof MentalStateSchema>;
-
-// ============================================================================
-// BOT MODELS
-// ============================================================================
-
-export const MultiSwitchRequestSchema = z.object({
-  member_ids: z.array(z.string()),
-});
-export type MultiSwitchRequest = z.infer<typeof MultiSwitchRequestSchema>;
diff --git a/src/system/routes/admin.ts b/src/system/routes/admin.ts
deleted file mode 100644
index ca26877..0000000
--- a/src/system/routes/admin.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { Hono } from "hono";
-
-import type { Env } from "../hono";
-import { requireAuth, requireAdmin } from "../middleware/auth";
-import { broadcastFrontendUpdate } from "../ws";
-import { HttpError } from "../errors";
-
-export const adminRoutes = new Hono<Env>();
-
-/** Force every connected /v2/ws client to refresh (admin only). */
-adminRoutes.post("/admin/refresh", requireAuth, requireAdmin, async (c) => {
-  try {
-    broadcastFrontendUpdate("force_refresh", { message: "Admin initiated refresh" });
-    return c.json({ success: true, message: "Refresh broadcast sent" });
-  } catch (err) {
-    throw new HttpError(500, `Failed to broadcast refresh: ${String(err)}`);
-  }
-});
diff --git a/src/system/routes/auth.ts b/src/system/routes/auth.ts
deleted file mode 100644
index 4c86a30..0000000
--- a/src/system/routes/auth.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Authentication — Doughmination SSO (OpenID Connect) only.
- *
- *   GET  /auth/sso/login     — redirect to the SSO to start the flow.
- *   GET  /auth/sso/callback  — the SSO redirects back here; we exchange the
- *                              code, link/create the account, open an SSO-backed
- *                              session, mint a JWT and hand the browser back to
- *                              the frontend with the token in the URL fragment.
- *   POST /auth/logout        — end the session here and at the SSO.
- *   POST /auth/app/token     — a native app swaps its one-time code and PKCE
- *                              verifier for the same JWT (see below).
- *
- * Native apps (the Plural Android app) start the same flow with
- * /auth/sso/login?app=<S256 PKCE challenge>. Their callback never carries the
- * JWT: it redirects to gay.doughmination.plural://auth?code=<one-time code>,
- * and the app redeems that code within a minute at /auth/app/token with the
- * verifier only it holds (services/app_codes.ts). Without `app` the flow is
- * exactly the website's, unchanged.
- *
- * /auth/pocketid/login and /auth/pocketid/callback remain as aliases: the
- * published @doughmination/react-api client still builds the old login URL.
- *
- * Everything downstream (the /user_info + /auth/is_* checks and every
- * requireAuth route) keeps using the same HS256 bearer token as before; it
- * now also carries the session id that requireAuth checks.
- */
-
-import { Hono, type Context } from "hono";
-
-import type { Env } from "../hono";
-import { UserResponseSchema } from "../models";
-import type { User } from "../models";
-import { findOrCreateFromSso } from "../services/users";
-import {
-  beginLogin,
-  completeLogin,
-  endSessionUrl,
-  isAppLogin,
-  revokeRefreshToken,
-} from "../services/oidc";
-import { APP_CODE, PKCE_CHALLENGE, PKCE_VERIFIER, saveAppCode, takeAppCode } from "../services/app_codes";
-import { createSsoSession, endSsoSession } from "../services/sso_sessions";
-import { ssoPostLoginUrl, ssoLoginErrorUrl, ACCESS_TOKEN_EXPIRE_MINUTES } from "../config";
-import { createAccessToken, decodeAccessToken } from "../security";
-import { requireAuth } from "../middleware/auth";
-
-export const authRoutes = new Hono<Env>();
-
-function toUserResponseJson(user: User) {
-  return UserResponseSchema.parse({
-    id: user.id,
-    username: user.username,
-    display_name: user.display_name,
-    email: user.email ?? null,
-    created_at: user.created_at ?? null,
-    is_admin: user.is_admin,
-    is_owner: user.is_owner,
-    is_pet: user.is_pet,
-    avatar_url: user.avatar_url ?? null,
-  });
-}
-
-/** A same-origin-ish app path, defended against open-redirect abuse: only a
- *  path beginning with a single "/" is accepted, never "//host", "/\host" or a
- *  full URL. */
-function safeReturnPath(raw: string | undefined): string {
-  if (!raw) return "/";
-  if (!raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return "/";
-  return raw;
-}
-
-/** Where an app-started login lands; the Plural Android app handles this scheme. */
-const APP_REDIRECT = "gay.doughmination.plural://auth";
-
-function loginError(c: Context<Env>, message: string, app = false) {
-  const url = new URL(app ? APP_REDIRECT : ssoLoginErrorUrl());
-  url.searchParams.set("error", message);
-  return c.redirect(url.toString(), 302);
-}
-
-/** Start the SSO login: 302 to the provider's authorization endpoint. */
-async function login(c: Context<Env>) {
-  const from = safeReturnPath(c.req.query("from"));
-  const app = c.req.query("app");
-  if (app !== undefined && !PKCE_CHALLENGE.test(app)) {
-    return c.json({ detail: "'app' must be an S256 PKCE challenge." }, 400);
-  }
-  const authUrl = await beginLogin(from, app);
-  return c.redirect(authUrl, 302);
-}
-
-/** The SSO redirects the browser back here after the user authenticates. */
-async function callback(c: Context<Env>) {
-  const code = c.req.query("code");
-  const state = c.req.query("state");
-  // Errors go back to whoever started the login: the app or the website.
-  const app = await isAppLogin(state);
-
-  const errorParam = c.req.query("error");
-  if (errorParam === "access_denied") {
-    return loginError(c, "Your SSO account isn't allowed to use this site.", app);
-  }
-  if (errorParam) return loginError(c, errorParam, app);
-
-  if (!code || !state) return loginError(c, "missing_code", app);
-
-  let result;
-  try {
-    result = await completeLogin(code, state, c.req.query("iss"));
-  } catch (err) {
-    return loginError(c, err instanceof Error ? err.message : "Login failed. Please try again.", app);
-  }
-
-  const { identity, tokens, from, appChallenge } = result;
-
-  let user: User;
-  try {
-    user = await findOrCreateFromSso({
-      sub: identity.sub,
-      issuer: identity.issuer,
-      username: identity.preferredUsername,
-      email: identity.email,
-      displayName: identity.displayName,
-    });
-  } catch (err) {
-    return loginError(c, err instanceof Error ? err.message : "Could not sign you in.", app);
-  }
-
-  const expiresAt = Date.now() + ACCESS_TOKEN_EXPIRE_MINUTES * 60 * 1000;
-  const sid = await createSsoSession(user, tokens, expiresAt);
-
-  const token = await createAccessToken({
-    sub: user.username,
-    id: user.id,
-    sid,
-    display_name: user.display_name,
-    admin: user.is_admin,
-    owner: user.is_owner,
-    pet: user.is_pet,
-    avatar_url: user.avatar_url ?? null,
-  });
-
-  // An app gets a one-time code, never the token: any app can claim a custom
-  // scheme, but only the one holding the PKCE verifier can redeem the code.
-  if (appChallenge) {
-    const appCode = await saveAppCode(token, appChallenge);
-    return c.redirect(`${APP_REDIRECT}?code=${encodeURIComponent(appCode)}`, 302);
-  }
-
-  // Token goes in the fragment so it never lands in a server access log or the
-  // Referer header; the frontend callback page reads it from location.hash.
-  const dest = new URL(ssoPostLoginUrl());
-  dest.hash = `token=${encodeURIComponent(token)}&from=${encodeURIComponent(from)}`;
-  return c.redirect(dest.toString(), 302);
-}
-
-authRoutes.get("/auth/sso/login", login);
-authRoutes.get("/auth/sso/callback", callback);
-authRoutes.get("/auth/pocketid/login", login);
-authRoutes.get("/auth/pocketid/callback", callback);
-
-/** A native app redeems its one-time code (and PKCE verifier) for the JWT. */
-authRoutes.post("/auth/app/token", async (c) => {
-  const body = (await c.req.json().catch(() => ({}))) as { code?: unknown; verifier?: unknown };
-  const code = typeof body.code === "string" ? body.code : "";
-  const verifier = typeof body.verifier === "string" ? body.verifier : "";
-  if (!APP_CODE.test(code) || !PKCE_VERIFIER.test(verifier)) {
-    return c.json({ detail: "Body must include 'code' and a PKCE 'verifier'." }, 422);
-  }
-
-  const token = await takeAppCode(code, verifier);
-  c.header("Cache-Control", "no-store");
-  if (!token) {
-    return c.json({ detail: "That sign-in code is invalid or has expired. Please sign in again." }, 400);
-  }
-  return c.json({ access_token: token, token_type: "bearer" });
-});
-
-/**
- * End the caller's session. Accepts an expired or already-revoked token so a
- * stale tab can still sign out cleanly; returns the SSO URL the browser should
- * visit to end the SSO session as well.
- */
-authRoutes.post("/auth/logout", async (c) => {
-  const header = c.req.header("Authorization") ?? "";
-  const token = header.toLowerCase().startsWith("bearer ") ? header.slice(7).trim() : "";
-
-  let sid: string | null = null;
-  if (token) {
-    try {
-      const payload = await decodeAccessToken(token, { allowExpired: true });
-      sid = typeof payload.sid === "string" ? payload.sid : null;
-    } catch {
-      // unverifiable token: nothing of ours to end
-    }
-  }
-
-  const session = sid ? await endSsoSession(sid) : null;
-  if (session?.refreshToken) {
-    await revokeRefreshToken(session.refreshToken).catch((err) =>
-      console.warn(`SSO refresh token revocation failed: ${String(err)}`),
-    );
-  }
-
-  let endSession: string | null = null;
-  try {
-    endSession = await endSessionUrl(session?.idToken ?? null);
-  } catch {
-    // SSO unreachable; the local session is gone regardless
-  }
-  return c.json({ ok: true, end_session_url: endSession });
-});
-
-authRoutes.get("/user_info", requireAuth, (c) => c.json(toUserResponseJson(c.get("user") as User)));
-
-authRoutes.get("/auth/is_admin", requireAuth, (c) =>
-  c.json({ isAdmin: c.get("user")?.is_admin ?? false }),
-);
-authRoutes.get("/auth/is_pet", requireAuth, (c) =>
-  c.json({ isPet: c.get("user")?.is_pet ?? false }),
-);
-authRoutes.get("/auth/is_owner", requireAuth, (c) =>
-  c.json({ isOwner: c.get("user")?.is_owner ?? false }),
-);
diff --git a/src/system/routes/bot.ts b/src/system/routes/bot.ts
deleted file mode 100644
index 4f27800..0000000
--- a/src/system/routes/bot.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Discord bot API. The token is now set manually (DOUGH_BOT_TOKEN secret),
- * so the two regenerate endpoints no longer mint tokens — they return 410
- * pointing at the secret. Everything else is a straight port.
- */
-
-import { Hono } from "hono";
-
-import type { Env } from "../hono";
-import { getSystem, getMembers, getFronters, setFront } from "../services/pluralkit";
-import { enrichMembersWithTags } from "../services/tags";
-import { enrichMembersWithStatus } from "../services/status";
-import { requireAuth, requireOwner, verifyBotAccess } from "../middleware/auth";
-import { HttpError } from "../errors";
-import { MultiSwitchRequestSchema } from "../models";
-
-export const botRoutes = new Hono<Env>();
-
-// ---- Health & token management --------------------------------------------
-
-botRoutes.get("/bot/health", verifyBotAccess, (c) =>
-  c.json({ status: "ok", message: "Bot API is operational", authenticated: true }),
-);
-
-const TOKEN_MANAGED_MSG =
-  "Bot token is now set manually via the DOUGH_BOT_TOKEN secret; rotate it with `wrangler secret put DOUGH_BOT_TOKEN`.";
-
-botRoutes.post("/bot/token/regenerate", requireAuth, requireOwner, () => {
-  throw new HttpError(410, TOKEN_MANAGED_MSG);
-});
-
-botRoutes.post("/bot/token/regenerate-self", verifyBotAccess, () => {
-  throw new HttpError(410, TOKEN_MANAGED_MSG);
-});
-
-// ---- System info ----------------------------------------------------------
-
-botRoutes.get("/bot/system/info", verifyBotAccess, async (c) => {
-  try {
-    return c.json({ success: true, data: await getSystem() });
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch system info: ${String(err)}`);
-  }
-});
-
-botRoutes.get("/bot/members", verifyBotAccess, async (c) => {
-  try {
-    const withTags = await enrichMembersWithTags(await getMembers());
-    const withStatus = await enrichMembersWithStatus(withTags);
-    return c.json({ success: true, data: withStatus });
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch members: ${String(err)}`);
-  }
-});
-
-botRoutes.get("/bot/fronters", verifyBotAccess, async (c) => {
-  try {
-    return c.json({ success: true, data: await getFronters() });
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch fronters: ${String(err)}`);
-  }
-});
-
-// ---- Fronting control -----------------------------------------------------
-
-botRoutes.post("/bot/switch", verifyBotAccess, async (c) => {
-  const parsed = MultiSwitchRequestSchema.safeParse(await c.req.json().catch(() => ({})));
-  if (!parsed.success) return c.json({ detail: parsed.error.issues }, 422);
-  const { member_ids } = parsed.data;
-
-  try {
-    const allMembers = await getMembers();
-    const validIds = new Set(allMembers.map((m) => m.id));
-    const invalidIds = member_ids.filter((mid) => !validIds.has(mid));
-    if (invalidIds.length > 0) {
-      throw new HttpError(400, `Invalid member IDs: ${invalidIds.join(", ")}`);
-    }
-
-    await setFront(member_ids);
-    const updatedFronters = await getFronters();
-
-    return c.json({
-      status: "success",
-      message: "Fronters updated successfully",
-      fronters: updatedFronters.members ?? [],
-      count: member_ids.length,
-    });
-  } catch (err) {
-    if (err instanceof HttpError) throw err;
-    throw new HttpError(500, `Failed to switch fronters: ${String(err)}`);
-  }
-});
diff --git a/src/system/routes/fronting.ts b/src/system/routes/fronting.ts
deleted file mode 100644
index 0983379..0000000
--- a/src/system/routes/fronting.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { Hono } from "hono";
-
-import type { Env } from "../hono";
-import { getFronters, setFront, getMembers } from "../services/pluralkit";
-import { enrichMembersWithTags } from "../services/tags";
-import { enrichMembersWithStatus } from "../services/status";
-import { requireAuth } from "../middleware/auth";
-import { broadcastFrontingUpdate } from "../ws";
-import { HttpError } from "../errors";
-
-export const frontingRoutes = new Hono<Env>();
-
-frontingRoutes.get("/fronters", async (c) => {
-  try {
-    const frontersData = await getFronters();
-    if ("members" in frontersData) {
-      const withTags = await enrichMembersWithTags(frontersData.members);
-      frontersData.members = await enrichMembersWithStatus(withTags);
-    }
-    return c.json(frontersData);
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch fronters: ${String(err)}`);
-  }
-});
-
-frontingRoutes.post("/switch", requireAuth, async (c) => {
-  const body = (await c.req.json().catch(() => ({}))) as { members?: unknown };
-  const memberIds = body.members ?? [];
-  if (!Array.isArray(memberIds)) throw new HttpError(400, "'members' must be a list of member IDs");
-
-  try {
-    await setFront(memberIds);
-    broadcastFrontingUpdate(await getFronters());
-    return c.json({ status: "success", message: "Front updated successfully" });
-  } catch (err) {
-    throw new HttpError(500, String(err));
-  }
-});
-
-frontingRoutes.post("/switch_front", requireAuth, async (c) => {
-  const body = (await c.req.json().catch(() => ({}))) as { member_id?: unknown };
-  if (!body.member_id) throw new HttpError(400, "member_id is required");
-
-  try {
-    const result = await setFront([String(body.member_id)]);
-    broadcastFrontingUpdate(await getFronters());
-    return c.json({ success: true, message: "Front updated", data: result });
-  } catch (err) {
-    throw new HttpError(500, `Failed to switch front: ${String(err)}`);
-  }
-});
-
-frontingRoutes.post("/multi_switch", requireAuth, async (c) => {
-  const body = (await c.req.json().catch(() => ({}))) as { member_ids?: unknown };
-  const memberIds = body.member_ids ?? [];
-  if (!Array.isArray(memberIds)) throw new HttpError(400, "'member_ids' must be a list");
-
-  try {
-    const allMembers = await getMembers();
-    const switchingMembers: Array<{ id: unknown; name: unknown; display_name: unknown }> = [];
-    for (const memberId of memberIds) {
-      const member = allMembers.find((m) => m.id === memberId);
-      if (member) {
-        switchingMembers.push({
-          id: member.id,
-          name: member.name,
-          display_name: member.display_name ?? member.name,
-        });
-      }
-    }
-
-    await setFront(memberIds);
-    broadcastFrontingUpdate(await getFronters());
-
-    return c.json({
-      status: "success",
-      message: "Fronters updated successfully",
-      fronters: switchingMembers,
-      count: switchingMembers.length,
-    });
-  } catch (err) {
-    throw new HttpError(500, String(err));
-  }
-});
diff --git a/src/system/routes/member_status.ts b/src/system/routes/member_status.ts
deleted file mode 100644
index 1b9a311..0000000
--- a/src/system/routes/member_status.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { Hono } from "hono";
-
-import type { Env } from "../hono";
-import { getMemberStatus, setMemberStatus, clearMemberStatus } from "../services/status";
-import { requireAuth, requireAdmin } from "../middleware/auth";
-import { HttpError } from "../errors";
-
-export const memberStatusRoutes = new Hono<Env>();
-
-/** Public: get a member's status. */
-memberStatusRoutes.get("/members/:member_identifier/status", async (c) => {
-  try {
-    const memberIdentifier = c.req.param("member_identifier") ?? "";
-    const status = await getMemberStatus(memberIdentifier);
-    return c.json({ success: true, member_identifier: memberIdentifier, status });
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch member status: ${String(err)}`);
-  }
-});
-
-/** Admin: set/update a member's status. */
-memberStatusRoutes.post("/members/:member_identifier/status", requireAuth, requireAdmin, async (c) => {
-  const memberIdentifier = c.req.param("member_identifier") ?? "";
-  const body = (await c.req.json().catch(() => ({}))) as { text?: unknown; emoji?: unknown };
-  const statusText = body.text;
-  const emoji = typeof body.emoji === "string" ? body.emoji : null;
-
-  if (!statusText) throw new HttpError(400, "Status text is required");
-  if (String(statusText).length > 100) {
-    throw new HttpError(400, "Status text must be 100 characters or less");
-  }
-
-  try {
-    const status = await setMemberStatus(memberIdentifier, String(statusText), emoji);
-    return c.json({ success: true, message: `Status updated for ${memberIdentifier}`, status });
-  } catch (err) {
-    throw new HttpError(500, `Failed to set member status: ${String(err)}`);
-  }
-});
-
-/** Admin: clear a member's status. */
-memberStatusRoutes.delete(
-  "/members/:member_identifier/status",
-  requireAuth,
-  requireAdmin,
-  async (c) => {
-    try {
-      const memberIdentifier = c.req.param("member_identifier") ?? "";
-      const ok = await clearMemberStatus(memberIdentifier);
-      return ok
-        ? c.json({ success: true, message: `Status cleared for ${memberIdentifier}` })
-        : c.json({ success: false, message: `No status found for ${memberIdentifier}` });
-    } catch (err) {
-      throw new HttpError(500, `Failed to clear member status: ${String(err)}`);
-    }
-  },
-);
diff --git a/src/system/routes/members.ts b/src/system/routes/members.ts
deleted file mode 100644
index 1c46449..0000000
--- a/src/system/routes/members.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { Hono } from "hono";
-import { z } from "zod";
-
-import type { Env } from "../hono";
-import { getMembers } from "../services/pluralkit";
-import {
-  getMemberTags,
-  updateMemberTags,
-  addMemberTag,
-  removeMemberTag,
-  enrichMembersWithTags,
-} from "../services/tags";
-import { enrichMembersWithStatus } from "../services/status";
-import {
-  getMemberPride,
-  addMemberPride,
-  removeMemberPride,
-  enrichMembersWithPride,
-} from "../services/pride";
-import { requireAuth, requireAdmin, requireOwner } from "../middleware/auth";
-import { setInCache } from "../cache";
-import { HttpError } from "../errors";
-
-export const membersRoutes = new Hono<Env>();
-
-membersRoutes.get("/members", async (c) => {
-  try {
-    const membersData = await getMembers();
-    const withTags = await enrichMembersWithTags(membersData);
-    const withStatus = await enrichMembersWithStatus(withTags);
-    const withPride = await enrichMembersWithPride(withStatus);
-    return c.json(withPride);
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch members: ${String(err)}`);
-  }
-});
-
-membersRoutes.get("/member/:member_id", async (c) => {
-  try {
-    const memberId = c.req.param("member_id") ?? "";
-    const members = await getMembers();
-    const member = members.find(
-      (m) => m.id === memberId || String(m.name ?? "").toLowerCase() === memberId.toLowerCase(),
-    );
-    if (!member) throw new HttpError(404, "Member not found");
-
-    const [withTags] = await enrichMembersWithTags([member]);
-    const [withStatus] = await enrichMembersWithStatus([withTags]);
-    const [withPride] = await enrichMembersWithPride([withStatus]);
-    return c.json(withPride);
-  } catch (err) {
-    if (err instanceof HttpError) throw err;
-    throw new HttpError(500, `Failed to fetch member details: ${String(err)}`);
-  }
-});
-
-// ---- Member tags ----------------------------------------------------------
-
-membersRoutes.get("/member-tags", requireAuth, requireAdmin, async (c) => {
-  try {
-    return c.json({ status: "success", member_tags: await getMemberTags() });
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch member tags: ${String(err)}`);
-  }
-});
-
-membersRoutes.post("/member-tags/:member_identifier", requireAuth, requireAdmin, async (c) => {
-  const parsed = z.array(z.string()).safeParse(await c.req.json().catch(() => null));
-  if (!parsed.success) return c.json({ detail: parsed.error.issues }, 422);
-
-  const memberIdentifier = c.req.param("member_identifier") ?? "";
-  try {
-    const ok = await updateMemberTags(memberIdentifier, parsed.data);
-    if (!ok) throw new HttpError(500, "Failed to update member tags");
-    setInCache("members_raw", null, 0);
-    return c.json({
-      status: "success",
-      message: `Updated tags for ${memberIdentifier}`,
-      tags: parsed.data,
-    });
-  } catch (err) {
-    if (err instanceof HttpError) throw err;
-    throw new HttpError(500, `Failed to update member tags: ${String(err)}`);
-  }
-});
-
-membersRoutes.post("/member-tags/:member_identifier/add", requireAuth, requireAdmin, async (c) => {
-  const body = (await c.req.json().catch(() => ({}))) as { tag?: unknown };
-  const memberIdentifier = c.req.param("member_identifier") ?? "";
-  if (typeof body.tag !== "string") {
-    return c.json({ detail: "Body must include a 'tag' string field" }, 422);
-  }
-  try {
-    const ok = await addMemberTag(memberIdentifier, body.tag);
-    setInCache("members_raw", null, 0);
-    return ok
-      ? c.json({ status: "success", message: `Added tag '${body.tag}' to ${memberIdentifier}` })
-      : c.json({ status: "info", message: `Tag '${body.tag}' already exists for ${memberIdentifier}` });
-  } catch (err) {
-    throw new HttpError(500, `Failed to add member tag: ${String(err)}`);
-  }
-});
-
-membersRoutes.delete(
-  "/member-tags/:member_identifier/:tag",
-  requireAuth,
-  requireAdmin,
-  async (c) => {
-    const memberIdentifier = c.req.param("member_identifier") ?? "";
-    const tag = c.req.param("tag") ?? "";
-    try {
-      const ok = await removeMemberTag(memberIdentifier, tag);
-      if (!ok) throw new HttpError(404, `Tag '${tag}' not found for ${memberIdentifier}`);
-      setInCache("members_raw", null, 0);
-      return c.json({ status: "success", message: `Removed tag '${tag}' from ${memberIdentifier}` });
-    } catch (err) {
-      if (err instanceof HttpError) throw err;
-      throw new HttpError(500, `Failed to remove member tag: ${String(err)}`);
-    }
-  },
-);
-
-// ---- Member pride identities ----------------------------------------------
-
-membersRoutes.get("/member-pride", requireAuth, requireOwner, async (c) => {
-  try {
-    return c.json({ status: "success", member_pride: await getMemberPride() });
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch member pride: ${String(err)}`);
-  }
-});
-
-membersRoutes.post(
-  "/member-pride/:member_identifier/add",
-  requireAuth,
-  requireOwner,
-  async (c) => {
-    const body = (await c.req.json().catch(() => ({}))) as { identity?: unknown };
-    const memberIdentifier = c.req.param("member_identifier") ?? "";
-    if (typeof body.identity !== "string") {
-      return c.json({ detail: "Body must include an 'identity' string field" }, 422);
-    }
-    try {
-      const added = await addMemberPride(memberIdentifier, body.identity);
-      setInCache("members_raw", null, 0);
-      return added
-        ? c.json({
-            status: "success",
-            message: `Added pride '${body.identity}' to ${memberIdentifier}`,
-          })
-        : c.json({
-            status: "info",
-            message: `Pride '${body.identity}' already set for ${memberIdentifier}`,
-          });
-    } catch (err) {
-      throw new HttpError(500, `Failed to add member pride: ${String(err)}`);
-    }
-  },
-);
-
-membersRoutes.delete(
-  "/member-pride/:member_identifier/:identity",
-  requireAuth,
-  requireOwner,
-  async (c) => {
-    const memberIdentifier = c.req.param("member_identifier") ?? "";
-    const identity = c.req.param("identity") ?? "";
-    try {
-      const removed = await removeMemberPride(memberIdentifier, identity);
-      if (!removed) {
-        throw new HttpError(404, `Pride '${identity}' not found for ${memberIdentifier}`);
-      }
-      setInCache("members_raw", null, 0);
-      return c.json({
-        status: "success",
-        message: `Removed pride '${identity}' from ${memberIdentifier}`,
-      });
-    } catch (err) {
-      if (err instanceof HttpError) throw err;
-      throw new HttpError(500, `Failed to remove member pride: ${String(err)}`);
-    }
-  },
-);
diff --git a/src/system/routes/metrics.ts b/src/system/routes/metrics.ts
deleted file mode 100644
index 2aa091c..0000000
--- a/src/system/routes/metrics.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { Hono } from "hono";
-import type { Context } from "hono";
-
-import type { Env } from "../hono";
-import { getFrontingTimeMetrics, getSwitchFrequencyMetrics } from "../services/metrics";
-import { HttpError } from "../errors";
-
-export const metricsRoutes = new Hono<Env>();
-
-function parseDays(c: Context): number {
-  const raw = c.req.query("days");
-  const parsed = Number(raw);
-  return raw !== undefined && !Number.isNaN(parsed) ? parsed : 30;
-}
-
-metricsRoutes.get("/metrics/fronting-time", async (c) => {
-  try {
-    return c.json(await getFrontingTimeMetrics(parseDays(c)));
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch fronting metrics: ${String(err)}`);
-  }
-});
-
-metricsRoutes.get("/metrics/switch-frequency", async (c) => {
-  try {
-    return c.json(await getSwitchFrequencyMetrics(parseDays(c)));
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch switch frequency metrics: ${String(err)}`);
-  }
-});
diff --git a/src/system/routes/relationships.ts b/src/system/routes/relationships.ts
deleted file mode 100644
index 9844416..0000000
--- a/src/system/routes/relationships.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { Hono } from "hono";
-import { z } from "zod";
-
-import type { Env } from "../hono";
-import {
-  getRelationships,
-  addRelationship,
-  removeRelationship,
-} from "../services/relationships";
-import { requireAuth, requireOwner } from "../middleware/auth";
-import { HttpError } from "../errors";
-
-export const relationshipsRoutes = new Hono<Env>();
-
-const relationshipSchema = z.object({
-  memberA: z.string().min(1),
-  memberB: z.string().min(1),
-  type: z.string().min(1).optional(),
-  since: z.string().nullable().optional(),
-});
-
-// Public read — the whole system's relationship map.
-relationshipsRoutes.get("/relationships", async (c) => {
-  try {
-    return c.json({ status: "success", relationships: await getRelationships() });
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch relationships: ${String(err)}`);
-  }
-});
-
-relationshipsRoutes.post("/relationships", requireAuth, requireOwner, async (c) => {
-  const parsed = relationshipSchema.safeParse(await c.req.json().catch(() => null));
-  if (!parsed.success) return c.json({ detail: parsed.error.issues }, 422);
-
-  if (parsed.data.memberA === parsed.data.memberB) {
-    return c.json({ detail: "A member cannot be in a relationship with themselves" }, 422);
-  }
-
-  try {
-    const relationship = await addRelationship(parsed.data);
-    return c.json({ status: "success", relationship });
-  } catch (err) {
-    throw new HttpError(400, err instanceof Error ? err.message : String(err));
-  }
-});
-
-relationshipsRoutes.delete("/relationships/:id", requireAuth, requireOwner, async (c) => {
-  const id = c.req.param("id") ?? "";
-  try {
-    const removed = await removeRelationship(id);
-    if (!removed) throw new HttpError(404, `Relationship '${id}' not found`);
-    return c.json({ status: "success", message: `Removed relationship ${id}` });
-  } catch (err) {
-    if (err instanceof HttpError) throw err;
-    throw new HttpError(500, `Failed to remove relationship: ${String(err)}`);
-  }
-});
diff --git a/src/system/routes/static.ts b/src/system/routes/static.ts
deleted file mode 100644
index b8abb98..0000000
--- a/src/system/routes/static.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Data-driven SEO files. Mounted under /v2/plural.
- *
- * NOTE: the old backend also served the frontend SPA (index.html) and
- * per-member SSR OG pages (/:member_name, /fronting) plus /avatars file
- * serving. Those are intentionally NOT ported — this Worker is now an API
- * and no longer hosts the website bundle or a filesystem. Serve the SPA +
- * OG meta from the frontend deploy. robots.txt + sitemap.xml are kept here
- * because they are self-contained and data-driven off PluralKit.
- */
-
-import { Hono } from "hono";
-
-import type { Env } from "../hono";
-import { getMembers } from "../services/pluralkit";
-
-export const staticRoutes = new Hono<Env>();
-
-const ROBOTS_TXT = `# Doughmination System® - Robots.txt
-User-agent: *
-Allow: /
-Crawl-delay: 1
-
-User-agent: Googlebot
-Allow: /
-Crawl-delay: 0
-
-User-agent: Bingbot
-Allow: /
-Crawl-delay: 1
-
-User-agent: Slurp
-Allow: /
-
-User-agent: AhrefsBot
-Disallow: /
-
-User-agent: SemrushBot
-Disallow: /
-
-User-agent: MJ12bot
-Disallow: /
-
-Sitemap: https://doughmination.uk/sitemap.xml
-`;
-
-staticRoutes.get("/robots.txt", (c) => c.text(ROBOTS_TXT));
-
-staticRoutes.get("/sitemap.xml", async (c) => {
-  const today = new Date().toISOString().slice(0, 10);
-
-  try {
-    const members = await getMembers();
-
-    let sitemap = `<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
-        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
-  <url>
-    <loc>https://doughmination.uk/</loc>
-    <lastmod>${today}</lastmod>
-    <changefreq>daily</changefreq>
-    <priority>1.0</priority>
-  </url>
-`;
-
-    for (const member of members) {
-      const memberName = String(member.name ?? "").replace(/ /g, "%20");
-      const avatarUrl = member.avatar_url ?? "";
-      const displayName = member.display_name ?? member.name;
-
-      sitemap += `  <url>
-    <loc>https://doughmination.uk/${memberName}</loc>
-    <lastmod>${today}</lastmod>
-    <changefreq>weekly</changefreq>
-    <priority>0.8</priority>`;
-
-      if (avatarUrl) {
-        sitemap += `
-    <image:image>
-      <image:loc>${avatarUrl}</image:loc>
-      <image:title>${displayName}</image:title>
-    </image:image>`;
-      }
-
-      sitemap += `
-  </url>
-`;
-    }
-
-    sitemap += "</urlset>";
-    return c.body(sitemap, 200, { "Content-Type": "application/xml" });
-  } catch (err) {
-    console.error(`Error generating sitemap: ${String(err)}`);
-    return c.body(
-      `<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
-  <url><loc>https://doughmination.uk/</loc><lastmod>${today}</lastmod></url>
-</urlset>`,
-      200,
-      { "Content-Type": "application/xml" },
-    );
-  }
-});
diff --git a/src/system/routes/system.ts b/src/system/routes/system.ts
deleted file mode 100644
index 11ae7cc..0000000
--- a/src/system/routes/system.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { Hono } from "hono";
-
-import type { Env } from "../hono";
-import { MentalStateSchema } from "../models";
-import { getSystem } from "../services/pluralkit";
-import { getMentalState, saveMentalState } from "../services/mental_state";
-import { requireAuth, requireAdmin } from "../middleware/auth";
-import { broadcastMentalStateUpdate } from "../ws";
-import { HttpError } from "../errors";
-
-export const systemRoutes = new Hono<Env>();
-
-/** PluralKit system info + mental state. */
-systemRoutes.get("/system", async (c) => {
-  try {
-    const systemData = await getSystem();
-    systemData.mental_state = await getMentalState();
-    return c.json(systemData);
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch system info: ${String(err)}`);
-  }
-});
-
-systemRoutes.get("/mental-state", async (c) => {
-  try {
-    return c.json(await getMentalState());
-  } catch (err) {
-    throw new HttpError(500, `Failed to fetch mental state: ${String(err)}`);
-  }
-});
-
-systemRoutes.post("/mental-state", requireAuth, requireAdmin, async (c) => {
-  const parsed = MentalStateSchema.safeParse(await c.req.json().catch(() => ({})));
-  if (!parsed.success) return c.json({ detail: parsed.error.issues }, 422);
-  const state = parsed.data;
-
-  try {
-    const ok = await saveMentalState(state);
-    if (!ok) throw new HttpError(500, "Failed to save mental state");
-
-    await broadcastMentalStateUpdate({ ...state, updated_at: state.updated_at.toISOString() });
-    return c.json({ success: true, message: "Mental state updated" });
-  } catch (err) {
-    if (err instanceof HttpError) throw err;
-    throw new HttpError(500, `Failed to update mental state: ${String(err)}`);
-  }
-});
diff --git a/src/system/routes/users.ts b/src/system/routes/users.ts
deleted file mode 100644
index 2da5fb2..0000000
--- a/src/system/routes/users.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * User CRUD. The old multipart avatar-UPLOAD endpoint (multer + sharp) is
- * gone — avatars are now external URLs, set via `avatar_url` on PUT /users/:id.
- */
-
-import { Hono } from "hono";
-
-import type { Env } from "../hono";
-import { UserCreateSchema, UserUpdateSchema, toUserResponse } from "../models";
-import type { User } from "../models";
-import { getUsers, createUser, updateUser, deleteUser } from "../services/users";
-import { requireAuth, requireAdmin } from "../middleware/auth";
-import { HttpError } from "../errors";
-
-export const usersRoutes = new Hono<Env>();
-
-usersRoutes.get("/users", requireAuth, requireAdmin, async (c) => {
-  const users = await getUsers();
-  return c.json(users.map(toUserResponse));
-});
-
-/** Render zod issues as a single human-readable message for the frontend. */
-function validationDetail(issues: Array<{ path: PropertyKey[]; message: string }>): string {
-  return issues.map((i) => (i.path.length ? `${i.path.join(".")}: ${i.message}` : i.message)).join("; ");
-}
-
-usersRoutes.post("/users", requireAuth, requireAdmin, async (c) => {
-  const parsed = UserCreateSchema.safeParse(await c.req.json().catch(() => ({})));
-  if (!parsed.success) return c.json({ detail: validationDetail(parsed.error.issues) }, 422);
-
-  try {
-    // Admin-provisioned account. It becomes usable once the person signs in
-    // through the SSO with a matching username (the link is filled in then),
-    // or immediately if `pocket_id` was supplied.
-    const newUser = await createUser(parsed.data, c.get("user") ?? null);
-    return c.json(toUserResponse(newUser));
-  } catch (err) {
-    throw new HttpError(400, String(err instanceof Error ? err.message : err));
-  }
-});
-
-usersRoutes.put("/users/:user_id", requireAuth, async (c) => {
-  const userId = c.req.param("user_id") ?? "";
-  const currentUser = c.get("user") as User;
-
-  if (!currentUser.is_admin && currentUser.id !== userId) {
-    throw new HttpError(403, "Not authorized to update this user");
-  }
-
-  const parsed = UserUpdateSchema.safeParse(await c.req.json().catch(() => ({})));
-  if (!parsed.success) return c.json({ detail: validationDetail(parsed.error.issues) }, 422);
-
-  try {
-    const updated = await updateUser(userId, parsed.data, currentUser);
-    if (!updated) throw new HttpError(404, "User not found");
-    return c.json(toUserResponse(updated));
-  } catch (err) {
-    if (err instanceof HttpError) throw err;
-    throw new HttpError(400, String(err instanceof Error ? err.message : err));
-  }
-});
-
-usersRoutes.delete("/users/:user_id", requireAuth, requireAdmin, async (c) => {
-  const userId = c.req.param("user_id") ?? "";
-  const currentUser = c.get("user") as User;
-
-  if (userId === currentUser.id) throw new HttpError(400, "Cannot delete your own account");
-
-  try {
-    const ok = await deleteUser(userId, currentUser);
-    if (!ok) throw new HttpError(404, "User not found");
-    return c.json({ message: "User deleted successfully" });
-  } catch (err) {
-    if (err instanceof HttpError) throw err;
-    throw new HttpError(403, String(err instanceof Error ? err.message : err));
-  }
-});
diff --git a/src/system/security.ts b/src/system/security.ts
index 1ccb2c2..4bd631b 100644
--- a/src/system/security.ts
+++ b/src/system/security.ts
@@ -4,48 +4,12 @@
  * See LICENCE.md in the project root for full licence information.
  */
 
-/**
- * Security utilities, rewritten for the Workers runtime (Web Crypto only —
- * no `bcrypt`, `jsonwebtoken`, or `axios`).
- *
- *  - JWT: HS256 signed/verified with SubtleCrypto HMAC. This is the token the
- *    API issues to the browser AFTER a successful SSO (OIDC) login, so every
- *    existing bearer-auth route keeps working unchanged. It carries the id of
- *    the SSO-backed session it belongs to (see services/sso_sessions.ts).
- *  - OIDC helpers: cryptographically random state/PKCE-verifier generation and
- *    the S256 code-challenge digest.
- *  - Turnstile: verified with `fetch` (still used by the public guestbook).
- *
- * Local password hashing has been removed — login is SSO-only.
- */
+/** Constant-time key comparison and Turnstile verification. */
 
-import { ACCESS_TOKEN_EXPIRE_MINUTES, jwtSecret, turnstileSecret } from "./config";
+import { turnstileSecret } from "./config";
 import { HttpError } from "./errors";
 
 const enc = new TextEncoder();
-const dec = new TextDecoder();
-
-// ---------------------------------------------------------------------------
-// base64url helpers
-// ---------------------------------------------------------------------------
-
-function bytesToB64url(bytes: Uint8Array): string {
-  let bin = "";
-  for (const b of bytes) bin += String.fromCharCode(b);
-  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
-}
-
-function b64urlToBytes(s: string): Uint8Array {
-  const b64 = s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "=");
-  const bin = atob(b64);
-  const out = new Uint8Array(bin.length);
-  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
-  return out;
-}
-
-function b64urlJson(obj: unknown): string {
-  return bytesToB64url(enc.encode(JSON.stringify(obj)));
-}
 
 /** Constant-time byte comparison. */
 function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
@@ -60,83 +24,6 @@ export function constantTimeStringEqual(a: string, b: string): boolean {
   return timingSafeEqual(enc.encode(a), enc.encode(b));
 }
 
-// ---------------------------------------------------------------------------
-// OIDC / PKCE helpers
-// ---------------------------------------------------------------------------
-
-/** A URL-safe, cryptographically random token — used for OIDC `state` and the
- *  PKCE code verifier. `bytes` is the amount of entropy, not the string length. */
-export function randomUrlToken(bytes = 32): string {
-  return bytesToB64url(crypto.getRandomValues(new Uint8Array(bytes)));
-}
-
-/** The PKCE S256 code challenge: base64url( SHA-256( verifier ) ). */
-export async function sha256Base64Url(input: string): Promise<string> {
-  const digest = await crypto.subtle.digest("SHA-256", enc.encode(input));
-  return bytesToB64url(new Uint8Array(digest));
-}
-
-// ---------------------------------------------------------------------------
-// JWT (HS256)
-// ---------------------------------------------------------------------------
-
-async function hmacKey(): Promise<CryptoKey> {
-  return crypto.subtle.importKey(
-    "raw",
-    enc.encode(jwtSecret()),
-    { name: "HMAC", hash: "SHA-256" },
-    false,
-    ["sign", "verify"],
-  );
-}
-
-export async function createAccessToken(data: Record<string, unknown>): Promise<string> {
-  const now = Math.floor(Date.now() / 1000);
-  const payload = {
-    ...data,
-    iat: now,
-    exp: now + ACCESS_TOKEN_EXPIRE_MINUTES * 60,
-  };
-  const header = { alg: "HS256", typ: "JWT" };
-  const signingInput = `${b64urlJson(header)}.${b64urlJson(payload)}`;
-  const key = await hmacKey();
-  const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(signingInput)));
-  return `${signingInput}.${bytesToB64url(sig)}`;
-}
-
-export interface JwtPayload {
-  sub?: string;
-  [k: string]: unknown;
-}
-
-/** `allowExpired` is only for logout, where a stale token should still end its session. */
-export async function decodeAccessToken(
-  token: string,
-  opts: { allowExpired?: boolean } = {},
-): Promise<JwtPayload> {
-  try {
-    const parts = token.split(".");
-    if (parts.length !== 3) throw new Error("malformed");
-    const [h, p, s] = parts;
-    const key = await hmacKey();
-    const valid = await crypto.subtle.verify(
-      "HMAC",
-      key,
-      b64urlToBytes(s),
-      enc.encode(`${h}.${p}`),
-    );
-    if (!valid) throw new Error("bad signature");
-
-    const payload = JSON.parse(dec.decode(b64urlToBytes(p))) as JwtPayload & { exp?: number };
-    if (!opts.allowExpired && typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1000)) {
-      throw new Error("expired");
-    }
-    return payload;
-  } catch {
-    throw new HttpError(401, "Invalid or expired token", { "WWW-Authenticate": "Bearer" });
-  }
-}
-
 // ---------------------------------------------------------------------------
 // Turnstile
 // ---------------------------------------------------------------------------
diff --git a/src/system/services/app_codes.ts b/src/system/services/app_codes.ts
deleted file mode 100644
index da2f71b..0000000
--- a/src/system/services/app_codes.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * One-time sign-in codes for native apps.
- *
- * A browser can be handed its JWT in a URL fragment, but an app's redirect URI
- * (a custom scheme) can be claimed by any other app on the phone. So an
- * app-started login ends with a short-lived, single-use code instead, and the
- * app swaps it at POST /v2/plural/auth/app/token together with the PKCE
- * verifier only it holds. Anyone else who catches the redirect gets a useless
- * code: without the verifier it can't be redeemed, and once redeemed (or after
- * a minute) it's gone.
- */
-
-import { rt } from "../runtime";
-import { constantTimeStringEqual, randomUrlToken, sha256Base64Url } from "../security";
-
-/** How long an app has to redeem its code. */
-export const APP_CODE_TTL_SECONDS = 60;
-
-/** An S256 PKCE challenge: base64url of a SHA-256 digest, 43 characters. */
-export const PKCE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
-
-/** A code from saveAppCode: 32 random bytes, base64url. */
-export const APP_CODE = /^[A-Za-z0-9_-]{43}$/;
-
-/** RFC 7636 verifier: 43–128 unreserved characters. */
-export const PKCE_VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
-
-interface StoredAppCode {
-  token: string;
-  challenge: string;
-  expiresAt: number;
-}
-
-function codeKey(code: string): string {
-  return `app_code:${code}`;
-}
-
-/** Park a freshly minted JWT behind a one-time code bound to the app's challenge. */
-export async function saveAppCode(token: string, challenge: string): Promise<string> {
-  const code = randomUrlToken(32);
-  await rt().store.put(codeKey(code), {
-    token,
-    challenge,
-    expiresAt: Date.now() + APP_CODE_TTL_SECONDS * 1000,
-  } satisfies StoredAppCode);
-  return code;
-}
-
-/**
- * The JWT for a code, exactly once. The code is consumed on the first attempt,
- * right or wrong, so a guessed verifier can't be retried. Null when the code is
- * unknown, already used, expired, or the verifier doesn't match.
- */
-export async function takeAppCode(code: string, verifier: string): Promise<string | null> {
-  const key = codeKey(code);
-  const stored = await rt().store.get<StoredAppCode | null>(key, null);
-  if (!stored) return null;
-  await rt().store.delete(key);
-
-  if (Date.now() > stored.expiresAt) return null;
-  const challenge = await sha256Base64Url(verifier);
-  return constantTimeStringEqual(challenge, stored.challenge) ? stored.token : null;
-}
diff --git a/src/system/services/keys.ts b/src/system/services/keys.ts
index 99d771e..4afb5d3 100644
--- a/src/system/services/keys.ts
+++ b/src/system/services/keys.ts
@@ -5,26 +5,17 @@
  */
 
 /**
- * Manual API-key verification (bot token + battery keys).
+ * Manual API-key verification (battery + guestbook keys).
  *
  * These keys are now set MANUALLY as secrets/vars — nothing is generated on
  * first run and there is no longer a regenerate flow. Verification is a
  * constant-time comparison against the configured value(s).
- *   - Bot token:  DOUGH_BOT_TOKEN
  *   - Battery:    BATTERY_API_KEYS (comma-separated, one or more)
  */
 
 import { rt } from "../runtime";
 import { constantTimeStringEqual } from "../security";
 
-// ---- Bot token ------------------------------------------------------------
-
-export function verifyBotToken(providedToken: string): boolean {
-  const configured = rt().env.DOUGH_BOT_TOKEN;
-  if (!configured || !providedToken) return false;
-  return constantTimeStringEqual(configured, providedToken);
-}
-
 // ---- Battery keys ---------------------------------------------------------
 
 function batteryKeys(): string[] {
diff --git a/src/system/services/mental_state.ts b/src/system/services/mental_state.ts
deleted file mode 100644
index eaf46a2..0000000
--- a/src/system/services/mental_state.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import type { MentalState } from "../models";
-import { parseTimestamp } from "../datetime";
-import { rt } from "../runtime";
-
-const KEY = "mental_state";
-
-interface StoredMentalState {
-  level: string;
-  updated_at: string;
-  notes?: string | null;
-}
-
-function defaultState(): MentalState {
-  return { level: "safe", updated_at: new Date(), notes: null };
-}
-
-export async function getMentalState(): Promise<MentalState> {
-  try {
-    const stateData = await rt().store.get<StoredMentalState | null>(KEY, null);
-    if (!stateData) return defaultState();
-    return {
-      level: stateData.level,
-      updated_at: parseTimestamp(stateData.updated_at),
-      notes: stateData.notes ?? null,
-    };
-  } catch (err) {
-    console.error(`Error loading mental state: ${String(err)}`);
-    return defaultState();
-  }
-}
-
-export async function saveMentalState(state: MentalState): Promise<boolean> {
-  try {
-    const stateData: StoredMentalState = {
-      level: state.level,
-      updated_at: state.updated_at.toISOString(),
-      notes: state.notes ?? null,
-    };
-    await rt().store.put(KEY, stateData);
-    return true;
-  } catch (err) {
-    console.error(`Error saving mental state: ${String(err)}`);
-    return false;
-  }
-}
-
-export async function updateMentalState(
-  level: string,
-  notes?: string | null,
-): Promise<MentalState> {
-  const state: MentalState = { level, updated_at: new Date(), notes: notes ?? null };
-  await saveMentalState(state);
-  return state;
-}
diff --git a/src/system/services/metrics.ts b/src/system/services/metrics.ts
deleted file mode 100644
index cea3bfe..0000000
--- a/src/system/services/metrics.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/** Fronting-time and switch-frequency metrics. Logic ported verbatim. */
-
-import { getSwitches, getMembers } from "./pluralkit";
-import { parseTimestamp } from "../datetime";
-import type { PKObject } from "../types";
-
-interface MemberDetail {
-  name: string;
-  display_name: string;
-  avatar_url: string | null;
-}
-
-interface FrontingTimeTotals {
-  total_seconds: number;
-  "24h": number;
-  "48h": number;
-  "5d": number;
-  "7d": number;
-  "30d": number;
-}
-
-const TIMEFRAME_KEYS = ["24h", "48h", "5d", "7d", "30d"] as const;
-
-function emptyFrontingMetrics(): PKObject {
-  return {
-    total_time: 0,
-    members: {},
-    timeframes: { "24h": {}, "48h": {}, "5d": {}, "7d": {}, "30d": {} },
-  };
-}
-
-export async function getFrontingTimeMetrics(days = 30): Promise<PKObject> {
-  try {
-    const switches = await getSwitches(1000);
-
-    const now = new Date();
-    const cutoffTime = new Date(now.getTime() - days * 24 * 3600 * 1000);
-
-    const memberDetails: Record<string, MemberDetail> = {};
-    try {
-      const members = await getMembers();
-      for (const member of members) {
-        memberDetails[member.id] = {
-          name: member.name,
-          display_name: member.display_name ?? member.name,
-          avatar_url: member.avatar_url ?? null,
-        };
-      }
-    } catch (err) {
-      console.error(`Error fetching member details: ${String(err)}`);
-    }
-
-    const filteredSwitches: PKObject[] = [];
-    for (const switchObj of switches) {
-      try {
-        const timestamp = parseTimestamp(switchObj.timestamp);
-        if (timestamp >= cutoffTime) {
-          filteredSwitches.push({ ...switchObj, _parsed_timestamp: timestamp });
-        }
-      } catch (err) {
-        console.error(`Error parsing timestamp: ${String(err)}`);
-      }
-    }
-
-    filteredSwitches.sort(
-      (a, b) => (a._parsed_timestamp as Date).getTime() - (b._parsed_timestamp as Date).getTime(),
-    );
-
-    if (filteredSwitches.length === 0) return emptyFrontingMetrics();
-
-    const currentMembers = filteredSwitches[filteredSwitches.length - 1].members;
-    filteredSwitches.push({
-      timestamp: now.toISOString(),
-      members: currentMembers,
-      _parsed_timestamp: now,
-    });
-
-    const frontingTimes: Record<string, FrontingTimeTotals> = {};
-    let totalTimeSeconds = 0;
-
-    for (let i = 1; i < filteredSwitches.length; i++) {
-      const prevSwitch = filteredSwitches[i - 1];
-      const currSwitch = filteredSwitches[i];
-
-      try {
-        const prevTime: Date = prevSwitch._parsed_timestamp;
-        const currTime: Date = currSwitch._parsed_timestamp;
-        const durationSeconds = (currTime.getTime() - prevTime.getTime()) / 1000;
-        totalTimeSeconds += durationSeconds;
-
-        for (const memberId of prevSwitch.members as string[]) {
-          if (!(memberId in frontingTimes)) {
-            frontingTimes[memberId] = {
-              total_seconds: 0,
-              "24h": 0,
-              "48h": 0,
-              "5d": 0,
-              "7d": 0,
-              "30d": 0,
-            };
-          }
-
-          frontingTimes[memberId].total_seconds += durationSeconds;
-
-          const timeAgo = (now.getTime() - prevTime.getTime()) / 1000;
-          if (timeAgo <= 24 * 3600) frontingTimes[memberId]["24h"] += durationSeconds;
-          if (timeAgo <= 48 * 3600) frontingTimes[memberId]["48h"] += durationSeconds;
-          if (timeAgo <= 5 * 24 * 3600) frontingTimes[memberId]["5d"] += durationSeconds;
-          if (timeAgo <= 7 * 24 * 3600) frontingTimes[memberId]["7d"] += durationSeconds;
-          if (timeAgo <= 30 * 24 * 3600) frontingTimes[memberId]["30d"] += durationSeconds;
-        }
-      } catch (err) {
-        console.error(`Error processing switch: ${String(err)}`);
-      }
-    }
-
-    const result: PKObject = {
-      total_time: totalTimeSeconds,
-      members: {},
-      timeframes: { "24h": {}, "48h": {}, "5d": {}, "7d": {}, "30d": {} },
-    };
-
-    for (const [memberId, times] of Object.entries(frontingTimes)) {
-      let name = memberId;
-      let displayName = memberId;
-      let avatarUrl: string | null = null;
-
-      if (memberId in memberDetails) {
-        name = memberDetails[memberId].name;
-        displayName = memberDetails[memberId].display_name;
-        avatarUrl = memberDetails[memberId].avatar_url;
-      }
-
-      const totalPercent = totalTimeSeconds > 0 ? (times.total_seconds / totalTimeSeconds) * 100 : 0;
-
-      result.members[memberId] = {
-        id: memberId,
-        name,
-        display_name: displayName,
-        avatar_url: avatarUrl,
-        total_seconds: times.total_seconds,
-        total_percent: totalPercent,
-        "24h": times["24h"],
-        "48h": times["48h"],
-        "5d": times["5d"],
-        "7d": times["7d"],
-        "30d": times["30d"],
-      };
-
-      for (const tf of TIMEFRAME_KEYS) {
-        result.timeframes[tf][memberId] = times[tf];
-      }
-    }
-
-    return result;
-  } catch (err) {
-    console.error(`Error in getFrontingTimeMetrics: ${String(err)}`);
-    return emptyFrontingMetrics();
-  }
-}
-
-export async function getSwitchFrequencyMetrics(days = 30): Promise<PKObject> {
-  try {
-    const switches = await getSwitches(1000);
-
-    const now = new Date();
-    const cutoffTime = new Date(now.getTime() - days * 24 * 3600 * 1000);
-
-    const filteredSwitches: PKObject[] = [];
-    for (const switchObj of switches) {
-      try {
-        const timestamp = parseTimestamp(switchObj.timestamp);
-        if (timestamp >= cutoffTime) {
-          filteredSwitches.push({ ...switchObj, _parsed_timestamp: timestamp });
-        }
-      } catch (err) {
-        console.error(`Error parsing timestamp in switch_frequency: ${String(err)}`);
-      }
-    }
-
-    const totalSwitches = filteredSwitches.length;
-    const timeframes: Record<string, number> = {
-      "24h": 0,
-      "48h": 0,
-      "5d": 0,
-      "7d": 0,
-      "30d": totalSwitches,
-    };
-
-    for (const switchObj of filteredSwitches) {
-      try {
-        const timestamp: Date = switchObj._parsed_timestamp;
-        const timeAgo = (now.getTime() - timestamp.getTime()) / 1000;
-        if (timeAgo <= 24 * 3600) timeframes["24h"] += 1;
-        if (timeAgo <= 48 * 3600) timeframes["48h"] += 1;
-        if (timeAgo <= 5 * 24 * 3600) timeframes["5d"] += 1;
-        if (timeAgo <= 7 * 24 * 3600) timeframes["7d"] += 1;
-      } catch (err) {
-        console.error(`Error calculating timeframes: ${String(err)}`);
-      }
-    }
-
-    const avgSwitchesPerDay = days > 0 ? totalSwitches / days : 0;
-
-    return {
-      total_switches: totalSwitches,
-      avg_switches_per_day: avgSwitchesPerDay,
-      timeframes,
-    };
-  } catch (err) {
-    console.error(`Error in getSwitchFrequencyMetrics: ${String(err)}`);
-    return {
-      total_switches: 0,
-      avg_switches_per_day: 0,
-      timeframes: { "24h": 0, "48h": 0, "5d": 0, "7d": 0, "30d": 0 },
-    };
-  }
-}
diff --git a/src/system/services/oidc.ts b/src/system/services/oidc.ts
deleted file mode 100644
index a2e39e8..0000000
--- a/src/system/services/oidc.ts
+++ /dev/null
@@ -1,339 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Doughmination SSO / OpenID Connect client.
- *
- * The API is a confidential OIDC client running Authorization Code + PKCE:
- *
- *   1. /auth/sso/login  — mint a `state` + PKCE verifier, stash them in the DO
- *      store, and 302 the browser to the SSO's authorization endpoint.
- *   2. The SSO authenticates the user and redirects back with `?code&state&iss`.
- *   3. /auth/sso/callback — validate `state` and `iss`, exchange the code for
- *      tokens over a direct TLS call to the token endpoint, then read the
- *      identity claims from the userinfo endpoint.
- *
- * Because the code exchange and userinfo call are server-to-server over TLS
- * with a client secret, their responses are trusted directly — we do not need
- * to separately verify the id_token's signature.
- *
- * The refresh token from step 3 is kept with the API session (see
- * sso_sessions.ts) and used to re-check the account with the SSO.
- */
-
-import {
-  ssoIssuer,
-  ssoClientId,
-  ssoClientSecret,
-  ssoRedirectUri,
-  ssoScopes,
-  ssoPostLogoutRedirectUri,
-  OIDC_STATE_TTL_MINUTES,
-} from "../config";
-import { randomUrlToken, sha256Base64Url } from "../security";
-import { HttpError } from "../errors";
-import { rt } from "../runtime";
-
-/** The subset of the OIDC discovery document we use. */
-interface OidcDiscovery {
-  issuer: string;
-  authorization_endpoint: string;
-  token_endpoint: string;
-  userinfo_endpoint: string;
-  end_session_endpoint?: string;
-  revocation_endpoint?: string;
-}
-
-/** Identity claims we care about, normalized from the userinfo response. */
-export interface OidcIdentity {
-  /** Stable subject identifier — the primary key we link accounts on. */
-  sub: string;
-  /** The issuer that vouched for `sub`. */
-  issuer: string;
-  /** preferred_username claim; the account username we match/create on. */
-  preferredUsername: string;
-  email: string | null;
-  displayName: string | null;
-}
-
-/** Tokens kept with the API session. */
-export interface SsoTokens {
-  refreshToken: string | null;
-  idToken: string | null;
-}
-
-/** Cached discovery document (the DO is a singleton, so module scope persists
- *  across requests in the same isolate). Re-fetched after the TTL. */
-let discoveryCache: { issuer: string; doc: OidcDiscovery; fetchedAt: number } | null = null;
-const DISCOVERY_TTL_MS = 60 * 60 * 1000; // 1 hour
-
-function assertConfigured(): void {
-  if (!ssoIssuer()) throw new HttpError(500, "SSO is not configured (SSO_ISSUER)");
-  if (!ssoClientId()) throw new HttpError(500, "SSO is not configured (SSO_CLIENT_ID)");
-  if (!ssoClientSecret()) throw new HttpError(500, "SSO is not configured (SSO_CLIENT_SECRET)");
-}
-
-/** Fetch (and cache) the issuer's OpenID configuration. */
-export async function discover(): Promise<OidcDiscovery> {
-  const issuer = ssoIssuer();
-  const now = Date.now();
-  if (
-    discoveryCache &&
-    discoveryCache.issuer === issuer &&
-    now - discoveryCache.fetchedAt < DISCOVERY_TTL_MS
-  ) {
-    return discoveryCache.doc;
-  }
-
-  const url = `${issuer}/.well-known/openid-configuration`;
-  let res: Response;
-  try {
-    res = await fetch(url, { headers: { Accept: "application/json" } });
-  } catch (err) {
-    throw new HttpError(502, `Could not reach the SSO: ${String(err)}`);
-  }
-  if (!res.ok) {
-    throw new HttpError(502, `SSO discovery failed (${res.status})`);
-  }
-  const doc = (await res.json()) as OidcDiscovery;
-  if (!doc.authorization_endpoint || !doc.token_endpoint || !doc.userinfo_endpoint) {
-    throw new HttpError(502, "SSO discovery document is missing required endpoints");
-  }
-  if (doc.issuer !== issuer) {
-    throw new HttpError(502, `SSO issuer mismatch: configured ${issuer}, discovered ${doc.issuer}`);
-  }
-  discoveryCache = { issuer, doc, fetchedAt: now };
-  return doc;
-}
-
-interface StoredState {
-  verifier: string;
-  from: string;
-  createdAt: number;
-  /** Set when a native app started this login: the app's own S256 PKCE challenge. */
-  appChallenge?: string;
-}
-
-function stateKey(state: string): string {
-  return `oidc_state:${state}`;
-}
-
-/**
- * Build the authorization redirect URL and persist the matching PKCE verifier.
- * `from` is the app path to return the user to after login. `appChallenge` is
- * set when a native app started the login (see routes/auth.ts).
- */
-export async function beginLogin(from: string, appChallenge?: string): Promise<string> {
-  assertConfigured();
-  const doc = await discover();
-
-  const state = randomUrlToken(32);
-  const verifier = randomUrlToken(64);
-  const challenge = await sha256Base64Url(verifier);
-
-  await rt().store.put(stateKey(state), {
-    verifier,
-    from: from || "/",
-    createdAt: Date.now(),
-    ...(appChallenge ? { appChallenge } : {}),
-  } satisfies StoredState);
-
-  const authUrl = new URL(doc.authorization_endpoint);
-  authUrl.searchParams.set("response_type", "code");
-  authUrl.searchParams.set("client_id", ssoClientId() as string);
-  authUrl.searchParams.set("redirect_uri", ssoRedirectUri());
-  authUrl.searchParams.set("scope", ssoScopes());
-  authUrl.searchParams.set("state", state);
-  authUrl.searchParams.set("code_challenge", challenge);
-  authUrl.searchParams.set("code_challenge_method", "S256");
-  return authUrl.toString();
-}
-
-export interface CallbackResult {
-  identity: OidcIdentity;
-  tokens: SsoTokens;
-  /** The original app path to return the user to. */
-  from: string;
-  /** The native app's PKCE challenge, when an app started this login. */
-  appChallenge?: string;
-}
-
-/**
- * Whether a pending login was started by a native app, without consuming it.
- * Lets a callback that fails before the code exchange (the SSO refusing the
- * account, say) still send the person back to the app rather than the website.
- */
-export async function isAppLogin(state: string | undefined): Promise<boolean> {
-  if (!state) return false;
-  const stored = await rt().store.get<StoredState | null>(stateKey(state), null);
-  return Boolean(stored?.appChallenge);
-}
-
-/** Thrown when the SSO definitively refuses a grant (as opposed to being unreachable). */
-export class GrantRejectedError extends Error {}
-
-async function tokenRequest(params: Record<string, string>): Promise<Record<string, unknown>> {
-  const doc = await discover();
-  const body = new URLSearchParams({
-    ...params,
-    client_id: ssoClientId() as string,
-    client_secret: ssoClientSecret() as string,
-  });
-
-  let res: Response;
-  try {
-    res = await fetch(doc.token_endpoint, {
-      method: "POST",
-      headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
-      body,
-    });
-  } catch (err) {
-    throw new HttpError(502, `SSO token request failed: ${String(err)}`);
-  }
-
-  if (!res.ok) {
-    const detail = await res.text().catch(() => "");
-    let error = "";
-    try {
-      error = String((JSON.parse(detail) as { error?: string }).error ?? "");
-    } catch {
-      // not JSON
-    }
-    if (error === "invalid_grant") throw new GrantRejectedError(detail);
-    throw new HttpError(res.status === 401 ? 502 : 401, `The SSO rejected the request (${res.status}). ${detail}`.trim());
-  }
-  return (await res.json()) as Record<string, unknown>;
-}
-
-/**
- * Complete the flow: validate state, exchange the code, and read identity
- * claims. Consumes the stored state (single use).
- */
-export async function completeLogin(code: string, state: string, iss: string | undefined): Promise<CallbackResult> {
-  assertConfigured();
-
-  const key = stateKey(state);
-  const stored = await rt().store.get<StoredState | null>(key, null);
-  // Consume immediately so a replayed callback can't reuse it.
-  await rt().store.delete(key);
-
-  if (!stored) {
-    throw new HttpError(400, "Login session expired or invalid. Please try again.");
-  }
-  if (Date.now() - stored.createdAt > OIDC_STATE_TTL_MINUTES * 60 * 1000) {
-    throw new HttpError(400, "Login session expired. Please try again.");
-  }
-
-  const doc = await discover();
-  // RFC 9207: when the SSO names itself on the callback it must be the one we
-  // sent the user to, so a response from a different provider can't be mixed in.
-  if (iss !== undefined && iss !== doc.issuer) {
-    throw new HttpError(400, "Login response came from an unexpected issuer.");
-  }
-
-  // ---- Exchange the authorization code for tokens (direct TLS) -----------
-  let tokens: Record<string, unknown>;
-  try {
-    tokens = await tokenRequest({
-      grant_type: "authorization_code",
-      code,
-      redirect_uri: ssoRedirectUri(),
-      code_verifier: stored.verifier,
-    });
-  } catch (err) {
-    if (err instanceof GrantRejectedError) {
-      throw new HttpError(401, "The SSO rejected the login. Please try again.");
-    }
-    throw err;
-  }
-
-  const accessToken = typeof tokens.access_token === "string" ? tokens.access_token : "";
-  if (!accessToken) {
-    throw new HttpError(502, "The SSO did not return an access token");
-  }
-
-  // ---- Read identity claims from the userinfo endpoint -------------------
-  let infoRes: Response;
-  try {
-    infoRes = await fetch(doc.userinfo_endpoint, {
-      headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
-    });
-  } catch (err) {
-    throw new HttpError(502, `SSO userinfo request failed: ${String(err)}`);
-  }
-  if (!infoRes.ok) {
-    throw new HttpError(502, `SSO userinfo request failed (${infoRes.status})`);
-  }
-
-  const claims = (await infoRes.json()) as Record<string, unknown>;
-  const sub = typeof claims.sub === "string" ? claims.sub : "";
-  if (!sub) throw new HttpError(502, "The SSO did not return a subject identifier");
-
-  const preferredUsername =
-    (typeof claims.preferred_username === "string" && claims.preferred_username) ||
-    (typeof claims.nickname === "string" && claims.nickname) ||
-    (typeof claims.name === "string" && claims.name) ||
-    // Last resort: a deterministic username derived from the subject.
-    `user_${sub.slice(0, 12)}`;
-
-  const email = typeof claims.email === "string" ? claims.email : null;
-  const displayName =
-    (typeof claims.name === "string" && claims.name) ||
-    (typeof claims.preferred_username === "string" && claims.preferred_username) ||
-    null;
-
-  return {
-    identity: { sub, issuer: doc.issuer, preferredUsername, email, displayName },
-    tokens: {
-      refreshToken: typeof tokens.refresh_token === "string" ? tokens.refresh_token : null,
-      idToken: typeof tokens.id_token === "string" ? tokens.id_token : null,
-    },
-    from: stored.from || "/",
-    ...(stored.appChallenge ? { appChallenge: stored.appChallenge } : {}),
-  };
-}
-
-/**
- * Ask the SSO whether it still vouches for a session. Throws
- * GrantRejectedError when it doesn't (account disabled, removed from this
- * app's allowed groups, signed out everywhere); any other error means the SSO
- * couldn't be asked.
- */
-export async function refreshTokens(refreshToken: string): Promise<SsoTokens> {
-  const tokens = await tokenRequest({ grant_type: "refresh_token", refresh_token: refreshToken });
-  return {
-    refreshToken: typeof tokens.refresh_token === "string" ? tokens.refresh_token : null,
-    idToken: typeof tokens.id_token === "string" ? tokens.id_token : null,
-  };
-}
-
-/** Best-effort RFC 7009 revocation of a session's refresh token. */
-export async function revokeRefreshToken(refreshToken: string): Promise<void> {
-  const doc = await discover();
-  if (!doc.revocation_endpoint) return;
-  await fetch(doc.revocation_endpoint, {
-    method: "POST",
-    headers: { "Content-Type": "application/x-www-form-urlencoded" },
-    body: new URLSearchParams({
-      token: refreshToken,
-      token_type_hint: "refresh_token",
-      client_id: ssoClientId() as string,
-      client_secret: ssoClientSecret() as string,
-    }),
-  });
-}
-
-/** Where to send the browser so the SSO session ends too. */
-export async function endSessionUrl(idToken: string | null): Promise<string | null> {
-  const doc = await discover();
-  if (!doc.end_session_endpoint) return null;
-  const url = new URL(doc.end_session_endpoint);
-  url.searchParams.set("post_logout_redirect_uri", ssoPostLogoutRedirectUri());
-  url.searchParams.set("client_id", ssoClientId() as string);
-  // With the id_token as proof, the SSO signs out without asking again.
-  if (idToken) url.searchParams.set("id_token_hint", idToken);
-  return url.toString();
-}
diff --git a/src/system/services/pluralkit.ts b/src/system/services/pluralkit.ts
deleted file mode 100644
index cb886ec..0000000
--- a/src/system/services/pluralkit.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * PluralKit API integration, rewritten to use `fetch` instead of `axios`.
- * Behaviour and caching match the old service.
- */
-
-import { PLURALKIT_BASE_URL, pluralkitHeaders, cacheTtl } from "../config";
-import { getFromCache, setInCache } from "../cache";
-import type { PKObject } from "../types";
-
-const SPECIAL_DISPLAY_NAMES: Record<string, string> = {
-  answer: "Answer Machine",
-  system: "Unsure",
-  sleeping: "I am sleeping",
-};
-
-async function pkGet<T>(path: string): Promise<T> {
-  const resp = await fetch(`${PLURALKIT_BASE_URL}${path}`, { headers: pluralkitHeaders() });
-  if (!resp.ok) {
-    throw new Error(`PluralKit GET ${path} failed: ${resp.status}`);
-  }
-  return (await resp.json()) as T;
-}
-
-export async function getSystem(): Promise<PKObject> {
-  const cacheKey = "system";
-  const cached = getFromCache<PKObject>(cacheKey);
-  if (cached) return cached;
-
-  const data = await pkGet<PKObject>("/systems/@me");
-  setInCache(cacheKey, data, cacheTtl());
-  return data;
-}
-
-export async function getMembers(): Promise<PKObject[]> {
-  const cacheKey = "members";
-  const cached = getFromCache<PKObject[]>(cacheKey);
-  if (cached) return cached;
-
-  const baseCacheKey = "members_raw";
-  let cachedRaw = getFromCache<PKObject[]>(baseCacheKey);
-  if (!cachedRaw) {
-    cachedRaw = await pkGet<PKObject[]>("/systems/@me/members");
-    setInCache(baseCacheKey, cachedRaw, cacheTtl());
-  }
-
-  const processedMembers: PKObject[] = cachedRaw.map((member) => {
-    const memberName = member.name;
-    if (memberName in SPECIAL_DISPLAY_NAMES) {
-      return {
-        ...member,
-        display_name: SPECIAL_DISPLAY_NAMES[memberName],
-        is_special: true,
-        original_name: memberName,
-      };
-    }
-    return member;
-  });
-
-  setInCache(cacheKey, processedMembers, cacheTtl());
-  return processedMembers;
-}
-
-export async function getFronters(): Promise<PKObject> {
-  const cacheKey = "fronters";
-  const cached = getFromCache<PKObject>(cacheKey);
-  if (cached) return cached;
-
-  const data = await pkGet<PKObject>("/systems/@me/fronters");
-
-  if ("members" in data) {
-    const allMembers = await getMembers();
-    data.members = (data.members as PKObject[]).map(
-      (member) => allMembers.find((m) => m.id === member.id) ?? member,
-    );
-  }
-
-  setInCache(cacheKey, data, cacheTtl());
-  return data;
-}
-
-/** Set the current front. Throws on a non-2xx PluralKit response. */
-export async function setFront(memberIds: string[]): Promise<unknown> {
-  setInCache("fronters", null, 0);
-
-  const resp = await fetch(`${PLURALKIT_BASE_URL}/systems/@me/switches`, {
-    method: "POST",
-    headers: { ...pluralkitHeaders(), "Content-Type": "application/json" },
-    body: JSON.stringify({ members: memberIds }),
-  });
-
-  if (resp.status !== 200 && resp.status !== 204) {
-    const body = await resp.text();
-    throw new Error(`Failed to set front: ${resp.status} - ${body}`);
-  }
-
-  if (resp.status === 204) return null;
-  const text = await resp.text();
-  return text ? JSON.parse(text) : null;
-}
-
-export async function getSwitches(limit = 1000): Promise<PKObject[]> {
-  const cacheKey = `switches_${limit}`;
-  const cached = getFromCache<PKObject[]>(cacheKey);
-  if (cached) return cached;
-
-  const data = await pkGet<PKObject[]>(`/systems/@me/switches?limit=${limit}`);
-  setInCache(cacheKey, data, cacheTtl());
-  return data;
-}
diff --git a/src/system/services/pride.ts b/src/system/services/pride.ts
deleted file mode 100644
index 4cc4537..0000000
--- a/src/system/services/pride.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import type { PKObject } from "../types";
-import { rt } from "../runtime";
-
-type MemberPrideMap = Record<string, string[]>;
-
-const KEY = "member_pride";
-
-const DEFAULT_MEMBER_PRIDE: MemberPrideMap = {};
-
-export async function getMemberPride(): Promise<MemberPrideMap> {
-  const stored = await rt().store.get<MemberPrideMap | null>(KEY, null);
-  if (!stored) {
-    await saveMemberPride(DEFAULT_MEMBER_PRIDE);
-    return { ...DEFAULT_MEMBER_PRIDE };
-  }
-  return stored;
-}
-
-export async function saveMemberPride(memberPride: MemberPrideMap): Promise<void> {
-  await rt().store.put(KEY, memberPride);
-}
-
-export async function getMemberPrideById(
-  memberId: string,
-  memberName: string,
-): Promise<string[]> {
-  const memberPride = await getMemberPride();
-  if (memberName in memberPride) return memberPride[memberName];
-  if (memberId in memberPride) return memberPride[memberId];
-  return [];
-}
-
-export async function updateMemberPride(
-  memberIdentifier: string,
-  identities: string[],
-): Promise<boolean> {
-  const memberPride = await getMemberPride();
-  memberPride[memberIdentifier] = identities;
-  await saveMemberPride(memberPride);
-  return true;
-}
-
-export async function addMemberPride(
-  memberIdentifier: string,
-  identity: string,
-): Promise<boolean> {
-  const memberPride = await getMemberPride();
-  if (!(memberIdentifier in memberPride)) memberPride[memberIdentifier] = [];
-  if (!memberPride[memberIdentifier].includes(identity)) {
-    memberPride[memberIdentifier].push(identity);
-    await saveMemberPride(memberPride);
-    return true;
-  }
-  return false;
-}
-
-export async function removeMemberPride(
-  memberIdentifier: string,
-  identity: string,
-): Promise<boolean> {
-  const memberPride = await getMemberPride();
-  const identities = memberPride[memberIdentifier];
-  if (identities && identities.includes(identity)) {
-    memberPride[memberIdentifier] = identities.filter((one) => one !== identity);
-    await saveMemberPride(memberPride);
-    return true;
-  }
-  return false;
-}
-
-export async function enrichMembersWithPride(members: PKObject[]): Promise<PKObject[]> {
-  const enriched: PKObject[] = [];
-  for (const member of members) {
-    const pride = await getMemberPrideById(member.id ?? "", member.name ?? "");
-    enriched.push({ ...member, pride });
-  }
-  return enriched;
-}
diff --git a/src/system/services/relationships.ts b/src/system/services/relationships.ts
deleted file mode 100644
index 479cd77..0000000
--- a/src/system/services/relationships.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { rt } from "../runtime";
-
-export interface Relationship {
-  id: string;
-  members: [string, string];
-  type: string;
-  since: string | null;
-}
-
-export interface RelationshipInput {
-  memberA: string;
-  memberB: string;
-  type?: string;
-  since?: string | null;
-}
-
-const KEY = "member_relationships";
-
-const DEFAULT_RELATIONSHIPS: Relationship[] = [];
-
-export async function getRelationships(): Promise<Relationship[]> {
-  const stored = await rt().store.get<Relationship[] | null>(KEY, null);
-  if (!stored) {
-    await saveRelationships(DEFAULT_RELATIONSHIPS);
-    return [...DEFAULT_RELATIONSHIPS];
-  }
-  return stored;
-}
-
-export async function saveRelationships(relationships: Relationship[]): Promise<void> {
-  await rt().store.put(KEY, relationships);
-}
-
-export async function addRelationship(input: RelationshipInput): Promise<Relationship> {
-  const relationships = await getRelationships();
-
-  const alreadyLinked = relationships.some(
-    (edge) =>
-      (edge.members[0] === input.memberA && edge.members[1] === input.memberB) ||
-      (edge.members[0] === input.memberB && edge.members[1] === input.memberA),
-  );
-  if (alreadyLinked) {
-    throw new Error("These members are already linked");
-  }
-
-  const relationship: Relationship = {
-    id: crypto.randomUUID(),
-    members: [input.memberA, input.memberB],
-    type: input.type ?? "partner",
-    since: input.since ?? null,
-  };
-
-  relationships.push(relationship);
-  await saveRelationships(relationships);
-  return relationship;
-}
-
-export async function removeRelationship(id: string): Promise<boolean> {
-  const relationships = await getRelationships();
-  const next = relationships.filter((edge) => edge.id !== id);
-  if (next.length === relationships.length) return false;
-  await saveRelationships(next);
-  return true;
-}
diff --git a/src/system/services/sso_sessions.ts b/src/system/services/sso_sessions.ts
deleted file mode 100644
index 82267c9..0000000
--- a/src/system/services/sso_sessions.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * SSO-backed sessions.
- *
- * The JWT the API hands the frontend is stateless, so on its own an account
- * disabled on the SSO would keep working here until the token expired. Each
- * JWT therefore carries a session id (`sid`) that points at one of these
- * records, which holds the SSO refresh token from the login:
- *
- *   - every authenticated request looks the session up, so logout (or the
- *     session expiring) ends the JWT immediately;
- *   - every RECHECK_AFTER_MS the refresh token is spent at the SSO. The SSO
- *     refuses it once the account is disabled, taken out of this app's
- *     allowed groups, or signed out everywhere — and the session ends.
- *
- * The DO is a single instance, so an in-memory map is enough to make
- * concurrent requests on one session share a single refresh; the SSO rotates
- * refresh tokens and treats replays outside a short grace period as theft.
- */
-
-import { randomUrlToken } from "../security";
-import { rt } from "../runtime";
-import { GrantRejectedError, refreshTokens, type SsoTokens } from "./oidc";
-
-const RECHECK_AFTER_MS = 10 * 60 * 1000;
-/** How long sessions survive while the SSO can't be reached. */
-const OUTAGE_GRACE_MS = 60 * 60 * 1000;
-/** Minimum gap between retries while the SSO is unreachable. */
-const RETRY_AFTER_MS = 60 * 1000;
-
-const INDEX_KEY = "sso_sessions_index";
-
-export interface SsoSession {
-  sid: string;
-  userId: string;
-  username: string;
-  refreshToken: string | null;
-  idToken: string | null;
-  createdAt: number;
-  verifiedAt: number;
-  checkedAt: number;
-  expiresAt: number;
-}
-
-interface IndexEntry {
-  sid: string;
-  expiresAt: number;
-}
-
-function sessionKey(sid: string): string {
-  return `sso_session:${sid}`;
-}
-
-/** Drops index entries (and their sessions) that have expired. */
-async function pruneExpired(index: IndexEntry[]): Promise<IndexEntry[]> {
-  const now = Date.now();
-  const live: IndexEntry[] = [];
-  for (const entry of index) {
-    if (entry.expiresAt > now) live.push(entry);
-    else await rt().store.delete(sessionKey(entry.sid));
-  }
-  return live;
-}
-
-export async function createSsoSession(
-  user: { id: string; username: string },
-  tokens: SsoTokens,
-  expiresAt: number,
-): Promise<string> {
-  const sid = randomUrlToken(24);
-  const now = Date.now();
-  const session: SsoSession = {
-    sid,
-    userId: user.id,
-    username: user.username,
-    refreshToken: tokens.refreshToken,
-    idToken: tokens.idToken,
-    createdAt: now,
-    verifiedAt: now,
-    checkedAt: now,
-    expiresAt,
-  };
-  await rt().store.put(sessionKey(sid), session);
-
-  const index = await pruneExpired(await rt().store.get<IndexEntry[]>(INDEX_KEY, []));
-  index.push({ sid, expiresAt });
-  await rt().store.put(INDEX_KEY, index);
-  return sid;
-}
-
-async function readSession(sid: string): Promise<SsoSession | null> {
-  const session = await rt().store.get<SsoSession | null>(sessionKey(sid), null);
-  if (!session) return null;
-  if (session.expiresAt <= Date.now()) {
-    await rt().store.delete(sessionKey(sid));
-    return null;
-  }
-  return session;
-}
-
-const inflight = new Map<string, Promise<SsoSession | null>>();
-
-async function revalidate(session: SsoSession): Promise<SsoSession | null> {
-  const now = Date.now();
-  if (now - session.verifiedAt < RECHECK_AFTER_MS || !session.refreshToken) return session;
-
-  const overdue = now - session.verifiedAt > RECHECK_AFTER_MS + OUTAGE_GRACE_MS;
-  if (now - session.checkedAt < RETRY_AFTER_MS) {
-    if (!overdue) return session;
-    await rt().store.delete(sessionKey(session.sid));
-    return null;
-  }
-
-  const pending = inflight.get(session.sid);
-  if (pending) return pending;
-
-  const task = (async (): Promise<SsoSession | null> => {
-    try {
-      const fresh = await refreshTokens(session.refreshToken!);
-      const at = Date.now();
-      const updated: SsoSession = {
-        ...session,
-        refreshToken: fresh.refreshToken ?? session.refreshToken,
-        idToken: fresh.idToken ?? session.idToken,
-        verifiedAt: at,
-        checkedAt: at,
-      };
-      await rt().store.put(sessionKey(session.sid), updated);
-      return updated;
-    } catch (err) {
-      if (err instanceof GrantRejectedError || overdue) {
-        await rt().store.delete(sessionKey(session.sid));
-        return null;
-      }
-      console.warn(`Could not reach the SSO to re-check a session: ${String(err)}`);
-      const updated = { ...session, checkedAt: Date.now() };
-      await rt().store.put(sessionKey(session.sid), updated);
-      return updated;
-    }
-  })().finally(() => inflight.delete(session.sid));
-
-  inflight.set(session.sid, task);
-  return task;
-}
-
-/** The live session for `sid`, re-checked with the SSO when due. */
-export async function currentSsoSession(sid: string): Promise<SsoSession | null> {
-  const session = await readSession(sid);
-  return session ? revalidate(session) : null;
-}
-
-/** Ends a session here and returns it, so the caller can end it at the SSO too. */
-export async function endSsoSession(sid: string): Promise<SsoSession | null> {
-  const session = await readSession(sid);
-  await rt().store.delete(sessionKey(sid));
-  return session;
-}
diff --git a/src/system/services/status.ts b/src/system/services/status.ts
deleted file mode 100644
index 65c903b..0000000
--- a/src/system/services/status.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import type { PKObject } from "../types";
-import { rt } from "../runtime";
-
-interface MemberStatus {
-  text: string;
-  emoji: string | null;
-  updated_at: string;
-}
-
-type StatusMap = Record<string, MemberStatus>;
-
-const KEY = "member_status";
-
-export async function getAllStatuses(): Promise<StatusMap> {
-  return rt().store.get<StatusMap>(KEY, {});
-}
-
-export async function saveAllStatuses(statuses: StatusMap): Promise<void> {
-  await rt().store.put(KEY, statuses);
-}
-
-export async function getMemberStatus(memberIdentifier: string): Promise<MemberStatus | null> {
-  const statuses = await getAllStatuses();
-  return statuses[memberIdentifier] ?? null;
-}
-
-export async function setMemberStatus(
-  memberIdentifier: string,
-  statusText: string,
-  emoji?: string | null,
-): Promise<MemberStatus> {
-  const statuses = await getAllStatuses();
-  const statusObj: MemberStatus = {
-    text: statusText,
-    emoji: emoji ?? null,
-    updated_at: new Date().toISOString(),
-  };
-  statuses[memberIdentifier] = statusObj;
-  await saveAllStatuses(statuses);
-  return statusObj;
-}
-
-export async function clearMemberStatus(memberIdentifier: string): Promise<boolean> {
-  const statuses = await getAllStatuses();
-  if (memberIdentifier in statuses) {
-    delete statuses[memberIdentifier];
-    await saveAllStatuses(statuses);
-    return true;
-  }
-  return false;
-}
-
-export async function enrichMemberWithStatus(member: PKObject): Promise<PKObject> {
-  const memberId = member.id;
-  const memberName = member.name;
-
-  let status: MemberStatus | null = null;
-  if (memberId) status = await getMemberStatus(String(memberId));
-  if (!status && memberName) status = await getMemberStatus(memberName);
-
-  return { ...member, status };
-}
-
-export async function enrichMembersWithStatus(members: PKObject[]): Promise<PKObject[]> {
-  return Promise.all(members.map((member) => enrichMemberWithStatus(member)));
-}
diff --git a/src/system/services/tags.ts b/src/system/services/tags.ts
deleted file mode 100644
index c6b0408..0000000
--- a/src/system/services/tags.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import type { PKObject } from "../types";
-import { rt } from "../runtime";
-
-type MemberTagsMap = Record<string, string[]>;
-
-const KEY = "member_tags";
-const DEFAULT_MEMBER_TAGS: MemberTagsMap = { C1: ["Host"] };
-
-export async function getMemberTags(): Promise<MemberTagsMap> {
-  const stored = await rt().store.get<MemberTagsMap | null>(KEY, null);
-  if (!stored) {
-    await saveMemberTags(DEFAULT_MEMBER_TAGS);
-    return { ...DEFAULT_MEMBER_TAGS };
-  }
-  return stored;
-}
-
-export async function saveMemberTags(memberTags: MemberTagsMap): Promise<void> {
-  await rt().store.put(KEY, memberTags);
-}
-
-export async function getMemberTagsById(memberId: string, memberName: string): Promise<string[]> {
-  const memberTags = await getMemberTags();
-  if (memberName in memberTags) return memberTags[memberName];
-  if (memberId in memberTags) return memberTags[memberId];
-  return [];
-}
-
-export async function updateMemberTags(memberIdentifier: string, tags: string[]): Promise<boolean> {
-  const memberTags = await getMemberTags();
-  memberTags[memberIdentifier] = tags;
-  await saveMemberTags(memberTags);
-  return true;
-}
-
-export async function addMemberTag(memberIdentifier: string, tag: string): Promise<boolean> {
-  const memberTags = await getMemberTags();
-  if (!(memberIdentifier in memberTags)) memberTags[memberIdentifier] = [];
-  if (!memberTags[memberIdentifier].includes(tag)) {
-    memberTags[memberIdentifier].push(tag);
-    await saveMemberTags(memberTags);
-    return true;
-  }
-  return false;
-}
-
-export async function removeMemberTag(memberIdentifier: string, tag: string): Promise<boolean> {
-  const memberTags = await getMemberTags();
-  const tags = memberTags[memberIdentifier];
-  if (tags && tags.includes(tag)) {
-    memberTags[memberIdentifier] = tags.filter((t) => t !== tag);
-    await saveMemberTags(memberTags);
-    return true;
-  }
-  return false;
-}
-
-export async function enrichMembersWithTags(members: PKObject[]): Promise<PKObject[]> {
-  const enriched: PKObject[] = [];
-  for (const member of members) {
-    const tags = await getMemberTagsById(member.id ?? "", member.name ?? "");
-    enriched.push({ ...member, tags });
-  }
-  return enriched;
-}
diff --git a/src/system/services/users.ts b/src/system/services/users.ts
deleted file mode 100644
index 8d27324..0000000
--- a/src/system/services/users.ts
+++ /dev/null
@@ -1,367 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * User management service.
- *
- * Authentication is the Doughmination SSO (OIDC) only — there are no passwords
- * here. Each account is linked to an SSO subject (`pocket_id` + `sso_issuer`);
- * on first login we match an existing, not-yet-linked account by username and
- * fill in the link, or provision a new non-admin account. Roles (admin/owner/pet), avatars and the owner
- * protections are unchanged. Storage is the DO blob store (key "users").
- */
-
-import type { User, UserCreate, UserUpdate } from "../models";
-import { adminUsername, adminDisplayName, adminEmail } from "../config";
-import { rt } from "../runtime";
-
-const USERS_KEY = "users";
-
-export function getOwnerUsername(): string {
-  return adminUsername();
-}
-
-export function isOwnerUsername(username: string): boolean {
-  return username.toLowerCase() === getOwnerUsername().toLowerCase();
-}
-
-export async function getUsers(): Promise<User[]> {
-  const usersData = await rt().store.get<Array<Record<string, unknown>>>(USERS_KEY, []);
-
-  return usersData.map((userDict) => {
-    if (!("is_owner" in userDict)) userDict.is_owner = false;
-    if (!("is_pet" in userDict)) userDict.is_pet = false;
-
-    if (isOwnerUsername(String(userDict.username ?? ""))) {
-      userDict.is_owner = true;
-      userDict.is_admin = true;
-      userDict.is_pet = true;
-      // The owner account predates the email field. Backfill it from
-      // ADMIN_EMAIL so contact metadata is present; an address already set by
-      // hand always wins.
-      if (!userDict.email) {
-        const seeded = adminEmail();
-        if (seeded) userDict.email = seeded;
-      }
-    }
-    return userDict as unknown as User;
-  });
-}
-
-export async function saveUsers(users: User[]): Promise<void> {
-  for (const user of users) {
-    if (isOwnerUsername(user.username)) {
-      user.is_owner = true;
-      user.is_admin = true;
-      user.is_pet = true;
-      if (!user.email) {
-        const seeded = adminEmail();
-        if (seeded) user.email = seeded;
-      }
-    }
-  }
-  await rt().store.put(USERS_KEY, users);
-}
-
-export async function getUserByUsername(username: string): Promise<User | null> {
-  const users = await getUsers();
-  return users.find((u) => u.username.toLowerCase() === username.toLowerCase()) ?? null;
-}
-
-export async function getUserById(userId: string): Promise<User | null> {
-  const users = await getUsers();
-  return users.find((u) => u.id === userId) ?? null;
-}
-
-export async function getUserBySub(sub: string, issuer: string): Promise<User | null> {
-  if (!sub) return null;
-  const users = await getUsers();
-  return users.find((u) => u.pocket_id === sub && u.sso_issuer === issuer) ?? null;
-}
-
-export function normalizeEmail(email: string): string {
-  return email.trim().toLowerCase();
-}
-
-export async function getUserByEmail(email: string): Promise<User | null> {
-  const target = normalizeEmail(email);
-  if (!target) return null;
-  const users = await getUsers();
-  return users.find((u) => u.email && normalizeEmail(u.email) === target) ?? null;
-}
-
-/** Throw if `email` is already used by a different account. */
-async function assertEmailAvailable(email: string, exceptUserId?: string): Promise<void> {
-  const target = normalizeEmail(email);
-  const users = await getUsers();
-  const clash = users.find(
-    (u) => u.id !== exceptUserId && u.email && normalizeEmail(u.email) === target,
-  );
-  if (clash) throw new Error("Email address is already in use");
-}
-
-export async function createUser(
-  userCreate: UserCreate,
-  requestingUser?: User | null,
-): Promise<User> {
-  const users = await getUsers();
-
-  if (await getUserByUsername(userCreate.username)) {
-    throw new Error(`Username '${userCreate.username}' already exists`);
-  }
-
-  if (isOwnerUsername(userCreate.username) && requestingUser != null) {
-    throw new Error(
-      "Cannot create user with owner username. Owner account must be created via initial setup.",
-    );
-  }
-
-  let isOwner: boolean;
-  let isAdmin: boolean;
-  let isPet: boolean;
-
-  if (isOwnerUsername(userCreate.username)) {
-    isOwner = true;
-    isAdmin = true;
-    isPet = false;
-  } else {
-    isOwner = false;
-    isAdmin = userCreate.is_admin;
-    isPet = userCreate.is_pet;
-  }
-
-  const email = userCreate.email ? normalizeEmail(userCreate.email) : null;
-  if (email) await assertEmailAvailable(email);
-
-  const newUser: User = {
-    id: crypto.randomUUID(),
-    username: userCreate.username,
-    pocket_id: userCreate.pocket_id ?? null,
-    display_name: userCreate.display_name ?? null,
-    email,
-    created_at: new Date().toISOString(),
-    is_admin: isAdmin,
-    is_owner: isOwner,
-    is_pet: isPet,
-    avatar_url: null,
-  };
-
-  users.push(newUser);
-  await saveUsers(users);
-  return newUser;
-}
-
-/**
- * Resolve an SSO login to a local account.
- *
- * Match order:
- *   1. the account already linked to this subject on this issuer;
- *   2. an account pre-provisioned with this subject but no issuer yet;
- *   3. by username (case-insensitive), but ONLY an account that isn't linked
- *      to this issuer yet — the owner seed, admin-provisioned accounts, and
- *      accounts from the PocketID days. Each such account is adopted once.
- *
- * An account already linked to a *different* subject on this issuer is never
- * taken over by username, so a reused or renamed SSO username can't inherit
- * someone else's account (including the owner's). Unknown users are
- * auto-provisioned as non-admins.
- */
-export async function findOrCreateFromSso(claims: {
-  sub: string;
-  issuer: string;
-  username: string;
-  email?: string | null;
-  displayName?: string | null;
-}): Promise<User> {
-  const users = await getUsers();
-  const sameName = (u: User) => u.username.toLowerCase() === claims.username.toLowerCase();
-
-  const linked = users.find((u) => u.pocket_id === claims.sub && u.sso_issuer === claims.issuer);
-  const preLinked = users.find((u) => u.pocket_id === claims.sub && !u.sso_issuer);
-  const byName = users.find((u) => sameName(u) && u.sso_issuer !== claims.issuer);
-  const existing = linked ?? preLinked ?? byName;
-
-  if (!existing && users.some(sameName)) {
-    throw new Error(
-      `The username '${claims.username}' here is linked to a different SSO account. Ask the owner to sort it out.`,
-    );
-  }
-
-  if (existing) {
-    const index = users.findIndex((u) => u.id === existing.id);
-    let changed = false;
-
-    if (existing.pocket_id !== claims.sub || existing.sso_issuer !== claims.issuer) {
-      console.info(`Linking account '${existing.username}' to ${claims.issuer} subject ${claims.sub}`);
-      existing.pocket_id = claims.sub;
-      existing.sso_issuer = claims.issuer;
-      changed = true;
-    }
-    // Backfill contact/profile metadata from the provider if we don't have it.
-    if (!existing.email && claims.email) {
-      existing.email = normalizeEmail(claims.email);
-      changed = true;
-    }
-    if (!existing.display_name && claims.displayName) {
-      existing.display_name = claims.displayName;
-      changed = true;
-    }
-
-    if (changed) {
-      users[index] = existing;
-      await saveUsers(users);
-    }
-    return existing;
-  }
-
-  // First-time login for an unknown SSO user → provision a plain account.
-  const created = await createUser({
-    username: claims.username,
-    pocket_id: claims.sub,
-    email: claims.email ?? null,
-    display_name: claims.displayName ?? null,
-    is_admin: false,
-    is_pet: false,
-  });
-  return linkIssuer(created.id, claims.issuer);
-}
-
-async function linkIssuer(userId: string, issuer: string): Promise<User> {
-  const users = await getUsers();
-  const index = users.findIndex((u) => u.id === userId);
-  users[index] = { ...users[index], sso_issuer: issuer };
-  await saveUsers(users);
-  return users[index];
-}
-
-export async function updateUser(
-  userId: string,
-  userUpdate: UserUpdate,
-  requestingUser?: User | null,
-): Promise<User | null> {
-  const users = await getUsers();
-
-  const index = users.findIndex((u) => u.id === userId);
-  if (index === -1) return null;
-
-  const user = users[index];
-
-  if (user.is_owner && userUpdate.is_admin === false) {
-    throw new Error("Cannot remove admin privileges from owner");
-  }
-
-  if (requestingUser && user.is_admin && requestingUser.id !== user.id) {
-    if (!requestingUser.is_owner) {
-      throw new Error("Only the owner can modify admin accounts");
-    }
-  }
-
-  // Role assignment (admin/pet) is the owner's job — plain admins can edit
-  // profiles but not grant or revoke roles.
-  const wantsAdminChange = userUpdate.is_admin != null && userUpdate.is_admin !== user.is_admin;
-  const wantsPetChange = userUpdate.is_pet != null && userUpdate.is_pet !== user.is_pet;
-  if ((wantsAdminChange || wantsPetChange) && !requestingUser?.is_owner) {
-    throw new Error("Only the owner can change user roles");
-  }
-
-  // ---- Email (contact metadata only) ------------------------------------
-  // Editable by the account's own user or by an admin/owner. Identity is
-  // proven by the SSO, so there is no confirmation step.
-  let email = user.email ?? null;
-  if (userUpdate.email !== undefined) {
-    const requestedEmail = userUpdate.email ? normalizeEmail(userUpdate.email) : null;
-    const isSelf = requestingUser?.id === user.id;
-    const isAdminActing = !!requestingUser?.is_admin;
-
-    if (requestedEmail !== email) {
-      if (!isSelf && !isAdminActing) {
-        throw new Error("You can only change your own email address");
-      }
-      if (requestedEmail) await assertEmailAvailable(requestedEmail, user.id);
-      email = requestedEmail;
-    }
-  }
-
-  const newIsOwner = isOwnerUsername(user.username);
-  const newIsAdmin = newIsOwner ? true : userUpdate.is_admin ?? user.is_admin;
-  const newIsPet = userUpdate.is_pet ?? user.is_pet;
-
-  const updatedUser: User = {
-    id: user.id,
-    username: user.username,
-    pocket_id: user.pocket_id ?? null,
-    sso_issuer: user.sso_issuer ?? null,
-    // `undefined` = field omitted, keep current value; explicit `null` clears it.
-    display_name: userUpdate.display_name !== undefined ? userUpdate.display_name : user.display_name,
-    email,
-    created_at: user.created_at ?? null,
-    is_admin: newIsAdmin,
-    is_owner: newIsOwner,
-    is_pet: newIsPet,
-    avatar_url: userUpdate.avatar_url !== undefined ? userUpdate.avatar_url : user.avatar_url ?? null,
-  };
-
-  users[index] = updatedUser;
-  await saveUsers(users);
-  return updatedUser;
-}
-
-export async function deleteUser(userId: string, requestingUser?: User | null): Promise<boolean> {
-  const users = await getUsers();
-
-  const userToDelete = users.find((u) => u.id === userId);
-  if (!userToDelete) return false;
-
-  if (userToDelete.is_owner) {
-    throw new Error("Cannot delete the owner account");
-  }
-
-  if (requestingUser && userToDelete.is_admin && !requestingUser.is_owner) {
-    throw new Error("Only the owner can delete admin accounts");
-  }
-
-  const remaining = users.filter((u) => u.id !== userId);
-  if (remaining.length < users.length) {
-    await saveUsers(remaining);
-    return true;
-  }
-  return false;
-}
-
-/**
- * Seed the owner account from ADMIN_* env vars if no users exist yet.
- *
- * The account has no password — it becomes usable the first time the owner
- * signs in through the SSO with a matching `preferred_username`, at which
- * point its SSO link is filled in automatically (see findOrCreateFromSso).
- * Runs lazily on first request.
- */
-export async function initializeAdminUser(): Promise<void> {
-  const users = await getUsers();
-  if (users.length > 0) return;
-
-  const username = adminUsername();
-  const displayName = adminDisplayName();
-
-  try {
-    const newUser: User = {
-      id: crypto.randomUUID(),
-      username,
-      pocket_id: null,
-      display_name: displayName,
-      email: adminEmail() ?? null,
-      created_at: new Date().toISOString(),
-      is_admin: true,
-      is_owner: true,
-      is_pet: false,
-      avatar_url: null,
-    };
-    await saveUsers([newUser]);
-    console.info(`Seeded owner user: ${username}`);
-  } catch (err) {
-    console.error(`Error creating owner user: ${String(err)}`);
-  }
-}
diff --git a/src/system/types.ts b/src/system/types.ts
index 9305949..17f42e9 100644
--- a/src/system/types.ts
+++ b/src/system/types.ts
@@ -5,12 +5,11 @@
  */
 
 /**
- * Environment bindings + secrets consumed by the Doughmination system API.
+ * Environment bindings + secrets consumed by the devices / guestbook / counter API.
  *
  * These are a subset of the Worker's full `Env` (see ../types.ts) — the
  * SystemState DO receives the same env object the Worker does. All auth
- * keys are now set MANUALLY (secrets / vars); nothing is generated on
- * first run any more.
+ * keys are set MANUALLY (secrets / vars).
  */
 export interface SystemEnv {
   // ---- Durable Object bindings -------------------------------------------
@@ -20,50 +19,15 @@ export interface SystemEnv {
    *  /v2/ws hub, so it pulls presence snapshots from here for INIT_STATE and
    *  receives live PRESENCE_UPDATE relays from it. */
   GATEWAY: DurableObjectNamespace;
+  /** The system site Worker (doughmination.co.uk). Guestbook moderation
+   *  checks admin tokens against it. */
+  SITE: Fetcher;
 
-  // ---- PluralKit ---------------------------------------------------------
-  /** PluralKit system token (Authorization header for api.pluralkit.me). */
-  SYSTEM_TOKEN?: string;
-  /** Seconds to cache PluralKit responses in-memory. Default 30. */
-  CACHE_TTL?: string;
-
-  // ---- Auth --------------------------------------------------------------
-  /** HMAC secret for signing the JWT the API issues after an SSO login.
-   *  REQUIRED in production. */
-  JWT_SECRET?: string;
+  // ---- Secrets -------------------------------------------------------------
   /** Cloudflare Turnstile secret (public guestbook captcha). */
   TURNSTILE_SECRET?: string;
   /** Back-compat alias for the original (typo'd) env name. */
   TURNSILE_SECRET?: string;
-
-  // ---- Doughmination SSO (OIDC) — the only login method -----------------
-  /** Issuer origin, e.g. https://auth.doughmination.gay (no trailing slash). */
-  SSO_ISSUER?: string;
-  /** OIDC client id of this API's application on the SSO. */
-  SSO_CLIENT_ID?: string;
-  /** OIDC client secret — set with `wrangler secret put SSO_CLIENT_SECRET`. */
-  SSO_CLIENT_SECRET?: string;
-  /** Registered redirect URI. Defaults to
-   *  `${BASE_URL}/v2/plural/auth/sso/callback`. */
-  SSO_REDIRECT_URI?: string;
-  /** Space-separated scopes. Defaults to "openid profile email offline_access". */
-  SSO_SCOPES?: string;
-  /** Frontend page the callback hands the minted JWT to (in the URL fragment).
-   *  Defaults to `${FRONTEND_URL}/user/login/callback`. */
-  SSO_POST_LOGIN_URL?: string;
-  /** Where the SSO sends the browser after logout. Defaults to `${FRONTEND_URL}/`. */
-  SSO_POST_LOGOUT_REDIRECT_URI?: string;
-
-  // ---- Initial owner seed (only used when no users exist yet) ------------
-  ADMIN_USERNAME?: string;
-  ADMIN_DISPLAY_NAME?: string;
-  /** Owner's contact email. Backfilled onto the owner account on read if it
-   *  doesn't have one yet. */
-  ADMIN_EMAIL?: string;
-
-  // ---- Manual API keys (replaces generate-on-first-run) ------------------
-  /** Static bearer token the Discord bot uses for /api/bot/*. */
-  DOUGH_BOT_TOKEN?: string;
   /** Comma-separated device battery-report keys (X-Battery-Key header). */
   BATTERY_API_KEYS?: string;
   /** Comma-separated guestbook moderation keys (X-Guestbook-Key header). */
@@ -80,7 +44,3 @@ export interface SystemEnv {
    *  leaves the counter open, so any well-formed id registers on first hit. */
   COUNTER_SITE_IDS?: string;
 }
-
-/** A member object from PluralKit is large and loosely typed upstream. */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export type PKObject = Record<string, any>;
diff --git a/src/types.ts b/src/types.ts
index e569ee6..14f828d 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -5,16 +5,11 @@ export interface Env {
   PROFILE_CACHE: KVNamespace;
   ASSETS?: Fetcher;
   SYSTEM: DurableObjectNamespace;
+  /** The system site Worker; guestbook moderation checks admin tokens against it. */
+  SITE: Fetcher;
 
-  SYSTEM_TOKEN?: string;
-  CACHE_TTL?: string;
-  JWT_SECRET?: string;
   TURNSTILE_SECRET?: string;
   TURNSILE_SECRET?: string;
-  ADMIN_USERNAME?: string;
-  ADMIN_PASSWORD?: string;
-  ADMIN_DISPLAY_NAME?: string;
-  DOUGH_BOT_TOKEN?: string;
   BATTERY_API_KEYS?: string;
   GUESTBOOK_ADMIN_KEYS?: string;
   BASE_URL?: string;
diff --git a/wrangler.jsonc b/wrangler.jsonc
index cfd19d4..f61cb8e 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -50,6 +50,13 @@
 		"html_handling": "none",
 		"not_found_handling": "none"
 	},
+	// The system site Worker. Guestbook moderation checks admin tokens against it
+	"services": [
+		{
+			"binding": "SITE",
+			"service": "doughmination-system"
+		}
+	],
 	"triggers": {
 		"crons": [
 			"*/2 * * * *"
@@ -69,22 +76,10 @@
 		"REVIEWDB_API_BASE": "https://manti.vendicated.dev/api/reviewdb",
 		"REVIEWDB_MAX": "25",
 
-		"CACHE_TTL": "30",
-		"ADMIN_USERNAME": "clove",
-		"ADMIN_DISPLAY_NAME": "Administrator",
-		"ADMIN_EMAIL": "[email protected]",
 		"BASE_URL": "https://doughmination.uk",
 		"CORS_ORIGINS": "",
 		"COUNTER_SITE_IDS": "is.doughmination.gay",
 		"FRONTEND_URL": "https://doughmination.co.uk",
 
-		// ---- Doughmination SSO (auth-server) -----
-		// Secrets: wrangler secret put SSO_CLIENT_ID / SSO_CLIENT_SECRET
-		"SSO_ISSUER": "https://auth.doughmination.gay",
-		"SSO_REDIRECT_URI": "https://doughmination.uk/v2/plural/auth/sso/callback",
-		"SSO_SCOPES": "openid profile email offline_access",
-		"SSO_POST_LOGIN_URL": "https://doughmination.co.uk/user/login/callback",
-		"SSO_POST_LOGOUT_REDIRECT_URI": "https://doughmination.co.uk/",
-
 	}
 }