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: refuse cross-site and DNS-rebound browser requests on password-free installs (#8707)

[._.]/ Adam Eivy37c9ff69a2ae
diff --git a/.env.example b/.env.example
index 138ac977b0..42268b1343 100644
--- a/.env.example
+++ b/.env.example
@@ -22,6 +22,12 @@ PGPASSWORD=portos
# Server host binding (hostname used for self-links and federation peer discovery)
# PORTOS_HOST=my-machine.ts.net
+# Extra hostnames a browser may use to reach PortOS (comma-separated; a leading dot admits
+# subdomains). IP literals, single-label names, .ts.net/.local/.lan/.internal/.home.arpa names,
+# the machine hostname and PORTOS_HOST are always accepted; any other Host is refused with
+# HOST_NOT_ALLOWED to block DNS rebinding.
+# PORTOS_ALLOWED_HOSTS=portos.example.com,.home.example.net
+
# Loopback HTTP port spawned when HTTPS is active so local curl skips the cert (default: 5553)
# PORTOS_HTTP_PORT=5553
diff --git a/client/vite.config.js b/client/vite.config.js
index 9a07400926..4ecd696256 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -7,7 +7,7 @@ import { resolve } from 'path';
import { resolveBundleNodeEnv } from './vite.buildEnv.js';
import { CHUNK_GROUPS } from './vite.chunkGroups.js';
-import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../lib/portosAuthCore.js';
+import { DEV_PROXY_CLIENT_ADDRESS_HEADER, devProxyForwardedOrigin } from '../lib/portosAuthCore.js';
import {
EIDOVERSE_HOST_PATH_PREFIX,
EIDOVERSE_ROOT_EXACT_PATHS,
@@ -107,6 +107,21 @@ function markProxyClientAddress(proxy) {
proxy.on('proxyReqWs', mark);
}
+// The API's browser-relay guard compares Origin with Host in both auth modes;
+// changeOrigin rewrites Host to the target, so re-stamp a same-origin Origin
+// to match (a foreign one is forwarded as-is and refused). Covers the HTTP
+// hop and the websocket upgrade.
+function forwardSameOrigin(target) {
+ const stamp = (proxyReq, req) => {
+ const origin = devProxyForwardedOrigin(req, target);
+ if (origin) proxyReq.setHeader('origin', origin);
+ };
+ return (proxy) => {
+ proxy.on('proxyReq', stamp);
+ proxy.on('proxyReqWs', stamp);
+ };
+}
+
// 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.
@@ -117,6 +132,7 @@ function eidoverseDevProxies(target) {
changeOrigin: true,
ws: true,
secure: false,
+ configure: forwardSameOrigin(target),
},
};
for (const exact of EIDOVERSE_ROOT_EXACT_PATHS) {
@@ -125,6 +141,7 @@ function eidoverseDevProxies(target) {
changeOrigin: true,
ws: exact === '/ws',
secure: false,
+ configure: forwardSameOrigin(target),
};
}
for (const prefix of EIDOVERSE_ROOT_PREFIX_PATHS) {
@@ -132,6 +149,7 @@ function eidoverseDevProxies(target) {
target,
changeOrigin: true,
secure: false,
+ configure: forwardSameOrigin(target),
bypass(req) {
if (prefix !== '/node_modules/' && prefix !== '/shared/') return undefined;
const referer = String(req.headers.referer || '');
@@ -201,7 +219,10 @@ export default defineConfig(({ command, mode }) => {
target: API_TARGET,
changeOrigin: true,
secure: false,
- configure: markProxyClientAddress
+ configure(proxy) {
+ markProxyClientAddress(proxy);
+ forwardSameOrigin(API_TARGET)(proxy);
+ }
},
// Every `/data/**` asset mount at once, instead of a hand-maintained
// list that silently fell behind the server's (see docs/PORTS.md:
@@ -215,7 +236,8 @@ export default defineConfig(({ command, mode }) => {
'^/data/': {
target: API_TARGET,
changeOrigin: true,
- secure: false
+ secure: false,
+ configure: forwardSameOrigin(API_TARGET)
},
// The socket carries host-control events (shell, iTerm2, app updates)
// gated on a local caller, so its handshake needs the same marker —
@@ -225,7 +247,10 @@ export default defineConfig(({ command, mode }) => {
changeOrigin: true,
ws: true,
secure: false,
- configure: markProxyClientAddress
+ configure(proxy) {
+ markProxyClientAddress(proxy);
+ forwardSameOrigin(API_TARGET)(proxy);
+ }
},
...eidoverseDevProxies(API_TARGET),
}
diff --git a/docs/COMPANION_APP_API.md b/docs/COMPANION_APP_API.md
index 565d970e3e..8dd124e3a8 100644
--- a/docs/COMPANION_APP_API.md
+++ b/docs/COMPANION_APP_API.md
@@ -77,10 +77,17 @@ build server-side.
is single-user, so the username half is ignored — only the password is verified.
Store the password **per instance in the iOS Keychain**.
-**CSRF note.** When auth is on, PortOS 403s cross-origin requests that carry an
-`Origin` header (the browser-session CSRF guard). A native `URLSession` sends **no**
-`Origin` header, so it passes the guard cleanly — no special handling needed. Do
-not set an `Origin` header manually.
+**CSRF note.** In both auth modes — with or without a password — PortOS 403s a
+browser request whose `Origin` does not match its `Host` (`CROSS_ORIGIN_BLOCKED`,
+including the opaque `Origin: null`), and a browser request (one carrying
+`Origin` or `Sec-Fetch-Site`) whose `Host` is not an IP literal, a single-label
+name, a `.localhost`/`.ts.net`/`.local`/`.home.arpa`/`.internal`/`.lan` name, the
+machine's own hostname, or a name listed in the comma-separated
+`PORTOS_ALLOWED_HOSTS` environment variable (`HOST_NOT_ALLOWED`; a leading dot
+admits every subdomain). This stops any web page from relaying requests onto
+loopback through the user's own browser, and DNS rebinding. A native
+`URLSession` sends **neither** header, so it passes the guard cleanly — no special
+handling needed. Do not set an `Origin` header manually.
A dedicated per-device API-key surface (a companion group in `apiRegistry.js` /
long-lived device token) is a **possible future enhancement**, not built here —
diff --git a/lib/portosAuthCore.js b/lib/portosAuthCore.js
index 8c59e18a74..45ce1be2f0 100644
--- a/lib/portosAuthCore.js
+++ b/lib/portosAuthCore.js
@@ -14,6 +14,8 @@
* credentials/sessions across every install, so treat them as a migration.
*/
import { createHash, timingSafeEqual, scrypt } from 'node:crypto';
+import { isIP } from 'node:net';
+import { hostname as osHostname } from 'node:os';
import { promisify } from 'node:util';
const scryptAsync = promisify(scrypt);
@@ -185,7 +187,8 @@ export const extractBasicPassword = (req) => {
return colonIdx === -1 ? decoded : decoded.slice(colonIdx + 1);
};
-// Reject cross-origin requests when auth is on. PortOS reflects `Origin` with
+// Reject cross-origin browser requests in both auth modes (see
+// browserRequestRefusal below). PortOS reflects `Origin` with
// `Access-Control-Allow-Credentials: true` so the UI works from any tailnet
// hostname / IP — but combined with the session cookie that becomes a CSRF
// surface: a malicious page on another tailnet host can fetch PortOS APIs with
@@ -210,7 +213,11 @@ const isLoopback = (hostname) => LOOPBACK_HOSTS.has(hostname.toLowerCase());
export const isCrossOrigin = (req) => {
const origin = req.headers?.origin;
- if (!origin || origin === 'null') return false;
+ if (!origin) return false;
+ // An opaque origin (sandboxed iframe, data: URL, cross-origin redirect) is
+ // never this install's own UI — a hidden sandboxed form would otherwise slip
+ // through as "no Origin".
+ if (origin === 'null') return true;
const host = req.headers?.host;
if (!host) return false;
// URL parses scheme://authority — we only compare the authority. A malformed
@@ -229,6 +236,64 @@ export const isCrossOrigin = (req) => {
return true;
};
+// DNS rebinding defeats the Origin-vs-Host comparison above: a hostname the
+// attacker controls resolves to this machine, so the page's Origin and the
+// request's Host match. A browser request therefore must also address PortOS
+// by a name no public site can rebind — an IP literal, a single-label name
+// (`localhost`, a MagicDNS short name), a private-use suffix, the machine's
+// own hostname, its configured PORTOS_HOST, or an operator-listed name in
+// PORTOS_ALLOWED_HOSTS (comma-separated; a leading dot allows every subdomain).
+const PRIVATE_HOST_SUFFIXES = ['.localhost', '.ts.net', '.local', '.home.arpa', '.internal', '.lan'];
+
+const normalizeHostname = (value) => stripPort(String(value).trim().toLowerCase()).replace(/\.$/, '');
+
+const configuredHosts = (env) => [env?.PORTOS_HOST, env?.PORTOS_ALLOWED_HOSTS].filter(Boolean).join(',')
+ .split(',').map((entry) => entry.trim())
+ .map((entry) => (entry.startsWith('.') ? `.${normalizeHostname(entry.slice(1))}` : normalizeHostname(entry)))
+ .filter((entry) => entry && entry !== '.');
+
+const MACHINE_HOSTNAME = osHostname();
+
+export const isAllowedHost = (hostHeader, { env = process.env, machineHostname = MACHINE_HOSTNAME } = {}) => {
+ if (typeof hostHeader !== 'string' || !hostHeader.trim()) return false;
+ const host = normalizeHostname(hostHeader);
+ if (!host) return false;
+ if (isIP(host) || (host.startsWith('[') && isIP(host.slice(1, -1)) === 6)) return true;
+ if (!host.includes('.')) return true;
+ if (PRIVATE_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) return true;
+ if (typeof machineHostname === 'string' && host === machineHostname.toLowerCase().replace(/\.$/, '')) return true;
+ return configuredHosts(env).some((entry) => (entry.startsWith('.')
+ ? host.endsWith(entry) || host === entry.slice(1)
+ : host === entry));
+};
+
+// Browsers stamp every request with `Sec-Fetch-Site` and every cross-origin or
+// state-changing one with `Origin`; curl, agents, peers, and native companion
+// apps send neither, so they never reach the checks below.
+const isBrowserRequest = (req) => Boolean(req.headers?.origin || req.headers?.['sec-fetch-site']);
+
+// The browser-relay guard. Applies whether or not the optional password is
+// set: without it, any page the user opens could drive loopback APIs (a
+// hidden form POST needs no preflight). Returns the refusal code, or null
+// when the request may proceed.
+export const browserRequestRefusal = (req, options) => {
+ if (!isBrowserRequest(req)) return null;
+ if (isCrossOrigin(req)) return 'CROSS_ORIGIN_BLOCKED';
+ if (!isAllowedHost(req.headers?.host, options)) return 'HOST_NOT_ALLOWED';
+ return null;
+};
+
+// The Vite dev proxy (:5554 → :5555, changeOrigin) rewrites Host to the API
+// target but forwards the browser's Origin, so a tailnet browser on
+// `https://<name>.ts.net:5554` would look cross-origin to the API. The proxy
+// vouches for a request that is same-origin to ITSELF by re-stamping Origin as
+// the target's; a foreign Origin is forwarded untouched and the API refuses it.
+// Returns the Origin to forward, or null to leave the header alone.
+export const devProxyForwardedOrigin = (req, target) => {
+ if (!req.headers?.origin || isCrossOrigin(req)) return null;
+ return new URL(target).origin;
+};
+
// Sliding-window login throttle. Auth is normally tailnet-only so this is
// defense in depth against a sidecar burning CPU on scrypt verifications.
// In-memory only (a restart resets the counters — acceptable for a
diff --git a/lib/sidecarAuthGate.js b/lib/sidecarAuthGate.js
index 2a19064b0f..feb44e1ffa 100644
--- a/lib/sidecarAuthGate.js
+++ b/lib/sidecarAuthGate.js
@@ -33,11 +33,11 @@ import { createHmac, timingSafeEqual } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import {
+ browserRequestRefusal,
createLoginThrottle,
extractBasicPassword,
extractTokens,
hashToken,
- isCrossOrigin,
parseCookie,
verifyPasswordAgainst,
} from './portosAuthCore.js';
@@ -172,17 +172,17 @@ export const createSidecarAuthGate = ({
return parts.join('; ');
};
- // Express middleware. No-ops entirely when the install has no password —
- // that's the documented PortOS trust model (single user on a private
- // tailnet), so an unprotected install keeps working exactly as before.
+ // Express middleware. The browser-relay guard (cross-origin + DNS-rebinding
+ // Host check) runs FIRST and in both modes: without a password any web page
+ // the user opens could otherwise drive this sidecar through the user's own
+ // browser, and the public logout endpoint still mutates state. Past that, an
+ // install with no password passes everything through.
const gate = async (req, res, next) => {
- if (!(await isEnabled())) return next();
- // The CSRF guard runs FIRST: the logout endpoint is public but still
- // mutates state, so a same-tailnet attacker could otherwise force actions
- // cross-origin through the public-path bypass.
- if (isCrossOrigin(req)) {
- return res.status(403).json({ error: 'Cross-origin request rejected', code: 'CROSS_ORIGIN_BLOCKED' });
+ const refusal = browserRequestRefusal(req);
+ if (refusal) {
+ return res.status(403).json({ error: 'Browser request rejected', code: refusal });
}
+ if (!(await isEnabled())) return next();
if (alwaysPublic.has(req.path)) return next();
if (await isAuthenticated(req)) return next();
return res.status(401).json({ error: 'Authentication required', code: 'AUTH_REQUIRED' });
diff --git a/lib/sidecarAuthGate.test.js b/lib/sidecarAuthGate.test.js
index bfbe21ba20..5f253e8230 100644
--- a/lib/sidecarAuthGate.test.js
+++ b/lib/sidecarAuthGate.test.js
@@ -69,6 +69,22 @@ describe('createSidecarAuthGate', () => {
expect((await run(gate, req('/api/stop/portos-server'))).nexted).toBe(true);
});
+ it('still refuses a cross-site or rebound browser request (#8707)', async () => {
+ const { gate } = makeGate();
+ for (const [headers, code] of [
+ [{ origin: 'https://attacker.example', host: '127.0.0.1:5560' }, 'CROSS_ORIGIN_BLOCKED'],
+ [{ origin: 'http://rebind.attacker.example:5560', host: 'rebind.attacker.example:5560' }, 'HOST_NOT_ALLOWED'],
+ ]) {
+ const { res, nexted } = await run(gate, req('/api/restart/portos-server', headers));
+ expect(nexted).toBe(false);
+ expect(res.statusCode).toBe(403);
+ expect(res.body.code).toBe(code);
+ }
+ expect((await run(gate, req('/api/restart/portos-server', {
+ origin: 'http://localhost:5555', host: 'localhost:5560',
+ }))).nexted).toBe(true);
+ });
+
it('reports enabled:false + authenticated:true from the status handler', async () => {
const { handleStatus } = makeGate();
const res = makeRes();
diff --git a/server/index.js b/server/index.js
index 067e302dae..c9b8340189 100644
--- a/server/index.js
+++ b/server/index.js
@@ -116,7 +116,7 @@ import reviewRoutes from './routes/review.js';
import githubRoutes from './routes/github.js';
import settingsRoutes from './routes/settings.js';
import authRoutes from './routes/auth.js';
-import { authGate, socketAuthGate } from './services/authGate.js';
+import { allowSocketRequest, authGate, socketAuthGate } from './services/authGate.js';
import telegramRoutes from './routes/telegram.js';
import updateRoutes from './routes/update.js';
import loopsRoutes from './routes/loops.js';
@@ -203,10 +203,16 @@ setHttpsEnabledAtBoot(httpsEnabled);
// Socket.IO with relative path support for Tailscale
const io = new Server(httpServer, {
+ // CORS headers are reflected only for handshakes allowRequest admits: the
+ // same browser-relay guard as the HTTP gate refuses a foreign Origin or a
+ // rebindable Host on both the polling and websocket transports, in both
+ // auth modes (a password-free install would otherwise take shell:start from
+ // any web page). Origin-less native/peer clients pass through.
cors: {
- origin: true, // Allow any origin (local network only)
+ origin: true,
credentials: true
},
+ allowRequest: allowSocketRequest,
path: '/socket.io'
});
diff --git a/server/routes/commands.test.js b/server/routes/commands.test.js
index e27517c103..22163a32ad 100644
--- a/server/routes/commands.test.js
+++ b/server/routes/commands.test.js
@@ -86,6 +86,9 @@ function createApp(io = { emit: vi.fn() }, { remoteAddress, withAuthGate = true
const app = express();
app.set('io', io);
app.use(express.json());
+ // Production parses form bodies globally (server/index.js), which is what
+ // makes a cross-site <form method=POST> a no-preflight attack path.
+ app.use(express.urlencoded({ extended: true }));
if (remoteAddress !== undefined) app.use((req, _res, next) => {
// Model the server's socket observation, never an HTTP header.
Object.defineProperty(req.socket, 'remoteAddress', { value: remoteAddress });
@@ -203,6 +206,35 @@ describe('commands routes', () => {
},
);
+ // #8707: the user's own browser relays a hidden form from any web page onto
+ // loopback, where password-free host control trusts the socket peer.
+ it.each([false, true])('refuses a cross-site form POST from the loopback browser (auth enabled: %s)', async enabled => {
+ isAuthEnabled.mockResolvedValue(enabled);
+ spawnMock.mockReturnValue(createChildProcess());
+ const { app } = createApp(undefined, { remoteAddress: '127.0.0.1' });
+ const response = await request(app).post('/api/commands/execute')
+ .set('Content-Type', 'application/x-www-form-urlencoded')
+ .set('Origin', 'https://attacker.example')
+ .set('Sec-Fetch-Site', 'cross-site')
+ .send('command=npx+--yes+example-package');
+ expect(response.status).toBe(403);
+ expect(response.body.code).toBe('CROSS_ORIGIN_BLOCKED');
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it('keeps a same-origin browser POST working on a password-free install', async () => {
+ spawnMock.mockReturnValue(createChildProcess());
+ const { app } = createApp(undefined, { remoteAddress: '127.0.0.1' });
+ const probe = await request(app).get('/api/commands/allowed');
+ expect(probe.status).toBe(200);
+ const started = await request(app).post('/api/commands/execute')
+ .set('Origin', 'http://localhost:5554')
+ .set('Sec-Fetch-Site', 'same-origin')
+ .send({ command: 'pwd' });
+ expect(started.status).toBe(202);
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ });
+
it('keeps local UI command control through the dev proxy', async () => {
const child = createChildProcess();
spawnMock.mockReturnValue(child);
diff --git a/server/services/authGate.js b/server/services/authGate.js
index a2fd056c03..84e2a1838a 100644
--- a/server/services/authGate.js
+++ b/server/services/authGate.js
@@ -3,7 +3,7 @@ import { isIP } from 'node:net';
import { isAuthEnabled, verifyPassword, verifyRequestSession } from './auth.js';
// Shared with sidecar processes (lib/sidecarAuthGate.js) so the Autofixer UI
// on :5560 applies byte-identical credential extraction and CSRF rules.
-import { DEV_PROXY_CLIENT_ADDRESS_HEADER, extractBasicPassword, isCrossOrigin } from '../../lib/portosAuthCore.js';
+import { browserRequestRefusal, DEV_PROXY_CLIENT_ADDRESS_HEADER, extractBasicPassword } from '../../lib/portosAuthCore.js';
import { getSettings, settingsEvents } from './settings.js';
import { isRegistryPublic } from '../lib/apiRegistry.js';
import {
@@ -102,6 +102,13 @@ const refusePeerScope = (req, res, path, peer) => {
export const __testing = { verifyBasicPassword };
+const BROWSER_REFUSAL_MESSAGES = {
+ CROSS_ORIGIN_BLOCKED: 'Cross-origin request rejected',
+ HOST_NOT_ALLOWED: 'Browser requests must address PortOS by an IP, a local or tailnet name, or a host listed in PORTOS_ALLOWED_HOSTS',
+};
+
+const browserRefusalError = (code) => new ServerError(BROWSER_REFUSAL_MESSAGES[code], { status: 403, code });
+
const isPublicPath = (path) => {
if (isAlwaysPublicApiPath(path)) return true;
// /api/* and /data/* are always gated. /sdapi/* (and any future non-/api
@@ -116,9 +123,10 @@ const isPublicPath = (path) => {
return true;
};
-// Express middleware. Bypasses everything when auth is off. When it's on,
-// allows the small public set above; gates the rest behind a valid token in
-// the cookie or Authorization: Bearer header.
+// Express middleware. The browser-relay guard (cross-origin + DNS-rebinding
+// Host check) runs in both modes. With auth off everything else passes; with
+// it on, allows the small public set above and gates the rest behind a valid
+// token in the cookie or Authorization: Bearer header.
export const authGate = async (req, res, next) => {
const enabled = await isAuthEnabled();
// Downstream peer-provider routes need to distinguish a verified peer Basic
@@ -133,6 +141,15 @@ export const authGate = async (req, res, next) => {
req.managedVisitorAuth = await authenticateManagedVisitorRequest(req);
return next();
}
+ // Runs FIRST, before the auth-off bypass and isPublicPath: without a password
+ // any web page the user opens could otherwise relay a hidden form POST onto
+ // loopback (where requireHostControl trusts the socket peer), and public
+ // endpoints like /api/auth/logout still mutate state.
+ const refusal = browserRequestRefusal(req);
+ if (refusal) {
+ sendErrorResponse(res, browserRefusalError(refusal));
+ return;
+ }
if (!enabled) {
// The pair token is independent of the instance password, so a paired peer
// stays identified after the password is removed: peer-provider routes
@@ -144,16 +161,6 @@ export const authGate = async (req, res, next) => {
if (peer) req.portosAuthContext = { enabled: false, authenticated: true, method: 'peer', peerId: peer.id };
return next();
}
- // CSRF guard runs FIRST, before isPublicPath — public endpoints like
- // /api/auth/logout still mutate state (clear the cookie + revoke the
- // session), so a same-tailnet attacker could force-logout a user
- // cross-origin if the guard sat behind the public-path bypass.
- if (isCrossOrigin(req)) {
- sendErrorResponse(res, new ServerError('Cross-origin request rejected', {
- status: 403, code: 'CROSS_ORIGIN_BLOCKED',
- }));
- return;
- }
// Express mounts match case-insensitively. Use the same casing for every
// authorization check, including public exceptions, without rewriting the
// request URL: downstream record IDs and asset filenames may be case-sensitive.
@@ -259,7 +266,7 @@ export const socketHasHostControl = (socket) => hasHostControl({ enabled: false
// Socket.IO middleware. Run after a successful HTTP-side handshake — same
// `req.headers.cookie` is available on `socket.handshake.headers`. When auth
// is off, every connection is allowed; when on, the handshake must carry a
-// valid cookie/header.
+// valid cookie/header. The browser-relay guard applies in both modes.
//
// NOTE: there is intentionally NO `isRegistryPublic` check here. The public
// API surface (apiRegistry) is HTTP-only — external callers hit REST endpoints,
@@ -275,17 +282,26 @@ const markAuthMethod = (socket, method) => {
socket.data.portosAuthMethod = method;
};
+// engine.io `allowRequest` for the Socket.IO server: refuses the transport
+// handshake itself (polling and websocket) for a foreign or rebindable browser
+// request, before socketAuthGate ever runs.
+export const allowSocketRequest = (req, callback) => callback(null, browserRequestRefusal(req) === null);
+
export const socketAuthGate = async (socket, next) => {
if (!socket.data) socket.data = {};
socket.data.portosLocalConnection = isLocalConnection(socket.handshake?.address, socket.handshake?.headers);
- const enabled = await isAuthEnabled();
- if (!enabled) return next();
const fakeReq = { headers: socket.handshake?.headers || {} };
- if (isCrossOrigin(fakeReq)) {
- const err = new Error('Cross-origin request rejected');
- err.data = { code: 'CROSS_ORIGIN_BLOCKED' };
+ // Before the auth-off bypass: a foreign page must not drive shell:start /
+ // iterm:input on a password-free install. server/index.js also refuses the
+ // engine.io handshake itself with the same predicate.
+ const refusal = browserRequestRefusal(fakeReq);
+ if (refusal) {
+ const err = new Error(BROWSER_REFUSAL_MESSAGES[refusal]);
+ err.data = { code: refusal };
return next(err);
}
+ const enabled = await isAuthEnabled();
+ if (!enabled) return next();
if (await verifyRequestSession(fakeReq)) {
markAuthMethod(socket, 'session');
return next();
diff --git a/server/services/authGate.test.js b/server/services/authGate.test.js
index eba7611f1b..cbf009d390 100644
--- a/server/services/authGate.test.js
+++ b/server/services/authGate.test.js
@@ -832,6 +832,92 @@ describe('paired peer credential (#8356)', () => {
});
});
+// #8707: without a password, the browser-relay guard is the only thing between
+// an arbitrary web page and the loopback-trusted host-control routes.
+describe('browser-relay guard in both auth modes', () => {
+ const enableAuth = async () => (await import('./auth.js')).setPassword({ newPassword: 'correct-horse' });
+ const gateWith = async (headers) => {
+ const { authGate } = await import('./authGate.js');
+ return runGate(authGate, { path: '/api/cos', method: 'POST', headers });
+ };
+
+ it.each([false, true])('rejects a foreign Origin and an opaque one (auth enabled: %s)', async (enabled) => {
+ if (enabled) await enableAuth();
+ for (const origin of ['https://attacker.example', 'null']) {
+ const result = await gateWith({ host: '127.0.0.1:5555', origin, 'sec-fetch-site': 'cross-site' });
+ expect(result.called).toBe(false);
+ expect(result.res.statusCode).toBe(403);
+ expect(result.res.body.code).toBe('CROSS_ORIGIN_BLOCKED');
+ }
+ });
+
+ it.each([false, true])('rejects a DNS-rebinding Host whose Origin matches (auth enabled: %s)', async (enabled) => {
+ if (enabled) await enableAuth();
+ for (const headers of [
+ { host: 'rebind.attacker.example:5555', origin: 'http://rebind.attacker.example:5555' },
+ // A same-origin GET carries no Origin, only Sec-Fetch-Site.
+ { host: 'rebind.attacker.example:5555', 'sec-fetch-site': 'same-origin' },
+ ]) {
+ const result = await gateWith(headers);
+ expect(result.called).toBe(false);
+ expect(result.res.statusCode).toBe(403);
+ expect(result.res.body.code).toBe('HOST_NOT_ALLOWED');
+ }
+ });
+
+ it('accepts same-origin browser requests on loopback, tailnet, LAN, and short names', async () => {
+ for (const host of ['localhost:5555', '127.0.0.1:5555', '[::1]:5555', 'portos.tailnet.ts.net', '192.0.2.10:5555', 'portos-box:5555', 'portos-box.local:5555']) {
+ const result = await gateWith({ host, origin: `http://${host}`, 'sec-fetch-site': 'same-origin' });
+ expect(result.called, host).toBe(true);
+ }
+ });
+
+ it('leaves Origin-less native, agent, and peer callers alone', async () => {
+ const result = await gateWith({ host: 'custom-name.example:5555', authorization: 'Bearer example-agent-token' });
+ expect(result.called).toBe(true);
+ });
+
+ it('admits an operator-listed custom hostname through PORTOS_ALLOWED_HOSTS', async () => {
+ const { isAllowedHost } = await import('../../lib/portosAuthCore.js');
+ const env = { PORTOS_ALLOWED_HOSTS: 'portos.example.com, .home.example.net' };
+ expect(isAllowedHost('portos.example.com:5555', { env, machineHostname: 'other' })).toBe(true);
+ expect(isAllowedHost('box.home.example.net', { env, machineHostname: 'other' })).toBe(true);
+ expect(isAllowedHost('evil-portos.example.com', { env, machineHostname: 'other' })).toBe(false);
+ expect(isAllowedHost('portos.example.com', { env: {}, machineHostname: 'portos.example.com' })).toBe(true);
+ expect(isAllowedHost('portos.example.com', { env: {}, machineHostname: 'other' })).toBe(false);
+ });
+
+ it('lets the Vite dev proxy vouch only for a request same-origin to itself', async () => {
+ const { devProxyForwardedOrigin } = await import('../../lib/portosAuthCore.js');
+ const target = 'http://localhost:5555';
+ // What the API sees after changeOrigin rewrites Host to the target.
+ const proxied = (browserHeaders) => {
+ const origin = devProxyForwardedOrigin({ headers: browserHeaders }, target) ?? browserHeaders.origin;
+ return gateWith({ host: 'localhost:5555', origin, 'sec-fetch-site': browserHeaders['sec-fetch-site'] });
+ };
+ const tailnet = await proxied({ host: 'portos.tailnet.ts.net:5554', origin: 'https://portos.tailnet.ts.net:5554', 'sec-fetch-site': 'same-origin' });
+ expect(tailnet.called).toBe(true);
+ const foreign = await proxied({ host: 'portos.tailnet.ts.net:5554', origin: 'https://attacker.example', 'sec-fetch-site': 'cross-site' });
+ expect(foreign.called).toBe(false);
+ expect(foreign.res.body.code).toBe('CROSS_ORIGIN_BLOCKED');
+ });
+
+ it('refuses a foreign Socket.IO handshake at the transport and the namespace gate', async () => {
+ const { allowSocketRequest, socketAuthGate } = await import('./authGate.js');
+ const foreign = { host: '127.0.0.1:5555', origin: 'https://attacker.example' };
+ const admitted = (headers) => new Promise((resolve) => allowSocketRequest({ headers }, (_e, ok) => resolve(ok)));
+ expect(await admitted(foreign)).toBe(false);
+ expect(await admitted({ host: 'rebind.attacker.example:5555', origin: 'http://rebind.attacker.example:5555' })).toBe(false);
+ // Same-origin UI, the Vite dev proxy's loopback pairing, and Origin-less peers.
+ expect(await admitted({ host: 'portos.tailnet.ts.net', origin: 'https://portos.tailnet.ts.net' })).toBe(true);
+ expect(await admitted({ host: 'localhost:5555', origin: 'http://localhost:5554' })).toBe(true);
+ expect(await admitted({ host: 'portos.tailnet.ts.net' })).toBe(true);
+ const err = await new Promise((resolve) => socketAuthGate({ handshake: { headers: foreign } }, resolve));
+ expect(err).toBeInstanceOf(Error);
+ expect(err.data).toEqual({ code: 'CROSS_ORIGIN_BLOCKED' });
+ });
+});
+
describe('socketAuthGate middleware', () => {
it('is a no-op when auth is disabled', async () => {
const { socketAuthGate } = await import('./authGate.js');