Skip to content

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

feat: same-origin Eidoverse host for single-port tailcat forwards (#6532)

atomanticagentef8e61c74acc
diff --git a/client/src/pages/Eidoverse.jsx b/client/src/pages/Eidoverse.jsx
index 7ef3cdda3e..95ab29f331 100644
--- a/client/src/pages/Eidoverse.jsx
+++ b/client/src/pages/Eidoverse.jsx
@@ -48,21 +48,25 @@ const FRESH_WORLD_VISIBLE_CHECKPOINTS = new Set([
const failedStart = (result) => Object.values(result?.results || {})
.find((entry) => entry?.success === false);
-// Prefer the PortOS-owned bridge whenever its scheme matches this page's. The
-// bridge answers the renderer's `/embed-config` with this page's origin, which
-// is the only thing that arms the frame bridge — a direct `:uiPort` load leaves
-// the renderer with no trusted parent and it never replies to the handshake.
-// An HTTP page in front of an HTTPS-only bridge is the one case that still goes
-// direct: the shared certificate covers the MagicDNS name, so an iframe pointed
-// at `https://localhost:5563` would fail on the certificate instead. There the
-// scene renders and the handshake stays dormant, as the contract intends.
+// Prefer the same-origin `/eidoverse-host/` path on the PortOS UI host+port.
+// A single-port tailcat forward (e.g. 127.0.0.1:15555 → remote :5555) only
+// tunnels :5555, so a dedicated :5563 iframe URL is unreachable from the
+// laptop; absolute `/ws` and `/version` fetches from the iframe also need to
+// hit that same origin (the main server reverse-proxies them while the host
+// is active). The path mount answers `/embed-config` with this page's full
+// origin (including a non-5555 forward port), which arms the frame handshake.
+//
+// Escape hatch: an HTTP page in front of an HTTPS-only host certificate still
+// cannot load `https://…/eidoverse-host/` when the cert does not cover the
+// hostname in use (loopback mirror / some Vite setups). There we keep the
+// direct `:uiPort` load — scene renders, handshake stays dormant.
export const hostUrlFor = (host, setup, location = window.location, identity = null) => {
if (location.protocol === 'https:' && host.protocol !== 'https') {
throw new Error('PortOS is using HTTPS, but the Eidoverse host could not load the shared certificate.');
}
- const baseUrl = location.protocol === 'https:' || host.protocol === 'http'
- ? `${host.protocol}://${location.hostname}:${host.port}/`
- : `http://${location.hostname}:${setup.uiPort}/`;
+ const baseUrl = location.protocol === 'http:' && host.protocol === 'https'
+ ? `http://${location.hostname}:${setup.uiPort}/`
+ : `${location.protocol}//${location.host}/eidoverse-host/`;
if (!identity) return baseUrl;
const url = new URL(baseUrl);
diff --git a/client/src/pages/Eidoverse.test.jsx b/client/src/pages/Eidoverse.test.jsx
index aaa8e6afa4..1a18295969 100644
--- a/client/src/pages/Eidoverse.test.jsx
+++ b/client/src/pages/Eidoverse.test.jsx
@@ -149,7 +149,7 @@ describe('Eidoverse hosted page', () => {
renderPage();
const frame = await screen.findByTitle('Eidoverse Worlds');
- expect(frame).toHaveAttribute('src', `http://${window.location.hostname}:5563/?world=portos&name=example-portos-user`);
+ expect(frame).toHaveAttribute('src', `${window.location.protocol}//${window.location.host}/eidoverse-host/?world=portos&name=example-portos-user`);
expect(screen.getByRole('button', { name: 'Refresh world' }))
.toHaveAttribute('aria-label', 'Refresh world');
expect(screen.getByRole('button', { name: 'Refresh world' })).not.toHaveClass('port-media-overlay');
@@ -163,7 +163,7 @@ describe('Eidoverse hosted page', () => {
expect(screen.queryByRole('region', { name: 'PortOS district legend' })).not.toBeInTheDocument();
expect(screen.queryByText('12/48 live signals')).not.toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Open Eidoverse without PortOS controls' }))
- .toHaveAttribute('href', `http://${window.location.hostname}:5563/?world=portos&name=example-portos-user`);
+ .toHaveAttribute('href', `${window.location.protocol}//${window.location.host}/eidoverse-host/?world=portos&name=example-portos-user`);
await waitFor(() => expect(api.projectEidoverseWorld).toHaveBeenCalledWith({ silent: true }));
expect(screen.getByRole('link', { name: 'Manage Eidoverse app' })).toHaveAttribute('href', '/apps/app-eidoverse/overview');
@@ -360,35 +360,38 @@ describe('Eidoverse hosted page', () => {
expect(api.startApp).toHaveBeenCalledTimes(2);
});
- it('uses the PortOS TLS bridge for an HTTPS MagicDNS page', () => {
+ it('uses the same-origin /eidoverse-host path for an HTTPS MagicDNS page', () => {
expect(hostUrlFor(
{ running: true, protocol: 'https', port: 5563 },
setup,
- { protocol: 'https:', hostname: 'host-alpha.example-tailnet.ts.net' },
- )).toBe('https://host-alpha.example-tailnet.ts.net:5563/');
+ { protocol: 'https:', hostname: 'host-alpha.example-tailnet.ts.net', host: 'host-alpha.example-tailnet.ts.net' },
+ )).toBe('https://host-alpha.example-tailnet.ts.net/eidoverse-host/');
expect(() => hostUrlFor(
{ running: true, protocol: 'http', port: 5563 },
setup,
- { protocol: 'https:', hostname: 'host-alpha.example-tailnet.ts.net' },
+ { protocol: 'https:', hostname: 'host-alpha.example-tailnet.ts.net', host: 'host-alpha.example-tailnet.ts.net' },
)).toThrow(/shared certificate/);
});
- // Only the bridge answers the renderer's /embed-config with this page's
- // origin, and without that answer the renderer never completes the frame
- // handshake — so a plain-HTTP install has to go through it too. The one
- // exception is an HTTP page in front of an HTTPS-only bridge (the loopback
- // mirror, the dev server): the shared certificate does not cover those
- // hostnames, so the iframe would fail on the certificate instead.
- it('routes a plain-HTTP page through the bridge, and only falls back when the bridge is HTTPS', () => {
+ // Same-origin path keeps a single-port tailcat forward working (UI host+port
+ // only). The one escape is an HTTP page in front of an HTTPS-only host
+ // certificate that does not cover the hostname — loopback mirror / some Vite
+ // setups — where we still fall back to the direct :uiPort load.
+ it('routes through /eidoverse-host on the UI origin, with a direct-uiPort escape for HTTP+HTTPS-cert', () => {
expect(hostUrlFor(
{ running: true, protocol: 'http', port: 5563 },
setup,
- { protocol: 'http:', hostname: 'host-alpha.example-tailnet.ts.net' },
- )).toBe('http://host-alpha.example-tailnet.ts.net:5563/');
+ { protocol: 'http:', hostname: 'host-alpha.example-tailnet.ts.net', host: 'host-alpha.example-tailnet.ts.net:5555' },
+ )).toBe('http://host-alpha.example-tailnet.ts.net:5555/eidoverse-host/');
+ expect(hostUrlFor(
+ { running: true, protocol: 'http', port: 5563 },
+ setup,
+ { protocol: 'http:', hostname: '127.0.0.1', host: '127.0.0.1:15555' },
+ )).toBe('http://127.0.0.1:15555/eidoverse-host/');
expect(hostUrlFor(
{ running: true, protocol: 'https', port: 5563 },
setup,
- { protocol: 'http:', hostname: 'localhost' },
+ { protocol: 'http:', hostname: 'localhost', host: 'localhost:5553' },
)).toBe(`http://localhost:${setup.uiPort}/`);
});
@@ -441,7 +444,7 @@ describe('Eidoverse hosted page', () => {
await waitFor(() => expect(screen.getByTitle('Eidoverse Worlds')).toHaveAttribute(
'src',
- `http://${window.location.hostname}:5563/?world=portos-two&name=example-portos-user`,
+ `${window.location.protocol}//${window.location.host}/eidoverse-host/?world=portos-two&name=example-portos-user`,
));
});
diff --git a/client/src/pages/EidoverseGuest.jsx b/client/src/pages/EidoverseGuest.jsx
index 480ed0fba0..b0b8658e09 100644
--- a/client/src/pages/EidoverseGuest.jsx
+++ b/client/src/pages/EidoverseGuest.jsx
@@ -21,7 +21,9 @@ export default function EidoverseGuest() {
if (!response.ok) throw new Error('This guest invitation is unavailable or has expired.');
const { host, identity } = await response.json();
if (window.location.protocol === 'https:' && host.protocol !== 'https') throw new Error('The destination renderer needs HTTPS.');
- const url = new URL(`${host.protocol}://${window.location.hostname}:${host.port}/`);
+ // Same-origin path so a single-port forward reaches the renderer; root
+ // `/ws` etc. are proxied on the destination's :5555 while its host is up.
+ const url = new URL(`${window.location.protocol}//${window.location.host}/eidoverse-host/`);
url.searchParams.set('guest', '1');
for (const key of ['world', 'name', 'avatar']) url.searchParams.set(key, identity[key]);
if (!controller.signal.aborted) setHostUrl(url.toString());
diff --git a/client/src/pages/EidoverseGuest.test.jsx b/client/src/pages/EidoverseGuest.test.jsx
index 89b3963dd1..115ff88c76 100644
--- a/client/src/pages/EidoverseGuest.test.jsx
+++ b/client/src/pages/EidoverseGuest.test.jsx
@@ -27,6 +27,7 @@ it('loads only visitor metadata and the remote renderer, without private PortOS
const iframe = await screen.findByTitle('Guest Eidoverse world');
const url = new URL(iframe.src);
expect(url.hostname).toBe(window.location.hostname);
+ expect(url.pathname).toBe('/eidoverse-host/');
expect(url.searchParams.get('guest')).toBe('1');
expect(url.searchParams.get('name')).toBe('guest-example');
expect(url.searchParams.get('world')).toBe('example-world');
diff --git a/client/vite.config.js b/client/vite.config.js
index 8c3044bdb0..8223261e35 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -7,6 +7,11 @@ import { resolve } from 'path';
import { resolveBundleNodeEnv } from './vite.buildEnv.js';
import { CHUNK_GROUPS } from './vite.chunkGroups.js';
+import {
+ EIDOVERSE_HOST_PATH_PREFIX,
+ EIDOVERSE_ROOT_EXACT_PATHS,
+ EIDOVERSE_ROOT_PREFIX_PATHS,
+} from '../server/lib/eidoverseProxyRoutes.js';
const ANALYZE_BUNDLE = process.env.ANALYZE === 'true';
const CONFIG_DIR = import.meta.dirname;
@@ -88,6 +93,43 @@ function buildStamp() {
const CERT_PATH = resolve(CONFIG_DIR, '..', 'data', 'certs', 'cert.pem');
const API_SCHEME = existsSync(CERT_PATH) ? 'https' : 'http';
+// Dev proxies for the same-origin Eidoverse iframe. Root routes only forward
+// while the API host is active; `/node_modules/` + `/shared/` keep a Referer
+// bypass so Vite's own dependency graph is not stolen.
+function eidoverseDevProxies(target) {
+ const entries = {
+ [`^${EIDOVERSE_HOST_PATH_PREFIX}(?:/|$)`]: {
+ target,
+ changeOrigin: true,
+ ws: true,
+ secure: false,
+ },
+ };
+ for (const exact of EIDOVERSE_ROOT_EXACT_PATHS) {
+ entries[`^${exact}$`] = {
+ target,
+ changeOrigin: true,
+ ws: exact === '/ws',
+ secure: false,
+ };
+ }
+ for (const prefix of EIDOVERSE_ROOT_PREFIX_PATHS) {
+ entries[`^${prefix}`] = {
+ target,
+ changeOrigin: true,
+ secure: false,
+ bypass(req) {
+ if (prefix !== '/node_modules/' && prefix !== '/shared/') return undefined;
+ const referer = String(req.headers.referer || '');
+ if (!referer.includes(EIDOVERSE_HOST_PATH_PREFIX)) return req.url;
+ return undefined;
+ },
+ };
+ }
+ return entries;
+}
+
+
export default defineConfig(({ command, mode }) => {
// Pin the build's NODE_ENV before Vite reads it. resolveConfig() only defaults
// it to 'production' when it is UNSET, and PortOS reaches this build from
@@ -161,7 +203,8 @@ export default defineConfig(({ command, mode }) => {
changeOrigin: true,
ws: true,
secure: false
- }
+ },
+ ...eidoverseDevProxies(API_TARGET),
}
},
build: {
diff --git a/docs/PORTS.md b/docs/PORTS.md
index 745cac35af..0edc055468 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -35,7 +35,7 @@ Common port labels:
| 5560 | portos-autofixer-ui | ui | Autofixer web UI |
| 5561 | portos-db (Docker container) | - | Infrastructure dependency: PostgreSQL Docker container provisioned by `scripts/setup-db.js` / Docker Compose (not a PM2 process in `server/services/apps.js`; native mode uses system pg on 5432). |
| 5562 | portos-whisper | whisper-server | Loopback whisper.cpp speech-to-text server. |
-| 5563 | portos-server | eidoverse-host | Optional HTTPS/WebSocket bridge for the embedded Eidoverse Worlds page. Starts on demand and forwards to the managed app on loopback `:8940`. |
+| 5563 | portos-server | eidoverse-host | Optional legacy HTTPS/WebSocket bridge for Eidoverse Worlds (on demand → loopback `:8940`). Prefer the same-origin path on `:5555` — `/eidoverse-host` plus root allowlist proxies — so a single-port tailcat forward (`:15555` → `:5555`) can embed the iframe. |
| 5564 | portos-slotstream | - | Loopback SSD-streaming MoE runtime. Optional PM2 process, started/stopped from Models → LLMs. Never 11434 — that port is a PortOS-managed Ollama. |
| 5568 | portos-llama-server | - | Loopback llama.cpp speculative-decoding server. Optional PM2 process, started/stopped from Models → LLMs. |
| 8000 | portos-mtplx | - | Loopback MTPLX OpenAI-compatible API (upstream's own default, kept so the shipped provider presets match). Optional PM2 process, started/stopped from Models → LLMs. See [features/mtplx.md](./features/mtplx.md). |
@@ -70,6 +70,13 @@ Rules of thumb:
Run `npm run setup:guide` to print the currently valid local URL, the exact trusted MagicDNS URL when available, and the next Tailscale/HTTPS prerequisite. The end-to-end walkthrough is in [SETUP.md](./SETUP.md).
+
+## Eidoverse on a single port (tailcat)
+
+A [tailcat](https://github.com/tailscale/tailcat) forward typically maps only `127.0.0.1:15555` → remote PortOS `:5555`. The Eidoverse iframe used to point at `:5563`, which is not tunneled, and the renderer issues absolute root requests (`/ws`, `/version`, …) that would miss a path-prefix-only iframe.
+
+PortOS now embeds via **`/eidoverse-host/`** on the same host+port as the UI. The API reverse-proxies that prefix to loopback `:8940` (prefix stripped) and, while the on-demand host is active, forwards an allowlist of Eidoverse root routes (including WebSocket `/ws`). `GET /embed-config` is terminated locally with a `parentOrigin` that preserves the browser `Host` (so `http://127.0.0.1:15555` works). The dedicated `:5563` bridge remains available as an optional/legacy listener.
+
## Defining Ports in ecosystem.config.cjs
Define all ports in a top-level `PORTS` object as the single source of truth:
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.md
index fb509d2756..1ef39dddf9 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -360,20 +360,23 @@ An instance that needs a broader trust model should configure Eidoverse access
control in that project before starting it.
Eidoverse itself remains a plain-HTTP service on `:8940`. The embedded page
-lazily opens a PortOS-owned HTTP/WebSocket bridge on `:5563` that forwards to
-`127.0.0.1:8940`; when a machine certificate is present it serves HTTPS using
-the same certificate as `:5555`, which is what avoids browser mixed-content
-rejection. Both external repositories stay unchanged. The bridge starts only
-when the page is opened, waits for the managed app to answer before mounting the
-iframe, and returns an explicit unavailable state when the runtime does not
-become ready.
-
-The page embeds through that bridge whenever the bridge's scheme matches the
-page's, because the bridge is also what arms the renderer's frame bridge (see
-below). The single exception is a plain-HTTP page in front of an HTTPS bridge —
-the loopback `:5553` mirror and the Vite dev server — where the shared
-certificate does not cover the hostname in use; there the iframe points straight
-at `:8940`, the scene renders normally, and the frame handshake stays dormant.
+starts the on-demand PortOS host and loads the renderer at the **same origin**
+as the PortOS UI — `${location.origin}/eidoverse-host/?…` — so a single-port
+tailcat forward (`127.0.0.1:15555` → remote `:5555`) works. The main `:5555`
+server reverse-proxies `/eidoverse-host` to loopback `:8940` (prefix stripped)
+and, while the host is active, also forwards allowlisted absolute root routes
+the renderer issues (`/ws`, `/version`, `/library/…`, `/node_modules/…`, …),
+including the WebSocket upgrade for `/ws`. Both external repositories stay
+unchanged. The host starts only when the page is opened, waits for the managed
+app to answer before mounting the iframe, and returns an explicit unavailable
+state when the runtime does not become ready.
+
+An optional legacy bridge on `:5563` still starts with the host (HTTPS when a
+machine certificate is present) for ExternalLink / direct access on the box.
+The iframe prefers the same-origin path; the single escape is a plain-HTTP page
+in front of an HTTPS-only host certificate that does not cover the hostname
+(loopback `:5553` / some Vite setups), where the iframe falls back to a direct
+`:uiPort` load — scene renders, handshake stays dormant.
Projection protocol and asset preflight target the same runtime. The default
HTTP library origin is derived from `EIDOVERSE_WS_URL` by mapping `ws`/`wss` to
@@ -465,9 +468,11 @@ the expected parent origin from its trusted embedding configuration; accepting
an arbitrary opener as the parent is not sufficient.
**PortOS supplies that configuration.** The renderer reads it from
-`GET /embed-config`, which the bridge on `:5563` answers itself rather than
-forwarding: the hostname is the one the browser just used to reach the bridge,
-and the scheme and port are PortOS's own. The checkout's static
+`GET /embed-config`, which PortOS answers itself rather than forwarding: on the
+same-origin `/eidoverse-host` mount (and the root allowlist proxy) the
+`parentOrigin` is the full browser `Host` including a non-5555 forward port
+(e.g. `http://127.0.0.1:15555`); on the legacy `:5563` bridge it is the PortOS
+page origin (hostname + API port), not the bridge port. The checkout's static
`EMBED_PARENT_ORIGIN` is deliberately left unset, because one install is
reachable as `localhost`, as a LAN address and as a MagicDNS name, and a single
configured origin could only ever match one of them — an unmatched origin leaves
diff --git a/server/index.js b/server/index.js
index f8b1b0c3de..9828479a2f 100644
--- a/server/index.js
+++ b/server/index.js
@@ -167,6 +167,7 @@ import remoteDesktopRoutes from './routes/remoteDesktop.js';
import remoteDesktopViewerRoutes from './routes/remoteDesktopViewer.js';
import { initSocket } from './services/socket.js';
import { remoteDesktopBroker } from './services/remoteDesktop.js';
+import { mountEidoverseOnServer } from './services/eidoverseHost.js';
import { bootstrapServices, runBootSequence, registerShutdownHandlers } from './services/bootstrap.js';
import { errorMiddleware } from './lib/errorHandler.js';
import { setHttpsEnabledAtBoot } from './lib/httpsState.js';
@@ -205,6 +206,9 @@ const io = new Server(httpServer, {
// request input. Mount the HTTPS server and its optional loopback HTTP mirror.
remoteDesktopBroker.mountWebSocket(httpServer);
remoteDesktopBroker.mountWebSocket(localHttpServer);
+// Eidoverse same-origin path + root allowlist (active only after the on-demand
+// host starts). Upgrade for `/ws` and `/eidoverse-host/**` on both listeners.
+mountEidoverseOnServer(null, [httpServer, localHttpServer]);
// Auth gate for Socket.IO — when settings.secrets.auth.enabled is true the
// handshake must carry a valid token cookie or Authorization: Bearer header
@@ -429,6 +433,12 @@ app.use('/api/harnesses', harnessRoutes);
app.use('/api/peer-sync', peerSyncRoutes);
app.use('/api/ask', askRoutes);
+// Eidoverse same-origin reverse-proxy (`/eidoverse-host` + root allowlist while
+// the host is active). Must sit above mountAssetRoutes so the `/eidoverse-host`
+// SERVER_OWNED terminator cannot 404 proxied paths, and above the SPA fallback
+// so `/version` / `/ws` are not answered with PortOS index.html.
+mountEidoverseOnServer(app);
+
// 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).
diff --git a/server/lib/README.md b/server/lib/README.md
index 7893ca2ffb..4833daa8ea 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -566,6 +566,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
| `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |
| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Async `resolveAppForgeTarget(app, {repoPath})` — the composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers holding the managed-app record, returning `{ tracker, target }` with the app's github/gitlab pin threaded in as `preferredForge` (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. |
+| `eidoverseProxyRoutes.js` | Allowlist + path helpers for the same-origin Eidoverse reverse-proxy on `:5555` (`/eidoverse-host` prefix strip and root routes like `/ws` / `/version` while the host is active). Shared by `services/eidoverseProxy.js` so the main server and the optional `:5563` bridge stay in sync with eidoverse-worlds `server/routes.ts`. |
| `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `isWithinAllowedRoots(realPath)` is the single complete test — on Windows it also allows any lettered non-system drive (`D:\code`), which appears in no root, so never render `ALLOWED_WORKSPACE_ROOTS` as "the directories you may use". `outsideAllowedRootsMessage(realPath, { field })` formats a redacted server-only diagnostic with the rejected realpath and every checked root. Also `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, split on the platform path delimiter — `;` on Windows — and symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Defaults cover home plus wherever the platform mounts secondary volumes: `/tmp` + `/Users` + `/Volumes` + `/mnt` + `/media` + `/opt` on POSIX; home + the temp dir plus the non-system-drive rule on Windows, where those POSIX literals would resolve to whatever drive the process happens to be on. Used by `routes/commands.js`, `routes/scaffold.js`, and `routes/git.js` (always scoped) and `routes/detect.js` (scoped only when configured). |
| `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |
diff --git a/server/lib/assetRoutePrefixes.js b/server/lib/assetRoutePrefixes.js
index 5b8bccd25b..95336ff6ee 100644
--- a/server/lib/assetRoutePrefixes.js
+++ b/server/lib/assetRoutePrefixes.js
@@ -58,4 +58,7 @@ export const SERVER_OWNED_PREFIXES = [
{ prefix: '/data', spaPaths: ['/data'] },
{ prefix: '/api', spaPaths: [] },
{ prefix: '/sdapi', spaPaths: [] },
+ // Same-origin Eidoverse iframe mount (reverse-proxied to :8940 while the
+ // host is active). No client router paths live under this prefix.
+ { prefix: '/eidoverse-host', spaPaths: [] },
];
diff --git a/server/lib/eidoverseProxyRoutes.js b/server/lib/eidoverseProxyRoutes.js
new file mode 100644
index 0000000000..c42166dedf
--- /dev/null
+++ b/server/lib/eidoverseProxyRoutes.js
@@ -0,0 +1,81 @@
+/**
+ * Root paths the Eidoverse Worlds sequencer owns (from its server/routes.ts
+ * matchers: exact + prefix). Import-free leaf so Vite, drift guards, and the
+ * reverse-proxy can share one list without dragging Express into the graph.
+ *
+ * Keep in sync when the managed checkout adds root routes. Do not edit
+ * checkouts under data/repos/ for PortOS-side proxy work — update THIS list.
+ *
+ * Mounted on PortOS :5555 only while the Eidoverse host is active, so these
+ * names never permanently steal PortOS SPA / API behaviour.
+ */
+export const EIDOVERSE_HOST_PATH_PREFIX = '/eidoverse-host';
+
+/** Exact pathnames (querystring ignored). `/host` is PortOS-terminated. */
+export const EIDOVERSE_ROOT_EXACT_PATHS = Object.freeze([
+ '/ws',
+ '/authcfg',
+ '/whoami',
+ '/auth',
+ '/logout',
+ '/geom',
+ '/residency',
+ '/upload',
+ '/seat-profile',
+ '/snap',
+ '/avatars',
+ '/tick',
+ '/defs',
+ '/animations',
+ '/relay-diag',
+ '/version',
+ '/embed-config',
+ '/perflog',
+ '/thumb',
+ '/library-list',
+ '/library-models',
+ '/health',
+ '/client-version',
+ '/favicon.ico',
+ '/host',
+]);
+
+/** Prefix matchers (path must start with the entry). */
+export const EIDOVERSE_ROOT_PREFIX_PATHS = Object.freeze([
+ '/thumb/',
+ '/library/',
+ '/node_modules/',
+ '/shared/',
+]);
+
+const EXACT = new Set(EIDOVERSE_ROOT_EXACT_PATHS);
+
+/**
+ * @param {string} pathname pathname without query (trailing slashes already normalized or not)
+ * @returns {boolean}
+ */
+export function isEidoverseRootProxyPath(pathname) {
+ const path = String(pathname || '').split('?')[0] || '/';
+ if (EXACT.has(path)) return true;
+ // Upstream matches /agents.md case-insensitively.
+ if (path.toLowerCase() === '/agents.md') return true;
+ return EIDOVERSE_ROOT_PREFIX_PATHS.some((prefix) => path.startsWith(prefix));
+}
+
+/**
+ * Strip `/eidoverse-host` from a request URL, leaving a leading `/` + query.
+ * Returns null when the URL is not under the prefix.
+ */
+export function stripEidoverseHostPrefix(url) {
+ const raw = String(url || '');
+ const q = raw.indexOf('?');
+ const path = q >= 0 ? raw.slice(0, q) : raw;
+ const query = q >= 0 ? raw.slice(q) : '';
+ if (path === EIDOVERSE_HOST_PATH_PREFIX || path === `${EIDOVERSE_HOST_PATH_PREFIX}/`) {
+ return `/${query}`;
+ }
+ if (path.startsWith(`${EIDOVERSE_HOST_PATH_PREFIX}/`)) {
+ return `${path.slice(EIDOVERSE_HOST_PATH_PREFIX.length)}${query}`;
+ }
+ return null;
+}
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 25b917b69c..49b81f6b09 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -235,7 +235,11 @@ describe('deferred imports stay deferred (#6156)', () => {
// not. services/pipeline/arcPlanner/context.test.js (78) and
// lib/editorial/checks/characterArcEvolution.test.js (68) are boundary tests
// over modules those trees already instantiate.
-const MAX_STATIC_INSTANTIATIONS = 95200;
+// #6532: same-origin Eidoverse proxy (`eidoverseProxy.js` + route allowlist)
+// loaded via the host mount at boot. Measured 95,246 on this branch (+46 over
+// the prior ceiling) — ordinary growth for an intentional main-server edge,
+// not an eager heavy subtree. Raise the ceiling to keep the ~1.5k allowance.
+const MAX_STATIC_INSTANTIATIONS = 95300;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
const serverTestFiles = (dir = SERVER_DIR, out = []) => {
diff --git a/server/lib/index.js b/server/lib/index.js
index e879be6120..1bf29ac659 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -547,6 +547,7 @@ export * from './userActionTypes.js';
export * from './uuid.js';
export * from './versionUtils.js';
export * from './workTracker.js';
+export * from './eidoverseProxyRoutes.js';
export * from './workspaceRoots.js';
export * from './zodCompat.js';
diff --git a/server/services/eidoverseHost.js b/server/services/eidoverseHost.js
index 7a0e4f349a..f862d9e45c 100644
--- a/server/services/eidoverseHost.js
+++ b/server/services/eidoverseHost.js
@@ -1,5 +1,4 @@
import { request as httpRequest } from 'node:http';
-import { createConnection } from 'node:net';
import { createTailscaleServers, watchCertReload } from '../../lib/tailscale-https.js';
import { certPaths } from '../../lib/certPaths.js';
import { isPortReachable } from '../lib/connectivity.js';
@@ -7,10 +6,15 @@ import { PATHS } from '../lib/fileUtils.js';
import { PORTS } from '../lib/ports.js';
import { ServerError } from '../lib/errorHandler.js';
import { EIDOVERSE_PORT } from './eidoverse.js';
+import {
+ handleEidoverseHttp,
+ proxyUpgradeToEidoverse,
+ createEidoverseExpressMiddleware,
+ mountEidoverseWebSocket,
+ EIDOVERSE_HOST_PATH_PREFIX,
+} from './eidoverseProxy.js';
-const BAD_GATEWAY_BODY = 'Eidoverse Worlds is not running.';
-const HOST_DESCRIPTOR_PATH = '/host';
-const EMBED_CONFIG_PATH = '/embed-config';
+export { EIDOVERSE_HOST_PATH_PREFIX };
// Where a conflicting listener would sit. A local squatter almost always claims
// loopback — Docker publishes to 127.0.0.1, dev servers bind localhost — and
@@ -19,133 +23,15 @@ const EMBED_CONFIG_PATH = '/embed-config';
// the startup path, before this bridge will accept anything.
const CONFLICT_PROBE_HOST = '127.0.0.1';
const CONFLICT_PROBE_TIMEOUT_MS = 300;
-const FORWARDED_HEADER_NAMES = new Set(['host', 'x-forwarded-host', 'x-forwarded-proto']);
-
-const targetAuthority = (host, port) => `${host}:${port}`;
-
-const forwardedHeaders = (req, protocol, targetHost, targetPort) => ({
- ...req.headers,
- host: targetAuthority(targetHost, targetPort),
- 'x-forwarded-host': req.headers.host || '',
- 'x-forwarded-proto': protocol,
-});
-
-const requestPathname = (url) => String(url || '').split('?')[0].replace(/\/+$/, '') || '/';
-
-// Node suppresses the body of a HEAD response itself, so every writer here can
-// pass one unconditionally.
-const writePlainText = (res, status, body, headers = {}) => {
- res.writeHead(status, {
- 'content-type': 'text/plain; charset=utf-8',
- 'content-length': Buffer.byteLength(body),
- ...headers,
- });
- res.end(body);
-};
-
-/**
- * Terminate `GET /host` at the bridge. Runs outside the Express lifecycle, so a
- * rejected read is caught here rather than crashing the process.
- */
-const serveHostDescriptor = async (req, res) => {
- if (req.method !== 'GET' && req.method !== 'HEAD') {
- writePlainText(res, 405, 'The PortOS host descriptor is read-only.', { allow: 'GET, HEAD' });
- return;
- }
- // Deferred import: this bridge is constructed from the always-loaded settings
- // route, while `/host` is a rare request. A static edge would drag the world
- // config graph into every suite that reaches this module (server/AGENTS.md,
- // "Import scoping").
- const descriptor = await import('./eidoverseWorld.js')
- .then(({ readEidoverseHostDescriptor }) => readEidoverseHostDescriptor())
- .catch((error) => {
- console.error(`❌ Eidoverse host descriptor failed: ${error.message}`);
- return null;
- });
- if (!descriptor) {
- writePlainText(res, 503, 'The PortOS host descriptor is unavailable.');
- return;
- }
- const body = JSON.stringify(descriptor);
- res.writeHead(200, {
- 'content-type': 'application/json; charset=utf-8',
- 'content-length': Buffer.byteLength(body),
- 'cache-control': 'no-store',
- });
- res.end(body);
-};
-
-// The hostname the browser actually used to reach this bridge. An origin keeps
-// IPv6 brackets and drops the port, so `[::1]:5563` and `host:5563` are split
-// differently; anything that is neither is refused rather than repaired.
-const requestHostname = (req) => {
- const raw = String(req.headers.host || '').trim();
- if (!raw) return null;
- const bracketed = raw.startsWith('[') && raw.includes(']') ? raw.slice(0, raw.indexOf(']') + 1) : null;
- const hostname = bracketed || raw.split(':')[0];
- return /^\[[0-9a-fA-F:.]+\]$/.test(hostname) || /^[a-zA-Z0-9.-]+$/.test(hostname) ? hostname : null;
-};
-
-/**
- * The PortOS page origin this bridge is embedded by. The renderer's frame
- * contract requires the parent origin to come from trusted embedding
- * configuration rather than from whoever opened the frame, and PortOS is that
- * configuration: the hostname is the one the browser just used, while the
- * scheme and port are PortOS's own. A static `EMBED_PARENT_ORIGIN` in the
- * external checkout cannot do this — one install is reachable as localhost, a
- * LAN address and a MagicDNS name, and only one of those would ever match.
- */
-const embedParentOrigin = (req, protocol) => {
- const hostname = requestHostname(req);
- return hostname ? `${protocol}://${hostname}:${Number(process.env.PORT) || PORTS.API}` : null;
-};
-
-// Terminated here rather than forwarded: the managed checkout answers this from
-// its own environment, which PortOS deliberately leaves unset.
-const serveEmbedConfig = (req, res, protocol) => {
- if (req.method !== 'GET' && req.method !== 'HEAD') {
- writePlainText(res, 405, 'The PortOS embedding configuration is read-only.', { allow: 'GET, HEAD' });
- return;
- }
- const body = JSON.stringify({ parentOrigin: embedParentOrigin(req, protocol) });
- res.writeHead(200, {
- 'content-type': 'application/json; charset=utf-8',
- 'content-length': Buffer.byteLength(body),
- 'cache-control': 'no-store',
- });
- res.end(body);
-};
-
-const writeBadGateway = (res) => {
- if (res.headersSent) {
- res.destroy();
- return;
- }
- res.writeHead(502, {
- 'content-type': 'text/plain; charset=utf-8',
- 'content-length': Buffer.byteLength(BAD_GATEWAY_BODY),
- });
- res.end(BAD_GATEWAY_BODY);
-};
-
-const websocketRequestHead = (req, protocol, targetHost, targetPort) => {
- const headers = [];
- for (let index = 0; index < req.rawHeaders.length; index += 2) {
- const name = req.rawHeaders[index];
- if (!FORWARDED_HEADER_NAMES.has(name.toLowerCase())) {
- headers.push(`${name}: ${req.rawHeaders[index + 1]}`);
- }
- }
- headers.push(`Host: ${targetAuthority(targetHost, targetPort)}`);
- headers.push(`X-Forwarded-Host: ${req.headers.host || ''}`);
- headers.push(`X-Forwarded-Proto: ${protocol}`);
- return `${req.method} ${req.url} HTTP/${req.httpVersion}\r\n${headers.join('\r\n')}\r\n\r\n`;
-};
/**
* Create the lazy Eidoverse HTTPS bridge. The target is fixed at construction
* time, so this is not a general-purpose proxy. No listener is opened until
* `start()` is called by the user-facing Eidoverse page.
+ *
+ * Prefer the main-server `/eidoverse-host` mount (see `mountEidoverseOnServer`)
+ * for same-origin / single-port forwards; :5563 remains an optional ExternalLink
+ * fallback when a machine certificate is in play.
*/
export function createEidoverseHost({
targetHost = '127.0.0.1',
@@ -179,61 +65,27 @@ export function createEidoverseHost({
};
const handleHttp = (req, res) => {
- const pathname = requestPathname(req.url);
- if (pathname === EMBED_CONFIG_PATH) {
- serveEmbedConfig(req, res, protocol());
- return;
- }
- if (pathname === HOST_DESCRIPTOR_PATH) {
- // Nothing holds this promise, and a client that hung up mid-write makes
- // `res` throw — so own the rejection here rather than killing the process.
- serveHostDescriptor(req, res).catch((error) => {
- console.error(`❌ Eidoverse host descriptor response failed: ${error.message}`);
- res.destroy();
- });
- return;
- }
- const upstream = httpRequest({
- hostname: targetHost,
- port: targetPort,
- method: req.method,
- path: req.url,
- headers: forwardedHeaders(req, protocol(), targetHost, targetPort),
- }, (upstreamResponse) => {
- res.writeHead(upstreamResponse.statusCode || 502, upstreamResponse.headers);
- upstreamResponse.once('error', () => res.destroy());
- upstreamResponse.pipe(res);
+ // Bridge mode: parent origin is the PortOS page (API port), not :5563.
+ handleEidoverseHttp({
+ req,
+ res,
+ protocol: protocol(),
+ embedMode: 'bridge',
+ targetHost,
+ targetPort,
});
- upstream.once('error', () => writeBadGateway(res));
- req.once('aborted', () => upstream.destroy());
- req.pipe(upstream);
};
const handleUpgrade = (req, clientSocket, head) => {
- trackSocket(clientSocket);
- const upstreamSocket = trackSocket(createConnection({ host: targetHost, port: targetPort }));
- let connected = false;
-
- upstreamSocket.once('connect', () => {
- connected = true;
- upstreamSocket.write(websocketRequestHead(req, protocol(), targetHost, targetPort));
- if (head.length > 0) upstreamSocket.write(head);
- clientSocket.pipe(upstreamSocket).pipe(clientSocket);
- });
-
- upstreamSocket.on('error', () => {
- if (connected) {
- clientSocket.destroy();
- return;
- }
- if (!clientSocket.destroyed) {
- clientSocket.end(
- `HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${Buffer.byteLength(BAD_GATEWAY_BODY)}\r\nConnection: close\r\n\r\n${BAD_GATEWAY_BODY}`,
- );
- }
+ proxyUpgradeToEidoverse({
+ req,
+ clientSocket,
+ head,
+ targetHost,
+ targetPort,
+ protocol: protocol(),
+ trackSocket,
});
- clientSocket.once('error', () => upstreamSocket.destroy());
- clientSocket.once('close', () => upstreamSocket.destroy());
};
const targetIsReady = () => new Promise((resolve) => {
@@ -344,8 +196,55 @@ export function createEidoverseHost({
let eidoverseHost = null;
+/** True once the on-demand host bridge has been started for this process. */
+export function isEidoverseHostActive() {
+ return Boolean(eidoverseHost?.status()?.running);
+}
+
export async function ensureEidoverseHost() {
eidoverseHost ||= createEidoverseHost();
await eidoverseHost.start();
return eidoverseHost.waitUntilReady();
}
+
+/**
+ * Wire the same-origin `/eidoverse-host` path proxy + root allowlist onto the
+ * main Express app and HTTP(S) servers. Call once at boot (like
+ * `remoteDesktopBroker.mountWebSocket`). Proxies only fire while the host is
+ * active after `ensureEidoverseHost()`.
+ */
+export function mountEidoverseOnServer(app, httpServers = []) {
+ if (app) {
+ app.use(createEidoverseExpressMiddleware({
+ isActive: isEidoverseHostActive,
+ targetHost: '127.0.0.1',
+ targetPort: EIDOVERSE_PORT,
+ getProtocol: (req) => {
+ if (req.secure) return 'https';
+ const forwarded = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim();
+ if (forwarded === 'https' || forwarded === 'http') return forwarded;
+ // HTTPS main server with HTTP loopback mirror: mirror is plain HTTP.
+ return 'http';
+ },
+ }));
+ }
+ for (const httpServer of httpServers) {
+ if (!httpServer) continue;
+ mountEidoverseWebSocket(httpServer, {
+ isActive: isEidoverseHostActive,
+ targetHost: '127.0.0.1',
+ targetPort: EIDOVERSE_PORT,
+ getProtocol: (req) => {
+ // Socket upgrades on the TLS server are https; the loopback mirror is http.
+ // `req.socket.encrypted` is set for TLS sockets.
+ if (req.socket?.encrypted) return 'https';
+ return 'http';
+ },
+ });
+ }
+}
+
+/** Test helper: replace the process-wide host singleton. */
+export function __setEidoverseHostForTests(host) {
+ eidoverseHost = host;
+}
diff --git a/server/services/eidoverseProxy.js b/server/services/eidoverseProxy.js
new file mode 100644
index 0000000000..cf633277b8
--- /dev/null
+++ b/server/services/eidoverseProxy.js
@@ -0,0 +1,327 @@
+/**
+ * Shared reverse-proxy primitives for Eidoverse Worlds.
+ *
+ * Used by:
+ * - the optional :5563 bridge (eidoverseHost.js)
+ * - the main :5555 server path `/eidoverse-host` + root allowlist (so a
+ * single-port tailcat forward can embed the iframe same-origin)
+ */
+import { request as httpRequest } from 'node:http';
+import { createConnection } from 'node:net';
+import {
+ EIDOVERSE_HOST_PATH_PREFIX,
+ isEidoverseRootProxyPath,
+ stripEidoverseHostPrefix,
+} from '../lib/eidoverseProxyRoutes.js';
+import { PORTS } from '../lib/ports.js';
+import { EIDOVERSE_PORT } from './eidoverse.js';
+
+export { EIDOVERSE_HOST_PATH_PREFIX, isEidoverseRootProxyPath, stripEidoverseHostPrefix };
+
+const BAD_GATEWAY_BODY = 'Eidoverse Worlds is not running.';
+const HOST_DESCRIPTOR_PATH = '/host';
+const EMBED_CONFIG_PATH = '/embed-config';
+const FORWARDED_HEADER_NAMES = new Set(['host', 'x-forwarded-host', 'x-forwarded-proto']);
+
+const targetAuthority = (host, port) => `${host}:${port}`;
+
+export const forwardedHeaders = (req, protocol, targetHost, targetPort) => ({
+ ...req.headers,
+ host: targetAuthority(targetHost, targetPort),
+ 'x-forwarded-host': req.headers.host || '',
+ 'x-forwarded-proto': protocol,
+});
+
+export const requestPathname = (url) => String(url || '').split('?')[0].replace(/\/+$/, '') || '/';
+
+export const writePlainText = (res, status, body, headers = {}) => {
+ res.writeHead(status, {
+ 'content-type': 'text/plain; charset=utf-8',
+ 'content-length': Buffer.byteLength(body),
+ ...headers,
+ });
+ res.end(body);
+};
+
+export const writeBadGateway = (res) => {
+ if (res.headersSent) {
+ res.destroy();
+ return;
+ }
+ res.writeHead(502, {
+ 'content-type': 'text/plain; charset=utf-8',
+ 'content-length': Buffer.byteLength(BAD_GATEWAY_BODY),
+ });
+ res.end(BAD_GATEWAY_BODY);
+};
+
+/**
+ * Hostname from the browser Host header. Keeps IPv6 brackets; refuses junk.
+ */
+export const requestHostname = (req) => {
+ const raw = String(req.headers.host || '').trim();
+ if (!raw) return null;
+ const bracketed = raw.startsWith('[') && raw.includes(']') ? raw.slice(0, raw.indexOf(']') + 1) : null;
+ const hostname = bracketed || raw.split(':')[0];
+ return /^\[[0-9a-fA-F:.]+\]$/.test(hostname) || /^[a-zA-Z0-9.-]+$/.test(hostname) ? hostname : null;
+};
+
+/**
+ * Validate a full Host header value (hostname or hostname:port / [ipv6]:port).
+ */
+const usableHostHeader = (raw) => {
+ const host = String(raw || '').trim();
+ if (!host) return null;
+ // Reuse hostname extraction — if the hostname portion is usable, keep the
+ // whole Host (including a non-5555 forward port like 15555).
+ const fakeReq = { headers: { host } };
+ return requestHostname(fakeReq) ? host : null;
+};
+
+/**
+ * Parent origin for GET /embed-config.
+ *
+ * - `same-origin`: preserve the browser Host as-is (including a tailcat local
+ * forward port such as 127.0.0.1:15555). Used when the iframe is mounted at
+ * `/eidoverse-host` on the main PortOS server.
+ * - `bridge`: hostname from Host + PortOS API port (not the :5563 bridge port).
+ * Used by the legacy dedicated bridge so ExternalLink embeds still handshake
+ * with the PortOS page origin.
+ */
+export const embedParentOrigin = (req, protocol, mode = 'bridge') => {
+ if (mode === 'same-origin') {
+ const host = usableHostHeader(req.headers.host);
+ return host ? `${protocol}://${host}` : null;
+ }
+ const hostname = requestHostname(req);
+ return hostname ? `${protocol}://${hostname}:${Number(process.env.PORT) || PORTS.API}` : null;
+};
+
+export const serveEmbedConfig = (req, res, protocol, mode = 'bridge') => {
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ writePlainText(res, 405, 'The PortOS embedding configuration is read-only.', { allow: 'GET, HEAD' });
+ return;
+ }
+ const body = JSON.stringify({ parentOrigin: embedParentOrigin(req, protocol, mode) });
+ res.writeHead(200, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'content-length': Buffer.byteLength(body),
+ 'cache-control': 'no-store',
+ });
+ res.end(body);
+};
+
+export const serveHostDescriptor = async (req, res) => {
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ writePlainText(res, 405, 'The PortOS host descriptor is read-only.', { allow: 'GET, HEAD' });
+ return;
+ }
+ const descriptor = await import('./eidoverseWorld.js')
+ .then(({ readEidoverseHostDescriptor }) => readEidoverseHostDescriptor())
+ .catch((error) => {
+ console.error(`❌ Eidoverse host descriptor failed: ${error.message}`);
+ return null;
+ });
+ if (!descriptor) {
+ writePlainText(res, 503, 'The PortOS host descriptor is unavailable.');
+ return;
+ }
+ const body = JSON.stringify(descriptor);
+ res.writeHead(200, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'content-length': Buffer.byteLength(body),
+ 'cache-control': 'no-store',
+ });
+ res.end(body);
+};
+
+export const websocketRequestHead = (req, protocol, targetHost, targetPort, pathOverride) => {
+ const headers = [];
+ for (let index = 0; index < req.rawHeaders.length; index += 2) {
+ const name = req.rawHeaders[index];
+ if (!FORWARDED_HEADER_NAMES.has(name.toLowerCase())) {
+ headers.push(`${name}: ${req.rawHeaders[index + 1]}`);
+ }
+ }
+ headers.push(`Host: ${targetAuthority(targetHost, targetPort)}`);
+ headers.push(`X-Forwarded-Host: ${req.headers.host || ''}`);
+ headers.push(`X-Forwarded-Proto: ${protocol}`);
+ const path = pathOverride ?? req.url;
+ return `${req.method} ${path} HTTP/${req.httpVersion}\r\n${headers.join('\r\n')}\r\n\r\n`;
+};
+
+export const proxyHttpToEidoverse = ({
+ req,
+ res,
+ targetHost = '127.0.0.1',
+ targetPort = EIDOVERSE_PORT,
+ protocol,
+ pathOverride,
+}) => {
+ const upstream = httpRequest({
+ hostname: targetHost,
+ port: targetPort,
+ method: req.method,
+ path: pathOverride ?? req.url,
+ headers: forwardedHeaders(req, protocol, targetHost, targetPort),
+ }, (upstreamResponse) => {
+ res.writeHead(upstreamResponse.statusCode || 502, upstreamResponse.headers);
+ upstreamResponse.once('error', () => res.destroy());
+ upstreamResponse.pipe(res);
+ });
+ upstream.once('error', () => writeBadGateway(res));
+ req.once('aborted', () => upstream.destroy());
+ req.pipe(upstream);
+};
+
+export const proxyUpgradeToEidoverse = ({
+ req,
+ clientSocket,
+ head,
+ targetHost = '127.0.0.1',
+ targetPort = EIDOVERSE_PORT,
+ protocol,
+ pathOverride,
+ trackSocket = (socket) => socket,
+}) => {
+ trackSocket(clientSocket);
+ const upstreamSocket = trackSocket(createConnection({ host: targetHost, port: targetPort }));
+ let connected = false;
+
+ upstreamSocket.once('connect', () => {
+ connected = true;
+ upstreamSocket.write(websocketRequestHead(req, protocol, targetHost, targetPort, pathOverride));
+ if (head.length > 0) upstreamSocket.write(head);
+ clientSocket.pipe(upstreamSocket).pipe(clientSocket);
+ });
+
+ upstreamSocket.on('error', () => {
+ if (connected) {
+ clientSocket.destroy();
+ return;
+ }
+ if (!clientSocket.destroyed) {
+ clientSocket.end(
+ `HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${Buffer.byteLength(BAD_GATEWAY_BODY)}\r\nConnection: close\r\n\r\n${BAD_GATEWAY_BODY}`,
+ );
+ }
+ });
+ clientSocket.once('error', () => upstreamSocket.destroy());
+ clientSocket.once('close', () => upstreamSocket.destroy());
+};
+
+/**
+ * Terminate PortOS-owned paths, else reverse-proxy to the sequencer.
+ * `pathname` is the upstream path (prefix already stripped for path mounts).
+ */
+export const handleEidoverseHttp = ({
+ req,
+ res,
+ protocol,
+ embedMode = 'bridge',
+ targetHost = '127.0.0.1',
+ targetPort = EIDOVERSE_PORT,
+ pathOverride,
+}) => {
+ const pathname = requestPathname(pathOverride ?? req.url);
+ if (pathname === EMBED_CONFIG_PATH) {
+ serveEmbedConfig(req, res, protocol, embedMode);
+ return;
+ }
+ if (pathname === HOST_DESCRIPTOR_PATH) {
+ serveHostDescriptor(req, res).catch((error) => {
+ console.error(`❌ Eidoverse host descriptor response failed: ${error.message}`);
+ res.destroy();
+ });
+ return;
+ }
+ proxyHttpToEidoverse({ req, res, targetHost, targetPort, protocol, pathOverride });
+};
+
+/**
+ * Express middleware: `/eidoverse-host/*` (prefix stripped) + allowlisted root
+ * routes, only while `isActive()` is true. Mount before the SPA fallback and
+ * before the `/eidoverse-host` SERVER_OWNED terminator.
+ */
+export function createEidoverseExpressMiddleware({
+ isActive,
+ targetHost = '127.0.0.1',
+ targetPort = EIDOVERSE_PORT,
+ getProtocol = (req) => (req.secure || req.headers['x-forwarded-proto'] === 'https' ? 'https' : 'http'),
+} = {}) {
+ return function eidoverseExpressProxy(req, res, next) {
+ if (!isActive?.()) return next();
+
+ const stripped = stripEidoverseHostPrefix(req.url);
+ if (stripped !== null) {
+ const protocol = getProtocol(req);
+ handleEidoverseHttp({
+ req,
+ res,
+ protocol,
+ embedMode: 'same-origin',
+ targetHost,
+ targetPort,
+ pathOverride: stripped,
+ });
+ return;
+ }
+
+ const pathname = String(req.path || requestPathname(req.url));
+ if (!isEidoverseRootProxyPath(pathname)) return next();
+
+ const protocol = getProtocol(req);
+ handleEidoverseHttp({
+ req,
+ res,
+ protocol,
+ embedMode: 'same-origin',
+ targetHost,
+ targetPort,
+ pathOverride: req.url,
+ });
+ };
+}
+
+const mountedUpgradeServers = new WeakSet();
+
+/**
+ * Attach an `upgrade` listener for `/ws` and `/eidoverse-host/**` while active.
+ * Safe to call for both the HTTPS server and the loopback HTTP mirror.
+ */
+export function mountEidoverseWebSocket(httpServer, {
+ isActive,
+ targetHost = '127.0.0.1',
+ targetPort = EIDOVERSE_PORT,
+ getProtocol = () => 'http',
+} = {}) {
+ if (!httpServer || mountedUpgradeServers.has(httpServer)) return;
+ mountedUpgradeServers.add(httpServer);
+
+ httpServer.on('upgrade', (req, clientSocket, head) => {
+ if (!isActive?.()) return;
+
+ const stripped = stripEidoverseHostPrefix(req.url);
+ let pathOverride = null;
+ if (stripped !== null) {
+ pathOverride = stripped;
+ } else {
+ const pathname = requestPathname(req.url);
+ if (pathname !== '/ws') return;
+ pathOverride = req.url;
+ }
+
+ const protocol = typeof getProtocol === 'function' ? getProtocol(req) : getProtocol;
+ proxyUpgradeToEidoverse({
+ req,
+ clientSocket,
+ head,
+ targetHost,
+ targetPort,
+ protocol,
+ pathOverride,
+ });
+ });
+}
+
+export const BAD_GATEWAY_MESSAGE = BAD_GATEWAY_BODY;
diff --git a/server/services/eidoverseProxy.test.js b/server/services/eidoverseProxy.test.js
new file mode 100644
index 0000000000..2373237e7c
--- /dev/null
+++ b/server/services/eidoverseProxy.test.js
@@ -0,0 +1,176 @@
+import { once } from 'node:events';
+import { createServer, request as httpRequest } from 'node:http';
+import express from 'express';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { WebSocket, WebSocketServer } from 'ws';
+import {
+ createEidoverseExpressMiddleware,
+ embedParentOrigin,
+ mountEidoverseWebSocket,
+ stripEidoverseHostPrefix,
+ isEidoverseRootProxyPath,
+} from './eidoverseProxy.js';
+
+const HOST_DESCRIPTOR = Object.freeze({
+ id: 'hst_0123456789ab',
+ kind: 'portos',
+ label: 'Luminous Systems Garden',
+ version: '9.9.9',
+ caps: { eido: false },
+});
+vi.mock('./eidoverseWorld.js', () => ({
+ readEidoverseHostDescriptor: vi.fn(async () => HOST_DESCRIPTOR),
+}));
+
+const servers = [];
+const webSocketServers = [];
+const webSocketClients = [];
+
+const listen = async (server) => {
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ servers.push(server);
+ return server.address().port;
+};
+
+const closeServer = (server) => new Promise((resolve, reject) => {
+ server.close((error) => (error ? reject(error) : resolve()));
+});
+
+const rawGet = (port, path, hostHeader) => new Promise((settle, reject) => {
+ const probe = httpRequest({ host: '127.0.0.1', port, path, headers: { host: hostHeader } }, (response) => {
+ let body = '';
+ response.setEncoding('utf8');
+ response.on('data', (chunk) => { body += chunk; });
+ response.on('end', () => settle({ status: response.statusCode, body }));
+ });
+ probe.once('error', reject);
+ probe.end();
+});
+
+afterEach(async () => {
+ webSocketClients.splice(0).forEach((client) => client.terminate());
+ await Promise.all(webSocketServers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))));
+ await Promise.all(servers.splice(0).map(closeServer));
+});
+
+describe('eidoverse proxy route helpers', () => {
+ it('strips the /eidoverse-host prefix for relative assets', () => {
+ expect(stripEidoverseHostPrefix('/eidoverse-host/')).toBe('/');
+ expect(stripEidoverseHostPrefix('/eidoverse-host')).toBe('/');
+ expect(stripEidoverseHostPrefix('/eidoverse-host/main.js')).toBe('/main.js');
+ expect(stripEidoverseHostPrefix('/eidoverse-host/a?b=1')).toBe('/a?b=1');
+ expect(stripEidoverseHostPrefix('/version')).toBe(null);
+ });
+
+ it('recognizes exact and prefix root allowlist entries from routes.ts', () => {
+ expect(isEidoverseRootProxyPath('/version')).toBe(true);
+ expect(isEidoverseRootProxyPath('/ws')).toBe(true);
+ expect(isEidoverseRootProxyPath('/library/foo.glb')).toBe(true);
+ expect(isEidoverseRootProxyPath('/node_modules/three/build/three.module.js')).toBe(true);
+ expect(isEidoverseRootProxyPath('/AGENTS.md')).toBe(true);
+ expect(isEidoverseRootProxyPath('/eidoverse')).toBe(false);
+ expect(isEidoverseRootProxyPath('/api/settings')).toBe(false);
+ });
+
+ it('preserves a non-5555 Host port in same-origin embed parent origins', () => {
+ const req = { headers: { host: '127.0.0.1:15555' } };
+ expect(embedParentOrigin(req, 'http', 'same-origin')).toBe('http://127.0.0.1:15555');
+ expect(embedParentOrigin(req, 'http', 'bridge')).toMatch(/:5555$/);
+ });
+});
+
+describe('main-server eidoverse reverse-proxy', () => {
+ const mountApp = async ({ active, upstreamPort, spaBody = 'spa' }) => {
+ const app = express();
+ app.use(createEidoverseExpressMiddleware({
+ isActive: () => active,
+ targetHost: '127.0.0.1',
+ targetPort: upstreamPort,
+ getProtocol: () => 'http',
+ }));
+ app.use((_req, res) => {
+ res.status(200).type('text/plain').send(spaBody);
+ });
+ const server = createServer(app);
+ mountEidoverseWebSocket(server, {
+ isActive: () => active,
+ targetHost: '127.0.0.1',
+ targetPort: upstreamPort,
+ getProtocol: () => 'http',
+ });
+ return listen(server);
+ };
+
+ it('strips /eidoverse-host and forwards to the sequencer', async () => {
+ const upstreamPort = await listen(createServer((req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ path: req.url }));
+ }));
+ const port = await mountApp({ active: true, upstreamPort });
+
+ const response = await fetch(`http://127.0.0.1:${port}/eidoverse-host/main.js?v=1`);
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ path: '/main.js?v=1' });
+ });
+
+ it('proxies root /version only while the host is active', async () => {
+ const upstreamPort = await listen(createServer((req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ path: req.url, from: 'eidoverse' }));
+ }));
+
+ const activePort = await mountApp({ active: true, upstreamPort, spaBody: 'spa-active' });
+ const active = await fetch(`http://127.0.0.1:${activePort}/version`);
+ expect(active.status).toBe(200);
+ expect(await active.json()).toEqual({ path: '/version', from: 'eidoverse' });
+
+ const inactivePort = await mountApp({ active: false, upstreamPort, spaBody: 'spa-inactive' });
+ const inactive = await fetch(`http://127.0.0.1:${inactivePort}/version`);
+ expect(inactive.status).toBe(200);
+ expect(await inactive.text()).toBe('spa-inactive');
+ });
+
+ it('answers path-mounted /embed-config with the full browser Host as parentOrigin', async () => {
+ const upstreamRequests = [];
+ const upstreamPort = await listen(createServer((req, res) => {
+ upstreamRequests.push(req.url);
+ res.writeHead(200);
+ res.end('sequencer');
+ }));
+ const port = await mountApp({ active: true, upstreamPort });
+
+ const result = await rawGet(port, '/eidoverse-host/embed-config', '127.0.0.1:15555');
+ expect(result.status).toBe(200);
+ expect(JSON.parse(result.body)).toEqual({ parentOrigin: 'http://127.0.0.1:15555' });
+ expect(upstreamRequests).toEqual([]);
+
+ const root = await rawGet(port, '/embed-config', '127.0.0.1:15555');
+ expect(root.status).toBe(200);
+ expect(JSON.parse(root.body)).toEqual({ parentOrigin: 'http://127.0.0.1:15555' });
+ });
+
+ it('upgrades root /ws to the sequencer while active', async () => {
+ const upstream = createServer();
+ const webSocketServer = new WebSocketServer({ server: upstream });
+ webSocketServers.push(webSocketServer);
+ webSocketServer.on('connection', (socket) => {
+ socket.send('ready');
+ socket.on('message', (message) => socket.send(`echo:${message}`));
+ });
+ const upstreamPort = await listen(upstream);
+ const port = await mountApp({ active: true, upstreamPort });
+
+ const client = new WebSocket(`ws://127.0.0.1:${port}/ws`);
+ webSocketClients.push(client);
+ const first = once(client, 'message');
+ await once(client, 'open');
+ expect(String((await first)[0])).toBe('ready');
+ const echo = once(client, 'message');
+ client.send('ping');
+ expect(String((await echo)[0])).toBe('echo:ping');
+ client.close();
+ await once(client, 'close');
+ webSocketClients.pop();
+ });
+});