Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: refuse remote shell, iTerm2 and app-update socket events on a password-free install (#8708)
[._.]/ Adam Eivy6f487e555e0e
diff --git a/client/src/hooks/useItermSession.js b/client/src/hooks/useItermSession.jsindex 99a97aa3d8..1efcbb4aad 100644--- a/client/src/hooks/useItermSession.js+++ b/client/src/hooks/useItermSession.js@@ -147,8 +147,10 @@ export function useItermSession({ itermSessionId, enabled = true } = {}) {// connection drops, and the URL must survive that. The next list// decides — re-attach if it is back, fall back if it is really gone.};- const handleError = ({ id, error }) => {- if (id !== pendingRef.current.target && id !== attachedIdRef.current) return;+ const handleError = ({ id, error, code }) => {+ // A host-control refusal (#8708) may answer the uncorrelated list request.+ const refused = code === 'HOST_CONTROL_FORBIDDEN';+ if (!refused && id !== pendingRef.current.target && id !== attachedIdRef.current) return;if (id === pendingRef.current.target) setPending(null);termRef.current?.writeln(`\r\n\x1b[31m[Error: ${error}]\x1b[0m`);};diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.jsindex 4a103a94b3..bc97a7c608 100644--- a/client/src/hooks/useShellSession.js+++ b/client/src/hooks/useShellSession.js@@ -119,6 +119,9 @@ export function useShellSession({ isFullscreen } = {}) {const [connected, setConnected] = useState(false);const [sessions, setSessions] = useState([]);const [activeSessionId, setActiveSessionId] = useState(null);+ // Set when the server refuses the shell to this connection: a remote+ // browser on a password-free install has no host-control authority (#8708).+ const [hostControlForbidden, setHostControlForbidden] = useState(false);const sessionsRef = useRef([]);useEffect(() => { urlSessionIdRef.current = urlSessionId; }, [urlSessionId]);@@ -741,7 +744,15 @@ export function useShellSession({ isFullscreen } = {}) {recoverToSurvivor(sid);};- const handleShellError = ({ error, sessionId: errSid }) => {+ const handleShellError = ({ error, code, sessionId: errSid }) => {+ // A refusal answers every shell event, including the list request no+ // pending attach correlates with — settle any pending start/attach and+ // surface it once instead of letting the page wait forever.+ if (code === 'HOST_CONTROL_FORBIDDEN') {+ cancelPendingAttach();+ setHostControlForbidden(true);+ return;+ }// Correlate this error to our current pending request before deciding whether// to display it. Four cases:// 1) start failure: server-side errSid omitted, our pending is 'new'. Show + recover.@@ -886,6 +897,7 @@ export function useShellSession({ isFullscreen } = {}) {return {terminalRef,connected,+ hostControlForbidden,sessions,activeSessionId,activeSession,diff --git a/client/src/hooks/useShellSession.test.jsx b/client/src/hooks/useShellSession.test.jsxindex 6676222b73..1cab038414 100644--- a/client/src/hooks/useShellSession.test.jsx+++ b/client/src/hooks/useShellSession.test.jsx@@ -65,6 +65,16 @@ describe('useShellSession', () => {expect(lastEmit('shell:start')).toBeTruthy();});+ // #8708: a remote socket on a password-free install is refused its very+ // first shell:list, which no pending request correlates with — the refusal+ // must still surface instead of leaving the page waiting.+ it('surfaces a host-control refusal of the uncorrelated list request', () => {+ const { result } = renderHook(() => useShellSession({}), { wrapper });+ expect(result.current.hostControlForbidden).toBe(false);+ fire('shell:error', { code: 'HOST_CONTROL_FORBIDDEN', error: 'Set an instance password to use it remotely.' });+ expect(result.current.hostControlForbidden).toBe(true);+ });+it('activates a started session and marks it connected', () => {const { result } = renderHook(() => useShellSession({}), { wrapper });fire('shell:sessions', []); // → startSession, pending target 'new'diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsxindex da3416b1cd..6682f193ed 100644--- a/client/src/pages/Shell.jsx+++ b/client/src/pages/Shell.jsx@@ -45,6 +45,7 @@ function PortosShellView() {const {terminalRef,connected,+ hostControlForbidden,sessions,activeSessionId,interactiveCount,@@ -299,6 +300,12 @@ function PortosShellView() {</div>)}+ {hostControlForbidden && (+ <div role="alert" className="shrink-0 px-3 py-2 rounded-lg border border-port-warning/40 bg-port-warning/10 text-sm text-port-warning">+ The shell only runs for a local connection while no instance password is set. Set an instance password in Settings to use the shell remotely.+ </div>+ )}+{/* Terminal container — drops the rounded border in fullscreen so it sits flush */}<div className={`flex-1 bg-port-bg overflow-hidden ${isFullscreen ? '' : 'rounded-lg border border-port-border'}`}><divdiff --git a/client/vite.config.js b/client/vite.config.jsindex 15d0ced0c9..9a07400926 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -95,6 +95,18 @@ function buildStamp() {const CERT_PATH = resolve(CONFIG_DIR, '..', 'data', 'certs', 'cert.pem');const API_SCHEME = existsSync(CERT_PATH) ? 'https' : 'http';+// The API sees Vite's loopback connection, not the browser's. Replace+// caller-supplied provenance, including duplicate headers; unknown socket+// peers must never become an implicit local caller. `proxyReqWs` covers a+// websocket upgrade, which never fires `proxyReq`.+function markProxyClientAddress(proxy) {+ const mark = (proxyReq, req) => {+ proxyReq.setHeader(DEV_PROXY_CLIENT_ADDRESS_HEADER, req.socket?.remoteAddress || 'unknown');+ };+ proxy.on('proxyReq', mark);+ proxy.on('proxyReqWs', mark);+}+// 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.@@ -189,14 +201,7 @@ export default defineConfig(({ command, mode }) => {target: API_TARGET,changeOrigin: true,secure: false,- configure(proxy) {- proxy.on('proxyReq', (proxyReq, req) => {- // The API sees Vite's loopback connection, not the browser's.- // Replace caller-supplied provenance, including duplicate headers;- // unknown socket peers must never become an implicit local caller.- proxyReq.setHeader(DEV_PROXY_CLIENT_ADDRESS_HEADER, req.socket?.remoteAddress || 'unknown');- });- }+ configure: markProxyClientAddress},// Every `/data/**` asset mount at once, instead of a hand-maintained// list that silently fell behind the server's (see docs/PORTS.md:@@ -212,11 +217,15 @@ export default defineConfig(({ command, mode }) => {changeOrigin: true,secure: false},+ // The socket carries host-control events (shell, iTerm2, app updates)+ // gated on a local caller, so its handshake needs the same marker —+ // on both the polling requests and the websocket upgrade (#8708).'/socket.io': {target: API_TARGET,changeOrigin: true,ws: true,- secure: false+ secure: false,+ configure: markProxyClientAddress},...eidoverseDevProxies(API_TARGET),}diff --git a/server/services/authGate.js b/server/services/authGate.jsindex a0de3edad1..a2fd056c03 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -220,25 +220,42 @@ const isLoopbackAddress = (value) => {return address === '::1' || (isIP(address) === 4 && address.startsWith('127.'));};+// A loopback connection, restricted further when it carries the dev proxy's+// client-address marker: Vite proxies every browser from its own loopback+// socket, so the marker's address is the real caller. A direct remote caller+// cannot gain authority by forging a loopback marker — its connection address+// is not loopback to begin with.+const isLocalConnection = (remoteAddress, headers) => {+ const proxyClient = headers?.[DEV_PROXY_CLIENT_ADDRESS_HEADER];+ return isLoopbackAddress(remoteAddress)+ && (proxyClient === undefined || isLoopbackAddress(proxyClient));+};+// Host execution needs operator authority: a peer's credential — the scoped-// peer token or the legacy Basic password — never qualifies.-// Mount after authGate: missing context fails closed. Password-free installs-// require loopback socket peers, including the dev proxy caller. Neither req.ip+// peer token or the legacy Basic password — never qualifies. Password-free+// installs require a local connection (see isLocalConnection). Neither req.ip// nor the machine-local warning acknowledgement can grant authority.+const hasHostControl = (auth, localConnection) =>+ (auth?.enabled === true && auth.authenticated === true && auth.method === 'session')+ || (auth?.enabled === false && localConnection === true);++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.';++// Mount after authGate: missing context fails closed.export const requireHostControl = (req, res, next) => {- const auth = req.portosAuthContext;- const proxyClient = req.headers[DEV_PROXY_CLIENT_ADDRESS_HEADER];- // Only restrict an actual loopback connection with the dev proxy's marker.- // A direct remote caller cannot gain authority by forging a loopback header.- const loopback = isLoopbackAddress(req.socket?.remoteAddress)- && (proxyClient === undefined || isLoopbackAddress(proxyClient));- if ((auth?.enabled === true && auth.authenticated === true && auth.method === 'session')- || (auth?.enabled === false && loopback)) return next();- sendErrorResponse(res, new ServerError('Host commands require an operator session, or a local connection when no password is set.', {+ if (hasHostControl(req.portosAuthContext, isLocalConnection(req.socket?.remoteAddress, req.headers))) return next();+ sendErrorResponse(res, new ServerError(HOST_CONTROL_FORBIDDEN_MESSAGE, {status: 403, code: 'HOST_CONTROL_FORBIDDEN',}));};+// The socket twin of requireHostControl on a password-free install, for the+// per-event re-check in socket.js (with a password set, that re-check already+// admits only a verified session to host-control events). Locality is+// recorded at the handshake by socketAuthGate; a socket that never passed the+// gate carries none and fails closed.+export const socketHasHostControl = (socket) => hasHostControl({ enabled: false }, socket.data?.portosLocalConnection);+// 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@@ -259,6 +276,8 @@ const markAuthMethod = (socket, method) => {};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 || {} };diff --git a/server/services/authGate.test.js b/server/services/authGate.test.jsindex 2e685039e4..eba7611f1b 100644--- a/server/services/authGate.test.js+++ b/server/services/authGate.test.js@@ -5,6 +5,7 @@ import { join } from 'path';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';import { bindSettingsFile } from '../lib/settingsTestUtil.js';import { request } from '../lib/testHelper.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-authgate-' });@@ -652,6 +653,23 @@ describe('host-control authority', () => {expect(peer.res.statusCode).toBe(403);expect(peer.res.body.code).toBe('HOST_CONTROL_FORBIDDEN');});++ // The socket twin (#8708): locality is recorded at the handshake from the+ // connection's own address, so a forged loopback dev-proxy marker on a+ // remote connection grants nothing, and a gate-less socket fails closed.+ it('records socket host-control locality at the handshake, never from a forged marker', async () => {+ const { socketAuthGate, socketHasHostControl } = await import('./authGate.js');+ const handshake = async (address, headers = {}) => {+ const socket = { handshake: { address, headers } };+ await new Promise((resolve) => socketAuthGate(socket, resolve));+ return socketHasHostControl(socket);+ };+ expect(await handshake('127.0.0.1')).toBe(true);+ expect(await handshake('::1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' })).toBe(true);+ expect(await handshake('::1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' })).toBe(false);+ expect(await handshake('192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' })).toBe(false);+ expect(socketHasHostControl({ handshake: { address: '127.0.0.1' } })).toBe(false);+ });});describe('paired peer credential (#8356)', () => {diff --git a/server/services/peerSocketRelayAuth.test.js b/server/services/peerSocketRelayAuth.test.jsindex 44e4b50b01..8f8166e58f 100644--- a/server/services/peerSocketRelayAuth.test.js+++ b/server/services/peerSocketRelayAuth.test.js@@ -18,6 +18,7 @@ import { writeFileSync } from 'fs';import { join } from 'path';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';import { bindSettingsFile } from '../lib/settingsTestUtil.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';const { tempRoot, makeProxy, cleanup: cleanupDataRoot } = mockPathsDataRoot({ prefix: 'portos-peer-relay-auth-' });@@ -60,6 +61,8 @@ let httpServer;let ioServer;let port;let clients = [];+// Host-control handlers the stand-ins below actually reached (#8708).+let reached = [];const startServer = async () => {const { socketAuthGate } = await import('./authGate.js');@@ -74,6 +77,15 @@ const startServer = async () => {// never actually reached by a peer-authenticated socket once the auth// middleware above disconnects it first.socket.on('shell:list', () => socket.emit('shell:sessions', { sessions: [] }));+ // Stand-ins for the host-control handlers (server/sockets/shell.js,+ // iterm.js, apps.js): record that the handler ran, which the gate must+ // prevent for a caller without host-control authority.+ socket.on('shell:start', (options) => {+ reached.push(['shell:start', options?.initialCommand]);+ socket.emit('shell:started', { sessionId: 'example-session' });+ });+ socket.on('iterm:input', () => reached.push(['iterm:input']));+ socket.on('app:update', () => reached.push(['app:update']));});await new Promise((resolve) => httpServer.listen(0, resolve));port = httpServer.address().port;@@ -82,6 +94,7 @@ const startServer = async () => {const stopServer = async () => {for (const client of clients) client.close();clients = [];+ reached = [];await new Promise((resolve) => ioServer.close(resolve));await new Promise((resolve) => httpServer.close(resolve));};@@ -97,6 +110,10 @@ const connectClient = (extraHeaders) => {return client;};+afterAll(() => {+ cleanupDataRoot();+});+const waitFor = (emitter, event) => new Promise((resolve) => emitter.once(event, resolve));describe('peer socket relay stays connected through cos:subscribe on a password-gated peer (#8386)', () => {@@ -110,10 +127,6 @@ describe('peer socket relay stays connected through cos:subscribe on a password-await stopServer();});- afterAll(() => {- cleanupDataRoot();- });-it('a peer-token-authenticated socket survives cos:subscribe but is disconnected by a shell:* event', async () => {const auth = await import('./auth.js');await auth.setPassword({ newPassword: 'instance-secret' });@@ -169,3 +182,78 @@ describe('peer socket relay stays connected through cos:subscribe on a password-expect(err.data?.code).toBe('AUTH_REQUIRED');});});++describe('host-control socket events need operator authority (#8708)', () => {+ const REMOTE_VIA_DEV_PROXY = { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' };++ beforeEach(async () => {+ vi.resetModules();+ resetSettings();+ instanceRegistry.data = { self: null, peers: [] };+ });++ afterEach(async () => {+ await stopServer();+ });++ it('auth off: a remote caller is refused every host-control event and runs nothing', async () => {+ await startServer();+ const client = connectClient(REMOTE_VIA_DEV_PROXY);+ await waitFor(client, 'connect');++ const shellRefused = waitFor(client, 'shell:error');+ client.emit('shell:start', { initialCommand: 'echo example' });+ expect(await shellRefused).toMatchObject({ code: 'HOST_CONTROL_FORBIDDEN' });++ const itermRefused = waitFor(client, 'iterm:error');+ client.emit('iterm:input', { id: 'example-iterm', data: 'ls\r' });+ expect(await itermRefused).toMatchObject({ code: 'HOST_CONTROL_FORBIDDEN', id: 'example-iterm' });++ const updateRefused = waitFor(client, 'app:update:error');+ client.emit('app:update', { appId: 'example-app' });+ expect(await updateRefused).toMatchObject({ code: 'HOST_CONTROL_FORBIDDEN', appId: 'example-app' });++ // Read-only subscriptions stay open, and the refusals did not disconnect.+ const subscribed = waitFor(client, 'cos:subscribed');+ client.emit('cos:subscribe');+ await subscribed;+ expect(client.connected).toBe(true);+ expect(reached).toEqual([]);+ });++ it('auth off: a local caller, direct or through the dev proxy, keeps the shell', async () => {+ await startServer();+ for (const headers of [{}, { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '::ffff:127.0.0.1' }]) {+ const client = connectClient(headers);+ await waitFor(client, 'connect');+ const started = waitFor(client, 'shell:started');+ client.emit('shell:start', { initialCommand: 'echo example' });+ await started;+ }+ expect(reached).toEqual([['shell:start', 'echo example'], ['shell:start', 'echo example']]);+ });++ it('auth on: a session socket keeps the shell; a remote connection does not change that', async () => {+ const auth = await import('./auth.js');+ const { token } = await auth.setPassword({ newPassword: 'instance-secret' });+ await startServer();+ const client = connectClient({ cookie: `portos_auth=${token}`, ...REMOTE_VIA_DEV_PROXY });+ await waitFor(client, 'connect');+ const started = waitFor(client, 'shell:started');+ client.emit('shell:start', {});+ await started;+ expect(reached).toEqual([['shell:start', undefined]]);+ });++ it('auth on: a Basic-authenticated relay socket never reaches a host-control handler', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'instance-secret' });+ await startServer();+ const client = connectClient({ Authorization: `Basic ${Buffer.from(':instance-secret').toString('base64')}` });+ await waitFor(client, 'connect');+ const disconnected = waitFor(client, 'disconnect');+ client.emit('shell:start', { initialCommand: 'echo example' });+ await disconnected;+ expect(reached).toEqual([]);+ });+});diff --git a/server/services/socket.js b/server/services/socket.jsindex 59ec6acc5b..932bf93102 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -61,6 +61,7 @@ import { detachShellSocket, registerShellHandlers } from '../sockets/shell.js';import { detachItermSocket, registerItermHandlers } from '../sockets/iterm.js';import { getBuildId } from '../lib/buildId.js';import { authEvents, isAuthEnabled, verifyRequestSession } from './auth.js';+import { HOST_CONTROL_FORBIDDEN_MESSAGE, socketHasHostControl } from './authGate.js';import { runEventLogEvents } from './agentRunEventLog.js';import { armSystemActivityWatchers, bindSystemActivityIo } from './systemActivityNotify.js';import { armReadinessWatchers, registerReadinessSocket } from './readinessNotify.js';@@ -133,13 +134,40 @@ function registerSubscriber(socket, namespace, set) {// mutating or host-affecting event here.const PEER_RELAY_ALLOWED_EVENTS = new Set(['cos:subscribe', 'cos:unsubscribe']);+// Events that execute on the host — an interactive PTY, keystrokes into the+// user's live iTerm2 sessions, or git/npm/PM2/deploy runs in a managed app's+// directory. They need the same operator authority as the HTTP+// requireHostControl routes (#8226): on a password-free install a remote+// LAN/tailnet socket is refused (#8708). Every `shell:*` and `iterm:*` event+// is included by prefix; read-only subscriptions stay open to remote sockets.+const HOST_CONTROL_SOCKET_EVENTS = new Set(['app:update', 'app:standardize', 'app:deploy', 'standardize:start']);+const HOST_CONTROL_SOCKET_PREFIXES = ['shell:', 'iterm:'];+const isHostControlSocketEvent = (event) => typeof event === 'string'+ && (HOST_CONTROL_SOCKET_EVENTS.has(event) || HOST_CONTROL_SOCKET_PREFIXES.some((prefix) => event.startsWith(prefix)));++// A refusal goes out on the error event the event's own client already+// listens on, so the waiting UI settles instead of hanging.+const hostControlRefusal = (event, payload) => {+ const refusal = { code: 'HOST_CONTROL_FORBIDDEN', error: HOST_CONTROL_FORBIDDEN_MESSAGE, message: HOST_CONTROL_FORBIDDEN_MESSAGE };+ if (event.startsWith('shell:')) return ['shell:error', { ...refusal, sessionId: payload?.sessionId }];+ if (event.startsWith('iterm:')) return ['iterm:error', { ...refusal, id: payload?.id }];+ if (event === 'standardize:start') return ['standardize:complete', { success: false, ...refusal }];+ return [`${event}:error`, { ...refusal, appId: payload?.appId }];+};+function registerAuthHandlers(socket, _io) {// Per-event auth re-check: the handshake gate only runs once at connection- // time, so every inbound event re-verifies an enabled session.+ // time, so every inbound event re-verifies an enabled session. With auth+ // off, host-control events still need a local connection.if (typeof socket.use === 'function') {- socket.use(async ([event, ..._args], next) => {+ socket.use(async ([event, payload], next) => {try {- if (!(await isAuthEnabled())) return next();+ if (!(await isAuthEnabled())) {+ if (!isHostControlSocketEvent(event) || socketHasHostControl(socket)) return next();+ console.warn(`⛔ Refused host-control socket event ${event} from a non-local connection`);+ socket.emit(...hostControlRefusal(event, payload));+ return;+ }if (await verifyRequestSession({ headers: socket.handshake?.headers || {} })) return next();const peerAuthMethod = socket.data?.portosAuthMethod;if ((peerAuthMethod === 'peer' || peerAuthMethod === 'basic') && PEER_RELAY_ALLOWED_EVENTS.has(event)) {