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

fix: serve the renderer's embedding origin from the PortOS bridge (#6298)

[._.]/ Adam Eivy40d727252081
diff --git a/client/src/pages/Eidoverse.jsx b/client/src/pages/Eidoverse.jsx
index e5ee1ae76a..746515af35 100644
--- a/client/src/pages/Eidoverse.jsx
+++ b/client/src/pages/Eidoverse.jsx
@@ -46,16 +46,21 @@ 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.
export const hostUrlFor = (host, setup, location = window.location, identity = null) => {
- let baseUrl;
- if (location.protocol === 'https:') {
- if (host.protocol !== 'https') {
- throw new Error('PortOS is using HTTPS, but the Eidoverse host could not load the shared certificate.');
- }
- baseUrl = `https://${location.hostname}:${host.port}/`;
- } else {
- baseUrl = `http://${location.hostname}:${setup.uiPort}/`;
+ 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}/`;
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 b7961b510c..a0d6d86156 100644
--- a/client/src/pages/Eidoverse.test.jsx
+++ b/client/src/pages/Eidoverse.test.jsx
@@ -147,7 +147,7 @@ describe('Eidoverse hosted page', () => {
renderPage();
const frame = await screen.findByTitle('Eidoverse Worlds');
- expect(frame).toHaveAttribute('src', `http://${window.location.hostname}:8940/?world=portos&name=example-portos-user`);
+ expect(frame).toHaveAttribute('src', `http://${window.location.hostname}:5563/?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');
@@ -155,7 +155,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}:8940/?world=portos&name=example-portos-user`);
+ .toHaveAttribute('href', `http://${window.location.hostname}:5563/?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');
@@ -365,6 +365,25 @@ describe('Eidoverse hosted page', () => {
)).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', () => {
+ 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/');
+ expect(hostUrlFor(
+ { running: true, protocol: 'https', port: 5563 },
+ setup,
+ { protocol: 'http:', hostname: 'localhost' },
+ )).toBe(`http://localhost:${setup.uiPort}/`);
+ });
+
it('keeps a successful local save visible when projection fails', async () => {
const user = userEvent.setup();
renderPage();
@@ -414,7 +433,7 @@ describe('Eidoverse hosted page', () => {
await waitFor(() => expect(screen.getByTitle('Eidoverse Worlds')).toHaveAttribute(
'src',
- `http://${window.location.hostname}:8940/?world=portos-two&name=example-portos-user`,
+ `http://${window.location.hostname}:5563/?world=portos-two&name=example-portos-user`,
));
});
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.md
index fab40d9da8..d038339f52 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -306,13 +306,21 @@ an empty join token; do not expose this configuration to the public internet.
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`. For an HTTPS PortOS
-session, the embedded page lazily opens a PortOS-owned HTTPS/WebSocket bridge on
-`:5563`, using the same machine certificate as `:5555` and forwarding to
-`127.0.0.1:8940`. This avoids browser mixed-content rejection while leaving both
-external repositories 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.
+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.
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
@@ -366,11 +374,16 @@ versions reject the newer config schema rather than discarding the aliases.
## Renderer capabilities and frame contract V1
-The external Worlds checkout remains the sole renderer. This PortOS contract
-can ship before its companion implementation in
-[Worlds issue 5](https://github.com/atomantic/eidoverse-worlds/issues/5).
+The external Worlds checkout remains the sole renderer. Its half of this
+contract shipped in
+[Worlds issue 5](https://github.com/atomantic/eidoverse-worlds/issues/5) and
+[Worlds issue 7](https://github.com/atomantic/eidoverse-worlds/issues/7).
End-to-end label/picking/touch/keyboard acceptance requires that companion;
-producer and frame-contract tests alone do not establish it.
+producer and frame-contract tests alone do not establish it, so
+`scripts/eidoverse-frame-acceptance.mjs` drives the whole exchange against a
+disposable synthetic world in a real browser. It is deliberately outside CI —
+it needs the installed checkout, Bun, Playwright and a real Chrome — and it
+never touches the install's own world under `data/eidoverse/worlds`.
`GET /version` advertises independently versioned capabilities alongside its
existing build identity:
@@ -396,7 +409,18 @@ The renderer validates `event.source === parent` and the embedding PortOS origin
then replies to that exact origin with `eidoverse:ready`, echoing `version` and
`nonce` and advertising its supported capabilities. The renderer must obtain
the expected parent origin from its trusted embedding configuration; accepting
-an arbitrary opener as the parent is not sufficient. Each later message carries
+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
+`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
+the frame bridge silently dormant. A request whose `Host` is unusable resolves
+to no embedder rather than to a repaired guess, since the browser compares
+origins with `===` and a repair would be a silent mismatch at handshake time. Each later message carries
the same version and nonce. A reload invalidates the prior session. Unsupported
clients simply ignore the handshake and continue rendering.
diff --git a/scripts/eidoverse-frame-acceptance.mjs b/scripts/eidoverse-frame-acceptance.mjs
new file mode 100644
index 0000000000..c3ac6eb9cd
--- /dev/null
+++ b/scripts/eidoverse-frame-acceptance.mjs
@@ -0,0 +1,318 @@
+#!/usr/bin/env node
+/**
+ * Renderer-dependent acceptance for the Eidoverse frame contract V1.
+ *
+ * node scripts/eidoverse-frame-acceptance.mjs
+ *
+ * Everything the producer and handshake unit tests cannot prove: that PortOS's
+ * OWN bridge arms the external renderer's frame bridge, that a real browser
+ * completes the handshake across two real origins, and that the messages a
+ * real renderer emits survive PortOS's navigation validator.
+ *
+ * Deliberately not a Vitest suite and deliberately not in CI: it needs the
+ * installed Worlds checkout, Bun, Playwright and a real Chrome, none of which a
+ * CI runner has. The regression coverage that DOES belong in CI is in
+ * `server/services/eidoverseHost.test.js` and `client/src/pages/Eidoverse.test.jsx`.
+ *
+ * The world it drives is disposable and synthetic — a child sequencer bound to
+ * a per-run nonce, writing to a scratch directory. It never joins, reads or
+ * writes the install's real world under `data/eidoverse/worlds`, and every
+ * fixture entity below is invented.
+ */
+import { spawn } from 'node:child_process';
+import { createServer } from 'node:http';
+import { mkdtempSync, rmSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { randomUUID } from 'node:crypto';
+import { createEidoverseHost } from '../server/services/eidoverseHost.js';
+import {
+ EIDOVERSE_FRAME_VERSION,
+ eidoverseNavigationTarget,
+ isEidoverseFrameMessage,
+} from '../client/src/lib/eidoverseFrame.js';
+
+const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const WORLDS = process.env.EIDOVERSE_WORLDS_DIR
+ || join(REPO, 'data', 'repos', 'anima-research', 'eidoverse-worlds');
+const VIDEO = process.env.EIDOVERSE_VIDEO_DIR
+ || join(REPO, 'data', 'repos', 'anima-research', 'eidoverse-video');
+const BUN = process.env.BUN_PATH || join(process.env.HOME || '', '.bun', 'bin', 'bun');
+const CHROME = process.env.PORTOS_TEST_CHROME
+ || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
+const JOIN_TOKEN = 'portos-frame-acceptance';
+
+let pass = 0;
+let fail = 0;
+const check = (name, ok, detail = '') => {
+ if (ok) { pass += 1; console.log(` ✅ ${name}`); }
+ else { fail += 1; console.log(` ❌ ${name}${detail ? ` — ${detail}` : ''}`); }
+};
+const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
+const until = async (want, ms = 15000) => {
+ for (const end = Date.now() + ms; Date.now() < end;) {
+ if (await want()) return true;
+ await sleep(100);
+ }
+ return false;
+};
+
+// Invented fixtures. `pin` is the only one that may ever become a destination;
+// the rest are the shapes a component could carry that must not.
+const SEED = {
+ pin: { label: { name: 'Example Goals', visibility: 'always' }, portos: { route: '/goals/list' } },
+ url: { label: { name: 'Elsewhere', visibility: 'always' }, portos: { route: 'https://evil.example/goals/list' } },
+ query: { label: { name: 'Queried', visibility: 'always' }, portos: { route: '/goals/list?steal=1' } },
+ plain: { label: { name: 'Bench', visibility: 'always' } },
+};
+// The saved projection legend PortOS would hold for that world.
+const LEGEND = [{ id: 'pin', route: '/goals/list' }];
+
+const PARENT_PAGE = `<!doctype html><html><head><meta charset="utf-8"><title>PortOS</title></head>
+<body style="margin:0">
+<iframe id="f" title="Eidoverse Worlds" style="width:100vw;height:100vh;border:0"></iframe>
+<script>
+window.received = [];
+addEventListener('message', (e) => { received.push({ origin: e.origin, data: e.data }); });
+window.rendererOrigin = new URLSearchParams(location.search).get('renderer') || '';
+window.mount = (src) => new Promise((done) => {
+ const frame = document.getElementById('f');
+ frame.addEventListener('load', () => done(true), { once: true });
+ frame.src = src;
+});
+window.post = (msg) => document.getElementById('f').contentWindow.postMessage(msg, rendererOrigin);
+window.readyFor = (nonce) => received.find((m) => m.data?.type === 'eidoverse:ready' && m.data.nonce === nonce) || null;
+window.navigates = () => received.filter((m) => m.data?.type === 'eidoverse:navigate');
+</script></body></html>`;
+
+const shutdown = [];
+const closeAll = async () => {
+ for (const stop of shutdown.reverse()) await stop().catch(() => {});
+};
+
+async function spawnDisposableWorld() {
+ const port = 8981 + Math.floor(Math.random() * 800);
+ const scratch = mkdtempSync(join(tmpdir(), 'portos-eidoverse-acceptance-'));
+ const nonce = randomUUID();
+ const child = spawn(BUN, ['server/server.ts'], {
+ cwd: WORLDS,
+ env: {
+ ...process.env,
+ PORT: String(port),
+ JOIN_TOKEN,
+ WORLDS_DIR: scratch,
+ EIDOVERSE_DIR: VIDEO,
+ EIDO_BOOT_NONCE: nonce,
+ // Left UNSET on purpose: proving PortOS's bridge is what arms the frame
+ // bridge means the checkout must have no embedder of its own.
+ EMBED_PARENT_ORIGIN: '',
+ },
+ stdio: ['ignore', 'ignore', 'ignore'],
+ });
+ shutdown.push(async () => {
+ child.kill('SIGTERM');
+ rmSync(scratch, { recursive: true, force: true });
+ });
+ const origin = `http://127.0.0.1:${port}`;
+ let version = null;
+ await until(async () => {
+ if (child.exitCode !== null) throw new Error(`Eidoverse child exited ${child.exitCode}`);
+ version = await fetch(`${origin}/version`).then((r) => r.json()).catch(() => null);
+ return version?.nonce === nonce;
+ }, 60000);
+ if (version?.nonce !== nonce) throw new Error('the disposable Eidoverse world never proved it was ours');
+ return { origin, version };
+}
+
+const serveParent = () => new Promise((ready) => {
+ const server = createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ res.end(PARENT_PAGE);
+ });
+ shutdown.push(() => new Promise((done) => server.close(done)));
+ server.listen(0, '127.0.0.1', () => ready(server.address().port));
+});
+
+async function main() {
+ for (const [label, path] of [['Worlds checkout', WORLDS], ['Video checkout', VIDEO], ['Bun', BUN], ['Chrome', CHROME]]) {
+ if (!existsSync(path)) throw new Error(`${label} not found at ${path}`);
+ }
+ // Playwright ships CommonJS, so the named export only exists on `default`
+ // for some builds — take whichever half of the interop actually carries it.
+ const playwright = await import(pathToFileURL(join(WORLDS, 'node_modules', 'playwright', 'index.js')).href);
+ const chromium = playwright.chromium || playwright.default?.chromium;
+ if (!chromium) throw new Error('Playwright resolved without a chromium launcher');
+
+ const parentPort = await serveParent();
+ // Read by the bridge when it answers /embed-config, so the derived parent
+ // origin names this harness rather than the install's real PortOS port.
+ process.env.PORT = String(parentPort);
+ const parentOrigin = `http://127.0.0.1:${parentPort}`;
+
+ const world = await spawnDisposableWorld();
+ console.log(`\nRenderer build ${world.version.sha} (${world.version.commitTime}) — capabilities ${JSON.stringify(world.version.capabilities)}`);
+
+ const bridge = createEidoverseHost({
+ targetHost: '127.0.0.1',
+ targetPort: Number(new URL(world.origin).port),
+ listenHost: '127.0.0.1',
+ listenPort: 0,
+ certDir: null,
+ });
+ shutdown.push(() => bridge.close());
+ const bridgeStatus = await bridge.start();
+ const bridgeOrigin = `http://127.0.0.1:${bridgeStatus.port}`;
+
+ console.log('\n— A. the renderer is armed by PortOS, not by its own environment —');
+ const direct = await fetch(`${world.origin}/embed-config`).then((r) => r.json());
+ check('the unconfigured checkout names no embedder of its own', direct.parentOrigin === null, JSON.stringify(direct));
+ const bridged = await fetch(`${bridgeOrigin}/embed-config`).then((r) => r.json());
+ check('the PortOS bridge names this page origin exactly',
+ bridged.parentOrigin === parentOrigin, JSON.stringify(bridged));
+ const refused = await fetch(`${bridgeOrigin}/embed-config`, { method: 'POST' });
+ check('the embedding configuration is read-only', refused.status === 405, String(refused.status));
+
+ const browser = await chromium.launch({ executablePath: CHROME, args: ['--enable-unsafe-webgpu'] });
+ shutdown.push(() => browser.close());
+ // Narrow and touch-capable: every action below has to be reachable by thumb.
+ const context = await browser.newContext({ viewport: { width: 390, height: 844 }, hasTouch: true });
+ const page = await context.newPage();
+ const pageErrors = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+
+ const nonce = Array.from(crypto.getRandomValues(new Uint8Array(16)),
+ (byte) => byte.toString(16).padStart(2, '0')).join('');
+ await page.goto(`${parentOrigin}/?renderer=${encodeURIComponent(bridgeOrigin)}`);
+ await page.evaluate((src) => window.mount(src), `${bridgeOrigin}/?spectate&key=${JOIN_TOKEN}&world=acceptance`);
+
+ console.log('\n— B. the handshake PortOS actually sends —');
+ await page.evaluate(([version, session]) => window.post({
+ type: 'portos:connect', version, nonce: session,
+ capabilities: { portosNavigation: 1, labelPreferences: 1 }, labelVisibility: 'nearby',
+ }), [EIDOVERSE_FRAME_VERSION, nonce]);
+ await until(async () => Boolean(await page.evaluate((s) => window.readyFor(s), nonce)), 60000);
+ const ready = await page.evaluate((s) => window.readyFor(s), nonce);
+ check('eidoverse:ready arrives from the bridge origin, echoing version and nonce',
+ Boolean(ready) && ready.origin === bridgeOrigin, JSON.stringify(ready));
+ check('PortOS accepts it as a message of the current session',
+ Boolean(ready) && isEidoverseFrameMessage(
+ { data: ready.data, source: 'frame', origin: bridgeOrigin },
+ { source: 'frame', origin: bridgeOrigin, nonce },
+ ), JSON.stringify(ready?.data));
+ check('ready advertises all three V1 capabilities as PortOS reads them',
+ ['objectLabels', 'portosNavigation', 'labelPreferences'].every((key) => ready?.data?.capabilities?.[key] === 1),
+ JSON.stringify(ready?.data?.capabilities));
+
+ const renderer = () => {
+ const frame = page.frames().find((entry) => entry.url().startsWith(bridgeOrigin));
+ if (!frame) throw new Error('renderer frame is gone');
+ return frame;
+ };
+ const panel = () => renderer().locator('details').filter({ hasText: 'Inspect objects' });
+ await panel().waitFor({ timeout: 90000 });
+
+ console.log('\n— C. a synthetic scene, and the one action it may offer —');
+ await renderer().evaluate(async (seed) => {
+ const [{ state, hydrate }, { entities }, { THREE, camera, scene }, { tickObjectLabels }] = await Promise.all([
+ import('/lib/state.js'), import('/lib/world.js'), import('/lib/core.js'), import('/lib/objectlabels.js')]);
+ camera.position.set(0, 2, 8); camera.lookAt(0, 1, 0); camera.updateMatrixWorld();
+ const snapshot = structuredClone(state.st);
+ snapshot.entities = {};
+ for (const [id, comp] of Object.entries(seed)) {
+ snapshot.entities[id] = { id, lib: 'missing.glb', pos: [0, 0, 0], comp };
+ }
+ hydrate(snapshot);
+ let index = 0;
+ for (const id of Object.keys(seed)) {
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(0.4, 1, 0.4), new THREE.MeshBasicMaterial());
+ mesh.position.set((index - 1.5) * 0.5, 0, 0);
+ index += 1;
+ scene.add(mesh);
+ mesh.updateMatrixWorld();
+ entities.set(id, mesh);
+ }
+ tickObjectLabels(performance.now() + 1000);
+ window.labelTick = tickObjectLabels;
+ const send = WebSocket.prototype.send;
+ window.sent = [];
+ WebSocket.prototype.send = function record(data) { window.sent.push(String(data)); return send.call(this, data); };
+ }, SEED);
+ await panel().getByText('Inspect objects', { exact: true }).click();
+ const open = panel().getByRole('button', { name: 'Open in PortOS' });
+ const select = (id) => panel().getByLabel('Choose object to inspect').selectOption(id);
+ await select('pin');
+ check('a projected object offers Open in PortOS', await open.count() === 1);
+ for (const id of ['url', 'query', 'plain']) {
+ await select(id);
+ check(`"${id}" offers no action — its component names no route PortOS knows`, await open.count() === 0);
+ }
+
+ console.log('\n— D. navigation is a user action, and PortOS validates what arrives —');
+ await select('pin');
+ await open.focus();
+ await page.keyboard.press('Enter');
+ await until(async () => (await page.evaluate(() => window.navigates().length)) === 1);
+ const [navigate] = await page.evaluate(() => window.navigates());
+ check('keyboard Enter emits eidoverse:navigate from the bridge origin',
+ navigate?.origin === bridgeOrigin, JSON.stringify(navigate));
+ check('PortOS resolves it to the legend route and nothing else',
+ Boolean(navigate) && isEidoverseFrameMessage(
+ { data: navigate.data, source: 'frame', origin: bridgeOrigin },
+ { source: 'frame', origin: bridgeOrigin, nonce },
+ ) && eidoverseNavigationTarget(navigate.data, LEGEND) === '/goals/list',
+ JSON.stringify(navigate?.data));
+ check('a stale session cannot navigate', Boolean(navigate) && !isEidoverseFrameMessage(
+ { data: navigate.data, source: 'frame', origin: bridgeOrigin },
+ { source: 'frame', origin: bridgeOrigin, nonce: 'retired-session' },
+ ));
+ check('an entity absent from the legend cannot navigate',
+ Boolean(navigate) && eidoverseNavigationTarget({ ...navigate.data, entityId: 'unknown' }, LEGEND) === null);
+ await open.tap();
+ check('the same action is reachable by touch on a narrow viewport',
+ await until(async () => (await page.evaluate(() => window.navigates().length)) === 2),
+ String(await page.evaluate(() => window.navigates().length)));
+
+ console.log('\n— E. label preference is browser-only, and rides the session —');
+ const preference = () => panel().getByLabel('Object labels', { exact: true }).inputValue();
+ const post = (message) => page.evaluate((value) => window.post(value), message);
+ const plaques = () => renderer().evaluate(() => [...document.querySelectorAll('body > div > span')]
+ .filter((element) => element.style.position === 'absolute' && element.style.display !== 'none').length);
+ await renderer().evaluate(() => window.labelTick(performance.now() + 2000));
+ check('nearby shows the authored plaques', await plaques() > 0, String(await plaques()));
+ await post({ type: 'portos:label-preference', version: EIDOVERSE_FRAME_VERSION, nonce, labelVisibility: 'all-nearby' });
+ check('all-nearby reaches the renderer', await until(async () => await preference() === 'all'), await preference());
+ await post({ type: 'portos:label-preference', version: EIDOVERSE_FRAME_VERSION, nonce, labelVisibility: 'off' });
+ const wentOff = await until(async () => await preference() === 'off');
+ await renderer().evaluate(() => window.labelTick(performance.now() + 4000));
+ check('off hides every floating plaque', wentOff && await plaques() === 0,
+ `${await preference()} / ${await plaques()} plaques`);
+ await select('pin');
+ check('off still leaves selected-object details readable',
+ /Entity: pin/.test(await panel().innerText()) && await open.count() === 1);
+
+ console.log('\n— F. repeated refresh, and no world write —');
+ await post({ type: 'portos:label-preference', version: EIDOVERSE_FRAME_VERSION, nonce, labelVisibility: 'nearby' });
+ await until(async () => await preference() === 'nearby');
+ await renderer().evaluate(() => window.labelTick(performance.now() + 6000));
+ const before = await plaques();
+ for (let round = 1; round <= 3; round += 1) {
+ await renderer().evaluate((step) => window.labelTick(performance.now() + 6000 + step * 500), round);
+ }
+ const after = await plaques();
+ check('a repeated refresh does not duplicate plaques', before > 0 && after === before, `${before} → ${after}`);
+ const written = await renderer().evaluate(() => window.sent.slice());
+ check('the whole exchange wrote no world verb',
+ written.every((line) => !/"verb"/.test(line)), written.filter((line) => /"verb"/.test(line)).join(' | '));
+ check('the browser reported no page error', pageErrors.length === 0, pageErrors.join(' | '));
+
+ console.log(`\n${fail === 0 ? '✅' : '❌'} ${pass} passed, ${fail} failed`);
+ return fail === 0 ? 0 : 1;
+}
+
+const code = await main().catch((error) => {
+ console.error(`❌ acceptance run failed: ${error.message}`);
+ return 1;
+});
+await closeAll();
+process.exit(code);
diff --git a/server/services/eidoverseHost.js b/server/services/eidoverseHost.js
index 60e5bd758c..6e4d54de09 100644
--- a/server/services/eidoverseHost.js
+++ b/server/services/eidoverseHost.js
@@ -9,6 +9,7 @@ import { EIDOVERSE_PORT } from './eidoverse.js';
const BAD_GATEWAY_BODY = 'Eidoverse Worlds is not running.';
const HOST_DESCRIPTOR_PATH = '/host';
+const EMBED_CONFIG_PATH = '/embed-config';
// 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
@@ -72,6 +73,47 @@ const serveHostDescriptor = async (req, res) => {
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();
@@ -135,7 +177,12 @@ export function createEidoverseHost({
};
const handleHttp = (req, res) => {
- if (requestPathname(req.url) === HOST_DESCRIPTOR_PATH) {
+ 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) => {
diff --git a/server/services/eidoverseHost.test.js b/server/services/eidoverseHost.test.js
index 933e9e11f6..14151e3199 100644
--- a/server/services/eidoverseHost.test.js
+++ b/server/services/eidoverseHost.test.js
@@ -1,5 +1,5 @@
import { once } from 'node:events';
-import { createServer } from 'node:http';
+import { createServer, request as httpRequest } from 'node:http';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { WebSocket, WebSocketServer } from 'ws';
import { createEidoverseHost } from './eidoverseHost.js';
@@ -35,6 +35,7 @@ const closeServer = (server) => new Promise((resolve, reject) => {
});
afterEach(async () => {
+ vi.unstubAllEnvs();
webSocketClients.splice(0).forEach((client) => client.terminate());
await Promise.all(bridges.splice(0).map((bridge) => bridge.close()));
await Promise.all(webSocketServers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))));
@@ -150,6 +151,80 @@ describe('Eidoverse host bridge', () => {
expect(upstreamRequests).toEqual([]);
});
+ // The renderer takes its trusted parent origin from GET /embed-config and
+ // stays permanently dormant without one. The external checkout answers that
+ // from a single static env var, which cannot name one install reachable as
+ // localhost, a LAN address AND a MagicDNS name — so PortOS answers instead,
+ // from the hostname the browser actually used plus its own scheme and port.
+ it('answers GET /embed-config with the PortOS page origin the browser reached it by', async () => {
+ const upstreamRequests = [];
+ const upstreamPort = await listen(createServer((req, res) => {
+ upstreamRequests.push(req.url);
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ parentOrigin: null }));
+ }));
+ const bridge = createEidoverseHost({
+ targetPort: upstreamPort,
+ listenHost: '127.0.0.1',
+ listenPort: 0,
+ certDir: null,
+ });
+ bridges.push(bridge);
+ vi.stubEnv('PORT', '5599');
+
+ const host = await bridge.start();
+ const response = await fetch(`http://127.0.0.1:${host.port}/embed-config`);
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get('cache-control')).toBe('no-store');
+ // The bridge's own port is never the answer — the parent is the PortOS page.
+ expect(await response.json()).toEqual({ parentOrigin: 'http://127.0.0.1:5599' });
+ // Forwarding it would hand back the checkout's unset value and leave the
+ // renderer with no embedder at all.
+ expect(upstreamRequests).toEqual([]);
+
+ const posted = await fetch(`http://127.0.0.1:${host.port}/embed-config`, { method: 'POST' });
+ expect(posted.status).toBe(405);
+ expect(upstreamRequests).toEqual([]);
+ });
+
+ it('names no embedder when the request carries no usable host', async () => {
+ const upstreamPort = await listen(createServer((_req, res) => {
+ res.writeHead(200);
+ res.end('sequencer');
+ }));
+ const bridge = createEidoverseHost({
+ targetPort: upstreamPort,
+ listenHost: '127.0.0.1',
+ listenPort: 0,
+ certDir: null,
+ });
+ bridges.push(bridge);
+
+ const host = await bridge.start();
+ // `fetch` refuses to set Host, so the raw client is the only way to ask.
+ // A repaired origin would be a silent mismatch at handshake time: the
+ // browser compares with ===, so an unusable host must resolve to "nobody".
+ const answer = await new Promise((settle, reject) => {
+ const probe = httpRequest({
+ host: '127.0.0.1',
+ port: host.port,
+ path: '/embed-config',
+ headers: { host: 'not a hostname' },
+ }, (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();
+ });
+
+ expect(answer.status).toBe(200);
+ expect(JSON.parse(answer.body)).toEqual({ parentOrigin: null });
+ });
+
it('refuses to write through the descriptor path, and reports an unreadable descriptor honestly', async () => {
const upstreamRequests = [];
const upstreamPort = await listen(createServer((req, res) => {