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 Autofixer process controls (#9438)
[._.]/ Adam Eivy7ccf4dad4bd0
diff --git a/autofixer/ui.js b/autofixer/ui.jsindex 542f9cba30..26e44d3cbf 100644--- a/autofixer/ui.js+++ b/autofixer/ui.js@@ -25,12 +25,9 @@ async function loadHistory() {return JSON.parse(data);}-// When the install is password protected (Settings → Security on :5555), this-// sidecar honours the same gate. It listens on 0.0.0.0 for tailnet access and-// can restart/stop PM2 processes and stream logs, so leaving it open while-// :5555 asks for a password would make the password meaningless. On an install-// with no password set, the gate is a no-op — the documented single-user-// trust model is unchanged.+// Reads honour the optional instance password. Process mutations additionally+// require an operator session, or a genuine local connection without a password.+// Reachability on the private network does not grant host-control authority.// `/` serves the static shell, which renders its own login overlay driven by// GET /api/auth/status — it carries no data, so it stays publicly reachable.const auth = createSidecarAuthGate({@@ -92,7 +89,7 @@ async function isRegisteredProcess(processName) {}// API: Restart a PM2 process-app.post('/api/restart/:process', async (req, res) => {+app.post('/api/restart/:process', auth.requireHostControl, async (req, res) => {const processName = req.params.process;if (!(await isRegisteredProcess(processName))) {return res.status(400).json({ success: false, error: 'Unknown process' });@@ -111,7 +108,7 @@ app.post('/api/restart/:process', async (req, res) => {});// API: Stop a PM2 process-app.post('/api/stop/:process', async (req, res) => {+app.post('/api/stop/:process', auth.requireHostControl, async (req, res) => {const processName = req.params.process;if (!(await isRegisteredProcess(processName))) {return res.status(400).json({ success: false, error: 'Unknown process' });diff --git a/autofixer/ui.test.js b/autofixer/ui.test.jsnew file mode 100644index 0000000000..714f8e6c14--- /dev/null+++ b/autofixer/ui.test.js@@ -0,0 +1,130 @@+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { hashPassword, hashToken } from '../lib/portosAuthCore.js';++const harness = vi.hoisted(() => ({ routes: new Map(), gates: [], auth: null, execPm2: vi.fn() }));+vi.mock('express', () => {+ const express = () => ({+ use: (handler) => harness.gates.push(handler),+ get: () => {},+ post: (path, ...handlers) => harness.routes.set(path, handlers),+ });+ express.json = () => (_req, _res, next) => next();+ return { default: express };+});+vi.mock('../lib/sidecarAuthGate.js', async (original) => ({+ ...await original(), createSidecarAuthGate: () => harness.auth,+}));+vi.mock('../lib/tailscale-https.js', () => ({+ createTailscaleServers: () => ({ server: { listen: vi.fn() }, httpsEnabled: false }),+ watchCertReload: vi.fn(),+}));+vi.mock('./shared.js', () => ({+ PM2_BIN: 'example-pm2', DATA_DIR: 'unused', INDEX_FILE: 'unused',+ execPm2: harness.execPm2, listProcessesStrict: vi.fn(),+ loadApps: async () => [{ pm2ProcessNames: ['example-process'] }],+}));++const PASSWORD = 'example-password';+const SALT = 'a1b2c3d4e5f60718293a4b5c6d7e8f90';+let passwordHash;+let dataDir;+beforeAll(async () => { passwordHash = await hashPassword(PASSWORD, SALT); }, 30_000);+beforeEach(async () => {+ dataDir = await mkdtemp(join(tmpdir(), 'autofixer-authority-'));+ harness.execPm2.mockReset().mockResolvedValue({ stdout: 'ok', stderr: '' });+ harness.gates.length = 0;+ harness.routes.clear();+});+afterEach(async () => { await rm(dataDir, { recursive: true, force: true }); });++const loadUi = async (enabled = false) => {+ await writeFile(join(dataDir, 'settings.json'), JSON.stringify({ secrets: { auth: {+ enabled, passwordHash, salt: SALT,+ } } }));+ await writeFile(join(dataDir, 'auth-sessions.json'), JSON.stringify({ tokens: [+ { tokenHash: hashToken('example-session'), expiresAt: Date.now() + 60_000 },+ ] }));+ const { createSidecarAuthGate } = await vi.importActual('../lib/sidecarAuthGate.js');+ harness.auth = createSidecarAuthGate({ dataDir, cookieName: 'portos_autofixer_auth' });+ vi.resetModules();+ const processOn = vi.spyOn(process, 'on').mockReturnValue(process);+ try { await import('./ui.js'); } finally { processOn.mockRestore(); }+};++const response = () => {+ const res = { statusCode: 200, body: null, headers: {} };+ res.status = (code) => { res.statusCode = code; return res; };+ res.json = (body) => { res.body = body; return res; };+ res.setHeader = (name, value) => { res.headers[name] = value; };+ return res;+};+const mutate = async (action, address = '192.0.2.10', headers = {}) => {+ const req = { path: `/api/${action}/example-process`, params: { process: 'example-process' },+ headers, socket: { remoteAddress: address } };+ const res = response();+ for (const handler of [...harness.gates, ...harness.routes.get(`/api/${action}/:process`)]) {+ let nexted = false;+ await handler(req, res, () => { nexted = true; });+ if (!nexted) break;+ }+ return res;+};++describe('Autofixer process-control authority', () => {+ it('refuses remote, forged forwarding, and remote dev-proxy callers before PM2', async () => {+ await loadUi();+ for (const action of ['restart', 'stop']) {+ for (const [address, headers] of [+ ['192.0.2.10', {}],+ ['192.0.2.10', { 'x-portos-dev-proxy-client-address': '127.0.0.1', 'x-forwarded-for': '127.0.0.1' }],+ ['127.0.0.1', { 'x-portos-dev-proxy-client-address': '192.0.2.10' }],+ ]) {+ const res = await mutate(action, address, headers);+ expect(res.statusCode).toBe(403);+ expect(res.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ }+ }+ expect(harness.execPm2).not.toHaveBeenCalled();+ });++ it('preserves password-free genuine loopback controls', async () => {+ await loadUi();+ expect((await mutate('restart', '::1')).body).toEqual({ success: true });+ expect((await mutate('stop', '::ffff:127.0.0.1')).body).toEqual({ success: true });+ expect(harness.execPm2.mock.calls).toEqual([[['restart', 'example-process']], [['stop', 'example-process']]]);+ });++ it('refuses Basic-only authority but accepts primary and sidecar sessions', async () => {+ await loadUi(true);+ const basic = `Basic ${Buffer.from(`:${PASSWORD}`).toString('base64')}`;+ for (const action of ['restart', 'stop']) {+ expect((await mutate(action, '127.0.0.1', { authorization: basic })).body.code).toBe('HOST_CONTROL_FORBIDDEN');+ }+ expect(harness.execPm2).not.toHaveBeenCalled();+ const loginRes = response();+ await harness.auth.handleLogin({ headers: {}, body: { password: PASSWORD } }, loginRes);+ const sidecarCookie = loginRes.headers['Set-Cookie'].split(';')[0];+ for (const headers of [{ cookie: 'portos_auth_5555=example-session' }, { authorization: 'Bearer example-session' }, { cookie: sidecarCookie }]) {+ for (const action of ['restart', 'stop']) {+ expect((await mutate(action, '192.0.2.10', headers)).body).toEqual({ success: true });+ }+ }+ expect(harness.execPm2).toHaveBeenCalledTimes(6);+ }, 30_000);++ it('keeps corrupt config and cross-origin requests closed without PM2 effects', async () => {+ await loadUi();+ expect((await mutate('restart', '127.0.0.1', { origin: 'https://attacker.example', host: 'localhost:5560' })).body.code).toBe('CROSS_ORIGIN_BLOCKED');+ await writeFile(join(dataDir, 'settings.json'), '{broken');+ expect((await mutate('stop', '127.0.0.1')).body.code).toBe('AUTH_REQUIRED');+ const { createSidecarAuthGate } = await vi.importActual('../lib/sidecarAuthGate.js');+ harness.auth = createSidecarAuthGate({ dataDir, cookieName: 'portos_autofixer_auth' });+ const res = response();+ await harness.auth.requireHostControl({ headers: {}, socket: { remoteAddress: '127.0.0.1' } }, res, vi.fn());+ expect(res.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ expect(harness.execPm2).not.toHaveBeenCalled();+ });+});diff --git a/lib/portosAuthCore.js b/lib/portosAuthCore.jsindex 45ce1be2f0..abed31323b 100644--- a/lib/portosAuthCore.js+++ b/lib/portosAuthCore.js@@ -325,3 +325,20 @@ export const createLoginThrottle = ({ maxAttempts = 10, windowMs = 60 * 1000 } =clear: (ip) => { if (typeof ip === 'string') attempts.delete(ip); },};};++const isLoopbackAddress = (value) => {+ if (typeof value !== 'string') return false;+ const address = value.replace(/^::ffff:/i, '');+ 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.+export const isLocalConnection = (remoteAddress, headers) => {+ const proxyClient = headers?.[DEV_PROXY_CLIENT_ADDRESS_HEADER];+ return isLoopbackAddress(remoteAddress)+ && (proxyClient === undefined || isLoopbackAddress(proxyClient));+};diff --git a/lib/sidecarAuthGate.js b/lib/sidecarAuthGate.jsindex feb44e1ffa..06a3256d34 100644--- a/lib/sidecarAuthGate.js+++ b/lib/sidecarAuthGate.js@@ -20,7 +20,10 @@* 2. A `portos_auth` session cookie or `Authorization: Bearer <token>` minted* by the main server. Cookies ignore port, so a browser already logged in* to PortOS on the same host is authenticated here with no second login.- * 3. `Authorization: Basic <base64(:password)>` — for curl/scripts.+ * 3. `Authorization: Basic <base64(:password)>` — for read-only curl/scripts.+ *+ * Mount requireHostControl on host mutations after gate: only verified sessions+ * qualify with a password, and password-free control requires a local socket.** The sidecar NEVER writes `auth-sessions.json`: the main server keeps that* store in memory and rewrites it wholesale on every mutation, so a second@@ -38,6 +41,7 @@ import {extractBasicPassword,extractTokens,hashToken,+ isLocalConnection,parseCookie,verifyPasswordAgainst,} from './portosAuthCore.js';@@ -141,7 +145,7 @@ export const createSidecarAuthGate = ({return typeof expiresAt === 'number' && expiresAt > Date.now();};- const isAuthenticated = async (req) => {+ const isAuthenticated = async (req, { sessionOnly = false } = {}) => {const { auth, corrupt } = await loadConfig();// Corrupt settings → no usable password hash → nothing can authenticate.if (corrupt || !auth?.passwordHash || !auth.salt) return false;@@ -152,6 +156,7 @@ export const createSidecarAuthGate = ({for (const token of extractTokens(req)) {if (await verifyServerSession(token)) return true;}+ if (sessionOnly) return false;const basic = extractBasicPassword(req);if (basic && await verifyPasswordAgainst(auth, basic)) return true;return false;@@ -188,6 +193,21 @@ export const createSidecarAuthGate = ({return res.status(401).json({ error: 'Authentication required', code: 'AUTH_REQUIRED' });};+ // Host mutations require operator sessions, never legacy Basic credentials.+ // Without a password only the genuine socket peer can grant local access.+ const requireHostControl = async (req, res, next) => {+ const refusal = browserRequestRefusal(req);+ if (refusal) return res.status(403).json({ error: 'Browser request rejected', code: refusal });+ const permitted = await isEnabled()+ ? await isAuthenticated(req, { sessionOnly: true })+ : isLocalConnection(req.socket?.remoteAddress, req.headers);+ if (permitted) return next();+ return res.status(403).json({+ error: 'Host control requires an operator session, or a local connection when no password is set. Set an instance password to use it remotely.',+ code: 'HOST_CONTROL_FORBIDDEN',+ });+ };+// GET <statusPath> → does this sidecar need a password, and does the caller// already have one? The UI polls this to decide whether to show its login// overlay, so it must stay reachable unauthenticated.@@ -226,5 +246,5 @@ export const createSidecarAuthGate = ({res.json({ success: true });};- return { gate, handleStatus, handleLogin, handleLogout, isEnabled, isAuthenticated };+ return { gate, requireHostControl, handleStatus, handleLogin, handleLogout, isEnabled, isAuthenticated };};diff --git a/lib/sidecarAuthGate.test.js b/lib/sidecarAuthGate.test.jsindex 5f253e8230..0252ee0366 100644--- a/lib/sidecarAuthGate.test.js+++ b/lib/sidecarAuthGate.test.js@@ -57,7 +57,7 @@ describe('createSidecarAuthGate', () => {});describe('when the install has no password', () => {- it('passes every request through when settings.json is absent', async () => {+ it('passes the password gate when settings.json is absent', async () => {const { gate, isEnabled } = makeGate();expect(await isEnabled()).toBe(false);expect((await run(gate, req('/api/restart/portos-server'))).nexted).toBe(true);@@ -93,6 +93,23 @@ describe('createSidecarAuthGate', () => {});});+ describe('host-control session boundary', () => {+ it('does not allow expired primary or tampered sidecar sessions', async () => {+ await authOn();+ await writeSessions([{ tokenHash: hashToken('expired'), expiresAt: Date.now() - 1 }]);+ const { requireHostControl } = makeGate();+ for (const headers of [+ { cookie: 'portos_auth=expired' },+ { cookie: `${COOKIE}=${Date.now() + 60_000}.bad-signature` },+ ]) {+ const { res, nexted } = await run(requireHostControl, req('/api/stop/example-process', headers));+ expect(nexted).toBe(false);+ expect(res.statusCode).toBe(403);+ expect(res.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ }+ });+ });+describe('when the install is password protected', () => {beforeEach(authOn);diff --git a/server/services/authGate.js b/server/services/authGate.jsindex 4bd678ae2d..4cb5b8b0e2 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -1,9 +1,8 @@import { createHash, timingSafeEqual } from 'node:crypto';-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 { browserRequestRefusal, DEV_PROXY_CLIENT_ADDRESS_HEADER, extractBasicPassword } from '../../lib/portosAuthCore.js';+import { browserRequestRefusal, isLocalConnection, extractBasicPassword } from '../../lib/portosAuthCore.js';import { getSettings, settingsEvents } from './settings.js';import { isRegistryPublic } from '../lib/apiRegistry.js';import {@@ -224,23 +223,6 @@ 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.'));-};--// 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. Password-free// installs require a local connection (see isLocalConnection). Neither req.ip