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: preserve command access restrictions through the dev proxy (#8226)
[._.]/ Adam Eivyba35f7262ad2
diff --git a/client/src/test/viteHostControlProxy.test.js b/client/src/test/viteHostControlProxy.test.jsnew file mode 100644index 0000000000..99e3f0739b--- /dev/null+++ b/client/src/test/viteHostControlProxy.test.js@@ -0,0 +1,24 @@+// @vitest-environment node+import { EventEmitter } from 'node:events';+import { describe, expect, it } from 'vitest';+import viteConfig from '../../vite.config.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../../lib/portosAuthCore.js';++describe('Vite API proxy host-control provenance', () => {+ it.each(['192.0.2.10', '127.0.0.1', '::1', undefined])(+ 'replaces caller headers with its own socket observation %s', remoteAddress => {+ const config = viteConfig({ command: 'serve', mode: 'test' });+ const proxy = new EventEmitter();+ config.server.proxy['^/api(?:/|$)'].configure(proxy);+ // Model the outbound request after the proxy copied incoming headers.+ const headers = { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: ['127.0.0.1', '::1'] };+ proxy.emit('proxyReq', {+ setHeader: (name, value) => { headers[name] = value; },+ }, {+ socket: { remoteAddress },+ headers: { ...headers, 'x-forwarded-for': '127.0.0.1', origin: 'http://localhost' },+ });+ expect(headers[DEV_PROXY_CLIENT_ADDRESS_HEADER]).toBe(remoteAddress || 'unknown');+ },+ );+});diff --git a/client/vite.config.js b/client/vite.config.jsindex 32ec55b50a..15d0ced0c9 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -7,6 +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 {EIDOVERSE_HOST_PATH_PREFIX,EIDOVERSE_ROOT_EXACT_PATHS,@@ -187,7 +188,15 @@ export default defineConfig(({ command, mode }) => {'^/api(?:/|$)': {target: API_TARGET,changeOrigin: true,- secure: false+ 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');+ });+ }},// Every `/data/**` asset mount at once, instead of a hand-maintained// list that silently fell behind the server's (see docs/PORTS.md:diff --git a/lib/portosAuthCore.js b/lib/portosAuthCore.jsindex f22aed1503..815ed0d7dc 100644--- a/lib/portosAuthCore.js+++ b/lib/portosAuthCore.js@@ -18,6 +18,10 @@ import { promisify } from 'node:util';const scryptAsync = promisify(scrypt);+// The bundled dev proxy overwrites this with its socket peer on every API hop.+// Consumers may use it only to RESTRICT loopback access, never to grant it.+export const DEV_PROXY_CLIENT_ADDRESS_HEADER = 'x-portos-dev-proxy-client-address';+export const COOKIE_NAME = 'portos_auth';export const SALT_BYTES = 16;export const HASH_BYTES = 64;diff --git a/server/routes/commands.test.js b/server/routes/commands.test.jsindex d4bb65fcce..1245c52763 100644--- a/server/routes/commands.test.js+++ b/server/routes/commands.test.js@@ -4,6 +4,7 @@ import express from 'express';import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { request } from '../lib/testHelper.js';import { errorEvents, errorMiddleware } from '../lib/errorHandler.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';import { ALLOWED_COMMANDS } from '../lib/commandSecurity.js';const spawnMock = vi.hoisted(() => vi.fn());@@ -117,7 +118,7 @@ describe('commands routes', () => {it.each([['password-free remote peer', false, {}],- ['spoofed forwarding headers', false, { 'X-Forwarded-For': '127.0.0.1', 'X-Real-IP': '::1' }],+ ['spoofed forwarding headers', false, { 'X-Forwarded-For': '127.0.0.1', 'X-Real-IP': '::1', [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }],['authenticated Basic peer', true, { Authorization: basic }],['unauthenticated password-protected peer', true, {}],['invalid operator session', true, { Authorization: 'Bearer invalid-session' }],@@ -144,6 +145,41 @@ describe('commands routes', () => {child.emit('close', 0);});+ it.each(['192.0.2.10', 'unknown', '127.0.0.1, 192.0.2.10'])(+ 'rejects a dev-proxied nonlocal or ambiguous caller %s', async proxyClient => {+ const child = createChildProcess();+ spawnMock.mockReturnValue(child);+ const { app } = createApp();+ const started = await request(app).post('/api/commands/execute').send({ command: 'pwd' });+ expect(started.status).toBe(202);+ spawnMock.mockClear();+ for (const path of ['/api/commands/execute', `/api/commands/${started.body.commandId}/stop`]) {+ const response = await request(app).post(path)+ .set(DEV_PROXY_CLIENT_ADDRESS_HEADER, proxyClient)+ .set('X-Forwarded-For', '127.0.0.1')+ .send({ command: 'npx --yes example-package' });+ expect(response.status).toBe(403);+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ }+ expect(spawnMock).not.toHaveBeenCalled();+ expect(child.kill).not.toHaveBeenCalled();+ child.emit('close', 0);+ },+ );++ it('keeps local UI command control through the dev proxy', async () => {+ const child = createChildProcess();+ spawnMock.mockReturnValue(child);+ const { app } = createApp();+ const started = await request(app).post('/api/commands/execute')+ .set(DEV_PROXY_CLIENT_ADDRESS_HEADER, '::ffff:127.0.0.1').send({ command: 'pwd' });+ expect(started.status).toBe(202);+ const stopped = await request(app).post(`/api/commands/${started.body.commandId}/stop`)+ .set(DEV_PROXY_CLIENT_ADDRESS_HEADER, '::1');+ expect(stopped.status).toBe(200);+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ });+it.each(['127.0.0.1', '127.0.0.2', '::1', '::ffff:127.0.0.1'])('keeps password-free local command control on %s', async remoteAddress => {const child = createChildProcess();@@ -165,7 +201,7 @@ describe('commands routes', () => {const child = createChildProcess();spawnMock.mockReturnValue(child);const { app } = createApp(undefined, { remoteAddress: '192.0.2.10' });- const started = await request(app).post('/api/commands/execute').set(header, value).send({ command: 'pwd' });+ const started = await request(app).post('/api/commands/execute').set(header, value).set(DEV_PROXY_CLIENT_ADDRESS_HEADER, '192.0.2.10').send({ command: 'pwd' });expect(started.status).toBe(202);const stopped = await request(app).post(`/api/commands/${started.body.commandId}/stop`).set(header, value);expect(stopped.status).toBe(200);diff --git a/server/services/authGate.js b/server/services/authGate.jsindex a53bbafbd2..b77f2d6a8e 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -3,7 +3,7 @@ import { isIP } from 'node:net';import { extractToken, isAuthEnabled, verifyPassword, verifySession } 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 { extractBasicPassword, isCrossOrigin } from '../../lib/portosAuthCore.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER, extractBasicPassword, isCrossOrigin } from '../../lib/portosAuthCore.js';import { getSettings, settingsEvents } from './settings.js';import { isRegistryPublic } from '../lib/apiRegistry.js';import { GATED_NON_API_PREFIXES, isAlwaysPublicApiPath } from '../lib/apiAccessPolicy.js';@@ -123,14 +123,23 @@ export const authGate = async (req, res, next) => {}));};+const isLoopbackAddress = (value) => {+ if (typeof value !== 'string') return false;+ const address = value.replace(/^::ffff:/i, '');+ return address === '::1' || (isIP(address) === 4 && address.startsWith('127.'));+};+// Host execution needs operator authority, not merely a peer's Basic credential.// Mount after authGate: missing context fails closed. Password-free installs-// permit only the actual loopback socket peer, never req.ip/forwarded headers or-// the machine-local warning acknowledgement.+// require loopback socket peers, including the dev proxy caller. Neither req.ip+// nor the machine-local warning acknowledgement can grant authority.export const requireHostControl = (req, res, next) => {const auth = req.portosAuthContext;- const address = req.socket?.remoteAddress?.replace(/^::ffff:/i, '');- const loopback = address === '::1' || (isIP(address ?? '') === 4 && address.startsWith('127.'));+ 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.', {