Dough Git

commit

MAOW

commit
22a5405cd483bf506900541ebe4468f74943a46b
author
Clove Twilight <[email protected]>
date
2026-07-16 10:50

diff --git a/README.md b/README.md
index 849fd34..2c93333 100644
--- a/README.md
+++ b/README.md
@@ -1,34 +1,46 @@
-# API
+# Doughmination API (`restful`)
 
-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). Everything returns one unified JSON shape, 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 the Doughmination plural-system API (fronting, members, mental state, devices, guestbook), Minecraft/Hypixel 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
+- **Licence:** ESAL-2.1 — see [LICENCE.md](LICENCE.md)
 
 ## Thanks
-This code wasn't just me. It took a good chunk of my own brain plus a lot of
-help from Dustin (@dstn.to), who was really generous explaining how he handles
-the tricky parts: rate limits, caching, and getting Discord to actually trust
-your requests. Thanks Dustin! And credit to Phineas for Lanyard, which inspired
-the presence half of this.
 
-## What's in here
+This code wasn't just me. It took a good chunk of my own brain plus a lot of help from Dustin (@dstn.to), who was really generous explaining how he handles the tricky parts: rate limits, caching, and getting Discord to actually trust your requests. Thanks Dustin! And credit to Phineas for Lanyard, which inspired the presence half of this.
+
+## Architecture
 
 Two Durable Objects behind the Worker router (`src/index.ts`):
 
 - **GATEWAY** (`GatewayManager`) — holds the single Discord gateway socket, ingests presences from `READY` / `GUILD_CREATE` / `PRESENCE_UPDATE`, and keeps an in-memory `userId → presence` map. It doesn't serve browser sockets; it relays each live presence change to the SYSTEM DO for fan-out.
-- **SYSTEM** (`SystemState`) — the old backend as one object: all persistent state (users, tags, statuses, mental state, devices) in DO storage, the visitor-log SQLite table, and the single realtime WebSocket hub.
+- **SYSTEM** (`SystemState`) — all persistent state (users, tags, statuses, mental state, devices) in DO storage, the visitor-log SQLite table, and the single realtime WebSocket hub.
+
+A cron trigger (`*/2 * * * *`) keeps the gateway DO connected. Static assets under `assets/` are served at the site root (`/icon.png`, `/capes/*`, …).
 
-### Endpoints (all under `/v2`)
+## Endpoints
 
-- `/v2/ws` — **the one WebSocket** for all live updates (see below).
-- `/v2/lanyard/users`, `/v2/lanyard/users/:id`, `/v2/lanyard/status` — REST presence.
-- `/v2/discord/users/:id`, `/v2/discord/users?ids=…`, `/v2/discord/guilds/:invite`, `/v2/discord/girls/:idType/:id` — profiles, badges, guild/role info.
-- `/v2/minecraft/general/:uuid`, `/v2/minecraft/hypixel/:uuid`, `/v2/minecraft/capes` — Mojang + Hypixel.
-- `/v2/contribapi` — merged git contribution heatmaps.
-- `/v2/plural/*`, `/v2/devices/*`, `/v2/guestbook/*`, `/v2/system-data/*` — the plural system API.
-- `/docs` — full HTML API reference.
+Full, filterable reference at [`/docs`](https://doughmination.uk/docs). The map:
+
+| Namespace | What it serves |
+|---|---|
+| `WS /v2/ws` | **The one WebSocket** for all live updates (see below) |
+| `/v2/lanyard/users`, `/v2/lanyard/users/:id`, `/v2/lanyard/status` | REST presence (single, batch up to 100, gateway health) |
+| `/v2/discord/users/:id`, `/v2/discord/users?ids=…` | Full profile + badges + live presence, single or batch |
+| `/v2/discord/guilds/:invite`, `/v2/discord/girls/:idType/:id` | Guild info from an invite; role/member lookups |
+| `/v2/minecraft/general/:uuid`, `/v2/minecraft/hypixel/:uuid`, `/v2/minecraft/capes` | Mojang identity + skins/capes, Hypixel stats, vanilla cape catalogue |
+| `/v2/contribapi` | Merged git contribution heatmaps (GitHub + Codeberg) |
+| `/v2/plural/*`, `/v2/devices/*`, `/v2/guestbook/*`, `/v2/system-data/*` | The plural-system API: fronting, members, mental state, devices/battery, guestbook, visitor logs |
+| `/v2/health` | Liveness: gateway connection + DO reachability (200 ok / 503 degraded) — point uptime monitors here |
+| `/docs`, `/openapi.json` | Full HTML API reference + machine-readable OpenAPI 3.1 spec (both generated from `src/apidata.ts`) |
+| `/abuse`, `/terms`, `/privacy`, `/.well-known/security.txt` | Abuse reports, terms of service, privacy, vulnerability disclosure |
+
+All JSON responses share one envelope: `{ success, data }` on success, `{ success: false, error: { code, message } }` on failure.
 
 ## Realtime — the single `/v2/ws`
 
-There's exactly **one** socket now (the old `/v2/lanyard/ws` and `/v2/plural/ws` are gone). Every frame is a `{ type, data }` object.
+There's exactly **one** socket (the old `/v2/lanyard/ws` and `/v2/plural/ws` are gone). Every frame is a `{ type, data }` object.
 
 On connect you get `connection_established`. These are then pushed to **every** client automatically as they happen:
 
@@ -50,24 +62,32 @@ Presence lives in the GATEWAY DO; when it changes, GATEWAY relays it to SYSTEM,
 
 ## Caching
 
-See the notes in each source file, but the short version:
+See the notes in each source file; the short version:
+
+| Data | Where | TTL |
+|---|---|---|
+| Presence | GATEWAY DO memory | never cached — live from the gateway |
+| PluralKit data (system, members, fronters) | SYSTEM DO memory | `CACHE_TTL` (default **30s**), busted on any switch/member/tag/status change |
+| Discord profiles | KV (`PROFILE_CACHE`) | `PROFILE_CACHE_TTL_SECONDS` (default **300s**, min 60), jittered ±20%; rich (userbot) fetches back off on 429 via a shared cooldown key (30–300s) |
+| Guild invites | KV | **300s** |
+| Guild memberships | KV | **6h** |
+| Client-mod badges (Equicord) | KV | **1h**, stale fallback |
+| Minecraft general + Hypixel | KV | **5min**; vanilla-cape registry kept permanently |
 
-- **Presence is never cached** — it's live from the Discord gateway, held in memory in the GATEWAY DO and pushed over the socket in real time.
-- **PluralKit data** (system, members, fronters) — in-memory in the SYSTEM DO, `CACHE_TTL` seconds (default **30s**). Busted immediately on any switch / member / tag / status change.
-- **Discord profiles** — KV (`PROFILE_CACHE`), `PROFILE_CACHE_TTL_SECONDS` (default **300s**, min 60), jittered ±20% so batches don't all expire at once. Rich (userbot) fetches back off on a 429 via a shared cooldown key (30–300s).
-- **Guild invites** — KV, **300s**. **Memberships** — KV, **6h**. **Client-mod badges** (Equicord) — KV, **1h** with stale fallback. **Minecraft** general + Hypixel — KV, **5min**; the vanilla-cape registry is kept **permanently**.
-- **HTTP `Cache-Control`** — JSON API responses are `no-store` (never edge/browser cached). `/docs` and `/v2/contribapi` are `public, max-age=3600` (1h).
+HTTP `Cache-Control`: JSON API responses are `no-store` (never edge/browser cached). HTML pages (`/docs`, `/abuse`, `/terms`, `/privacy`), `/openapi.json`, and `/v2/contribapi` are `public, max-age=3600`. All responses carry security headers (HSTS, nosniff; CSP + frame-deny on HTML).
 
 ## Setup
 
-### 1. Settings
+### 1. Discord application
+
 1. https://discord.com/developers/applications → **New Application** → **Bot**.
 2. **Reset Token**, copy it (this is `DISCORD_BOT_TOKEN`).
 3. Under **Privileged Gateway Intents**, enable **PRESENCE INTENT** and **SERVER MEMBERS INTENT**.
 4. Invite the bot to a server that contains the people you want to track (OAuth2 URL generator → scope `bot`). Presence is only visible for users sharing a server with the bot — same model as Lanyard.
-5. Optionally set `TRACKED_GUILD_IDS` in `wrangler.jsonc` (comma-separated) to limit monitoring to specific servers; empty = every guild the bots can see.
+5. Optionally set `TRACKED_GUILD_IDS` in `wrangler.jsonc` (comma-separated) to limit monitoring to specific servers; empty = every guild the bot can see.
+
+### 2. Install & deploy
 
-### 2. Commands
 ```bash
 # REQUIRED
 bun install
@@ -79,17 +99,48 @@ bunx wrangler kv namespace create PROFILE_CACHE
 bunx wrangler secret put DISCORD_BOT_TOKEN
 # Optional, ToS risk — only if you want the rich badges:
 bunx wrangler secret put DISCORD_USER_TOKEN
-# Optional second userbot
+# Optional 2nd/3rd userbot:
 bunx wrangler secret put DISCORD_USER_TOKEN2
-# Optional 3rd userbot
 bunx wrangler secret put DISCORD_USER_TOKEN3
 
-# If you need to update the X-Super-Properties to latest version
-bun decode "X-Super-Properties: [BASE64 HERE]"
-
-# Local test
+# Local dev (uses .dev.vars — see .dev.vars.example)
 bun dev
 
 # Production
 bun deploy
 ```
+
+Other secrets for the plural-system half (`JWT_SECRET`, `SYSTEM_TOKEN`, `TURNSTILE_SECRET`, `ADMIN_PASSWORD`, `DOUGH_BOT_TOKEN`, `BATTERY_API_KEYS`) go in `.dev.vars` locally and `wrangler secret put <NAME>` in production — `.dev.vars.example` documents all of them.
+
+### 3. Useful commands
+
+```bash
+bun typecheck   # tsc --noEmit
+bun tail        # live production logs
+# Update X-Super-Properties when Discord bumps the client build:
+bun decode "X-Super-Properties: [BASE64 HERE]"
+```
+
+### Configuration (`wrangler.jsonc` vars)
+
+| Var | Purpose |
+|---|---|
+| `TRACKED_GUILD_IDS` | Comma-separated guilds to monitor; empty = all the bot sees |
+| `MEMBERSHIP_GUILD_IDS` | Guilds to resolve per-user membership for; falls back to `TRACKED_GUILD_IDS` |
+| `PROFILE_CACHE_TTL_SECONDS` | Profile KV cache TTL (min 60) |
+| `CACHE_TTL` | PluralKit cache TTL in seconds |
+| `DISCORD_CLIENT_BUILD_NUMBER` | For userbot `X-Super-Properties` (update with `bun decode`) |
+| `PRONOUNDB_API_BASE`, `TIMEZONE_API_BASE`, `REVIEWDB_API_BASE` | Third-party enrichment sources, overridable for self-hosted forks |
+| `BASE_URL`, `CORS_ORIGINS` | Plural-system base URL and CORS allowlist |
+
+## Abuse, privacy & security
+
+- **Terms:** [`/terms`](https://doughmination.uk/terms) — the short version: be reasonable with request volume or your IP gets blocked.
+- **Privacy:** [`/privacy`](https://doughmination.uk/privacy) — what's logged (visitor IPs, guestbook entries, brief Discord/Minecraft caches) and how to get it removed.
+- **Report abuse / request data removal:** [`/abuse`](https://doughmination.uk/abuse) or email **[email protected]**.
+- **Opt out of presence tracking:** leave the Discord server(s) the bot is in, or email with your Discord user ID to be blocked from lookups.
+- **Vulnerability disclosure:** email the address above; machine-readable contact at [`/.well-known/security.txt`](https://doughmination.uk/.well-known/security.txt). Responsible disclosure appreciated.
+
+## Licence
+
+[ESAL-2.1](LICENCE.md).
diff --git a/src/abuse.ts b/src/abuse.ts
new file mode 100644
index 0000000..fa0475b
--- /dev/null
+++ b/src/abuse.ts
@@ -0,0 +1,104 @@
+/* =====================================================================
+ * abuse.ts — the /abuse page + /.well-known/security.txt.
+ *
+ * Self-contained HTML (same Catppuccin Mocha look as /docs, no deps).
+ * Covers abuse reports, acceptable use, privacy / opt-out, takedowns,
+ * and vulnerability disclosure. Keep ABUSE_CONTACT in sync everywhere.
+ * ===================================================================== */
+
+export const ABUSE_CONTACT = "[email protected]";
+
+/** RFC 9116 security.txt. Expires is generated per-request (must be < 1 year
+ *  out), so this is a function rather than a constant. */
+export function securityTxt(origin: string): string {
+  const expires = new Date(Date.now() + 180 * 24 * 60 * 60 * 1000); // ~6 months
+  return [
+    `Contact: mailto:${ABUSE_CONTACT}`,
+    `Expires: ${expires.toISOString()}`,
+    `Preferred-Languages: en`,
+    `Canonical: ${origin}/.well-known/security.txt`,
+    `Policy: ${origin}/abuse`,
+    "",
+  ].join("\n");
+}
+
+export const ABUSE_HTML = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<link rel="icon" type="image/png" href="/icon.png" />
+<title>Abuse & contact — Doughmination API</title>
+<style>
+  :root {
+    color-scheme: dark;
+    --base: #1e1e2e; --mantle: #181825; --surface0: #313244; --surface1: #45475a;
+    --surface2: #585b70; --subtext0: #a6adc8; --subtext1: #bac2de; --text: #cdd6f4;
+    --pink: #f5c2e7; --red: #f38ba8; --green: #a6e3a1; --blue: #89b4fa;
+    --bg: var(--base); --line: var(--surface2); --fg: var(--text); --muted: var(--subtext0);
+    --mono: ui-monospace, SFMono-Regular, Menlo, monospace; --accent: var(--pink);
+  }
+  * { box-sizing: border-box; }
+  body { margin: 0; font: 15px/1.65 system-ui, sans-serif; background: var(--bg); color: var(--fg); }
+  header { padding: 24px 20px 14px; border-bottom: 1px solid var(--line); }
+  .inner { max-width: 720px; margin: 0 auto; }
+  h1 { margin: 0 0 4px; font-size: 21px; }
+  header p { margin: 0; color: var(--subtext0); font-size: 13.5px; }
+  main { max-width: 720px; margin: 0 auto; padding: 20px; }
+  h2 { font-size: 16.5px; margin: 28px 0 8px; }
+  p, li { color: var(--subtext1); font-size: 14.5px; }
+  ul { padding-left: 22px; margin: 8px 0; }
+  a { color: var(--accent); }
+  code { font: 12.5px var(--mono); background: var(--mantle); color: var(--pink); padding: 1px 5px; border-radius: 4px; border: 1px solid var(--line); }
+  .card { border: 1px solid var(--line); background: var(--surface0); border-radius: 10px; padding: 14px 16px; margin: 14px 0; }
+  .card strong { color: var(--fg); }
+  .back { font-size: 13.5px; }
+  ::selection { background: rgba(245,194,231,.28); }
+</style>
+</head>
+<body>
+<header><div class="inner">
+  <h1>Abuse &amp; contact</h1>
+  <p>How to report abuse, request data removal, or disclose a vulnerability. <a class="back" href="/docs">← API reference</a></p>
+</div></header>
+<main>
+
+<div class="card">
+  <strong>Contact:</strong> <a href="mailto:${ABUSE_CONTACT}">${ABUSE_CONTACT}</a><br />
+  Reports are usually answered within a few days. This is a small, personally-run service — please be patient.
+</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 (Lanyard-style), Minecraft skin/Hypixel lookups, a public guestbook, and the Doughmination plural-system API. It only tracks Discord users who share a server with its bot, the same model as Lanyard.</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>
+<ul>
+  <li>Harassment, spam, or illegal content in the public guestbook</li>
+  <li>Impersonation, or profile/presence data being used to stalk or harass someone</li>
+  <li>Content that infringes your rights (copyright, trademark, personal data)</li>
+  <li>Abusive automated traffic originating from or targeting this API</li>
+</ul>
+<p>Please include: the full URL(s) involved, what the problem is, timestamps if relevant, and how to reach you. For guestbook entries, the entry text or its position in the list is enough — every entry has a deletable ID on our side.</p>
+
+<h2>Privacy &amp; data removal (opt-out)</h2>
+<p>If your Discord presence or profile appears on this API and you want it gone:</p>
+<ul>
+  <li>Leaving the Discord server(s) the tracking bot is in removes your live presence automatically.</li>
+  <li>For anything else — cached profile data, guestbook entries you posted, or a block on future lookups of your account — email <a href="mailto:${ABUSE_CONTACT}">${ABUSE_CONTACT}</a> with your Discord user ID and it will be removed.</li>
+</ul>
+<p>Profile caches expire on their own within hours; presence is never stored beyond live memory.</p>
+
+<h2>Security vulnerabilities</h2>
+<p>Found a vulnerability? Email <a href="mailto:${ABUSE_CONTACT}">${ABUSE_CONTACT}</a> with reproduction steps. Please practise responsible disclosure: no destructive testing, no accessing other people's data, and give a reasonable window to fix before publishing. Machine-readable details live at <a href="/.well-known/security.txt"><code>/.well-known/security.txt</code></a>.</p>
+
+<h2>Acceptable use</h2>
+<p>The public endpoints are free to use, but don't hammer them: batch endpoints exist so 100 users cost one request, JSON responses are intentionally <code>no-store</code>, and abusive traffic gets blocked at the edge. Don't use this API to build harassment, stalking, or mass-surveillance tooling — that's grounds for an immediate block and a report to the relevant platform.</p>
+
+</main>
+<footer style="max-width:720px;margin:0 auto;padding:8px 20px 28px;font-size:13px;color:var(--muted)">
+  <a href="/docs">API reference</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a>
+</footer>
+</body>
+</html>
+`;
diff --git a/src/apidata.ts b/src/apidata.ts
new file mode 100644
index 0000000..97a28fc
--- /dev/null
+++ b/src/apidata.ts
@@ -0,0 +1,270 @@
+/* =====================================================================
+ * apidata.ts — the single source of truth for the endpoint catalogue.
+ *
+ * Consumed by docs.ts (rendered client-side on /docs) and openapi.ts
+ * (converted to the /openapi.json spec). Keep this in sync when routes
+ * change — nothing else needs editing.
+ * ===================================================================== */
+
+export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "WS";
+export type AuthKind = "public" | "auth" | "admin" | "owner" | "pet" | "jwt" | "bot" | "key";
+
+export interface EndpointDef {
+  m: HttpMethod;
+  path: string;
+  auth: AuthKind;
+  desc: string;
+  /** [name, description] pairs; names starting with "?" are query params. */
+  params?: [string, string][];
+  example?: string;
+  note?: string;
+  /** True when the path is at the site root rather than under /v2. */
+  root?: boolean;
+}
+
+export interface GroupDef {
+  id: string;
+  name: string;
+  blurb: string;
+  endpoints: EndpointDef[];
+}
+
+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." },
+      { 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>'." },
+    ],
+  },
+  {
+    id: "lanyard", name: "Lanyard — live presence", blurb: "Real-time Discord presence.",
+    endpoints: [
+      { m: "GET", path: "/lanyard/users/:id", auth: "public",
+        desc: "A user's live presence: online status, current activities, Spotify, and which platforms they're on (desktop/mobile/web). Returns 404 if the user doesn't share a tracked server with the bot.",
+        params: [["id", "Discord user ID."]] },
+      { m: "GET", path: "/lanyard/users?ids=a,b,c", auth: "public",
+        desc: "Live presence for up to 100 users at once. Returns a map of user ID → presence (or null).",
+        params: [["ids", "Comma-separated Discord user IDs, max 100."]] },
+      { m: "GET", path: "/lanyard/status", auth: "public",
+        desc: "Live-presence connection health: whether it's connected, how many users are tracked, and recent reconnect activity." },
+    ],
+  },
+  {
+    id: "discord", name: "Discord — profiles & guilds", blurb: "Profile, badges, and guild/role info from Discord.",
+    endpoints: [
+      { m: "GET", path: "/discord/users/:id", auth: "public",
+        desc: "A user's full profile — avatar, banner, badges, connected accounts, and (when available) bio, pronouns and reviews — combined with their live presence.",
+        params: [["id", "Discord user ID."], ["?fresh / ?nocache / ?refresh", "Skip the cache and fetch fresh."]] },
+      { m: "GET", path: "/discord/users?ids=a,b,c", auth: "public",
+        desc: "The same full profile for up to 100 users at once. Returns a map of user ID → profile (or null if not found).",
+        params: [["ids", "Comma-separated Discord user IDs, max 100."]] },
+      { m: "GET", path: "/discord/guilds/:invite", auth: "public",
+        desc: "Public guild info resolved from an invite code: name, icon/banner/splash, member + online counts.",
+        params: [["invite", "Invite code (the part after discord.gg/)."]] },
+      { m: "GET", path: "/discord/girls/:idType/:id", auth: "public",
+        desc: "Look up a role or a member inside the 'girls' server.",
+        params: [["idType", "'role' or 'member'."], ["id", "The role ID or member (user) ID."]] },
+    ],
+  },
+  {
+    id: "minecraft", name: "Minecraft", blurb: "Skins and Hypixel stats for a Minecraft account.",
+    endpoints: [
+      { m: "GET", path: "/minecraft/general/:uuid", auth: "public",
+        desc: "A player's Mojang identity: username, UUID (both dashed and short forms), skin and cape texture URLs, the skin's arm model (classic or slim), every cape the player has across providers (Minecraft, OptiFine, MinecraftCapes, LabyMod, 5zig, TLauncher, SkinMC — plus a custom 'doughmination' cape for hand-picked accounts) via the capes array, and a set of ready-to-embed mc-heads render images (face, head, body, player, combo, skin) — each render includes the overlay/hat layer, with _flat variants for the inner skin only. Returns 404 if no Minecraft account has that UUID.",
+        params: [["uuid", "Minecraft UUID — 32 hex characters, dashes optional."], ["?fresh / ?nocache / ?refresh", "Skip the cache and fetch fresh."]],
+        example: 'GET /minecraft/general/853c80ef3c3749fdaa49938b674adae6  →  { name, uuid, skin_url, cape_url, skin_model, capes: [ { source, cape_url } ], render: { face, head, body, player, combo, skin } }' },
+      { m: "GET", path: "/minecraft/capes", auth: "public",
+        desc: "The set of vanilla (Mojang) capes the API has seen, persisted to memory. It grows over time: every account looked up via /minecraft/general has its equipped vanilla cape remembered, deduped by texture hash. Third-party capes (OptiFine, LabyMod, etc.) are loaded fresh per request and are not persisted here.",
+        params: [],
+        example: 'GET /minecraft/capes  →  { count, capes: [ { source: "minecraft", cape_url } ] }' },
+      { m: "GET", path: "/minecraft/hypixel/:uuid", auth: "public",
+        desc: "A player's Hypixel stats: the full player object (network level and every game's stats — Bedwars, SkyWars, Duels, and the rest) plus their SkyBlock profiles. Always returns 200; the 'source' field tells you whether each section loaded ('ok') or why it's null — 'not_found' if the player has never joined Hypixel, 'unavailable' if this server isn't serving Hypixel data.",
+        params: [["uuid", "Minecraft UUID — 32 hex characters, dashes optional."], ["?fresh / ?nocache / ?refresh", "Skip the cache and fetch fresh."]],
+        example: 'GET /minecraft/hypixel/853c80ef3c3749fdaa49938b674adae6  →  { name, player: {…}, skyblock: [{…}], source: { player: "ok", skyblock: "ok" } }' },
+    ],
+  },
+  {
+    id: "plural-auth", name: "Plural — accounts & auth", blurb: "Login, signup, 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), display_name?, turnstile_token }." },
+      { m: "GET", path: "/plural/users/check-username?username=", auth: "public",
+        desc: "Check username availability. Returns { username, exists, available }." },
+      { 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, display_name?, is_admin?, is_pet? }." },
+      { 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." },
+      { 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: "auth",
+        desc: "Per-member fronting time across 24h/48h/5d/7d/30d windows and totals." },
+      { m: "GET", path: "/plural/metrics/switch-frequency?days=30", auth: "auth",
+        desc: "Switch counts per window and average switches/day." },
+    ],
+  },
+  {
+    id: "plural-realtime", name: "Plural — realtime & admin", blurb: "The unified WebSocket + broadcast controls.",
+    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." },
+    ],
+  },
+  {
+    id: "devices", name: "Devices", blurb: "Latest known device state (battery, charging, low power mode, wifi).",
+    endpoints: [
+      { m: "GET", path: "/devices", auth: "public", desc: "All devices → { device, level, charging, lowPowerMode, wifi, watch, airpods, updated_at }." },
+      { m: "GET", path: "/devices/:device", auth: "public", desc: "One device, or 404." },
+      { m: "POST", path: "/devices?device=iphone&level=25&charging=1&lpm=0&wifi=Home&watch=1&airpods=0", auth: "key",
+        desc: "Report device state. Only 'device' is required; supplied fields are updated, the rest untouched. Send the X-Battery-Key header.",
+        params: [["device", "1–64 chars (required)."], ["level", "Optional. Integer 0–100."], ["charging", "Optional. 1 (true) or 0 (false)."], ["lpm", "Optional. 1 (true) or 0 (false) → lowPowerMode."], ["wifi", "Optional. Any string (network name), ≤128 chars."], ["watch", "Optional. 1 (connected) or 0 (not connected)."], ["airpods", "Optional. 1 (connected) or 0 (not connected)."]] },
+      { m: "DELETE", path: "/devices?device=iphone", auth: "key",
+        desc: "Delete a device's state. Returns 404 if the device doesn't exist. Send the X-Battery-Key header.",
+        params: [["device", "1–64 chars (required)."]] },
+    ],
+  },
+  {
+    id: "guestbook", name: "Guestbook", blurb: "Public guestbook. Each entry gets a random UID so it can be deleted individually.",
+    endpoints: [
+      { m: "GET", path: "/guestbook?limit=50&offset=0", auth: "public",
+        desc: "List entries, newest first → { entries: [{ id, name, message, website, ts }], total, limit, offset }.",
+        params: [["limit", "Optional. 1–200, default 50."], ["offset", "Optional. ≥0, default 0."]] },
+      { m: "POST", path: "/guestbook", auth: "public",
+        desc: "Sign the guestbook. Honeypot (url2) + Turnstile (when configured) + per-IP rate limit (60s). Returns { ok, entry } with the new UID.",
+        example: 'POST body: { "name": "Clove", "message": "hi!", "website": "https://…", "turnstileToken": "…" }' },
+      { m: "DELETE", path: "/guestbook/:id", auth: "key",
+        desc: "Delete an entry by its UID. Returns 404 if not found. Send the X-Battery-Key header.",
+        params: [["id", "The entry's UID (required)."]] },
+      { m: "POST", path: "/guestbook/import", auth: "key",
+        desc: "Migration import: insert an entry with a fresh UID, bypassing captcha + rate limit. Send the X-Battery-Key header. Body { name, message, website? }." },
+    ],
+  },
+  {
+    id: "system-data", name: "System-data — visitor logs", blurb: "Visit logging plus an admin-only log viewer.",
+    endpoints: [
+      { m: "POST", path: "/system-data/helper", auth: "public",
+        desc: "Log a page visit (the frontend pings this on navigation). Body { path? }." },
+      { m: "GET", path: "/system-data/helper?path=", auth: "public", desc: "Log a page visit via a plain GET, for cases where a POST isn't convenient." },
+      { m: "GET", path: "/system-data", auth: "admin", desc: "HTML log viewer (single page)." },
+      { m: "GET", path: "/system-data/api/stats", auth: "admin", desc: "Totals, unique IPs, last-24h, top paths." },
+      { m: "GET", path: "/system-data/api/recent?limit=100", auth: "admin", desc: "Recent visits." },
+      { m: "GET", path: "/system-data/api/by-ip/:ip", auth: "admin", desc: "Visits from an IP." },
+      { m: "GET", path: "/system-data/api/by-path?q=", auth: "admin", desc: "Visits matching a path substring." },
+      { m: "GET", path: "/system-data/api/suspicious", auth: "admin", desc: ">20 hits/hour from one IP." },
+      { m: "GET", path: "/system-data/api/entry/:id", auth: "admin", desc: "One full log row." },
+    ],
+  },
+  {
+    id: "contrib", name: "Contrib", blurb: "Merged git contribution heatmaps.",
+    endpoints: [
+      { m: "GET", path: "/contribapi", auth: "public",
+        desc: "A single contribution heatmap that merges activity from GitHub and Codeberg. Updated at most hourly." },
+    ],
+  },
+  {
+    id: "meta", name: "Meta", blurb: "Service info, health, docs, and legal pages.",
+    endpoints: [
+      { m: "GET", path: "/", auth: "public", desc: "Service info (JSON) — the namespace map, plus docs/health/abuse/terms/privacy links.", root: true },
+      { m: "GET", path: "/health", auth: "public",
+        desc: "Liveness: Discord gateway connection state + tracked-user count + SYSTEM DO reachability. Returns HTTP 200 when everything is up, 503 when degraded — point your uptime monitor here." },
+      { m: "GET", path: "/docs", auth: "public", desc: "This page.", root: true },
+      { m: "GET", path: "/openapi.json", auth: "public", desc: "Machine-readable OpenAPI 3.1 spec generated from the same catalogue that renders this page.", root: true },
+      { m: "GET", path: "/abuse", auth: "public", desc: "Abuse & contact page: how to report abuse, request data removal / opt-out, or disclose a vulnerability.", root: true },
+      { m: "GET", path: "/terms", auth: "public", desc: "Terms of service — the short version: be reasonable with request volume or your IP gets blocked.", root: true },
+      { m: "GET", path: "/privacy", auth: "public", desc: "Privacy page: what's logged (visitor IPs, guestbook entries, cached Discord data), why, and how to get it removed.", root: true },
+      { m: "GET", path: "/.well-known/security.txt", auth: "public", desc: "RFC 9116 security contact file. Also available at /security.txt.", root: true },
+    ],
+  },
+];
diff --git a/src/docs.ts b/src/docs.ts
index 0270527..e294704 100644
--- a/src/docs.ts
+++ b/src/docs.ts
@@ -7,6 +7,12 @@
  * sync when routes change.
  * ===================================================================== */
 
+import { GROUPS } from "./apidata";
+
+// Serialised for the client-side renderer; "<" escaped so "</script>" in a
+// description can never terminate the inline script block.
+const GROUPS_JSON = JSON.stringify(GROUPS).replace(/</g, "\\u003c");
+
 export const DOCS_HTML = `<!doctype html>
 <html lang="en">
 <head>
@@ -191,7 +197,7 @@ export const DOCS_HTML = `<!doctype html>
 <header>
   <div class="header-text">
     <h1>Doughmination API reference</h1>
-    <p>Universal API: live Discord presence (Lanyard), Discord profiles, Minecraft skins & Hypixel stats, the plural system, and misc services. Base URL: <code>https://doughmination.uk/v2</code></p>
+    <p>Universal API: live Discord presence (Lanyard), Discord profiles, Minecraft skins & Hypixel stats, 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>
   </div>
   <button id="navToggle" class="nav-toggle" type="button" aria-expanded="false" aria-controls="nav">
     <span aria-hidden="true">☰</span>
@@ -208,238 +214,7 @@ export const DOCS_HTML = `<!doctype html>
 
 <script>
 // Auth legend: public | auth (any logged-in) | admin | owner | pet | jwt | bot | key
-var GROUPS = [
-  {
-    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." },
-      { 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>'." }
-    ]
-  },
-  {
-    id: "lanyard", name: "Lanyard — live presence", blurb: "Real-time Discord presence.",
-    endpoints: [
-      { m: "GET", path: "/lanyard/users/:id", auth: "public",
-        desc: "A user's live presence: online status, current activities, Spotify, and which platforms they're on (desktop/mobile/web). Returns 404 if the user doesn't share a tracked server with the bot.",
-        params: [["id", "Discord user ID."]] },
-      { m: "GET", path: "/lanyard/users?ids=a,b,c", auth: "public",
-        desc: "Live presence for up to 100 users at once. Returns a map of user ID → presence (or null).",
-        params: [["ids", "Comma-separated Discord user IDs, max 100."]] },
-      { m: "GET", path: "/lanyard/status", auth: "public",
-        desc: "Live-presence connection health: whether it's connected, how many users are tracked, and recent reconnect activity." }
-    ]
-  },
-  {
-    id: "discord", name: "Discord — profiles & guilds", blurb: "Profile, badges, and guild/role info from Discord.",
-    endpoints: [
-      { m: "GET", path: "/discord/users/:id", auth: "public",
-        desc: "A user's full profile — avatar, banner, badges, connected accounts, and (when available) bio, pronouns and reviews — combined with their live presence.",
-        params: [["id", "Discord user ID."], ["?fresh / ?nocache / ?refresh", "Skip the cache and fetch fresh."]] },
-      { m: "GET", path: "/discord/users?ids=a,b,c", auth: "public",
-        desc: "The same full profile for up to 100 users at once. Returns a map of user ID → profile (or null if not found).",
-        params: [["ids", "Comma-separated Discord user IDs, max 100."]] },
-      { m: "GET", path: "/discord/guilds/:invite", auth: "public",
-        desc: "Public guild info resolved from an invite code: name, icon/banner/splash, member + online counts.",
-        params: [["invite", "Invite code (the part after discord.gg/)."]] },
-      { m: "GET", path: "/discord/girls/:idType/:id", auth: "public",
-        desc: "Look up a role or a member inside the 'girls' server.",
-        params: [["idType", "'role' or 'member'."], ["id", "The role ID or member (user) ID."]] }
-    ]
-  },
-  {
-    id: "minecraft", name: "Minecraft", blurb: "Skins and Hypixel stats for a Minecraft account.",
-    endpoints: [
-      { m: "GET", path: "/minecraft/general/:uuid", auth: "public",
-        desc: "A player's Mojang identity: username, UUID (both dashed and short forms), skin and cape texture URLs, the skin's arm model (classic or slim), every cape the player has across providers (Minecraft, OptiFine, MinecraftCapes, LabyMod, 5zig, TLauncher, SkinMC — plus a custom 'doughmination' cape for hand-picked accounts) via the capes array, and a set of ready-to-embed mc-heads render images (face, head, body, player, combo, skin) — each render includes the overlay/hat layer, with _flat variants for the inner skin only. Returns 404 if no Minecraft account has that UUID.",
-        params: [["uuid", "Minecraft UUID — 32 hex characters, dashes optional."], ["?fresh / ?nocache / ?refresh", "Skip the cache and fetch fresh."]],
-        example: 'GET /minecraft/general/853c80ef3c3749fdaa49938b674adae6  →  { name, uuid, skin_url, cape_url, skin_model, capes: [ { source, cape_url } ], render: { face, head, body, player, combo, skin } }' },
-      { m: "GET", path: "/minecraft/capes", auth: "public",
-        desc: "The set of vanilla (Mojang) capes the API has seen, persisted to memory. It grows over time: every account looked up via /minecraft/general has its equipped vanilla cape remembered, deduped by texture hash. Third-party capes (OptiFine, LabyMod, etc.) are loaded fresh per request and are not persisted here.",
-        params: [],
-        example: 'GET /minecraft/capes  →  { count, capes: [ { source: "minecraft", cape_url } ] }' },
-      { m: "GET", path: "/minecraft/hypixel/:uuid", auth: "public",
-        desc: "A player's Hypixel stats: the full player object (network level and every game's stats — Bedwars, SkyWars, Duels, and the rest) plus their SkyBlock profiles. Always returns 200; the 'source' field tells you whether each section loaded ('ok') or why it's null — 'not_found' if the player has never joined Hypixel, 'unavailable' if this server isn't serving Hypixel data.",
-        params: [["uuid", "Minecraft UUID — 32 hex characters, dashes optional."], ["?fresh / ?nocache / ?refresh", "Skip the cache and fetch fresh."]],
-        example: 'GET /minecraft/hypixel/853c80ef3c3749fdaa49938b674adae6  →  { name, player: {…}, skyblock: [{…}], source: { player: "ok", skyblock: "ok" } }' }
-    ]
-  },
-  {
-    id: "plural-auth", name: "Plural — accounts & auth", blurb: "Login, signup, 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), display_name?, turnstile_token }." },
-      { m: "GET", path: "/plural/users/check-username?username=", auth: "public",
-        desc: "Check username availability. Returns { username, exists, available }." },
-      { 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, display_name?, is_admin?, is_pet? }." },
-      { 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." },
-      { 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: "auth",
-        desc: "Per-member fronting time across 24h/48h/5d/7d/30d windows and totals." },
-      { m: "GET", path: "/plural/metrics/switch-frequency?days=30", auth: "auth",
-        desc: "Switch counts per window and average switches/day." }
-    ]
-  },
-  {
-    id: "plural-realtime", name: "Plural — realtime & admin", blurb: "The unified WebSocket + broadcast controls.",
-    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." }
-    ]
-  },
-  {
-    id: "devices", name: "Devices", blurb: "Latest known device state (battery, charging, low power mode, wifi).",
-    endpoints: [
-      { m: "GET", path: "/devices", auth: "public", desc: "All devices → { device, level, charging, lowPowerMode, wifi, watch, airpods, updated_at }." },
-      { m: "GET", path: "/devices/:device", auth: "public", desc: "One device, or 404." },
-      { m: "POST", path: "/devices?device=iphone&level=25&charging=1&lpm=0&wifi=Home&watch=1&airpods=0", auth: "key",
-        desc: "Report device state. Only 'device' is required; supplied fields are updated, the rest untouched. Send the X-Battery-Key header.",
-        params: [["device", "1–64 chars (required)."], ["level", "Optional. Integer 0–100."], ["charging", "Optional. 1 (true) or 0 (false)."], ["lpm", "Optional. 1 (true) or 0 (false) → lowPowerMode."], ["wifi", "Optional. Any string (network name), ≤128 chars."], ["watch", "Optional. 1 (connected) or 0 (not connected)."], ["airpods", "Optional. 1 (connected) or 0 (not connected)."]] },
-      { m: "DELETE", path: "/devices?device=iphone", auth: "key",
-        desc: "Delete a device's state. Returns 404 if the device doesn't exist. Send the X-Battery-Key header.",
-        params: [["device", "1–64 chars (required)."]] }
-    ]
-  },
-  {
-    id: "guestbook", name: "Guestbook", blurb: "Public guestbook. Each entry gets a random UID so it can be deleted individually.",
-    endpoints: [
-      { m: "GET", path: "/guestbook?limit=50&offset=0", auth: "public",
-        desc: "List entries, newest first → { entries: [{ id, name, message, website, ts }], total, limit, offset }.",
-        params: [["limit", "Optional. 1–200, default 50."], ["offset", "Optional. ≥0, default 0."]] },
-      { m: "POST", path: "/guestbook", auth: "public",
-        desc: "Sign the guestbook. Honeypot (url2) + Turnstile (when configured) + per-IP rate limit (60s). Returns { ok, entry } with the new UID.",
-        example: 'POST body: { "name": "Clove", "message": "hi!", "website": "https://…", "turnstileToken": "…" }' },
-      { m: "DELETE", path: "/guestbook/:id", auth: "key",
-        desc: "Delete an entry by its UID. Returns 404 if not found. Send the X-Battery-Key header.",
-        params: [["id", "The entry's UID (required)."]] },
-      { m: "POST", path: "/guestbook/import", auth: "key",
-        desc: "Migration import: insert an entry with a fresh UID, bypassing captcha + rate limit. Send the X-Battery-Key header. Body { name, message, website? }." }
-    ]
-  },
-  {
-    id: "system-data", name: "System-data — visitor logs", blurb: "Visit logging plus an admin-only log viewer.",
-    endpoints: [
-      { m: "POST", path: "/system-data/helper", auth: "public",
-        desc: "Log a page visit (the frontend pings this on navigation). Body { path? }." },
-      { m: "GET", path: "/system-data/helper?path=", auth: "public", desc: "Log a page visit via a plain GET, for cases where a POST isn't convenient." },
-      { m: "GET", path: "/system-data", auth: "admin", desc: "HTML log viewer (single page)." },
-      { m: "GET", path: "/system-data/api/stats", auth: "admin", desc: "Totals, unique IPs, last-24h, top paths." },
-      { m: "GET", path: "/system-data/api/recent?limit=100", auth: "admin", desc: "Recent visits." },
-      { m: "GET", path: "/system-data/api/by-ip/:ip", auth: "admin", desc: "Visits from an IP." },
-      { m: "GET", path: "/system-data/api/by-path?q=", auth: "admin", desc: "Visits matching a path substring." },
-      { m: "GET", path: "/system-data/api/suspicious", auth: "admin", desc: ">20 hits/hour from one IP." },
-      { m: "GET", path: "/system-data/api/entry/:id", auth: "admin", desc: "One full log row." }
-    ]
-  },
-  {
-    id: "contrib", name: "Contrib", blurb: "Merged git contribution heatmaps.",
-    endpoints: [
-      { m: "GET", path: "/contribapi", auth: "public",
-        desc: "A single contribution heatmap that merges activity from GitHub and Codeberg. Updated at most hourly." }
-    ]
-  },
-  {
-    id: "meta", name: "Meta", blurb: "",
-    endpoints: [
-      { m: "GET", path: "/", auth: "public", desc: "Service info (JSON) — the namespace map." },
-      { m: "GET", path: "/docs", auth: "public", desc: "This page." }
-    ]
-  }
-];
+var GROUPS = ${GROUPS_JSON};
 
 function esc(s) {
   return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
diff --git a/src/index.ts b/src/index.ts
index 4d73c97..548d9c3 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -10,6 +10,9 @@
  *   /v2/devices/*     — device state (battery, etc.) (SystemState DO)
  *   /v2/guestbook/*   — public guestbook            (SystemState DO)
  *   /v2/system-data/* — visitor logs + viewer      (SystemState DO)
+ *   /abuse, /terms, /privacy, /.well-known/security.txt — contact & legal pages
+ *   /docs, /openapi.json — API reference (HTML + OpenAPI 3.1)
+ *   /v2/health        — liveness for uptime monitors
  *
  * Two Durable Objects:
  *   GATEWAY  — singleton holding the Discord gateway socket (presence). Relays
@@ -36,6 +39,9 @@ import { getGirlsResource, isGirlsIdType } from "./girls";
 import { getMinecraftGeneral, getMinecraftHypixel, getVanillaCapeList, normalizeMcUuid, MojangUpstreamError } from "./minecraft";
 import { getContributions } from "./contribapi";
 import { DOCS_HTML } from "./docs";
+import { ABUSE_HTML, ABUSE_CONTACT, securityTxt } from "./abuse";
+import { TERMS_HTML, PRIVACY_HTML, NOT_FOUND_HTML } from "./pages";
+import { OPENAPI_JSON } from "./openapi";
 import { SystemState } from "./system/do";
 
 export { GatewayManager, SystemState };
@@ -46,10 +52,37 @@ const CORS = {
   "Access-Control-Allow-Headers": "Content-Type",
 };
 
+// Security headers on every Worker response. HTML pages additionally get a
+// CSP: they're fully self-contained (inline style + script, /icon.png), so
+// everything else is locked down.
+const SECURITY_HEADERS = {
+  "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
+  "X-Content-Type-Options": "nosniff",
+  "Referrer-Policy": "no-referrer",
+};
+const HTML_SECURITY_HEADERS = {
+  ...SECURITY_HEADERS,
+  "Content-Security-Policy":
+    "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
+  "X-Frame-Options": "DENY",
+};
+
 function json<T>(body: ApiEnvelope<T>, status = 200): Response {
   return new Response(JSON.stringify(body), {
     status,
-    headers: { "Content-Type": "application/json", "Cache-Control": "no-store", ...CORS },
+    headers: { "Content-Type": "application/json", "Cache-Control": "no-store", ...CORS, ...SECURITY_HEADERS },
+  });
+}
+
+function html(body: string, status = 200): Response {
+  return new Response(body, {
+    status,
+    headers: {
+      "Content-Type": "text/html; charset=utf-8",
+      "Cache-Control": status === 200 ? "public, max-age=3600" : "no-store",
+      ...CORS,
+      ...HTML_SECURITY_HEADERS,
+    },
   });
 }
 
@@ -160,13 +193,53 @@ export default {
 
     if (req.method === "OPTIONS") return new Response(null, { headers: CORS });
 
-    // ---- API reference ---------------------------------------------------
-    if (path === "/docs") {
-      return new Response(DOCS_HTML, {
-        headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "public, max-age=3600", ...CORS },
+    // ---- API reference + OpenAPI spec ------------------------------------
+    if (path === "/docs") return html(DOCS_HTML);
+    if (path === "/openapi.json") {
+      return new Response(OPENAPI_JSON, {
+        headers: { "Content-Type": "application/json", "Cache-Control": "public, max-age=3600", ...CORS, ...SECURITY_HEADERS },
       });
     }
 
+    // ---- Abuse / terms / privacy / security contact ----------------------
+    if (path === "/abuse") return html(ABUSE_HTML);
+    if (path === "/terms") return html(TERMS_HTML);
+    if (path === "/privacy") return html(PRIVACY_HTML);
+    if (path === "/.well-known/security.txt" || path === "/security.txt") {
+      return new Response(securityTxt(url.origin), {
+        headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "public, max-age=86400", ...CORS, ...SECURITY_HEADERS },
+      });
+    }
+
+    // ---- /v2/health  (liveness for uptime monitors) ----------------------
+    // Gateway DO status + SYSTEM DO reachability in parallel. 200 when both
+    // are up and the Discord gateway socket is connected, 503 otherwise.
+    if (path === "/v2/health") {
+      const [gw, sys] = await Promise.all([
+        gatewayStub(env)
+          .fetch("https://do/status")
+          .then((r) => (r.ok ? (r.json() as Promise<{ connected: boolean; tracked: number; connected_since: number | null }>) : null))
+          .catch(() => null),
+        systemStub(env)
+          .fetch("https://do/v2/health-probe") // any response (even 404) proves the DO is up
+          .then(() => true)
+          .catch(() => false),
+      ]);
+      const ok = !!gw?.connected && sys;
+      return json(
+        {
+          success: true,
+          data: {
+            status: ok ? "ok" : "degraded",
+            gateway: gw ?? { connected: false },
+            system: sys ? "ok" : "unreachable",
+            timestamp: Date.now(),
+          },
+        } as never,
+        ok ? 200 : 503,
+      );
+    }
+
     // ---- Lanyard gateway status (debug) ----------------------------------
     if (path === "/v2/lanyard/status") {
       const res = await gatewayStub(env).fetch("https://do/status");
@@ -184,6 +257,13 @@ export default {
           licence: "ESAL-2.1",
           repository_url: "https://github.com/doughmination/restful",
           docs: "/docs",
+          openapi: "/openapi.json",
+          health: "/v2/health",
+          abuse: "/abuse",
+          abuse_contact: ABUSE_CONTACT,
+          terms: "/terms",
+          privacy: "/privacy",
+          security_txt: "/.well-known/security.txt",
         },
       } as never);
     }
@@ -372,7 +452,13 @@ export default {
       return json<UnifiedRecord>({ success: true, data: buildRecord(profile, presence) });
     }
 
-    return json({ success: false, error: { code: "not_found", message: "Unknown route." } }, 404);
+    // ---- 404 --------------------------------------------------------------
+    // Browsers (Accept: text/html) get the friendly page; API clients keep
+    // the JSON error envelope.
+    if ((req.headers.get("accept") || "").includes("text/html")) {
+      return html(NOT_FOUND_HTML, 404);
+    }
+    return json({ success: false, error: { code: "not_found", message: "Unknown route. See /docs." } }, 404);
   },
 
   // Cron keepalive — keep the gateway DO connected.
diff --git a/src/openapi.ts b/src/openapi.ts
new file mode 100644
index 0000000..75e8593
--- /dev/null
+++ b/src/openapi.ts
@@ -0,0 +1,191 @@
+/* =====================================================================
+ * openapi.ts — generates /openapi.json from the apidata.ts catalogue.
+ *
+ * One source of truth: the same GROUPS structure that renders /docs is
+ * converted here into an OpenAPI 3.1 document at module load. WebSocket
+ * endpoints and the auth-overview pseudo-group are represented in the
+ * info/securitySchemes sections rather than as paths.
+ * ===================================================================== */
+
+import { GROUPS, type EndpointDef } from "./apidata";
+import { ABUSE_CONTACT } from "./abuse";
+
+const BASE = "https://doughmination.uk";
+
+type JsonObj = Record<string, unknown>;
+
+const ENVELOPE_OK: JsonObj = {
+  type: "object",
+  required: ["success", "data"],
+  properties: {
+    success: { type: "boolean", const: true },
+    data: { description: "Endpoint-specific payload." },
+  },
+};
+
+const ENVELOPE_ERR: JsonObj = {
+  type: "object",
+  required: ["success", "error"],
+  properties: {
+    success: { type: "boolean", const: false },
+    error: {
+      type: "object",
+      required: ["code", "message"],
+      properties: { code: { type: "string" }, message: { type: "string" } },
+    },
+  },
+};
+
+const RESPONSES: JsonObj = {
+  "200": {
+    description: "Success envelope.",
+    content: { "application/json": { schema: { $ref: "#/components/schemas/Envelope" } } },
+  },
+  "4XX": {
+    description: "Error envelope.",
+    content: { "application/json": { schema: { $ref: "#/components/schemas/ErrorEnvelope" } } },
+  },
+};
+
+/** Map the docs auth tag to OpenAPI security requirements. */
+function security(auth: EndpointDef["auth"]): JsonObj[] | undefined {
+  switch (auth) {
+    case "public":
+      return undefined;
+    case "key":
+      return [{ batteryKey: [] }];
+    case "bot":
+      return [{ bearerAuth: [] }];
+    default: // auth / admin / owner / pet / jwt
+      return [{ bearerAuth: [] }];
+  }
+}
+
+/** "/lanyard/users?ids=a,b,c" → { path: "/lanyard/users", query: ["ids"] };
+ *  ":param" segments become "{param}". */
+function normalizePath(raw: string): { path: string; query: string[]; pathParams: string[] } {
+  const [pathPart, queryPart] = raw.split("?");
+  const pathParams: string[] = [];
+  const path = pathPart
+    .split("/")
+    .map((seg) => {
+      if (seg.startsWith(":")) {
+        pathParams.push(seg.slice(1));
+        return `{${seg.slice(1)}}`;
+      }
+      return seg;
+    })
+    .join("/");
+  const query = queryPart
+    ? queryPart.split("&").map((kv) => kv.split("=")[0]).filter(Boolean)
+    : [];
+  return { path, query, pathParams };
+}
+
+/** Build the parameters array from the endpoint's documented params plus any
+ *  query keys embedded in the illustrative path. */
+function parameters(ep: EndpointDef, pathParams: string[], queryKeys: string[]): JsonObj[] {
+  const out: JsonObj[] = [];
+  const seen = new Set<string>();
+
+  for (const [rawName, desc] of ep.params ?? []) {
+    // "?fresh / ?nocache / ?refresh" documents several optional query flags.
+    const names = rawName.split("/").map((n) => n.trim().replace(/^\?/, "")).filter(Boolean);
+    const isQueryDoc = rawName.trimStart().startsWith("?");
+    for (const name of names) {
+      if (seen.has(name)) continue;
+      seen.add(name);
+      const inPath = pathParams.includes(name) && !isQueryDoc;
+      out.push({
+        name,
+        in: inPath ? "path" : "query",
+        required: inPath,
+        description: desc,
+        schema: { type: "string" },
+      });
+    }
+  }
+
+  // Path params that had no docs row still must be declared.
+  for (const p of pathParams) {
+    if (seen.has(p)) continue;
+    seen.add(p);
+    out.push({ name: p, in: "path", required: true, schema: { type: "string" } });
+  }
+  // Query keys shown in the illustrative path but not documented separately.
+  for (const q of queryKeys) {
+    if (seen.has(q)) continue;
+    seen.add(q);
+    out.push({ name: q, in: "query", required: false, schema: { type: "string" } });
+  }
+  return out;
+}
+
+function buildSpec(): JsonObj {
+  const paths: Record<string, JsonObj> = {};
+
+  for (const group of GROUPS) {
+    if (group.id === "auth-overview") continue; // described in securitySchemes
+    for (const ep of group.endpoints) {
+      if (ep.m === "WS") continue; // not representable as an HTTP operation
+      const { path, query, pathParams } = normalizePath(ep.path);
+      const fullPath = ep.root ? path : `/v2${path}`;
+      const item = (paths[fullPath] ??= {});
+      const op: JsonObj = {
+        tags: [group.name],
+        summary: ep.desc.split(". ")[0].slice(0, 120),
+        description: ep.desc + (ep.note ? `\n\n${ep.note}` : "") + (ep.example ? `\n\nExample: ${ep.example}` : ""),
+        responses: RESPONSES,
+      };
+      const params = parameters(ep, pathParams, query);
+      if (params.length) op.parameters = params;
+      const sec = security(ep.auth);
+      if (sec) op.security = sec;
+      if (ep.m === "POST" || ep.m === "PUT") {
+        op.requestBody = {
+          required: false,
+          content: { "application/json": { schema: { type: "object" } } },
+        };
+      }
+      item[ep.m.toLowerCase()] = op;
+    }
+  }
+
+  return {
+    openapi: "3.1.0",
+    info: {
+      title: "Doughmination API",
+      version: "2.0.0",
+      description:
+        "Combined Discord presence (Lanyard-style) + profile/badges API, Minecraft/Hypixel lookups, git contribution heatmaps, and the Doughmination plural-system API — 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",
+      contact: { email: ABUSE_CONTACT, url: `${BASE}/abuse` },
+      termsOfService: `${BASE}/terms`,
+    },
+    servers: [{ url: BASE, description: "Production. Most routes live under /v2 (included in the paths below)." }],
+    externalDocs: { url: `${BASE}/docs`, description: "Human-readable API reference" },
+    paths,
+    components: {
+      securitySchemes: {
+        bearerAuth: {
+          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.",
+        },
+        batteryKey: {
+          type: "apiKey",
+          in: "header",
+          name: "X-Battery-Key",
+          description: "Device key for reporting/deleting device state and managing guestbook entries.",
+        },
+      },
+      schemas: { Envelope: ENVELOPE_OK, ErrorEnvelope: ENVELOPE_ERR },
+    },
+  };
+}
+
+/** Serialised once at module load — the catalogue is static per deploy. */
+export const OPENAPI_JSON = JSON.stringify(buildSpec());
diff --git a/src/pages.ts b/src/pages.ts
new file mode 100644
index 0000000..4f2662b
--- /dev/null
+++ b/src/pages.ts
@@ -0,0 +1,141 @@
+/* =====================================================================
+ * pages.ts — shared HTML shell + the /terms, /privacy and 404 pages.
+ *
+ * Same self-contained Catppuccin Mocha look as /docs. The shell is also
+ * used by abuse.ts so the styling lives in exactly one place.
+ * ===================================================================== */
+
+import { ABUSE_CONTACT } from "./abuse";
+
+const FOOTER_LINKS = `<a href="/docs">API reference</a> · <a href="/abuse">Abuse</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a>`;
+
+/** Wraps page content in the shared document shell. `body` is trusted HTML. */
+export function pageShell(title: string, subtitle: string, body: string): string {
+  return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<link rel="icon" type="image/png" href="/icon.png" />
+<title>${title} — Doughmination API</title>
+<style>
+  :root {
+    color-scheme: dark;
+    --base: #1e1e2e; --mantle: #181825; --surface0: #313244; --surface1: #45475a;
+    --surface2: #585b70; --subtext0: #a6adc8; --subtext1: #bac2de; --text: #cdd6f4;
+    --pink: #f5c2e7; --red: #f38ba8; --green: #a6e3a1; --blue: #89b4fa;
+    --bg: var(--base); --line: var(--surface2); --fg: var(--text); --muted: var(--subtext0);
+    --mono: ui-monospace, SFMono-Regular, Menlo, monospace; --accent: var(--pink);
+  }
+  * { box-sizing: border-box; }
+  body { margin: 0; font: 15px/1.65 system-ui, sans-serif; background: var(--bg); color: var(--fg); }
+  header { padding: 24px 20px 14px; border-bottom: 1px solid var(--line); }
+  .inner { max-width: 720px; margin: 0 auto; }
+  h1 { margin: 0 0 4px; font-size: 21px; }
+  header p { margin: 0; color: var(--subtext0); font-size: 13.5px; }
+  main { max-width: 720px; margin: 0 auto; padding: 20px; }
+  h2 { font-size: 16.5px; margin: 28px 0 8px; }
+  p, li { color: var(--subtext1); font-size: 14.5px; }
+  ul { padding-left: 22px; margin: 8px 0; }
+  a { color: var(--accent); }
+  code { font: 12.5px var(--mono); background: var(--mantle); color: var(--pink); padding: 1px 5px; border-radius: 4px; border: 1px solid var(--line); }
+  .card { border: 1px solid var(--line); background: var(--surface0); border-radius: 10px; padding: 14px 16px; margin: 14px 0; }
+  .card strong { color: var(--fg); }
+  footer { max-width: 720px; margin: 0 auto; padding: 8px 20px 28px; font-size: 13px; color: var(--muted); }
+  .big { font: 700 64px var(--mono); color: var(--accent); margin: 30px 0 6px; }
+  ::selection { background: rgba(245,194,231,.28); }
+</style>
+</head>
+<body>
+<header><div class="inner">
+  <h1>${title}</h1>
+  <p>${subtitle}</p>
+</div></header>
+<main>
+${body}
+</main>
+<footer>${FOOTER_LINKS}</footer>
+</body>
+</html>
+`;
+}
+
+// ---------------------------------------------------------------------------
+// /terms
+// ---------------------------------------------------------------------------
+
+export const TERMS_HTML = pageShell(
+  "Terms of service",
+  `The short version: be reasonable, and this stays free and open. <a href="/docs">← API reference</a>`,
+  `
+<div class="card">
+  <strong>tl;dr:</strong> the public endpoints are free to use. Please be reasonable with your request volume — if you hammer the API, your IP gets blocked. That's the whole deal.
+</div>
+
+<h2>Use of the API</h2>
+<ul>
+  <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>
+</ul>
+
+<h2>No guarantees</h2>
+<p>This is a small, personally-run service on Cloudflare Workers. It's provided <strong>as-is, with no warranty and no uptime guarantee</strong>. Endpoints, response shapes, and these terms may change — or the whole service may shut down — at any time, though breaking changes are versioned under <code>/v2</code> where practical. Check <a href="/v2/health"><code>/v2/health</code></a> if something seems down.</p>
+
+<h2>Data served</h2>
+<p>Discord and Minecraft data served by this API belongs to its respective owners and is passed through (briefly cached) for convenience. If your data appears here and you want it removed, see the <a href="/privacy">privacy page</a> or the <a href="/abuse">abuse page</a>.</p>
+
+<h2>Contact</h2>
+<p>Questions, problems, or an appeal to an IP block: <a href="mailto:${ABUSE_CONTACT}">${ABUSE_CONTACT}</a>.</p>
+`,
+);
+
+// ---------------------------------------------------------------------------
+// /privacy
+// ---------------------------------------------------------------------------
+
+export const PRIVACY_HTML = pageShell(
+  "Privacy",
+  `What this service stores, why, and how to get it removed. <a href="/docs">← API reference</a>`,
+  `
+<div class="card">
+  <strong>tl;dr:</strong> no ads, no analytics, no selling anything. Visit logs (IP + path) are kept for abuse monitoring, guestbook posts are public, and Discord/Minecraft data is cached briefly. Email <a href="mailto:${ABUSE_CONTACT}">${ABUSE_CONTACT}</a> to have anything about you removed.
+</div>
+
+<h2>What's collected</h2>
+<ul>
+  <li><strong>Visit logs.</strong> Requests logged via the site frontend record IP address, request path, user agent, and timestamp. They exist purely for security and abuse monitoring (spotting floods and probes) and are visible only to the admin. They are not shared with anyone and are cleared periodically.</li>
+  <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 (the Lanyard model). Presence is held in memory only and never written to storage. Profile data (avatar, badges, connections) is cached for minutes-to-hours and then expires on its own.</li>
+  <li><strong>Minecraft & Hypixel data.</strong> Public data fetched from Mojang/Hypixel 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>
+</ul>
+
+<h2>What's NOT collected</h2>
+<p>No advertising, no third-party analytics, no tracking cookies, no fingerprinting, and nothing is ever sold or shared. Cloudflare hosts the service, so requests pass through their network like any Cloudflare-proxied site.</p>
+
+<h2>Your data, your call</h2>
+<ul>
+  <li><strong>Presence opt-out:</strong> leave the Discord server(s) the bot is in — your presence disappears automatically — or email to be blocked from lookups entirely.</li>
+  <li><strong>Guestbook removal:</strong> email with (roughly) what the entry says; every entry is individually deletable.</li>
+  <li><strong>Anything else:</strong> email <a href="mailto:${ABUSE_CONTACT}">${ABUSE_CONTACT}</a> with your Discord user ID or details, and it gets removed.</li>
+</ul>
+`,
+);
+
+// ---------------------------------------------------------------------------
+// 404
+// ---------------------------------------------------------------------------
+
+export const NOT_FOUND_HTML = pageShell(
+  "Not found",
+  `This route doesn't exist.`,
+  `
+<div style="text-align:center">
+  <div class="big">404</div>
+  <p>Nothing lives at this path. Everything real is under <code>/v2</code> — the full list is on the <a href="/docs">API reference</a>.</p>
+  <p><a href="/">← service info</a> · <a href="/docs">docs</a> · <a href="/v2/health">health</a></p>
+</div>
+`,
+);