The API v2 plan is revised down to the work that is actually justified: a CSP hardening pass and an in-place domain split of the monolithic route wiring. - Auth merge (httpOnly cookies -> bearer + rotating refresh for every client) is removed and re-filed as deferred behind trigger conditions. httpOnly+SameSite is the stronger model, session.service.js already unifies cookie and bearer, the SSO/PKCE transaction cookies survive any merge, and it dragged the admin SSE fetch/ReadableStream rewrite along as a dependency for no user-visible payoff. A revival must first spec refresh-token reuse detection and a rollback procedure. - No parallel /api/v2. The URL surface is already grouped by capability, so each new router file mounts at the prefix it already owns and every URL stays byte-identical. No dual mount, no per-route migration, no v1 retirement; the SPA, Discord bot, and Android app are all untouched. API_V2_SKELETON.md is marked superseded (kept as the recipe if a versioned API is ever forced). - The /api/mobile facade and app-version floor are deferred with the revival note that it starts as a one-line alias mount, not ~70 hand-written delegates. The M11 milestone is dropped from android/PLAN.md. - Adds PR 0: a generated route manifest, so "every URL is unchanged" is proved by a zero-line diff rather than asserted in review. The baseline api-route-inventory.json (199 API routes + 2 internal) is committed here and is what PR 0's generator must reproduce byte-for-byte. - Split sequenced as five grouped PRs; CSP fixed to report-only first, then enforce (the old plan contradicted itself), with the verified delta being just form-action 'self' and frame-ancestors 'none'. Co-Authored-By: Claude <noreply@anthropic.com>
22 KiB
Website API — router domain split + CSP hardening
Status: planning · Target repo: website/ · Docs owner: this file + BACKEND_DESIGN.md
This file replaces the earlier "API v2" plan (auth merge → CSP → domain split, with a parallel
/api/v2mount and an/api/mobilefacade). Three of those four pieces are not being built: the auth merge and the mobile facade are deferred with their reasoning recorded below, and the parallel-version scaffold in API_V2_SKELETON.md is superseded. The filename is kept so existing links resolve. What remains is genuinely useful work:
- CSP hardening — small, independent, ships on its own cadence.
- The domain split —
admin.routes.js(1552 lines, 110 routes) broken into one router file per business capability, in place, with every URL unchanged. This is the actual driver.
Why the auth merge is out
The original plan replaced httpOnly session cookies with a bearer JWT + rotating refresh token for every client, so web and mobile would share one session model. Reasons that no longer hold up:
- The current model is the more secure one. httpOnly + SameSite cookies are unreadable from JS
and carry CSRF protection by default. Every migration target is a sideways or backwards move:
- Refresh token in
localStorage→ any XSS becomes persistent full account takeover, not a bounded access-token window. A short access TTL does not help; the attacker mints new pairs. - Refresh token in an httpOnly cookie scoped to the refresh endpoint → safe, but that is cookies with extra steps. It concedes the premise.
- Refresh token in
- "One session model everywhere" is already true where it matters.
auth/session.service.jsunifies cookie and bearer into a single session, andauth/token.jsalready extracts from eitherCookieorAuthorization: Bearer. That abstraction is written, working, and paid for. The merge would move complexity out ofextractTokenand into the SPA. - The cookie codepath survives the merge anyway. The SSO / email-connect redirect flow must keep its short-lived httpOnly tx / PKCE-verifier / pending-TOTP cookies — the browser leaves for the IdP and returns with no JS context. So the merge never actually delivered "cookies are gone."
- It carried the plan's most bug-prone work as a dependency. The admin SSE rewrite
(
EventSource→ hand-rolledfetch+ReadableStream+ SSE frame parser + reconnect/backoff + refresh-on-401) existed only to serve the bearer model. Without the merge, the admin stream stays onEventSourcewithwithCredentialsand that code is never written. - It is a contract change with no user-visible payoff, competing for the same review attention as the domain split, which is the thing that actually hurts today.
Dropped with it
- v2 bearer auth routes (
/api/v2/auth/{login,refresh,logout,login/totp}). - Deletion of the
setAuthCookie/clearAuthCookiepath. rg_trustcookie →X-Trust-Tokenheader migration for web (the header stays available for native clients viaextractTrustToken, unchanged).api/client.jsbearer + silent-refresh rewrite.lib/useShardFeed.jsadmin-stream fetch rewrite. The admin SSE stream stays as-is.
Kept from it
- CSP hardening — now its own phase (below). It was justified as a compensating control for a JS-held token; it is worth doing regardless, just no longer urgent.
- The public/admin SSE allowlist split — unchanged security boundary, unrelated to session model.
- The tx-cookie carve-out reasoning — recorded here so a future merge attempt doesn't rediscover it.
Deferred: the auth merge
Not cancelled — parked behind trigger conditions. Revisit if any of these become true:
| Trigger | Why it changes the answer |
|---|---|
| The API becomes genuinely cross-origin (separate API host) | SameSite cookies stop being the easy path; bearer becomes the natural model. |
| Third-party or OAuth clients are introduced | Cookies don't serve clients you don't control. |
| Mobile and web session behavior diverge enough to cause real bugs | The unification argument gets teeth it currently lacks. |
If it is ever revived, two specs the original plan lacked must be written first:
- Refresh-token reuse detection. Rotation is only useful with it: replay of an already-consumed refresh must revoke the entire token family, not just fail the one request.
- Rollback procedure. Once web clients have discarded their cookies, a bad deploy locks everyone out. Needs a documented path back.
Why there is no /api/v2
The domain split reorganizes router files. It does not need to move a single URL — because the URL
surface is already grouped by capability. Inventory taken from the live Express stack — 196
/api/v1 routes, plus three outside it (GET /api/health, GET /api/docs.json,
GET /.well-known/assetlinks.json) and 2 on the internal port. Full machine-readable list:
api-route-inventory.json.
| Group | Routes | Second segment → capability |
|---|---|---|
/admin |
110 | shard 16 · moderation 15 · users 15 · wiki 14 · posts 9 · pages 7 · account 6 · email 6 · uo-link 5 · auth 4 · invites 3 · bot-activity 2 · discord-bot 2 · settings 2 · activity 1 · dashboard 1 · site-mode 1 · uploads 1 |
/auth |
42 | me 23 · mobile 5 · sso 4 · password 3 · invite 2 · login 2 · logout 1 · providers 1 · register 1 |
/public |
24 | shard 12 · wiki 4 · pages 2 · posts 2 · contact 1 · settings 1 · status 1 · version 1 |
/player |
20 | account 8 · shard 8 · appeals 4 |
Every capability already owns a URL prefix, so each new router file mounts at the prefix it already owns and the emitted paths are byte-identical. No URL change means no contract change, and no contract change means no reason to mount a parallel version.
Consequences of doing it in place:
- No
/api/v2, no dual mount, no route-by-route migration, no v1-usage telemetry project, and no v1-retirement sequence. BASE = /api/v1inclient/src/api/client.jsnever changes. The Discord bot'sSITE_PUBLIC_URLnever changes. The Android app is untouched.- API_V2_SKELETON.md (the
router/v2/scaffold) is superseded and not scheduled. It is kept as the concrete recipe if a real contract break ever forces a versioned API.
Tripwire: if any endpoint turns out to need a new URL, that is a contract change, not a refactor. List it explicitly, and reopen the versioning question before writing the code — do not smuggle a URL change into a "mechanical" PR.
Deferred: the /api/mobile facade and the app-version floor
The earlier plan's Phase 0 stood up a version-agnostic /api/mobile namespace and migrated the
Android app onto it, plus an app-version header and a server-side min-version floor.
Why it was proposed: the app hardcodes 69 distinct api/v1/… paths (data/api/*.kt,
core/net/ShardStreamClient.kt, core/net/HostSelectionInterceptor.kt,
core/auth/sso/SsoAuthManager.kt), has no version negotiation and no force-update, and installs in
the wild cannot be forced forward. Under a parallel-/api/v2 plan that made the app the load-bearing
coupling: v1 could not be retired until the fleet aged out.
Why it is deferred: with the split done in place, no URL moves and nothing is being deleted — so there is no fleet to sunset and no coupling to break. A facade would add ~70 permanently maintained delegate routes plus a contract-test suite to solve a problem that does not currently exist. The version floor was scoped to sunsetting the pre-facade fleet, so it goes with it.
If it is ever revived (the trigger is the mobile contract genuinely needing to diverge from web — different response shapes, a mobile-only aggregation endpoint, a real breaking change):
- Start with the alias mount, not a delegate layer:
apiRouter.use('/mobile', v1Router)gives the app a stable, version-agnostic namespace with identical wiring, identical middleware and zero per-route maintenance. Build hand-written delegates only for the routes that actually diverge. - A facade is a security surface, not a convenience alias. Any hand-written route must carry the
same middleware chain as the route it mirrors (
requireAuth,staffOnly/adminOnly, validators, the public/admin SSE allowlist split). A re-exposed admin route missingadminOnlyis privilege escalation. - It needs contract tests. The moment the app pins a namespace, its response shapes are a committed contract; an internal refactor that changes a shape must fail a test before it ships to installed apps.
- The mobile SSE stream stays anonymous under whatever path it gets — the app sends no
Authorizationheader.
Phase 1 — CSP hardening (independent)
Previously bundled with the auth merge as a compensating control for a JS-held token. With no token in JS, this is defense in depth on its own merits — cheap, worth doing, blocking nothing. It has no dependency on the domain split and can ship at any time.
Sequencing fix from the original plan: the old version both "ships with the auth merge" and called for a one-release report-only soak. Those contradict. Correct order is report-only first, observe one release, then enforce — now trivially satisfiable since nothing waits on it.
The app already ships a tuned policy (server/src/app.js). Two directives are load-bearing and are
already correct — the job is to keep them that way:
script-src 'self'— no'unsafe-inline'/'unsafe-eval'. Primary defense.connect-src 'self'— the exfiltration channel. Don't widen it unless the API genuinely becomes cross-origin (which would also reopen the auth-merge question — see the trigger table).
style-src 'unsafe-inline' stays — it permits inline styling, not script execution, and React's
pervasive style={{…}} attributes can't be nonce'd. Not a meaningful hole. The /api/docs route keeps
its deliberately looser policy (swagger-ui injects an inline bootstrap script); that carve-out is
scoped to the one route and stays scoped.
Target enforced policy:
default-src 'self';
script-src 'self';
connect-src 'self';
img-src 'self' data: https:;
style-src 'self' 'unsafe-inline'; /* + fonts.googleapis.com only until fonts are self-hosted */
font-src 'self'; /* + fonts.gstatic.com only until fonts are self-hosted */
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
Delta vs. the policy in server/src/app.js today — the whole change is two directives:
- Add
form-action 'self'(currently absent) — blocks an injected<form action="https://evil">from POSTing credentials off-origin, an exfil pathconnect-srcdoesn't cover. - Tighten
frame-ancestors'self'→'none'— nothing legitimately frames the site. - Unchanged:
default-src,script-src,connect-src,object-src 'none',base-uri 'self', andimg-src … https:(externalBRAND_*logo/hero and<img>in sanitized wiki/news bodies rely onhttps:).
Rollout: ship via Content-Security-Policy-Report-Only with report-to for one release, watch for
violations, then flip to enforce.
Before trusting script-src 'self': Vite's build injects an inline modulepreload-polyfill <script>
into dist/index.html, which that directive blocks (harmless, but throws a violation). Confirm it's
disabled or set build.modulepreload.polyfill = false in the Vite config. (The renderIndexHtml
branding injection adds only <meta>/<link> tags — no inline script, no nonce needed.)
Tracked follow-ups (own PRs):
- Self-host the Cinzel font → drop
fonts.googleapis.comfromstyle-srcandfonts.gstatic.comfromfont-src, removing two third-party origins from the trust surface. - Trusted Types —
require-trusted-types-for 'script'+ atrusted-typespolicy, report-only first. AuditdangerouslySetInnerHTML+ thesanitizeHtmlrender path first.
Phase 2 — The domain split
This is the reason the plan exists. Everything else is supporting work.
Rule: one router file = one business capability; the URL names the domain; related endpoints live
together regardless of HTTP method; no generic admin.routes.js catch-all. Controllers are already
domain-split — this re-wires routes, not logic.
Invariant: each capability router mounts at the prefix it already owns, so the emitted URL set does not change. Proved per PR by the route manifest (§ PR 0).
Target tree — derived from the inventory above, inside router/v1/ (no v2/ directory):
router/v1/
admin/
index.js # mounts the capability routers below under /admin, keeps the
# shared `noindex, isLoggedIn, staffOnly` gate in one place
users.router.js account.router.js invites.router.js
authProviders.router.js moderation.router.js botActivity.router.js
posts.router.js pages.router.js wiki.router.js
uploads.router.js shard.router.js uoLink.router.js
email.router.js discordBot.router.js settings.router.js
dashboard.router.js # + the /activity and /site-mode singletons
auth/
login.router.js register.router.js password.router.js invite.router.js
sso.router.js mobile.router.js me.routes.js (already split, 23 routes)
public/
news.router.js (posts) pages.router.js wiki.router.js shard.router.js
site.router.js # status, settings, version, contact
player/
account.router.js shard.router.js appeals.router.js
internal/ (unchanged — stays on the unpublished port, never mounted publicly)
Steps:
- Land PR 0 (route manifest) first — the mechanical proof that later PRs move no URL.
- Carve
admin.routes.jsinto the per-capability files above, each requiring its already-existing controller.admin/index.jskeeps the shared gate (noindex, isLoggedIn, staffOnly) and mounts each capability router at its existing prefix; theadminOnly/modAccessgates move with the routes that use them. - Split
public.routes.js,player.routes.js, and the remainingauth.routes.jsgroups the same way.auth/me.routes.jsis already a separate file and stays. - Keep
/internaloff the public listener exactly as today (separateinternalApp.jsport). - Move each route's
#swagger.*annotations with the route, then regenerate (cd website/server && npm run swagger). - Update
BACKEND_DESIGN.md§2 (folder structure) and §4 (API contract — it namesadmin.routes.js → admin.controller.jsand friends) as routers move, plusPROJECT_TREE.md.
Because the auth model is untouched and the URLs are frozen, each PR is a pure mechanical refactor with a green test suite and a zero-diff route manifest as its acceptance criteria — which is what makes grouped PRs actually reviewable.
PR 0 — the route manifest (prerequisite of the first split PR)
"Every URL is unchanged" must be proved by a diff, not asserted in review. PR 0 lands the tool that proves it, with no router file moved.
- Generator:
server/scripts/routeManifest.js, wired asnpm run routes:manifest. It requiressrc/app.js(which exports the app and neither listens nor connects to the DB —server.jsowns those), walksapp._router.stackrecursively through mounted routers, reconstructs each full path from the layer regexps, and writes a sorted array of{ "method": "GET", "path": "/api/v1/admin/users/:id" }toserver/routes.manifest.json.internalApp.jsis walked into a separateinternalsection so the unpublished port is inventoried without being confused for public surface. - Scope it to the API surface, or it won't be deterministic. Three mounts are filesystem
conditional: the SPA catch-all
GET *(only whenclient/dist/index.htmlexists), the/brandstatic mount, and/api/docs*(only whenswagger-output.jsonis present — it is committed, so it is stable). The manifest keeps only/api/**,/.well-known/**, and the internal app's routes, so it does not change depending on whether CI built the client. Static mounts are not API contract. - The baseline already exists:
api-route-inventory.jsonin this directory is today's frozen surface — 199 API routes (110 of them/api/v1/admin) plus 2 internal. PR 0's generator must reproduce this file byte-for-byte; that is PR 0's own acceptance test, and it means the freeze is already in effect before the first router moves. - Runtime introspection, not source parsing. It is authoritative about mounts, and the route paths
in
admin.routes.jssit on the line afteradminRouter.get(, which defeats naive greps. - Not
swagger-output.json. That is annotation-derived (only annotated routes appear) and churns for unrelated reasons; it documents intent, the manifest records reality. - Frozen key: method + path only. That is exactly the contract being preserved. Handler names are
useless as a guard check here —
requireRole(...)returns an anonymous arrow, and router-level gates likeadminRouter.use(noindex, isLoggedIn, staffOnly)never appear in a route's own stack. - Guard coverage, separately. The generator also emits a non-gated review aid: per route, the
handler count plus any named middleware collected along the mount chain. If a stable behavioral
check proves cheap, prefer it — a test that fires an unauthenticated request at every manifest
path and snapshots the status code catches a dropped
adminOnly(403 → 200) in a way names cannot. Try it in PR 0; if DB-touching public routes make it slow or noisy against the dead-port pool the tests use, drop it rather than ship a flaky gate. - CI:
.gitea/workflows/pr-checks.ymlrunsnpm run routes:manifestandgit diff --exit-code server/routes.manifest.json. A PR that moves a URL fails unless it deliberately commits the new manifest — which puts the URL change in front of a reviewer instead of letting it pass silently. - Published copy:
docs/website/api-route-inventory.jsonmirrorsserver/routes.manifest.jsonand is refreshed in each split PR's mandatory docs edit. The markdown table above is orientation for a human reader; the manifest is the authoritative freeze.
Sequencing & PR breakdown
CSP and the split are independent; the only hard ordering is PR 0 before the first split PR.
- PR — CSP report-only. Tightened policy behind
Content-Security-Policy-Report-Only+report-to. - PR — CSP enforce. One release later, assuming a clean violation report.
- PR 0 — route manifest. Generator + CI check + committed baseline of today's surface. No routers moved.
- PR 1 — admin:
users,account,invites,auth(providers). - PR 2 — admin:
moderation,bot-activity,activity. - PR 3 — admin (content):
posts,pages,wiki,uploads. - PR 4 — admin (ops/config):
shard,uo-link,email,discord-bot,settings,site-mode,dashboard. - PR 5 —
public/*+player/*(and the residualauth/*grouping).
Each PR: zero-line diff in routes.manifest.json, server tests green
(cd website/server && npm test), Swagger regenerated, matching docs/ edit, Conventional Commit,
AI-disclosure trailer, branch from a freshly-pulled main.
Cross-component blast radius
Three independent clients consume the site's HTTP/SSE API, two of them in separate repos on separate release cadences. With the auth merge and the version bump both gone, the blast radius is empty — no client's URLs or authentication change at all.
| Consumer | Repo (cadence) | Pinning | Impact under this plan |
|---|---|---|---|
| Browser SPA | website/client (lockstep) |
BASE = /api/v1 in client/src/api/client.js |
None. Same URLs, same cookie session. |
| Android app | android-app (app-store cadence, un-updatable installs in the wild) |
69 hardcoded api/v1/… paths; SSE path in ShardStreamClient.kt; SSO in SsoAuthManager.kt |
None. No repoint, no release required. |
| Discord bot | website/bot (separate deploy, env-configured) |
SITE_PUBLIC_URL env → /api/v1/public |
None. Anonymous public reads on unchanged paths. |
Standing constraints, unchanged:
- The public SSE stream stays anonymous. Consumed by logged-out browser visitors and the Android
ShardStreamClient, neither of which sends anAuthorizationheader. AddingrequireAuthblacks out the public live boards on web and mobile. The single most likely regression in a careless refactor is reflexively wrapping both shard streams in auth. - The admin SSE stream keeps its current cookie-based gating (
isLoggedIn,EventSource+withCredentials) — the rewrite that would have changed this went out with the auth merge. - The public/admin allowlist split is a security boundary, not an implementation detail. Preserve
it verbatim in
utils/shardBroadcast.js/utils/shardIngest.jsas routes move. - SSO / email-connect transaction cookies are load-bearing for web and native. The Android SSO
flow opens a Custom Tab to the website's
/auth/…/sso/startand rides the same server-side redirect transaction and the same tx cookies. Nothing in this plan touches them; don't let a future "cookies go away" push delete them. link/is out of scope. The sidecar contract (uoLinkConfig,utils/uoLinkClient.js,utils/shardIngest.js,X-UOLink-Version) is a separate versioning axis.PROTOCOL_VERSIONdoes not bump for this work.
Appendix: mapping from the previous plan
| Previous | Now |
|---|---|
Phase 0 — /api/mobile facade + app-version floor |
Deferred. See § Deferred: the /api/mobile facade |
| Phase 1 — auth merge | Removed. See § Why the auth merge is out and § Deferred: the auth merge |
| Phase 1b — CSP hardening (shipped with the auth merge) | Phase 1, standalone; report-only-first ordering fixed |
Phase 2 — domain split under router/v2/ |
Phase 2, in place under router/v1/; now the primary driver |
PR 1 — /api/v2 scaffold (API_V2_SKELETON.md) |
Superseded, kept as the recipe if a versioned API is ever forced |
| PR final — retire v1 | Not applicable — v1 is never replaced |