commit
No need for these anymore
diff --git a/docs/decisions.md b/docs/decisions.md
deleted file mode 100644
index ecbb6f4..0000000
--- a/docs/decisions.md
+++ /dev/null
@@ -1,640 +0,0 @@
-# pkviewer — decision log
-
-Signed-off decisions. Implementation follows these; changing one is a deliberate
-act, not a refactor. Numbering is stable so other documents can cite it.
-
-## Architecture
-
-**A1. Two processes.** Hono on Bun owns everything stateful — database, sessions,
-PluralKit client, OAuth, business logic — and is the only process that opens
-SQLite, so there is exactly one writer. Next.js on Node renders and reaches the
-API over HTTP. **Next.js never imports anything under `apps/api/src/db`.**
-
-**A2. SSR is required**, not decorative: public pages are shared into Discord,
-whose unfurler does not run JavaScript. Server-rendered `<meta>` is the point.
-
-**A3. No serverless.** SQLite needs a persistent disk. Single VPS or a volume.
-
-## Core decisions
-
-1. **Domain is configuration.** `pkviewer.xyz` is the deployment; it moved there
- from `system.doughmination.gay` without a code change, which is the point. No absolute pkviewer URL is ever persisted to the database; public
- URLs are composed at render time from config. Enforced by
- `scripts/check-no-hardcoded-origin.sh` in CI.
-2. ~~**User content gets its own origin.**~~ **Reversed.** pkviewer now serves
- everything from one user-facing origin; see O1 for what that costs and what
- replaces it.
-3. **Management lives under `/manage/...`**, never `/s/:system/...`, so a member
- slug can never collide with an app route.
-4. **Slugs are `[a-z0-9-]` only.** Eliminates homograph squatting outright
- rather than mitigating it. Widening the character set would require
- confusable folding first.
-5. **Private members 404**, with nothing distinguishing them from a member that
- never existed. PluralKit's own 404 already behaves this way, and `PkNotFound`
- deliberately does not separate the two cases.
-6. **Slug reservation is 7 days and subject-owned** — the reclaim right follows
- the system or member, not the account that held it.
-7. **A contested claim is blocked automatically**, with a manual appeal path.
- The legitimate case and the attack case are indistinguishable to us, so there
- is no safe automatic policy.
-8. **`/s/<pk-id>` and `/s/<slug>` both return 200**; the slug is canonical via
- `<link rel="canonical">`. Never a 301 for anything slug-based — permanent
- redirects outlive slug ownership.
-9. **Only system principals sign in.** `grants(subject_type, subject_id)` is
- shaped to hold others, so widening it is rows rather than a migration.
-10. **PluralKit Dispatch is opt-in**, never required for claiming. A system has
- only one webhook URL, so enabling ours overwrites any other integration —
- this must be stated plainly in the UI.
-11. **Unclaiming**: 7-day slug reservation, 30-day configuration grace, reclaim
- within the window restores everything.
-12. **No custom CSS.** Theming is the token vocabulary and nothing else. See O1
- for why enabling free-form CSS is not a small change.
-
-## Origins
-
-**O1. One user-facing origin.** *(Supersedes the two-origin split. Product
-decision, taken deliberately with the consequence below understood.)*
-
-Everything a person visits is served from a single origin:
-
-| Path | |
-|---|---|
-| `/` | landing page |
-| `/login` | Discord sign-in |
-| `/auth/...` | OAuth callbacks, proxied to the API by the web tier |
-| `/manage/...` | authenticated management UI |
-| `/s/...` | public system and member pages |
-
-Production: `https://pkviewer.xyz`, reached through a Cloudflare Tunnel.
-Development: `http://system.localhost:3000`.
-Configured as `PUBLIC_ORIGIN`, read at runtime, never baked into a build.
-
-The API stays internal and does not become browser-facing. The browser never
-calls it directly; the web tier proxies `/auth/...` and every management read
-and write server-side, which is what keeps `INTERNAL_API_ORIGIN` internal.
-
-### What the previous split protected, and what replaces it
-
-pkviewer previously served public pages and the management UI from two hosts.
-The `__Host-` cookie is pinned to one host, so a total compromise of a `/s/...`
-page could not reach the session cookie — it was never sent there. That was a
-structural guarantee, and consolidating gives it up.
-
-**It costs nothing today.** There is no user-authored executable content: no HTML,
-no JavaScript, no free-form CSS. Themes are a closed vocabulary of validated
-values (six-digit hex, declared enums, allow-listed font ids) and social links
-are `href` only, validated to http(s), never fetched. There is nothing on a
-public page that could exploit sharing an origin.
-
-**It matters for custom CSS, which is what the split was insurance for.** User
-CSS would run on the same origin that holds the session cookie. CSS cannot read an httpOnly cookie, but it can exfiltrate visible DOM
-content through attribute selectors and `url()`, and it can cover the viewport
-with `position: fixed` — and a convincing fake sign-in overlay is *more*
-dangerous on an origin that genuinely serves `/login`.
-
-> **Do not simply switch custom CSS on.** Under one origin it needs isolation of
-> its own — a sandboxed iframe with an opaque origin, or a separate host for
-> user content. This is the constraint the origin split used to satisfy for
-> free, recorded here so enabling CSS is not mistaken for a small change.
-
-### What now carries the weight instead
-
-**O2. `__Host-` is still required.** It no longer separates two pkviewer hosts,
-but it still forbids a `Domain` attribute, so the cookie is pinned to exactly
-this host and no sibling subdomain — a docs site, a future service — can set or
-overwrite it.
-
-**O3. Public pages must never render session state.** This was previously
-structural: the cookie could not arrive. It is now a property of the code, so it
-is enforced by test rather than by architecture. Public page models carry no
-account, grant, session or Discord data, signed in or not.
-
-**O4. The Origin check and `SameSite=Lax` now carry the CSRF weight alone.**
-Every state-changing API request must present a recognised Origin. With one
-origin there is no second host to cross-check against, so this is the boundary.
-
-## Public routes
-
-All first-class, not afterthoughts. Split by origin per O1:
-
-All served from the one origin (O1): `/`, `/login`, `/auth/...`, `/manage/...`,
-`/s/...`. **Documentation is a separate site** (`PUBLIC_DOCS_URL`) and is not
-served by this application; an empty value hides the links entirely.
-
-## Access
-
-**B1. There is no beta gate.** `BETA_MODE` and `BETA_ALLOWED_DISCORD_IDS` are
-removed rather than defaulted off: a disabled flag still reads as a working
-gate, and the dead branches were the part most likely to be re-enabled by
-accident. Claiming is open to any signed-in account and is gated by proving
-control of the system, never by membership of a list. Public pages are
-indexable; `/manage` and `/admin` carry `noindex` both as metadata and as a
-header, since a `<meta>` tag cannot reach a non-HTML response. Guarded by
-`apps/web/test/no-beta.test.ts`, which walks the tree for the whole vocabulary.
-
-**B2. `SIGNUP_ENABLED` survives and defaults to open.** It gates creating a NEW
-account and nothing else, so an existing account can always sign in. It was the
-beta's companion switch and defaulted closed; with the allow-list gone, a
-deployment that sets nothing should let people in.
-
-## Credentials
-
-**C1. No PluralKit token is ever persisted.** A PK token is full
-read/write — it can delete members. Tier-3 claim verification uses one within a
-single request and discards it.
-
-**C2. No feature may require a PluralKit token.** Tier 1 (Discord-linked account)
-and tier 2 (description challenge) both work without one.
-
-**C3. Authenticated responses never enter a public cache.** Enforced structurally
-by `auth_scope` in the `pk_snapshots` primary key, not by convention.
-
-**C4. Discord access tokens are discarded** immediately after the code exchange.
-We read the user id once and never call Discord again — no refresh tokens, no
-token table.
-
-## PluralKit
-
-**P1. One canonical User-Agent**, from config, non-overridable, pointing at the
-**repository** rather than the deployment origin so it survives the domain move.
-
-**P2. Limits are per-IP and our limiter is per-process.** Correct for a single
-API process. A second instance behind the same egress IP requires a shared
-limiter.
-
-**P3. PluralKit downtime must not take public pages down.** Stale-while-revalidate
-from `pk_snapshots`, with a visible "may be out of date" marker.
-
-## UI
-
-**U1. Bootstrap Icons via `react-bootstrap-icons`** is the standard icon set —
-navigation, settings, socials, status, actions, auth, editing, alerts, menus,
-chevrons, external links, privacy indicators, management. Named imports only
-(`import { Github } from "react-bootstrap-icons"`), never namespace imports, so
-it tree-shakes: the package sets `sideEffects: false` and ships an ESM entry.
-
-A bespoke icon is introduced only where no suitable Bootstrap Icon exists and the
-distinction matters to the product.
-
-**U2. Bootstrap Icons are the icon source only.** The visual design is pkviewer's
-own and does not adopt Bootstrap's styling.
-
-## Security invariants
-
-Properties the tests already demonstrate, written down so a later refactor
-cannot weaken one by accident. Each names the test that would catch its loss.
-
-**S1. The caller can never choose the identity used as proof of ownership.**
-Tier-1 verification reads Discord ids from the authenticated session and
-server-side account state only, never from request-controlled input. A request
-body naming a Discord id must never influence which identity is treated as
-proven. *Guarded by: "refuses when the system is not linked to the caller".*
-
-**S2. A description challenge is bound to the `(account, system)` pair that
-created it**, and can only be redeemed by that account. The lookup is keyed on
-both, so another account presenting a valid challenge id gets
-`challenge_not_found` — not a different error, and not a hint the challenge
-exists. *Guarded by: "another account cannot verify someone else's challenge".*
-
-**S3. Challenge verification never reads a cached description.** It fetches with
-`maxAgeMs: 0`, which is an unconditional cache bypass rather than "fresh within
-0ms". A stale copy must never prove ownership the user no longer holds.
-*Guarded by: "maxAgeMs 0 always refetches, even within the same millisecond" and
-"verification reads the description fresh, bypassing the cache".*
-
-**S4. A PluralKit token is never persisted, cached or logged.** Tier 3 uses one
-inside a single request and discards it. *Guarded by: "the token is never
-persisted", which dumps every row of every table and asserts the token appears
-nowhere.*
-
-**S5. At most one owner per subject, enforced by the database.** The partial
-unique index `idx_grants_single_owner` is the gate; the application-level check
-exists only for a clean error message. *Guarded by: "the single-owner index
-blocks a second owner row outright".*
-
-**S6. Refusals leak nothing about who holds a thing.** `already_claimed` never
-identifies the owner; a reserved slug reports only when the reservation lapses,
-never the holder. *Guarded by: "a reserved slug is refused to others, without
-naming the holder".*
-
-**S7. Discord snowflakes are not public pkviewer identifiers.** Public `/s/...`
-resolution must reject a Discord snowflake rather than resolving it to a system.
-
-The distinction is deliberate and must be preserved:
-
-- Discord ids MAY participate in authenticated ownership verification.
-- Tier-1 claiming takes the Discord identity from authenticated session and
- account state, never from request input (see S1).
-- Public URL resolution must NEVER turn a Discord id into a browsable system
- lookup.
-
-Without this, pkviewer would expose a Discord-account to PluralKit-system
-mapping through URL enumeration — a mapping PluralKit's API permits but which no
-public pkviewer URL should hand out by guessing. *Guarded by: "a Discord
-snowflake is refused as a public reference".*
-
-**S8. A private member is indistinguishable from one that never existed** — even
-when a pkviewer slug points at it. *Guarded by: "a slug pointing at a non-public
-member resolves to nothing".*
-
-**S9. The PluralKit UUID is the identity; the short id is mutable metadata.**
-Grants, slugs, reservations, foreign keys and cache keys are all keyed on the
-UUID. The short id is refreshed on claim because users can re-roll it, and is
-used only for display and lookup. It must never become an identity.
-
-**S10. Identity and navigation are separate.** A slug is a mutable presentation
-label. Changing one never changes what a system or member *is*, and never
-transfers anything.
-
-## Slugs
-
-**L1. System slugs may not take the shape of a PluralKit short id**
-(`[a-z]{5,6}`). System slugs and system ids share one global namespace at
-`/s/<ref>`, so an id-shaped slug could shadow another system's id URL — a URL
-its owner never gave up. Removing the shape from the namespace removes the
-ambiguity with no lookup required.
-
-**Member slugs are deliberately not restricted this way.** They are namespaced
-per system, so a collision can only shadow a member of a system the claimant
-already controls: self-inflicted, not an attack. Claiming one warns
-(`shadows_member_id`) rather than refusing, which keeps ordinary names like
-`clove` available where people actually want them.
-
-**L1b. A slug must not contain `--` anywhere.** Stated as the literal substring
-rather than "no consecutive hyphens", so every validator enforces exactly the
-same rule. The purpose is to keep the punycode marker `xn--` unclaimable, so
-slugs stay safe to place in a hostname if per-system subdomains ever happen.
-
-**L2. `SLUG_MAX_LENGTH` is 32, below a UUID's 36.** This guarantees no slug can
-ever shadow `/s/<uuid>`, so every system keeps one permanently unambiguous URL
-no matter what anyone claims. Raising this limit past 35 would break that.
-
-**L3. Resolution is slug first, then id**, and neither redirects — both return
-200 and the canonical form is advertised with `<link rel="canonical">`. A 301
-would outlive slug ownership and permanently point a cached URL at whoever holds
-the name next.
-
-**L4. A subject holds at most one active slug per scope.** Claiming a new one
-releases the previous into its own 7-day reservation rather than freeing it, so
-a rename cannot be used to snipe the old URL and the owner can change their mind.
-
-**L5. Reservations follow the subject, not the account.** A different account
-managing the same system can reclaim a slug that system released.
-
-## Unclaiming
-
-**Unclaiming removes management access. Reclaiming within the grace period
-restores the saved configuration, but does not restore previous manager
-grants.** Every grant is deleted on unclaim, not just the owner's — an unclaimed
-system genuinely has no managers. The 30-day grace window restores themes and
-reserved slugs; anyone who was previously a manager must be re-invited.
-
-## Theme vocabulary
-
-The product's public design API. Changing it is a product decision, not a
-refactor. Lives in `packages/shared/src/theme/`.
-
-**T1. Theme is how things look. Composition is what appears and how it is
-arranged.** A knob that changes which information is on the page, or where it
-sits, is composition. A knob that changes the appearance of whatever is there is
-a theme token. This is why `directory.columns` is composition and `shape.radius`
-is a token — and why `directory.card.min` never became a token at all: the
-renderer needed a pixel value, but the product concept is "how many columns".
-
-**T2. Named options, never free values.** A user picks `relaxed`, not `1.3`.
-Every enum maps to concrete CSS in exactly one function, so the scale can be
-retuned later without invalidating a single stored theme. This is what keeps the
-product from being "CSS custom properties with a UI".
-
-**T3. Colour is six-digit hex only.** Not `rgb()`, not `color-mix()`, not named
-colours, not three-digit hex. One shape is trivial to validate, trivial to put
-behind a colour picker, and leaves no room for a function call to smuggle
-something through.
-
-**T4. Fonts come from a fixed table of eight**, each either the system stack or
-a Google Fonts family. A font token carries an id, never a family name and never
-a URL, so a theme can never point the browser at a resource we did not choose.
-
-**T5. One colour value per token, not one per scheme.** The platform default
-carries both light and dark grounds; a custom colour applies to whichever ground
-is active. Doubling the vocabulary to carry two of every colour would be the
-wrong trade for a non-technical editor.
-
-### Theme tokens (14)
-
-| Key | Type | Default | Member |
-|---|---|---|---|
-| `color.scheme` | enum auto/light/dark | `auto` | no |
-| `color.page` | color | `#FAF8FB` / `#151219` | yes |
-| `color.surface` | color | `#FFFFFF` / `#1E1A24` | yes |
-| `color.text` | color | `#1C1721` / `#EEEAF2` | yes |
-| `color.muted` | color | `#6B6478` / `#9A93A6` | yes |
-| `color.accent` | color | `#A23B72` / `#F58FC2` | yes |
-| `color.border` | color | `#E6E1EC` / `#302938` | yes |
-| `font.body` | font | `system` | yes |
-| `font.heading` | font | `newsreader` | yes |
-| `font.size` | enum small/medium/large | `medium` | yes |
-| `shape.radius` | enum none/small/medium/large | `medium` | yes |
-| `surface.style` | enum outlined/filled/plain | `outlined` | yes |
-| `density` | enum compact/normal/relaxed | `normal` | yes |
-| `avatar.shape` | enum circle/rounded/square | `rounded` | yes |
-
-`color.scheme` is the only system-only token. It is a property of the SITE: a
-member page flipping to dark while the system page is light reads as broken
-navigation rather than personal expression. Everything else is member
-overridable, because a member page being visually its own thing is the point.
-
-### Composition configuration (7)
-
-Separate vocabulary, separate storage, not CSS custom properties.
-
-| Key | Type | Default | Member |
-|---|---|---|---|
-| `banner.display` | enum auto/hidden | `auto` | yes |
-| `avatar.size` | enum small/medium/large | `medium` | yes |
-| `directory.columns` | enum auto/one/two/three | `auto` | no |
-| `directory.card` | enum compact/detailed | `compact` | no |
-| `directory.sort` | enum pluralkit/name | `pluralkit` | no |
-| `show.pronouns` | boolean | `true` | yes |
-| `show.birthday` | boolean | `true` | yes |
-
-Directory settings are system-only: the directory belongs to the system page,
-so a member has nothing to override there.
-
-### The `length` and `boolean` types
-
-Both are implemented and tested in the validation layer. No theme token uses
-`length` — every dimension is a named option instead, which is what keeps
-arbitrary values out. Tokens were not invented merely to exercise a type.
-
-### Presets (5)
-
-Applied by copying values into a system theme, so a preset is a starting point
-rather than a mode: everything stays editable, and a preset can be retuned later
-without silently changing anyone's page.
-
-- **Notebook** — the default, refined. Warm off-white, serif headings, soft
- outlined cards, normal density.
-- **Broadsheet** — editorial and dense. Display serif, square corners, hairline
- rules instead of cards, compact.
-- **Bloom** — soft and friendly. Rounded typeface, large radius, filled cards,
- circular avatars, relaxed.
-- **Terminal** — deliberately technical. Monospaced, near-black, square, no card
- decoration, compact.
-- **Midnight** — modern dark. Geometric headings, filled cards, soft corners.
-
-They differ in typeface, corner treatment, card style, density and ground — a
-test asserts that, so five colour swaps could not pass for five presets.
-
-### Inheritance
-
-`platform default -> system theme -> member override`, with the three states
-already locked: absent inherits, a value overrides, and an explicit `null` resets
-to the platform default while ignoring the system. That third state is what lets
-a member escape a loud system theme without restating every default by hand.
-
-Member-overridability is enforced in validation, not merely ignored at render, so
-an editor can say why something was refused.
-
-## Management plane
-
-**M1. The server is authoritative for authorization.** Every management read and
-write re-checks the grant server-side. The client can ask about any system id it
-likes; it is told 404 for every one it does not manage.
-
-**M2. Unauthorised access reports 404, never 403.** A 403 would confirm the
-system exists on pkviewer, which an unauthorised caller should not be able to
-probe for.
-
-**M3. A save is all or nothing.** If any value in a save is rejected, nothing is
-written. Dropping the invalid keys and saving the rest would silently discard
-settings the user already had — a destructive save wearing the costume of a
-validation error. *Guarded by: "a rejected save leaves existing settings
-untouched".*
-
-**M4. Theme and composition are written independently.** A save names the layer
-it touches, so saving appearance can never wipe directory settings. *Guarded by:
-"saving one layer leaves the other untouched".*
-
-**M5. The management UI does not reveal private members.** It lists the members
-PluralKit returns publicly, from the same public request the public site makes.
-Being signed in as the owner does not change what the public API returns and
-pkviewer does not ask for more, so a private member is absent here and 404s
-individually. *Guarded by: "a member PluralKit withholds is absent, and 404s
-individually".*
-
-**M6. The management app has its own visual language.** It never inherits the
-user's public theme: it must look the same whichever system you are editing. Its
-custom properties are namespaced `--mg-*` so they cannot collide with the
-`--pkv-*` tokens a preview renders with.
-
-**M7. One source of truth for how a token becomes a style.** The editor's
-preview calls the same `resolveTheme` and `themeToCssVars` the public renderer
-does. Only the sample content is local to the editor.
-
-**M8. The browser never talks to the API directly.** Server components and
-server actions forward the session cookie, so `INTERNAL_API_ORIGIN` stays
-internal and the `__Host-` cookie's host pinning is never loosened to permit a
-cross-origin call.
-
-**M9. Inheritance is UI, not data the user authors.** Nobody types `null`,
-deletes a field, or edits JSON. A control is either following what it inherits
-or explicitly set, with buttons to move between those states. Inherited versus
-overridden is shown by a word and a border, never by colour alone.
-
-**M10. Applying a preset at member level is an explicit member configuration.**
-It never reaches up and changes the system.
-
-## Public addresses
-
-The public URL is a product feature, not an implementation detail. "Slug" is
-internal vocabulary; the UI says **address** throughout.
-
-**U3. A chosen address is never required for a page to be public.** A claimed
-system is reachable at its PluralKit ID address from the moment it is claimed. A
-chosen address only makes the link friendlier to share, and the ID address keeps
-working afterwards. The no-address state says so plainly rather than reading as
-an incomplete setup.
-
-**U4. Copying is never the only way to get an address.** Every public URL is
-shown as selectable text and offered as an ordinary link alongside the copy
-button, so it works without JavaScript, without clipboard permission, and for
-anyone who would rather select it by hand. Copy success is announced in words
-through a live region, never signalled by colour alone.
-
-**U5. Availability checks are advisory.** The client checks as you type purely
-for immediate feedback; the claim path re-checks transactionally, because
-availability can change between the two. The server's answer is the only one
-that counts.
-
-**U6. A held address never names its holder.** A conflict reports only that the
-address is held and when the hold lapses. Neither the holding system nor its
-managers appear anywhere in the response.
-
-**U7. Changing an address breaks links to the old one.** The old address enters
-its 7-day hold immediately and stops resolving; it is not redirected, because a
-redirect would outlive ownership. The UI says this before the change, not after.
-
-## Audit findings
-
-**A4. Nothing may be statically prerendered if it embeds a configured origin.**
-Prerendering bakes the BUILD-TIME origin into the HTML, so a domain move would
-need a rebuild rather than an env change — which is precisely what
-decision 1 forbids. `/`, `/docs` and the not-found page are therefore
-`force-dynamic`. Verified by building with one origin and serving with another.
-
-**A5. A visibility setting removes the value, it does not hide it.** `show.pronouns`
-and `show.birthday` strip the field in the page model rather than omitting it in
-markup, so a hidden value is not shipped in the page source at all. This is
-public PluralKit data either way, but a setting should do what it says.
-
-**A6. The three inheritance states must survive storage.** A reset is stored as
-an explicit null; reading a layer through a string-only filter collapsed three
-states into two and made "use the platform default" land on the system's value.
-Stored layers are read as `Record<string, string | null>`.
-
-**A7. Staleness is measured against the reference that was actually fetched.**
-A slug resolves through the stored UUID and an id through the id itself, so
-asking "how old is this data" under a guessed key silently missed for id-based
-URLs. `ResolvedSystem.cacheRef` carries the key that was used.
-
-**A8. Audit breadcrumbs must not block account deletion.** `grants.granted_by`
-and `themes.updated_by` record who did something; they are not ownership. Left
-without an `ON DELETE` rule they defaulted to RESTRICT, so deleting an account
-that had ever granted a role or saved a theme failed outright — and account
-deletion is a stated requirement. Both are now `ON DELETE SET NULL`
-(migration 004). *Guarded by: "an account that has granted a role and saved a
-theme can be deleted".*
-
-### Known limitation
-
-`notFound()` called under a layout that has already streamed renders the correct
-page but does not set a 404 status, so unauthorised `/manage/<id>` returns 200
-with the right content. Confirmed in both dev and production builds. The content
-is correct and discloses nothing — a system that does not exist and one that
-belongs to someone else are indistinguishable — and every management page is
-`noindex`. Worth revisiting if it ever matters for monitoring.
-
-## Deployment
-
-**D1. Two containers, mirroring the two processes.** The API is the only SQLite
-writer, so it is the only container with the data volume. It is `expose`d to the
-compose network and never `ports:`-published: the browser reaches it only
-through the web tier's proxy, so publishing 3001 would put the management API on
-the host network. The web tier publishes `3000:3000` on every interface: the
-reference deployment has no public IP and gets its traffic through a Cloudflare
-Tunnel, which dials out and forwards inward, and a loopback bind is unreachable
-from another container or machine. TLS terminates at Cloudflare. The http hop
-from tunnel to container is safe because `Secure` is set unconditionally rather
-than inferred from the request, so no forwarded-proto trust is configured
-anywhere. Guarded by `apps/web/test/docker.test.ts`.
-
-**D2. Compose runs images, it never builds them.** There is one
-`docker-compose.yml` with no `build:` section at all;
-`.github/workflows/images.yml` publishes `doughmination/pkviewer-api` and
-`doughmination/pkviewer-web` to **Docker Hub** for amd64 and arm64. Building on the
-server costs CPU it has none of and, worse, makes the running code a function of
-whatever source happens to be checked out rather than of a known commit. An
-overlay file offering both modes was tried and rejected as a second thing to
-keep in step. Docker Hub over GHCR was the owner's preference — both registries
-pin identically, so this was not a technical constraint. CI authenticates with a
-scoped access token in `DOCKERHUB_TOKEN`, never a password.
-
-**D3. Compose runs `latest`, and every start pulls.** The image names and the
-tag are written into `docker-compose.yml` literally — nothing about which image
-runs is configurable, so there is no server-side variable that can drift from
-what CI publishes, and a deploy is `pull && up -d` with nothing to edit.
-`pull_policy: always` is what makes a moving tag work at all: without it a
-restart reuses the local image cache. The owner chose this over pinning an
-immutable tag, having weighed it twice; CI still publishes `sha-<short>` and
-semver tags, so a rollback means retagging one of those as `latest` by hand.
-The accepted costs are that a bad `main` reaches the server on the next pull,
-and that the running version is recorded nowhere. A test asserts CI publishes
-exactly the images compose runs, because nothing else connects those two files
-and the failure only surfaces at deploy time.
-
-**D4. Origins are configuration, never baked into an image.** The web image
-builds with `http://build.invalid` placeholders precisely so that a value
-leaking into the bundle would be obvious. Every page embedding an origin is
-force-dynamic and reads config at request time, which is what keeps the eventual
-domain move a config change rather than a rebuild.
-
-**D5. The container Bun must match the lockfile's Bun.** A stale pin (1.2 against
-a 1.4 lockfile) built locally and failed on the server, since `--frozen-lockfile`
-cannot satisfy a newer lockfile. `--frozen-lockfile` stays — it was correctly
-reporting a real mismatch — and a test asserts the pinned tag tracks the Bun the
-suite runs under.
-
-**D6. Missing Discord credentials warn, they do not abort.** Production once
-hard-failed without them, which contradicted the documented read-only
-deployment and showed up only as an unhealthy container. Public pages work
-without sign-in; the warning names the three variables that enable it.
-
-## Recognition
-
-**R1. Admin is a grant over the platform, not a flag on an account.**
-`grants(account_id, subject_type='platform', subject_id='pkviewer', role='admin')`.
-Reusing the existing table means one authorization concept rather than two, and
-it produces the permission boundary structurally: every system-scoped check
-looks up a grant whose `subject_id` is that system, so a platform grant cannot
-satisfy it. **An admin administers pkviewer; an admin does not gain access to
-anyone's system, theme, address or links.** Migration 005's CHECK constraint
-refuses to store `admin` over a system, or `owner` over the platform, so this
-cannot regress into a code question. *Guarded by: "an admin grant does not
-confer access to any system", and by route tests asserting all fourteen `/admin`
-endpoints 404 for a signed-in non-admin.*
-
-**R2. The first admin comes from outside the application.** `bun run
-admin:grant <discord-id>`. Not an environment variable — that would re-promote
-whoever holds the id on every restart, with no record — and not an HTTP route,
-because there is nobody to authorise the first one. The script reads only
-`DATABASE_PATH`, so it works when the rest of the configuration is broken.
-
-**R3. A badge is platform-issued, and its appearance must be unreachable from
-the theme.** This is the whole value of the feature: a badge is worth something
-only because a system cannot produce one. Themes emit `--pkv-*`; badge CSS uses
-`--pkvb-*` and literals exclusively, and states its own font, size, weight and
-radius rather than inheriting them. A badge that read `--pkv-color-accent` could
-be recoloured to impersonate another badge, or set to the page background to
-hide one. Every badge links to `/badges`, which pkviewer owns, so imitation text
-has nowhere convincing to point. *Guarded by: "no badge rule reads a theme
-property", which parses the stylesheet by selector rather than by position.*
-
-**R4. Badge wording is data; badge appearance is code.** The catalogue is a
-table so a new badge type is an admin action rather than a deploy, but `icon`
-and `tone` are keys validated against a fixed list in `packages/shared/src/
-recognition.ts` before a row is written. No stored value ever becomes a colour,
-a class, markup or a URL. A row whose icon or tone is unrecognised is dropped at
-read time rather than rendered unstyled.
-
-**R5. A badge is an offer, not a fact.** `pending → accepted | declined`, plus
-`hidden` (recipient) and `revoked` (admin); `accepted` is the only state that
-renders, filtered in one query so a new caller cannot leak a pending offer. A
-badge appears on someone else's page and describes them to their visitors —
-"Girlfriend" discloses a relationship, and a vulnerability badge names someone in
-connection with a disclosure. A grant auto-accepts only when the granting admin
-also manages the subject, which is what makes the owner's own badge frictionless
-without special-casing it. A hidden badge is indistinguishable from one never
-granted.
-
-**R6. Badges attach to the system, credits attach to nobody.** A badge's subject
-is `systems.id`; member pages carry none, because a badge recognises the system
-and repeating it per member would misattribute it. Credits are a separate model
-entirely (`credit_sections` + `credits`) with a name, what they did, and an
-optional link — someone who emails a vulnerability report and never signs in
-still gets named. Sections are rows, so the public page contains no list of
-categories to fall out of date. Credit URLs follow the social-link rule: http(s)
-only, rendered as links, never fetched.
-
-**R7. Retiring a badge does not remove it from pages.** A retired catalogue
-entry cannot be granted again but keeps rendering where already accepted;
-deleting the row would silently strip a badge from someone's page because the
-catalogue was tidied.
-
-## Guardrails
-
-No user JavaScript, ever. No arbitrary HTML. No custom CSS. No
-server-side fetching of user-supplied URLs (SSRF) — social links are rendered as
-links and never fetched for previews or favicons. Public pages show only what
-PluralKit makes public. Fonts come from a fixed allow-list; no arbitrary font
-URLs or uploads.
diff --git a/docs/deployment.md b/docs/deployment.md
deleted file mode 100644
index 5643274..0000000
--- a/docs/deployment.md
+++ /dev/null
@@ -1,380 +0,0 @@
-# Deploying pkviewer
-
-## Shape
-
-Two processes on one machine, behind a reverse proxy that terminates TLS:
-
-```
- ┌──────────────────────────────┐
- users ────┤ proxy (TLS) │
- └──────────────┬───────────────┘
- │
- apps/web (Node) :3000
- │ localhost HTTP
- apps/api (Bun) :3001
- │
- SQLite file on a persistent disk
-```
-
-One hostname, one Next process. There is no origin-based routing: every route
-is served from the same origin.
-
-**This cannot run on a serverless platform.** SQLite needs a persistent disk and
-a single long-lived writer. A small VPS, or a container with a real volume.
-
-Only the web tier is reachable from outside. The API binds loopback by default
-(`API_HOST`, default `127.0.0.1`) — the browser never calls it, and the web tier
-proxies everything. In containers it binds `0.0.0.0` because the container
-network provides the isolation instead, and its port is never published.
-
-## Environment variables
-
-`.env` lives at the repository root and is read by both tiers.
-
-Legend: **required** = the process refuses to start without it ·
-**production** = additionally required when `NODE_ENV=production` ·
-*secret* = never commit, never log, never send to the browser.
-
-### Origins — required
-
-| Variable | Consumed by | Notes |
-|---|---|---|
-| `PUBLIC_ORIGIN` | api, web | **The one user-facing origin.** Serves `/`, `/login`, `/auth/...`, `/manage/...` and `/s/...`. Must be https in production. |
-| `PUBLIC_ASSET_ORIGIN` | api | *Optional.* Defaults to `PUBLIC_ORIGIN`. Reserved for serving media elsewhere. |
-| `INTERNAL_API_ORIGIN` | web | Where the web tier reaches the API. Internal; never reaches the browser. |
-| `PUBLIC_DOCS_URL` | web | *Optional.* The separate documentation site. Empty hides every documentation link rather than producing a dead one. |
-
-These are read at **runtime**, not baked into the build. A domain move is a
-config change plus a restart, not a rebuild — every page that embeds an origin
-is `force-dynamic` specifically to keep that true.
-
-### PluralKit — one required
-
-| Variable | Required | Notes |
-|---|---|---|
-| `PK_USER_AGENT_CONTACT` | **required** | URL placed in the `User-Agent`. **Point it at the repository, not the deployment origin**, so it survives a domain move. PluralKit asks that an application's UA be stable and identifiable. |
-| `PK_API_BASE` | optional | Defaults to `https://api.pluralkit.me/v2`. |
-| `PK_RATE_LIMIT_READ_RPS` | optional | Default 6, deliberately under PluralKit's documented 10/s. |
-| `PK_RATE_LIMIT_WRITE_RPS` | optional | Default 2, under their 3/s. |
-
-### Sessions and Discord
-
-| Variable | Required | Notes |
-|---|---|---|
-| `SESSION_SECRET` *secret* | **production** | ≥32 chars. `openssl rand -base64 32`. Outside production an ephemeral one is generated per start, with a warning. |
-| `DISCORD_CLIENT_ID` | **production** | From the Discord developer portal. |
-| `DISCORD_CLIENT_SECRET` *secret* | **production** | Same. |
-| `DISCORD_REDIRECT_URIS` | **production** | Comma-separated. **Register both the old and new URIs together** before a domain move, so it is a cutover rather than a flag day. Each must be `<public origin>/auth/discord/callback` and registered identically in Discord. |
-
-Without Discord credentials the app still runs and every public page works —
-nobody can sign in, and `/auth/discord/start` answers 503. That is a legitimate
-read-only deployment, and startup says so rather than refusing to boot.
-
-`PUBLIC_ORIGIN` must still be https in production even before a certificate
-exists: it is the public URL visitors will use, TLS terminates at the proxy in
-front, and the container itself speaks http behind it. Session cookies are
-`Secure`, so sign-in cannot work over http.
-
-### Database
-
-| Variable | Required | Notes |
-|---|---|---|
-| `API_HOST` | optional | Interface the API binds to. Default `127.0.0.1`. Set `0.0.0.0` only where something else isolates it, such as a container network with an unpublished port. |
-| `API_PORT` | optional | Default `3001`. |
-| `DATABASE_PATH` | optional | Default `./data/pkviewer.db`. **Relative paths resolve against the API process's working directory**, which is `apps/api` under `bun run dev` — so the dev database is at `apps/api/data/pkviewer.db`. **Use an absolute path in production.** |
-
-### Other flags
-
-| Variable | Default | Notes |
-|---|---|---|
-| `SIGNUP_ENABLED` | `true` | Gates creating a **new** account only. Turning it off never locks an existing account out of what it already has. |
-| `API_PORT` | `3001` | |
-| `NODE_ENV` | `development` | `production` turns on the stricter checks above. |
-
-pkviewer is no longer in beta. `BETA_MODE` and `BETA_ALLOWED_DISCORD_IDS` are
-gone rather than defaulted off — setting them now does nothing. Claiming is open
-to any signed-in account, gated by proving control of the system rather than by
-membership of a list, and public pages are indexable.
-
-### Minimum production set
-
-```
-NODE_ENV=production
-PUBLIC_ORIGIN=https://system.example
-INTERNAL_API_ORIGIN=http://127.0.0.1:3001
-DATABASE_PATH=/var/lib/pkviewer/pkviewer.db
-PK_USER_AGENT_CONTACT=https://github.com/OWNER/pkviewer
-PUBLIC_DOCS_URL=https://docs.example
-SESSION_SECRET=<openssl rand -base64 32>
-DISCORD_CLIENT_ID=<from Discord>
-DISCORD_CLIENT_SECRET=<from Discord>
-DISCORD_REDIRECT_URIS=https://system.example/auth/discord/callback
-SIGNUP_ENABLED=true
-```
-
-Under Docker, `INTERNAL_API_ORIGIN` and `DATABASE_PATH` are set by compose
-(`http://api:3001` and `/data/pkviewer.db`) rather than by `.env`.
-
-Configuration is validated at startup and a missing or malformed value fails
-loudly, naming the variable. It never falls back to an insecure default in
-production.
-
-## Database
-
-One SQLite file, in WAL mode. Migrations apply automatically at API start, in
-filename order, each in its own transaction; already-applied ones are skipped.
-
-Schema changes are additive: **add a new migration, never edit an applied one.**
-
-### What to back up
-
-| | |
-|---|---|
-| `DATABASE_PATH` | The database. Everything pkviewer owns. |
-| `<path>-wal`, `<path>-shm` | Sidecars. Present while running; a copy without them can be inconsistent. |
-| `.env` | Secrets. **Back up separately from the database, not alongside it.** |
-
-**Never `cp` a live database.** WAL means a plain copy can be torn. Take a
-consistent snapshot while running with:
-
-```bash
-sqlite3 /var/lib/pkviewer/pkviewer.db ".backup '/backups/pkviewer-$(date +%F).db'"
-```
-
-or `VACUUM INTO`. Both are safe against a running server. For continuous
-protection, [Litestream](https://litestream.io) replicates WAL to object storage
-and preserves the "it's just a file" model — the highest-value addition when this
-carries other people's data.
-
-### If the database is lost
-
-PluralKit data is not lost — it is PluralKit's, and re-fetches. What is lost is
-everything pkviewer owns: accounts and their Discord links, which systems are
-claimed and by whom, chosen addresses and their reservations, themes, layout
-settings, and social links.
-
-Public pages would keep working for systems reachable by PluralKit ID; chosen
-addresses would stop resolving and would become claimable by anyone. Claiming
-would have to be redone. **Treat the database as the thing that actually needs
-backing up.**
-
-## Running with Docker
-
-`docker-compose.yml` runs images; it never builds them. Images are built and
-published by `.github/workflows/images.yml`, so what runs on the server is
-always something CI produced from a known commit — the server needs no
-toolchain, no source checkout and no spare CPU, and there is no question of
-which working copy the running code came from.
-
-Which images run is not configurable: `docker-compose.yml` names
-`doughmination/pkviewer-api:latest` and `doughmination/pkviewer-web:latest`
-outright. On the server, that file and `.env` are all that is needed:
-
-```bash
-cp .env.example .env # fill in the production values
-docker compose pull
-docker compose up -d
-```
-
-Two containers, mirroring the architecture: `api` owns SQLite and is the only
-writer; `web` renders and proxies. Configuration comes from `.env` at run time —
-nothing secret is baked into an image, and no origin is compiled in, so moving
-domains stays a config change.
-
-Four details in `docker-compose.yml` are deliberate:
-
-- **`api` has no `ports:`, only `expose:`.** Publishing 3001 would put the
- management API straight onto the host network, reachable without going through
- the web tier. It is addressable only as `http://api:3001` from inside.
-- **`web` publishes `3000:3000`, on every interface.** A loopback-only bind is
- unreachable from another container or another machine, which is what
- Cloudflare Tunnel needs. TLS terminates at Cloudflare; the container is never
- the thing facing the internet. See below.
-- **`pull_policy: always`.** A pinned tag is only a pin if a restart actually
- fetches it rather than reusing whatever is in the local image cache.
-- **The named volume `pkviewer-data` is the whole of pkviewer's state.** Back
- that up; see below.
-
-Backups work the same way, run against the container:
-
-```bash
-docker compose exec api sh -c \
- "bun -e 'new (require(\"bun:sqlite\").Database)(\"/data/pkviewer.db\").exec(\"VACUUM INTO \\\"/data/backup.db\\\"\")'"
-```
-
-or more simply, stop the stack and copy the volume. Never `cp` a live WAL
-database.
-
-### Getting traffic in: Cloudflare Tunnel
-
-The reference deployment has no public IP. `cloudflared` dials out to
-Cloudflare, which terminates TLS and forwards to the container, so nothing is
-inbound-reachable and no ports need opening at the network edge.
-
-Point the tunnel at `http://<host-lan-ip>:3000` — or `http://web:3000` if
-`cloudflared` runs as a container on the same compose network, which avoids
-publishing the port at all. `3000:3000` rather than `127.0.0.1:3000:3000` is
-what makes the first form work: a loopback bind is not reachable from another
-container or another machine.
-
-**Plain http on that hop is fine.** The browser talks https to Cloudflare, and
-`Secure` is set unconditionally rather than inferred from the request
-(`apps/api/src/http/cookies.ts`), so no forwarded-proto trust needs configuring.
-`PUBLIC_ORIGIN` must still be the https URL: it is what the CSRF check compares
-the `Origin` header against, and what every absolute link is built from.
-
-One thing to be aware of if this ever runs on a host that *does* have a public
-IP: Docker publishes through the `DOCKER-USER` chain and `nat PREROUTING`, which
-run **before** the `INPUT` chain `ufw` and `firewalld` manage, so `ufw deny 3000`
-does nothing. Restricting it then means a security group, or
-`iptables -I DOCKER-USER -p tcp --dport 3000 ! -s <source> -j DROP`.
-
-## Administrators
-
-Admin is a grant row, not an environment variable. `ADMIN_*` does not exist, and
-neither does an HTTP route that creates the first one — there would be nobody to
-authorise it, and a variable would silently re-promote whoever held that Discord
-id on every restart, with no record of when or by whom.
-
-```bash
-bun run admin:list
-bun run admin:grant <discord-user-id>
-bun run admin:revoke <discord-user-id>
-```
-
-Run from the repository root, so `.env` is picked up. Under Docker:
-
-```bash
-docker compose exec api bun run scripts/admin.ts list
-```
-
-The account must exist first: sign in with that Discord account once, then grant
-it. Only the database path is read, so this still works when Discord
-credentials are missing — which is when you are most likely to need it.
-
-**What an admin can do** is grant badges and edit the credits page. **What an
-admin cannot do** is touch anyone's system, theme, address or links: system
-access is a grant whose subject is that system, and a platform grant can never
-satisfy that lookup. The database refuses to store `admin` over a system at all
-(migration 005), so this is a schema constraint rather than a convention.
-
-## Publishing images
-
-`.github/workflows/images.yml` builds both images for amd64 and arm64 on every
-push to `main` and publishes them to Docker Hub.
-
-It needs one repository secret, under Settings → Secrets and variables →
-Actions: **`DOCKERHUB_TOKEN`**, a personal access token with Read & Write scope,
-from Docker Hub → Account settings → Personal access tokens.
-
-Use an access token, never the account password: a token is scoped, listed, and
-revocable on its own without changing the password everywhere else it is used.
-The account name is not a secret — it is half of every published image name —
-so it sits in the workflow as `DOCKERHUB_USER`.
-
-The two repositories — `doughmination/pkviewer-api` and
-`doughmination/pkviewer-web` — are created by the first successful push. They
-are public by default; make them private in Docker Hub if that is wanted, and
-then `docker login` on the server before pulling.
-
-**The images pin Bun to the version that wrote `bun.lock`.** A frozen install
-cannot satisfy a lockfile written by a newer Bun, so an image pinned behind the
-lockfile fails while building fine locally. When you upgrade Bun, update
-`docker/*.Dockerfile` in the same commit — a test asserts they match.
-
-To build an image by hand, from the repository root:
-
-```bash
-docker build -f docker/api.Dockerfile .
-docker build -f docker/web.Dockerfile .
-```
-
-### Tags
-
-Every build is published under several tags:
-
-| Tag | Moves | Notes |
-| --- | --- | --- |
-| `latest` | yes, on every push to `main` | what compose runs |
-| `sha-abc1234` | never | the exact commit |
-| `1.2.3` | never | a release, from a `v1.2.3` git tag |
-| `1.2` | yes, within a minor series | a patch series |
-
-Compose runs `latest` and nothing else, so a `docker compose pull` is the whole
-upgrade and there is no version to keep in step between the repository and the
-server. The cost is that a bad `main` reaches the server on the next pull, and
-that the running version is not recorded anywhere.
-
-To go back, pull an older tag under the `latest` name by hand:
-
-```bash
-docker pull doughmination/pkviewer-api:sha-abc1234
-docker tag doughmination/pkviewer-api:sha-abc1234 doughmination/pkviewer-api:latest
-docker compose up -d --no-deps api # without `pull`, which would undo it
-```
-
-That holds until the next `docker compose pull`, so it buys time to fix `main`
-rather than being a place to sit.
-
-### Deploying a new image
-
-```bash
-docker compose pull
-docker compose up -d
-```
-
-Nothing to edit: CI publishes `latest`, `pull` fetches it, `up -d` recreates
-whichever containers changed.
-
-Migrations run on API start, inside the one process that owns the database, and
-are forward-only. Test them against a copy of production data before deploying a
-schema change — retagging an older image does not roll a migration back.
-
-## Working locally
-
-Deployment goes through images, but the checks that gate one still run here:
-
-```bash
-bun install
-bun run check # guard, typecheck, tests
-bun run build
-```
-
-The production build writes to `.next-prod` and the dev server uses `.next`, so
-building never disturbs a running development server. `NEXT_DIST_DIR` overrides
-the directory if a deployment needs it elsewhere.
-
-Running the two processes directly — `bun run dev` — needs the same environment
-variables as the containers, minus the image ones. `API_HOST` defaults to
-`127.0.0.1` outside Docker; the images set it to `0.0.0.0` so the web container
-can reach the API over the compose network.
-
-## Moving domains
-
-Under the rules above this is configuration, with two things that are not free:
-
-1. **Sessions end.** Cookies are host-scoped; everyone signs in again.
-2. **PluralKit dispatch webhooks break silently** if that integration is ever
- enabled — the URL lives on PluralKit's side. Keep the old host answering
- `/dispatch` through the transition; do not rely on a redirect.
-
-Register both redirect URIs in Discord before the move, and keep the old host
-redirecting for a long while.
-
-## Security posture
-
-Set by the web tier, since the browser never talks to the API directly:
-`Content-Security-Policy` (including `frame-ancestors 'none'`),
-`X-Content-Type-Options`, `Referrer-Policy`, `X-Frame-Options`,
-`Permissions-Policy`, `Cross-Origin-Opener-Policy`, and `Strict-Transport-Security`
-in production.
-
-Two deliberate CSP exceptions, both documented in `apps/web/next.config.ts`:
-`script-src` allows `'unsafe-inline'` because Next bootstraps through inline
-scripts and tightening it needs per-request nonces; `img-src` allows any https
-host because avatars and banners live wherever each system put them. Neither is
-load-bearing for XSS, because pkviewer accepts no user HTML, no user JavaScript
-and no free-form CSS.
-
-TLS is terminated at the proxy. Cookies are `Secure` and `__Host-` prefixed, so
-**the app must be served over https in production or sign-in will not work.**