Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
close every server-owned namespace with a 404 instead of the SPA index (#4688)
[._.]/ Adam Eivye87dcc74040a
diff --git a/docs/PORTS.md b/docs/PORTS.mdindex e890a6cfb3..677099d090 100644--- a/docs/PORTS.md+++ b/docs/PORTS.md@@ -54,7 +54,10 @@ Rules of thumb:1. **`:5555` is the only port a remote user ever needs.** The scheme (HTTP vs HTTPS) flips based on whether a TLS cert is provisioned (`npm run setup:cert`); the port number does not.2. **`:5553` is a convenience for local terminals.** When HTTPS is on, `https://localhost:5555` would trip a cert warning (the cert covers `<machine>.<tailnet>.ts.net`, not `localhost`). The loopback HTTP mirror on `:5553` lets curl/scripts skip TLS entirely. It binds to `127.0.0.1` only — never reachable over the network.3. **`:5554` is `vite dev` only.** In `npm run dev`, Vite serves the React UI from `:5554` and proxies `/api`, `/data` and `/socket.io` to `:5555`. In `npm start` (production), the React build is served from `:5555` itself; `:5554` is unused.- - **Anything the server serves must be in that proxy list.** An unproxied path does not 404 in dev — Vite's SPA fallback answers it with `index.html` and a `200`, so a loader expecting bytes parses HTML and fails somewhere far from the cause (a missing `/data/image-to-3d` entry surfaced as `Unexpected token '<' … is not valid JSON` from the GLB viewer, which took its whole route down). `/data` is therefore proxied as one wildcard prefix, and `scripts/dev-proxy-drift.test.js` fails if a server `/data/**` mount ever falls outside it.+ - **A server-owned path must never be answered by an SPA fallback — and there are two of them.** Neither 404s. In dev, Vite answers an unproxied path with `index.html` and a `200`; in production the fallback in `server/index.js` skips a request only when its path carries a file extension, so an EXTENSIONLESS one falls through the same way. Either shape hands a binary loader HTML, which fails far from the cause (a missing `/data/image-to-3d` proxy entry surfaced as `Unexpected token '<' … is not valid JSON` from the GLB viewer, which took its whole route down), or hands an API client HTML with a success status.+ - **Dev side:** `/data` is proxied as one wildcard prefix, so a new mount is covered the moment it is added.+ - **Production side:** `server/lib/assetRoutePrefixes.js` lists the namespaces the server owns (`SERVER_OWNED_PREFIXES`) alongside the exact client routes inside them (`spaPaths` — `/data` itself is the Data Manager page), and `mountAssetRoutes` closes each one with a terminating 404 (#4688).+ - `scripts/dev-proxy-drift.test.js` fails if the proxy, the mounts, or the client's own routes (`NAV_COMMANDS`) drift apart — including when a new client page is added *under* a server-owned prefix, which the terminator would otherwise 404 silently.## Defining Ports in ecosystem.config.cjsdiff --git a/scripts/dev-proxy-drift.test.js b/scripts/dev-proxy-drift.test.jsindex 0bb2a2d80b..fe508bbaef 100644--- a/scripts/dev-proxy-drift.test.js+++ b/scripts/dev-proxy-drift.test.js@@ -1,19 +1,26 @@/**- * Drift guard for the Vite dev proxy, in both directions.+ * Drift guard for the server's owned URL prefixes, in both directions.** Under `npm run dev` (and under PM2, which runs the UI as the Vite dev server)* the browser talks to :5554, so anything the API serves must be proxied to* :5555 — and anything the CLIENT routes must NOT be. Both mistakes fail* quietly, which is why they are pinned here rather than left to review:*- * - a MISSING mount is answered by Vite's SPA fallback with index.html and a- * 200, so a binary loader parses HTML and reports something unrelated to- * the cause (`/data/image-to-3d` was absent, and the GLB viewer died on- * "Unexpected token '<' ... is not valid JSON", taking its route with it);+ * - a MISSING proxy context is answered by Vite's SPA fallback with+ * index.html and a 200, so a binary loader parses HTML and reports+ * something unrelated to the cause (`/data/image-to-3d` was absent, and the+ * GLB viewer died on "Unexpected token '<' ... is not valid JSON");* - an OVER-BROAD context steals a page: Vite matches a plain context with a* bare `url.startsWith`, so a `'/data'` key would also capture the `/data`* and `/datadog` routes and hand the browser the API's built index.html.*+ * Production has the same hole on the other side — the SPA fallback in+ * `server/index.js` skips a request only when its path carries a file+ * extension. `SERVER_OWNED_PREFIXES` is what closes it, and the third section+ * below covers the one failure neither the proxy nor the terminator can see+ * alone: a client route added UNDER a server-owned prefix, which the terminator+ * would 404 with nothing failing near the new route.+ ** Full story in docs/PORTS.md.*/import { describe, it, expect } from 'vitest';@@ -22,15 +29,12 @@ import { dirname, join } from 'path';import { fileURLToPath } from 'url';import { NAV_COMMANDS } from '../server/lib/navManifest.js';+import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from '../server/lib/assetRoutePrefixes.js';+import { ASSET_MOUNTS } from '../server/lib/assetMounts.js';const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');const read = (rel) => readFileSync(join(REPO_ROOT, rel), 'utf8');-/** Every `app.use('/data…', …)` mount declared by the server. */-function serverDataMounts(source) {- return [...source.matchAll(/app\.use\(\s*['"](\/data(?:\/[^'"]*)?)['"]/g)].map(([, path]) => path);-}-/*** Every proxy context in the dev server config.*@@ -56,28 +60,66 @@ function devProxyContexts(source) {const proxyMatches = (context, url) =>(context[0] === '^' && new RegExp(context).test(url)) || url.startsWith(context);+const navPaths = NAV_COMMANDS.map((command) => command.path);+describe('vite dev proxy vs the server and the client router', () => {- const mounts = serverDataMounts(read('server/index.js'));+ // The mounts come from the table `server/index.js` mounts from, not from a+ // regex over its source — that table is why the two cannot disagree.const contexts = devProxyContexts(read('client/vite.config.js'));- it('finds the mounts and the proxy contexts it is comparing', () => {- // A regex that silently matched nothing would make every assertion below- // vacuously true.- expect(mounts.length).toBeGreaterThan(5);+ it('finds the prefixes and the proxy contexts it is comparing', () => {+ // An empty list on either side would make every assertion below vacuously+ // true — this is the one that fails if the wiring itself breaks.+ expect(ASSET_ROUTE_PREFIXES.length).toBeGreaterThan(5);expect(contexts).toContain('/api');+ expect(navPaths.length).toBeGreaterThan(5);});- it('proxies an asset under every /data mount the server serves', () => {- const unproxied = mounts.filter(- (mount) => !contexts.some((context) => proxyMatches(context, `${mount}/probe.bin`)),+ it('proxies an asset under every mount the server serves', () => {+ const unproxied = ASSET_ROUTE_PREFIXES.filter(+ (route) => !contexts.some((context) => proxyMatches(context, `${route}/probe.bin`)),);expect(unproxied).toEqual([]);});it('leaves every client route to the dev server', () => {- const stolen = NAV_COMMANDS- .map((command) => command.path)- .filter((path) => contexts.some((context) => proxyMatches(context, path)));+ const stolen = navPaths.filter(+ (path) => contexts.some((context) => proxyMatches(context, path)),+ );expect(stolen).toEqual([]);});});++describe('the asset table vs what the server mounts', () => {+ it('has a mount, in order, for every asset route prefix', () => {+ // `ASSET_MOUNTS` is what actually gets mounted; the prefix list is what the+ // dev proxy is checked against. A route in one and not the other is drift.+ expect(ASSET_MOUNTS.map((mount) => mount.route)).toEqual(ASSET_ROUTE_PREFIXES);+ expect(ASSET_MOUNTS.every((mount) => typeof mount.dir === 'function')).toBe(true);+ });++ it('serves every asset route from inside a terminated namespace', () => {+ // A mount outside every `SERVER_OWNED_PREFIXES` entry keeps the pre-#4688+ // behaviour: an extensionless path under it answered with the SPA index.+ const prefixes = SERVER_OWNED_PREFIXES.map(({ prefix }) => prefix);+ const unterminated = ASSET_ROUTE_PREFIXES.filter(+ (route) => !prefixes.some((prefix) => route.startsWith(`${prefix}/`)),+ );+ expect(unterminated).toEqual([]);+ });+});++describe('server-owned prefixes vs the client router', () => {+ it('declares every client route that lives under a server-owned prefix', () => {+ // The failure this catches: someone adds a `/data/backups` page. The+ // terminator 404s it, the page simply does not exist, and nothing points at+ // `assetRoutePrefixes.js`. Adding the route to that entry's `spaPaths` is+ // the fix — this test is what says so.+ const undeclared = SERVER_OWNED_PREFIXES.flatMap(({ prefix, spaPaths }) => (+ navPaths.filter((path) => (+ (path === prefix || path.startsWith(`${prefix}/`)) && !spaPaths.includes(path)+ ))+ ));+ expect(undeclared).toEqual([]);+ });+});diff --git a/server/index.js b/server/index.jsindex 9bf186c3bb..0f3e79f69e 100644--- a/server/index.js+++ b/server/index.js@@ -3,6 +3,7 @@ import { Server } from 'socket.io';import { fileURLToPath } from 'url';import { dirname, join } from 'path';import { PATHS } from './lib/fileUtils.js';+import { mountAssetRoutes } from './lib/assetMounts.js';import { existsSync } from 'fs';import { createTailscaleServers } from '../lib/tailscale-https.js';import { certPaths } from '../lib/certPaths.js';@@ -151,7 +152,6 @@ import { bootstrapServices, runBootSequence, registerShutdownHandlers } from './import { errorMiddleware } from './lib/errorHandler.js';import { setHttpsEnabledAtBoot } from './lib/httpsState.js';import { JSON_BODY_LIMIT } from './lib/uploadLimits.js';-import { wrWorksDir } from './services/writersRoom/_shared.js';import { createPortOSProviderRoutes } from './routes/providers.js';import { createPortOSRunsRoutes } from './routes/runs.js';import { createPortOSPromptsRoutes } from './routes/prompts.js';@@ -386,52 +386,13 @@ app.use('/api/midi-runtime', midiRuntimeRoutes);app.use('/api/peer-sync', peerSyncRoutes);app.use('/api/ask', askRoutes);-// Asset static mounts. `acceptRanges: true` is the serve-static default-// already, but we set it explicitly because the federated peer-sync receiver-// (services/sharing/peerSync.js) background-pulls missing assets from these-// URLs and relies on HTTP Range to resume partial downloads over flaky-// Tailnet links — losing range support here would silently force every-// retry to restart from byte 0 on a multi-MB PNG / video. Same posture for-// every kind below (image, image-ref, video, video-thumbnail).-const ASSET_STATIC_OPTS = { acceptRanges: true };-app.use('/data/images', express.static(PATHS.images, ASSET_STATIC_OPTS));-// Reference images (multi-ref upload inputs + generated character reference-// sheets) — served read-only so the UI can render thumbnails by URL.-app.use('/data/image-refs', express.static(PATHS.imageRefs, ASSET_STATIC_OPTS));-// LoRA training dataset images (lora-datasets/<id>/images/*.png).-app.use('/data/lora-datasets', express.static(PATHS.loraDatasets, ASSET_STATIC_OPTS));-// Serve generated videos + thumbnails so the Media UI and tailnet clients-// can pull them by URL without going through an explicit download route.-app.use('/data/videos', express.static(PATHS.videos, ASSET_STATIC_OPTS));-app.use('/data/video-thumbnails', express.static(PATHS.videoThumbnails, ASSET_STATIC_OPTS));-// Sprite Manager library previews (anchors, strips, atlases) render inline-// via <img src="/data/sprites/<id>/<rel>"> (#2895).-app.use('/data/sprites', express.static(PATHS.sprites, ASSET_STATIC_OPTS));-// Image-to-3D GLB meshes (#2952) — the /3d R3F viewer loads them inline-// via drei useGLTF from <model.assetPath> (/data/image-to-3d/<id>/model.glb).-app.use('/data/image-to-3d', express.static(PATHS.imageTo3d, ASSET_STATIC_OPTS));-// Voice-over WAVs rendered by the pipeline audio stage — the AudioStage UI-// pulls them inline via <audio src="/data/audio/<filename>">.-app.use('/data/audio', express.static(PATHS.audio));-// Background-music tracks (uploaded today, generated locally tomorrow). The-// AudioStage music picker plays them inline via <audio src="/data/music/...">.-app.use('/data/music', express.static(PATHS.music));-// Extracted third-party import assets (ChatGPT export images/audio/PDFs). The-// Brain Memory conversation viewer renders these inline (``) and as asset links. Read-only; range support for large PDFs.-app.use('/data/brain-imports', express.static(PATHS.brainImportAssets, ASSET_STATIC_OPTS));-// Writers Room file-primary draft prose bodies (works/<workId>/drafts/<draftId>.md).-// Federation (#1565) pulls them peer→peer from this mount: a receiver that merged-// a work record GETs each missing body's bytes by its nested path. Read-only;-// range support for large drafts. (Tailnet-only per the project's threat model.)-// The gate restricts the mount to the draft-body path ONLY — without it, the-// static root would also serve adjacent work-metadata JSON (manifest.json /-// manifest.imported.json on file-backend/migrated installs) to any client that-// knows a work id. Only `<workId>/drafts/<draftId>.md` is needed for body pulls.-app.use('/data/writers-room/works', (req, res, next) => {- if (!/^\/[^/]+\/drafts\/[^/]+\.md$/.test(req.path)) return res.status(404).end();- next();-}, express.static(wrWorksDir(), ASSET_STATIC_OPTS));+// Asset static mounts, then a terminating 404 for every server-owned prefix so+// an extensionless `/data/…` or a mistyped `/api/…` can no longer fall through+// to the SPA fallback below and be answered with index.html and a 200 (#4688).+// Both lists live in lib/assetRoutePrefixes.js, which `client/vite.config.js`+// and `scripts/dev-proxy-drift.test.js` read as data — so the dev proxy and the+// guard cannot fall behind this file.+mountAssetRoutes(app);// Serve built client UI (production mode — no Vite dev server needed)const CLIENT_DIST = join(__dirname, '..', 'client', 'dist');diff --git a/server/lib/README.md b/server/lib/README.mdindex 563201ec8f..b447a3d24c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -361,6 +361,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `apiRegistry.js` | Single source of truth for which PortOS services are externally-callable HTTP APIs (`voice`, `sdapi`). `API_REGISTRY` declares each API's `publicPrefixes` (read/compute-safe surface only) + defaults; `isRegistryPublic(settings, path)` tells `authGate` when an `exposed && !requireAuth` API re-opens its prefix; `resolveApiAccess(settings)` merges persisted `apiAccess` flags for the Settings UI + OpenAPI docs. || `arrayUtils.js` | `shuffle(arr)` — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never `arr.sort(() => Math.random() - 0.5)`, which is biased. Shared by `meatspacePostCognitive.js` (Schulte table / mental rotation) and `meatspacePostMemory.js` (memory drill generators). |+| `assetMounts.js` | `ASSET_MOUNTS` — every `/data/**` static mount as `{ route, dir, gate? }` (`dir` a thunk so a test that re-roots `PATHS.data` still steers it) — plus `mountAssetRoutes(app)`, which mounts them and then TERMINATES each `SERVER_OWNED_PREFIXES` namespace with a 404. The terminator matters: the SPA fallback only skips paths carrying a file extension, so an extensionless `/data/…` or a mistyped `/api/…` used to be answered with index.html and a 200 — a binary loader parsed HTML, an API client got HTML with a success status (#4688). |+| `assetRoutePrefixes.js` | Import-free leaf holding the URL prefixes the server owns: `ASSET_ROUTE_PREFIXES` (every `/data/**` static mount) and `SERVER_OWNED_PREFIXES` (what must never reach the SPA fallback, each with the exact `spaPaths` that ARE client routes). `scripts/dev-proxy-drift.test.js` checks the dev proxy's `^/data/` wildcard against the mounts, and fails if a `NAV_COMMANDS` route is ever added under a server-owned prefix without being declared. || `asyncMutex.js` | Promise-based async mutex. || `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. Consults `apiRegistry.isRegistryPublic` so an exposed+passwordless API (voice/sdapi) bypasses the gate on its public prefix only. || `concurrencyGate.js` | `createConcurrencyGate(limit)` → `run(fn)` — cap on simultaneous async work for ONE module-scoped budget, released FIFO. Sibling to `mapWithConcurrency.js`, which caps in-flight work *within one array map*; a gate is shared state, so several call sites fanning out at the same remote respect one budget instead of each respecting its own while the host sees the sum. `createMutex` (`asyncMutex.js`) is this with `limit` fixed at 1 — prefer it for mutual exclusion. Note the budget is per-MODULE, not per-host: two modules calling one host each get their own gate. Used by `huggingFaceCatalog.js` (4) and `ollamaRegistryCatalog.js` (16), whose cold catalog-enrichment bursts otherwise arrive at a free public API as a thundering herd — which the Hub answers with an HTTP/2 GOAWAY that surfaces as a bare `fetch failed`. |diff --git a/server/lib/assetMounts.js b/server/lib/assetMounts.jsnew file mode 100644index 0000000000..75f07a6f9c--- /dev/null+++ b/server/lib/assetMounts.js@@ -0,0 +1,110 @@+/**+ * The server's static asset mounts, as data, plus the terminator that stops a+ * server-owned path from being answered with the SPA index.+ *+ * `server/index.js` used to spell each `app.use('/data/…', express.static(…))`+ * out inline, so nothing could enumerate what was served without regexing the+ * source. This is the `server/lib/navManifest.js` pattern the root CLAUDE.md+ * recommends for exactly that drift problem: one table, iterated by the thing+ * that mounts and read as data by the guards. The route strings themselves live+ * one level down in `assetRoutePrefixes.js`, an import-free leaf that+ * `client/vite.config.js` also reads — that is what keeps the dev proxy from+ * falling behind the mounts.+ *+ * `dir` is a thunk, not a string: `wrWorksDir()` derives its path at call time,+ * and a test that re-roots `PATHS.data` at a temp tree needs every entry to+ * resolve after the mock, not at import.+ */+import express from 'express';+import { PATHS } from './fileUtils.js';+import { ServerError, sendErrorResponse } from './errorHandler.js';+import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from './assetRoutePrefixes.js';+import { wrWorksDir } from '../services/writersRoom/_shared.js';++// `acceptRanges: true` is the serve-static default already, but we set it+// explicitly because the federated peer-sync receiver+// (services/sharing/peerSync.js) background-pulls missing assets from these+// URLs and relies on HTTP Range to resume partial downloads over flaky+// Tailnet links — losing range support here would silently force every+// retry to restart from byte 0 on a multi-MB PNG / video.+const ASSET_STATIC_OPTS = { acceptRanges: true };++// Only `<workId>/drafts/<draftId>.md` is needed for federation body pulls.+// Without this gate the static root would also serve adjacent work-metadata+// JSON (manifest.json / manifest.imported.json on file-backend/migrated+// installs) to any client that knows a work id.+const writersRoomDraftBodiesOnly = (req, res, next) => {+ if (!/^\/[^/]+\/drafts\/[^/]+\.md$/.test(req.path)) return res.status(404).end();+ next();+};++// Keyed by route so the mount order stays owned by `ASSET_ROUTE_PREFIXES` — the+// list `client/vite.config.js` reads — rather than being restated here.+const ASSET_DIRS = {+ '/data/images': () => PATHS.images,+ // Reference images (multi-ref upload inputs + generated character reference+ // sheets) — served read-only so the UI can render thumbnails by URL.+ '/data/image-refs': () => PATHS.imageRefs,+ // LoRA training dataset images (lora-datasets/<id>/images/*.png).+ '/data/lora-datasets': () => PATHS.loraDatasets,+ // Generated videos + thumbnails, so the Media UI and tailnet clients can pull+ // them by URL without going through an explicit download route.+ '/data/videos': () => PATHS.videos,+ '/data/video-thumbnails': () => PATHS.videoThumbnails,+ // Sprite Manager library previews (anchors, strips, atlases) render inline+ // via <img src="/data/sprites/<id>/<rel>"> (#2895).+ '/data/sprites': () => PATHS.sprites,+ // Image-to-3D GLB meshes (#2952) — the /3d R3F viewer loads them inline+ // via drei useGLTF from <model.assetPath> (/data/image-to-3d/<id>/model.glb).+ '/data/image-to-3d': () => PATHS.imageTo3d,+ // Voice-over WAVs rendered by the pipeline audio stage — the AudioStage UI+ // pulls them inline via <audio src="/data/audio/<filename>">.+ '/data/audio': () => PATHS.audio,+ // Background-music tracks (uploaded today, generated locally tomorrow). The+ // AudioStage music picker plays them inline via <audio src="/data/music/...">.+ '/data/music': () => PATHS.music,+ // Extracted third-party import assets (ChatGPT export images/audio/PDFs). The+ // Brain Memory conversation viewer renders these inline (``) and as asset links. Read-only; range support for large PDFs.+ '/data/brain-imports': () => PATHS.brainImportAssets,+ // Writers Room file-primary draft prose bodies (works/<workId>/drafts/<draftId>.md).+ // Federation (#1565) pulls them peer→peer from this mount: a receiver that merged+ // a work record GETs each missing body's bytes by its nested path. Read-only;+ // range support for large drafts. (Tailnet-only per the project's threat model.)+ '/data/writers-room/works': wrWorksDir,+};++const ASSET_GATES = { '/data/writers-room/works': writersRoomDraftBodiesOnly };++/** Every asset mount as `{ route, dir, gate? }`, in mount order. */+export const ASSET_MOUNTS = ASSET_ROUTE_PREFIXES.map((route) => ({+ route,+ dir: ASSET_DIRS[route],+ gate: ASSET_GATES[route],+}));++/**+ * Mount every asset route, then close each server-owned namespace with a 404.+ *+ * The terminators are the point. The SPA fallback skips a request only when its+ * path carries a file extension (`/\.\w+$/`), so an EXTENSIONLESS server path —+ * `/data/image-to-3d/<id>/model`, or a mistyped `/api/…` — used to fall through+ * to the stamped index.html with a 200. A binary loader then parses HTML and+ * dies on a JSON syntax error naming a `<` token, nowhere near the real cause+ * (#4688); an API client gets HTML where it expects JSON, with a success+ * status. The envelope comes from `sendErrorResponse` so this 404 is the same+ * shape as every other one PortOS emits.+ */+export function mountAssetRoutes(app) {+ ASSET_MOUNTS.forEach(({ route, dir, gate }) => {+ app.use(route, ...(gate ? [gate] : []), express.static(dir(), ASSET_STATIC_OPTS));+ });+ SERVER_OWNED_PREFIXES.forEach(({ prefix, spaPaths }) => {+ app.use(prefix, (req, res, next) => (+ // `app.use('/data', …)` reduces the page's own request to `req.path === '/'`.+ spaPaths.includes(prefix + (req.path === '/' ? '' : req.path))+ ? next()+ : sendErrorResponse(res, new ServerError('Not found', { status: 404 }))+ ));+ });+}diff --git a/server/lib/assetMounts.test.js b/server/lib/assetMounts.test.jsnew file mode 100644index 0000000000..5db216c249--- /dev/null+++ b/server/lib/assetMounts.test.js@@ -0,0 +1,129 @@+/**+ * The server-owned namespaces have a hole that only shows up on an+ * EXTENSIONLESS path.+ *+ * The SPA fallback in `server/index.js` skips a request when its path carries a+ * file extension (`/\.\w+$/`), which worked only because every asset happened to+ * carry one. `/data/image-to-3d/<id>/model` — no extension, no matching mount —+ * fell through to the stamped index.html with a 200, so a binary loader parsed+ * HTML and died on a JSON syntax error naming a `<` token, nowhere near the+ * cause. A mistyped `/api/…` had the same hole, handing an API client HTML with+ * a success status. The terminators close both, and this pins every half: they+ * fire, the client's own `/data` page still reaches the SPA fallback, and real+ * assets are still served.+ */+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';+import express from 'express';+import { mkdirSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { request } from './testHelper.js';+import { createTempDataRoot, makePathsProxy } from './mockPathsDataRoot.js';++// Re-roots every `PATHS` member under a temp tree, so the mounts resolve there+// instead of at the running install's `data/` — including `wrWorksDir()`, which+// derives from `PATHS.data`. This is why every `dir` in the table is a thunk:+// it has to read `PATHS` after this mock applies, not at import.+const tempRoot = createTempDataRoot('portos-asset-mounts-');+vi.mock('./fileUtils.js', async (importOriginal) => (+ makePathsProxy(await importOriginal(), { dataRoot: tempRoot })+));+afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));++// Dynamic, not a static import: the `vi.mock` factory above closes over+// `tempRoot`, and a static import would be hoisted above that binding.+const { ASSET_MOUNTS, mountAssetRoutes } = await import('./assetMounts.js');++// Stand-in for the SPA fallback `server/index.js` installs after the asset+// mounts — same extension guard, so the test exercises the real interaction+// between the terminators and the fallback rather than a terminator alone.+const spaFallback = (req, res, next) => {+ if (req.path.match(/\.\w+$/) && !req.path.endsWith('.html')) return next();+ res.type('html').send('<!DOCTYPE html><html><body>PortOS</body></html>');+};++let app;++beforeAll(() => {+ // Real files under real mounts, so "the asset mounts still work" is proved by+ // bytes coming back rather than by the absence of a 404.+ mkdirSync(join(tempRoot, 'images'), { recursive: true });+ writeFileSync(join(tempRoot, 'images', 'probe.png'), 'PNGBYTES');+ const drafts = join(tempRoot, 'writers-room', 'works', 'wr-work-1');+ mkdirSync(join(drafts, 'drafts'), { recursive: true });+ writeFileSync(join(drafts, 'drafts', 'd1.md'), '# body');+ writeFileSync(join(drafts, 'manifest.json'), '{"private":true}');++ app = express();+ mountAssetRoutes(app);+ app.use(spaFallback);+});++describe('the server-owned namespace terminators', () => {+ it('404s an extensionless /data path instead of answering with the SPA index', async () => {+ const res = await request(app).get('/data/image-to-3d/abc123/model');+ expect(res.status).toBe(404);+ expect(res.body).toMatchObject({ error: 'Not found', code: 'NOT_FOUND' });+ expect(res.text).not.toContain('<!DOCTYPE');+ });++ it('404s an extensioned /data path that no mount serves', async () => {+ const res = await request(app).get('/data/image-to-3d/abc123/model.glb');+ expect(res.status).toBe(404);+ expect(res.body).toMatchObject({ code: 'NOT_FOUND' });+ });++ // Same hole, worse symptom: a client asking for JSON got HTML and a 200.+ it('404s a mistyped API path instead of answering with the SPA index', async () => {+ for (const path of ['/api/does-not-exist', '/sdapi/v1/nope']) {+ const res = await request(app).get(path);+ expect(res.status).toBe(404);+ expect(res.body).toMatchObject({ code: 'NOT_FOUND' });+ }+ });++ it('still hands the client its own /data page', async () => {+ for (const path of ['/data', '/data/']) {+ const res = await request(app).get(path);+ expect(res.status).toBe(200);+ expect(res.text).toContain('PortOS');+ }+ });++ it('leaves a sibling route whose name merely starts with "data" alone', async () => {+ // `app.use('/data', …)` matches on segment boundaries. `/datadog` is the+ // probe that observes that — `/devtools/datadog` never reaches the+ // terminator under any implementation, so it would prove nothing.+ const res = await request(app).get('/datadog');+ expect(res.status).toBe(200);+ expect(res.text).toContain('PortOS');+ });++ it('still serves an asset from a mount', async () => {+ const res = await request(app).get('/data/images/probe.png');+ expect(res.status).toBe(200);+ expect(res.text).toBe('PNGBYTES');+ });+});++describe('the writers-room draft-body gate', () => {+ it('serves a draft body but not the metadata beside it', async () => {+ const body = await request(app).get('/data/writers-room/works/wr-work-1/drafts/d1.md');+ expect(body.status).toBe(200);+ expect(body.text).toBe('# body');++ // The gate is what keeps the static root from also serving adjacent+ // work-metadata JSON to any client that knows a work id.+ const manifest = await request(app).get('/data/writers-room/works/wr-work-1/manifest.json');+ expect(manifest.status).toBe(404);+ expect(manifest.text).not.toContain('private');+ });+});++describe('ASSET_MOUNTS', () => {+ it('anchors every route under a namespace the terminators close', () => {+ // A mount added outside `/data/` would keep the pre-#4688 behaviour: an+ // extensionless path under it answered with the SPA index and a 200.+ expect(ASSET_MOUNTS.length).toBeGreaterThan(5);+ expect(ASSET_MOUNTS.filter(({ route }) => !route.startsWith('/data/'))).toEqual([]);+ });+});diff --git a/server/lib/assetRoutePrefixes.js b/server/lib/assetRoutePrefixes.jsnew file mode 100644index 0000000000..148da133e8--- /dev/null+++ b/server/lib/assetRoutePrefixes.js@@ -0,0 +1,59 @@+/**+ * The URL prefixes the SERVER owns, as data — deliberately a leaf module with+ * zero imports, so anything (a Vite config, a drift guard, a build script) can+ * read it without dragging express or a service into its graph.+ *+ * Two lists, for two different jobs:+ *+ * - `ASSET_ROUTE_PREFIXES` is every `/data/**` static mount. Under+ * `npm run dev` the browser talks to Vite on :5554, and an UNPROXIED path+ * does not 404 — Vite's SPA fallback answers it with index.html and a 200,+ * so a binary loader parses HTML and fails far from the cause. The dev+ * proxy covers the namespace with one `'^/data/'` wildcard rather than a+ * list that can fall behind; this is what+ * `scripts/dev-proxy-drift.test.js` checks that wildcard against, mount by+ * mount, so a future mount added OUTSIDE `/data/` still fails loudly.+ *+ * - `SERVER_OWNED_PREFIXES` is what must never reach the SPA fallback in+ * PRODUCTION. That fallback skips a request only when its path carries a+ * file extension (`/\.\w+$/`), which held only because every asset happened+ * to have one: an extensionless `/data/image-to-3d/<id>/model` fell through+ * to the stamped index.html with a 200 — the same HTML-instead-of-bytes+ * failure as the dev-proxy hole, on the other side of the deployment+ * (#4688). `/api` and `/sdapi` have the identical hole for a mistyped path,+ * where the symptom is worse: a client asking for JSON gets HTML and a 200.+ *+ * Keeping the two beside each other is the point: a new server namespace is+ * one edit, not two half-remembered ones.+ */+/** Every `/data/**` static mount, in the order `server/index.js` mounts them. */+export const ASSET_ROUTE_PREFIXES = [+ '/data/images',+ '/data/image-refs',+ '/data/lora-datasets',+ '/data/videos',+ '/data/video-thumbnails',+ '/data/sprites',+ '/data/image-to-3d',+ '/data/audio',+ '/data/music',+ '/data/brain-imports',+ '/data/writers-room/works',+];++/**+ * Namespaces that belong to the API, never to the client router. A request+ * under one of these that matched no route is a 404, not a page.+ *+ * `spaPaths` names the exact paths inside a prefix that ARE client routes and+ * must still reach the SPA — `/data` itself is the Data Manager page. Exact+ * paths only, not prefixes: `nav.data` has no children (`/devtools/datadog` is+ * a sibling, not a child), and `scripts/dev-proxy-drift.test.js` fails if a+ * NAV_COMMANDS route is ever added under one of these prefixes without being+ * listed here.+ */+export const SERVER_OWNED_PREFIXES = [+ { prefix: '/data', spaPaths: ['/data'] },+ { prefix: '/api', spaPaths: [] },+ { prefix: '/sdapi', spaPaths: [] },+];diff --git a/server/lib/index.js b/server/lib/index.jsindex eaf8c74734..ea3deaa9cf 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -337,6 +337,8 @@ export * from './viteAllowedHosts.js';// === General utilities ===export * from './apiRegistry.js';export * from './arrayUtils.js';+export * from './assetMounts.js';+export * from './assetRoutePrefixes.js';export * from './asyncMutex.js';export * from './authGate.js';export * from './concurrencyGate.js';