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: require operator authority for host commands (#8226)
[._.]/ Adam Eivydb3bc1f9cb42
diff --git a/server/routes/commands.js b/server/routes/commands.jsindex 442ea5e156..fbcece59e1 100644--- a/server/routes/commands.js+++ b/server/routes/commands.js@@ -2,6 +2,7 @@ import { Router } from 'express';import { existsSync, statSync, realpathSync } from 'fs';import { resolve } from 'path';import * as commands from '../services/commands.js';+import { requireHostControl } from '../services/authGate.js';import * as pm2Service from '../services/pm2.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { isWithinAllowedRoots, outsideAllowedRootsMessage } from '../lib/workspaceRoots.js';@@ -9,7 +10,7 @@ import { isWithinAllowedRoots, outsideAllowedRootsMessage } from '../lib/workspaconst router = Router();// POST /api/commands/execute - Execute a command-router.post('/execute', asyncHandler(async (req, res) => {+router.post('/execute', requireHostControl, asyncHandler(async (req, res) => {const { command, workspacePath } = req.body;if (!command) {@@ -72,7 +73,7 @@ router.post('/execute', asyncHandler(async (req, res) => {}));// POST /api/commands/:id/stop - Stop a running command-router.post('/:id/stop', asyncHandler(async (req, res) => {+router.post('/:id/stop', requireHostControl, asyncHandler(async (req, res) => {const stopped = commands.stopCommand(req.params.id);if (!stopped) {diff --git a/server/routes/commands.test.js b/server/routes/commands.test.jsindex 81bcfd1770..d4bb65fcce 100644--- a/server/routes/commands.test.js+++ b/server/routes/commands.test.js@@ -36,6 +36,23 @@ vi.mock('fs', async (importOriginal) => {};});+vi.mock('../services/auth.js', async () => {+ const { extractToken } = await import('../../lib/portosAuthCore.js');+ return {+ extractToken,+ isAuthEnabled: vi.fn().mockResolvedValue(false),+ verifySession: vi.fn(async token => token === 'example-operator-session'),+ verifyPassword: vi.fn(async password => password === 'example-peer-password'),+ };+});++vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn().mockResolvedValue({}),+ settingsEvents: new EventEmitter(),+}));++import { authGate } from '../services/authGate.js';+import { isAuthEnabled } from '../services/auth.js';import { existsSync, realpathSync, statSync } from 'fs';import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';import commandsRoutes from './commands.js';@@ -51,10 +68,16 @@ function createChildProcess() {return child;}-function createApp(io = { emit: vi.fn() }) {+function createApp(io = { emit: vi.fn() }, { remoteAddress, withAuthGate = true } = {}) {const app = express();app.set('io', io);app.use(express.json());+ 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 });+ next();+ });+ if (withAuthGate) app.use(authGate);app.use('/api/commands', commandsRoutes);app.use(errorMiddleware);return { app, io };@@ -82,12 +105,82 @@ describe('commands routes', () => {beforeEach(() => {vi.clearAllMocks();+ isAuthEnabled.mockResolvedValue(false);});afterEach(() => {vi.restoreAllMocks();});+ describe('host-control authorization through the real auth gate', () => {+ const basic = `Basic ${Buffer.from(':example-peer-password').toString('base64')}`;++ it.each([+ ['password-free remote peer', false, {}],+ ['spoofed forwarding headers', false, { 'X-Forwarded-For': '127.0.0.1', 'X-Real-IP': '::1' }],+ ['authenticated Basic peer', true, { Authorization: basic }],+ ['unauthenticated password-protected peer', true, {}],+ ['invalid operator session', true, { Authorization: 'Bearer invalid-session' }],+ ])('rejects %s before spawning or stopping a process', async (_name, enabled, headers) => {+ const child = createChildProcess();+ spawnMock.mockReturnValue(child);+ const local = createApp().app;+ const started = await request(local).post('/api/commands/execute').send({ command: 'pwd' });+ expect(started.status).toBe(202);+ spawnMock.mockClear();+ isAuthEnabled.mockResolvedValue(enabled);+ const { app } = createApp(undefined, { remoteAddress: '192.0.2.10' });+ app.set('trust proxy', true);++ for (const path of ['/api/commands/execute', `/api/commands/${started.body.commandId}/stop`]) {+ const pending = request(app).post(path).send({ command: 'npx --yes example-package' });+ for (const [key, value] of Object.entries(headers)) pending.set(key, value);+ const response = await pending;+ expect(response.status).toBe(enabled && !headers.Authorization?.startsWith('Basic') ? 401 : 403);+ expect(response.body.code).toBe(response.status === 401 ? 'AUTH_REQUIRED' : 'HOST_CONTROL_FORBIDDEN');+ }+ expect(spawnMock).not.toHaveBeenCalled();+ expect(child.kill).not.toHaveBeenCalled();+ child.emit('close', 0);+ });++ 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();+ spawnMock.mockReturnValue(child);+ const { app } = createApp(undefined, { remoteAddress });+ const started = await request(app).post('/api/commands/execute').send({ command: 'pwd' });+ expect(started.status).toBe(202);+ const stopped = await request(app).post(`/api/commands/${started.body.commandId}/stop`);+ expect(stopped.status).toBe(200);+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ },+ );++ it.each([+ ['Cookie', 'portos_auth=example-operator-session'],+ ['Authorization', 'Bearer example-operator-session'],+ ])('allows authenticated operator commands through %s', async (header, value) => {+ isAuthEnabled.mockResolvedValue(true);+ 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' });+ 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);+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ });++ it('fails closed when mounted without the global auth gate', async () => {+ const { app } = createApp(undefined, { withAuthGate: false });+ const response = await request(app).post('/api/commands/execute').send({ command: 'pwd' });+ expect(response.status).toBe(403);+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ expect(spawnMock).not.toHaveBeenCalled();+ });+ });+describe('POST /api/commands/execute', () => {it('rejects a missing command before touching the filesystem or process boundary', async () => {const { app } = createApp();diff --git a/server/services/authGate.js b/server/services/authGate.jsindex d28b9b2dd3..a53bbafbd2 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -1,4 +1,5 @@import { createHash } from 'node:crypto';+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.@@ -122,6 +123,21 @@ export const authGate = async (req, res, next) => {}));};+// 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.+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.'));+ 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.', {+ status: 403, code: 'HOST_CONTROL_FORBIDDEN',+ }));+};+// 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 adiff --git a/server/services/authGate.test.js b/server/services/authGate.test.jsindex e66dddb292..c6592f1dc6 100644--- a/server/services/authGate.test.js+++ b/server/services/authGate.test.js@@ -628,6 +628,24 @@ describe('authGate HTTP Basic auth (peer federation)', () => {);});+describe('host-control authority', () => {+ it('accepts a real operator session and refuses peer Basic credentials even on loopback', async () => {+ const auth = await import('./auth.js');+ const { token } = await auth.setPassword({ newPassword: 'example-password' });+ const { authGate, requireHostControl } = await import('./authGate.js');+ const gate = (req, res, next) => authGate(req, res, () => requireHostControl(req, res, next));+ const req = { path: '/api/commands/execute', socket: { remoteAddress: '127.0.0.1' } };+ const operator = await runGate(gate, { ...req, headers: { cookie: `portos_auth=${token}` } });+ expect(operator.called).toBe(true);+ const peer = await runGate(gate, { ...req, headers: {+ authorization: `Basic ${Buffer.from(':example-password').toString('base64')}`,+ } });+ expect(peer.called).toBe(false);+ expect(peer.res.statusCode).toBe(403);+ expect(peer.res.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ });+});+describe('socketAuthGate middleware', () => {it('is a no-op when auth is disabled', async () => {const { socketAuthGate } = await import('./authGate.js');