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(auth): refuse host control to Tailcat ingress callers that arrive over the loopback hop

Adam Eivy53cde6898940
diff --git a/docs/features/tailcat-peers.md b/docs/features/tailcat-peers.md
index 542282a802..5c27fce171 100644
--- a/docs/features/tailcat-peers.md
+++ b/docs/features/tailcat-peers.md
@@ -22,9 +22,15 @@ No `tailcat serve all`, no exit-node mode, and no Tailscale daemon are used.
Managed serve exposes the **remote** PortOS API on loopback `:5565`, with the same
HTTP/HTTPS mode and optional instance authentication as the main API. The listener
-marks requests as remote before dispatch, so Agent Context MCP and its manifest
-reject them even though Tailcat connects from localhost. Headers cannot claim local
-authority. Local MCP clients on the main API or HTTP mirror continue to work.
+marks requests as remote before dispatch — HTTP requests and the Socket.IO
+handshake alike — so a Tailcat caller is never a *local connection*: on a
+password-free install the host-control routes and socket events (command
+execution, shells, CoS spawns, setting the first password) refuse it with
+`HOST_CONTROL_FORBIDDEN`, and Agent Context MCP and its manifest reject it. Set an
+instance password and sign in to use host control through Tailcat. Headers cannot
+claim local authority. Local MCP clients on the main API or HTTP mirror continue to
+work. Starting managed serve or a forward is itself a host-control action (it
+installs the `tailcat` binary and starts relay processes).
A Tailcat capability still grants normal remote PortOS API access. Share it only
with trusted peers; this is not a restricted API for an untrusted sandbox.
diff --git a/server/lib/README.md b/server/lib/README.md
index 7a5523777a..351516ba59 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -799,7 +799,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `privateSecuritySandbox.js` | Loopback-only local-provider gate and macOS Seatbelt launch with isolated CLI home and scratch workspace. |
-| `requestOrigin.js` | `remoteRequestHandler` and `isRemoteRequest` preserve remote transport identity across a localhost hop without trusting client headers. |
+| `requestOrigin.js` | `remoteRequestHandler`, `markRemoteServer` (covers the Socket.IO handshake and upgrade a handler never sees) and `isRemoteRequest` preserve remote transport identity across a localhost hop without trusting client headers; the host-control gates refuse a marked request as non-local. |
| `cosFederationPolicy.js` | `isMachineLocalCosTask` excludes private assessments and explicitly machine-local tasks and agent archives from federation. |
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index f53ac795f1..4279aaff3f 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -321,6 +321,13 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
// Instances: runs the Tailscale CLI and writes a TLS certificate and private
// key into the install's cert directory.
'POST /api/instances/provision-cert',
+ // Tailcat: installs the binary (brew / go install) and starts the relay
+ // processes; serve opens the remote ingress and reveals its bearer address.
+ // GET status and the DELETEs (they stop a relay) stay open.
+ 'POST /api/instances/peers/tailcat',
+ 'POST /api/instances/peers/tailcat/forwards/:id/retry',
+ 'POST /api/instances/peers/tailcat/serve',
+ 'POST /api/instances/peers/tailcat/serve/retry',
// Apps: create/edit choose the repo path and the start/build commands; the
// lifecycle and launch routes run them under PM2 or the native launcher.
diff --git a/server/lib/requestOrigin.js b/server/lib/requestOrigin.js
index fa9f7731ff..5f162529fd 100644
--- a/server/lib/requestOrigin.js
+++ b/server/lib/requestOrigin.js
@@ -9,4 +9,16 @@ export function remoteRequestHandler(handler) {
};
}
+// Socket.IO's `attach` intercepts its own handshake and upgrade requests before
+// the server's request handler runs, so a handler-level mark never sees them.
+// Prepending here (after `io.attach`) marks every request and upgrade the
+// listener accepts; the engine.io socket keeps that handshake request as
+// `socket.request`, which is what the socket auth gate checks.
+export function markRemoteServer(server) {
+ const mark = (req) => { remoteRequests.add(req); };
+ server.prependListener('request', mark);
+ server.prependListener('upgrade', mark);
+ return server;
+}
+
export const isRemoteRequest = (req) => remoteRequests.has(req);
diff --git a/server/routes/auth.js b/server/routes/auth.js
index 8b1891c9d0..5cf2f87eea 100644
--- a/server/routes/auth.js
+++ b/server/routes/auth.js
@@ -27,6 +27,7 @@ import { getAgentKeyStatus, rotateAgentKey, setAgentKeyEnabled } from '../servic
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { logSecurityEvent } from '../lib/securityAuditLog.js';
+import { isRemoteRequest } from '../lib/requestOrigin.js';
const router = Router();
@@ -49,7 +50,9 @@ const isSecure = (req) => !!req.secure;
// Source address for the audit trail. `req.ip` is the socket peer (no reverse
// proxy in front of PortOS), so a forged header cannot name another machine.
-const sourceOf = (req) => req.ip || req.socket?.remoteAddress || 'unknown';
+// A Tailcat ingress request reports the loopback hop as its address; keep its
+// throttle bucket and audit lines apart from genuine local logins.
+const sourceOf = (req) => (isRemoteRequest(req) ? 'tailcat-ingress' : (req.ip || req.socket?.remoteAddress || 'unknown'));
// The session cookie name is port-scoped from the browser-facing `Host` (see
// sessionCookieNameFor in lib/portosAuthCore.js) — e.g. `portos_auth_15555`
diff --git a/server/services/authGate.js b/server/services/authGate.js
index 6a4df10bcf..06c1ae4ad7 100644
--- a/server/services/authGate.js
+++ b/server/services/authGate.js
@@ -14,6 +14,7 @@ import {
} from '../lib/apiAccessPolicy.js';
import { sendErrorResponse, ServerError } from '../lib/errorHandler.js';
import { logSecurityEvent } from '../lib/securityAuditLog.js';
+import { isRemoteRequest } from '../lib/requestOrigin.js';
import {
changedHostControlSettingsPaths, changedVoiceConfigHostControlPaths, hostControlBodyKeys,
hostControlSettingsPathsIn, isHostControlRoute, voiceConfigHostControlPathsIn,
@@ -239,10 +240,13 @@ const hasHostControl = (auth, localConnection) =>
export const HOST_CONTROL_FORBIDDEN_MESSAGE = 'Host control requires an operator session, or a local connection when no password is set. Set an instance password to use it remotely.';
+// A request the Tailcat ingress accepted arrives from a loopback socket, so
+// the address alone would read as local; the listener's remote mark wins.
+const requestIsLocalConnection = (req) => !isRemoteRequest(req)
+ && isLocalConnection(req.socket?.remoteAddress, req.headers);
+
// Server-derived HTTP authority; never read caller-provided body fields.
-export const requestHasHostControl = (req) => hasHostControl(
- req.portosAuthContext, isLocalConnection(req.socket?.remoteAddress, req.headers),
-);
+export const requestHasHostControl = (req) => hasHostControl(req.portosAuthContext, requestIsLocalConnection(req));
// Re-check at tool dispatch, after any STT/LLM wait. A handshake/session that
// was valid when a turn started is not a durable grant to execute later.
@@ -297,7 +301,7 @@ export const hostControlBodyGate = async (req, res, next) => {
const settingsNamed = hostControlSettingsPathsIn(req.method, req.path, req.body);
const voiceNamed = voiceConfigHostControlPathsIn(req.method, req.path, req.body);
if ((settingsNamed.length === 0 && voiceNamed.length === 0)
- || hasHostControl(req.portosAuthContext, isLocalConnection(req.socket?.remoteAddress, req.headers))) return next();
+ || hasHostControl(req.portosAuthContext, requestIsLocalConnection(req))) return next();
if (settingsNamed.length > 0
&& changedHostControlSettingsPaths(settingsNamed, req.body, await getSettings(), req.method, req.path).length > 0) {
return requireHostControl(req, res, next);
@@ -342,7 +346,10 @@ export const allowSocketRequest = (req, callback) => callback(null, browserReque
export const socketAuthGate = async (socket, next) => {
if (!socket.data) socket.data = {};
- socket.data.portosLocalConnection = isLocalConnection(socket.handshake?.address, socket.handshake?.headers);
+ // `socket.request` is the engine.io handshake request; the Tailcat ingress
+ // marks it remote even though the handshake address is loopback.
+ socket.data.portosLocalConnection = !isRemoteRequest(socket.request)
+ && isLocalConnection(socket.handshake?.address, socket.handshake?.headers);
const fakeReq = { headers: socket.handshake?.headers || {} };
// 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
diff --git a/server/services/authGate.test.js b/server/services/authGate.test.js
index f9a13a3019..00e427f922 100644
--- a/server/services/authGate.test.js
+++ b/server/services/authGate.test.js
@@ -792,6 +792,42 @@ describe('host-control authority', () => {
vi.useRealTimers();
});
+ // The Tailcat ingress accepts remote peers on a loopback listener, so the
+ // socket address reads as local. Only the listener's mark separates them;
+ // it must refuse password-free host control for HTTP and for the Socket.IO
+ // handshake (which engine.io intercepts before the app handler).
+ it('refuses password-free host control to requests the Tailcat ingress marked remote', async () => {
+ const { remoteRequestHandler, markRemoteServer } = await import('../lib/requestOrigin.js');
+ const { hostControlBodyGate, requestHasHostControl, socketAuthGate, socketHasHostControl } = await import('./authGate.js');
+ const local = { headers: {}, socket: { remoteAddress: '127.0.0.1' }, portosAuthContext: { enabled: false } };
+ const viaIngress = { headers: {}, socket: { remoteAddress: '127.0.0.1' }, portosAuthContext: { enabled: false } };
+ remoteRequestHandler(() => {})(viaIngress, {});
+ expect(requestHasHostControl(local)).toBe(true);
+ expect(requestHasHostControl(viaIngress)).toBe(false);
+
+ const policyWrite = { ...viaIngress, method: 'PUT', path: '/api/cos/config', body: { autonomyMode: 'execute' } };
+ remoteRequestHandler(() => {})(policyWrite, {});
+ const bodyGate = await runGate(hostControlBodyGate, policyWrite);
+ expect(bodyGate.called).toBe(false);
+ expect(bodyGate.res.statusCode).toBe(403);
+ expect(bodyGate.res.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+
+ const { EventEmitter } = await import('node:events');
+ const server = markRemoteServer(new EventEmitter());
+ const handshake = async (request) => {
+ const socket = { request, handshake: { address: '127.0.0.1', headers: {} } };
+ await new Promise((resolve) => socketAuthGate(socket, resolve));
+ return socketHasHostControl(socket);
+ };
+ const upgradeRequest = {};
+ server.emit('upgrade', upgradeRequest);
+ const pollingRequest = {};
+ server.emit('request', pollingRequest);
+ expect(await handshake({})).toBe(true);
+ expect(await handshake(upgradeRequest)).toBe(false);
+ expect(await handshake(pollingRequest)).toBe(false);
+ });
+
it('keeps password-free socket host control limited to connected local sockets', async () => {
const { socketHasCurrentHostControl } = await import('./authGate.js');
expect(await socketHasCurrentHostControl({ data: { portosLocalConnection: true } })).toBe(true);
diff --git a/server/services/tailcatIngress.js b/server/services/tailcatIngress.js
index 8ca55a2018..9a3d71558d 100644
--- a/server/services/tailcatIngress.js
+++ b/server/services/tailcatIngress.js
@@ -2,7 +2,7 @@
import { createTailscaleServers, watchCertReload } from '../../lib/tailscale-https.js';
import { PORTS } from '../lib/ports.js';
import { ServerError } from '../lib/errorHandler.js';
-import { remoteRequestHandler } from '../lib/requestOrigin.js';
+import { markRemoteServer, remoteRequestHandler } from '../lib/requestOrigin.js';
let configuration = null;
let listener = null;
@@ -43,6 +43,7 @@ export function ensureTailcatIngress() {
server.removeListener('error', reject);
server.on('error', (err) => console.error(`❌ Tailcat ingress failed: ${err.message}`));
io.attach(server);
+ markRemoteServer(server);
if (httpsEnabled) stopWatching = watchCertReload(server, certDir);
resolve();
} catch (err) {
diff --git a/server/services/tailcatIngress.test.js b/server/services/tailcatIngress.test.js
index 3d65a7965b..9baeb005d2 100644
--- a/server/services/tailcatIngress.test.js
+++ b/server/services/tailcatIngress.test.js
@@ -26,3 +26,40 @@ it('binds one loopback listener on demand and marks requests independently of he
await ensureTailcatIngress();
expect(io.attach).toHaveBeenCalledTimes(1);
});
+
+it('marks the handshake requests Socket.IO intercepts before the app handler', async () => {
+ // Mirrors engine.io's attach: it replaces the server's request listeners and
+ // answers its own path itself, and takes the websocket upgrade directly.
+ const io = {
+ attach: vi.fn((server) => {
+ const listeners = server.listeners('request').slice(0);
+ server.removeAllListeners('request');
+ server.on('request', (req, res) => {
+ if (req.url.startsWith('/socket.io/')) return res.end(JSON.stringify({ remote: isRemoteRequest(req) }));
+ for (const listener of listeners) listener.call(server, req, res);
+ });
+ server.on('upgrade', (req, socket) => {
+ socket.end(`HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n${JSON.stringify({ remote: isRemoteRequest(req) })}`);
+ });
+ }),
+ };
+ configureTailcatIngress({ app: (req, res) => res.end(JSON.stringify({ remote: isRemoteRequest(req), app: true })), io });
+ await ensureTailcatIngress();
+ const { port } = io.attach.mock.calls[0][0].address();
+ const polling = await fetch(`http://127.0.0.1:${port}/socket.io/?EIO=4&transport=polling`);
+ expect(await polling.json()).toEqual({ remote: true });
+ const plain = await fetch(`http://127.0.0.1:${port}/api/system/health`);
+ expect(await plain.json()).toEqual({ remote: true, app: true });
+
+ const { connect } = await import('node:net');
+ const upgrade = await new Promise((resolve, reject) => {
+ const client = connect(port, '127.0.0.1', () => {
+ client.write('GET /socket.io/?EIO=4&transport=websocket HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n');
+ });
+ let raw = '';
+ client.on('data', (chunk) => { raw += chunk; });
+ client.on('end', () => resolve(raw));
+ client.on('error', reject);
+ });
+ expect(JSON.parse(upgrade.slice(upgrade.indexOf('\r\n\r\n') + 4))).toEqual({ remote: true });
+});