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: require operator authority for app, CoS agent, git and scaffold routes (#8716)

[._.]/ Adam Eivyb30d302a27cb
diff --git a/client/src/hooks/useErrorNotifications.js b/client/src/hooks/useErrorNotifications.js
index be767b3b36..aeb4098ba4 100644
--- a/client/src/hooks/useErrorNotifications.js
+++ b/client/src/hooks/useErrorNotifications.js
@@ -91,11 +91,17 @@ export function useErrorNotifications() {
socket.on('error:notified', handleError);
socket.on('system:critical-error', handleCriticalError);
socket.on('error:recover:requested', handleRecoveryRequested);
+ // The server refuses `error:recover` from a non-local socket on a
+ // password-free install (HOST_CONTROL_FORBIDDEN); say so instead of
+ // leaving the optimistic "dispatched" toast as the last word.
+ const handleRecoveryError = (payload) => toast.error(payload?.message || 'Recovery agent could not be dispatched');
+ socket.on('error:recover:error', handleRecoveryError);
return () => {
socket.off('error:notified', handleError);
socket.off('system:critical-error', handleCriticalError);
socket.off('error:recover:requested', handleRecoveryRequested);
+ socket.off('error:recover:error', handleRecoveryError);
};
}, []);
diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.js
index cd98a6ec7a..1dc7a2b7f7 100644
--- a/client/src/services/apiCore.js
+++ b/client/src/services/apiCore.js
@@ -75,7 +75,12 @@ export async function request(endpoint, options = {}) {
try {
await throwApiError(response);
} catch (err) {
- if (!silent) {
+ // A host-control refusal (server: lib/hostControlRoutes.js) always
+ // surfaces, even from a silent caller: the operator pressed a button
+ // that ran nothing, and only this message says why.
+ if (err.code === 'HOST_CONTROL_FORBIDDEN') {
+ toast.error(err.message);
+ } else if (!silent) {
// Platform unavailability is a warning, not an error
if (err.code === 'PLATFORM_UNAVAILABLE') {
toast(err.message, { icon: '⚠️' });
diff --git a/docs/API.md b/docs/API.md
index 37369bb31e..afd2d989a7 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -38,6 +38,7 @@ PortOS can execute host commands and access private files. It must remain on the
- **Command policies**: Execution follows each surface's operator/unattended policy and agent execution profile (see `server/lib/commandSecurity.js`); these controls do not sandbox the entire application
- **Input validation**: All API inputs are validated using Zod schemas
- **Opt-in authentication**: Off by default (trusting private network/Tailscale), PortOS supports opt-in instance password authentication (enforced by `server/services/authGate.js`) gating `/api/*`, `/data/*`, and `/sdapi/*` via session cookies, Bearer tokens, or HTTP Basic credentials
+- **Host-control authority**: routes that execute on the host — `/api/commands/*` plus the audited `HOST_CONTROL_ROUTES` list in `server/lib/hostControlRoutes.js` (app create/start/restart, CoS agent queueing, git, scaffold, standardize) — and the matching Socket.IO events need an operator session, or a local connection when no password is set. A remote LAN/tailnet caller on a password-free install, and any peer or Basic credential, gets `403 HOST_CONTROL_FORBIDDEN`
Never publish PortOS administration, APIs, sockets, sidecars, or host controls through public tunnels, reverse proxies, or forwarding. A password or TLS does not make public deployment supported. For private deployments, consider:
- Binding to `127.0.0.1` instead of `0.0.0.0`
diff --git a/server/index.js b/server/index.js
index c9b8340189..ee4b80f682 100644
--- a/server/index.js
+++ b/server/index.js
@@ -116,7 +116,7 @@ import reviewRoutes from './routes/review.js';
import githubRoutes from './routes/github.js';
import settingsRoutes from './routes/settings.js';
import authRoutes from './routes/auth.js';
-import { allowSocketRequest, authGate, socketAuthGate } from './services/authGate.js';
+import { allowSocketRequest, authGate, hostControlRouteGate, socketAuthGate } from './services/authGate.js';
import telegramRoutes from './routes/telegram.js';
import updateRoutes from './routes/update.js';
import loopsRoutes from './routes/loops.js';
@@ -274,6 +274,9 @@ app.set('io', io);
// except the small public set in services/authGate.js (auth status/whoami/login/
// logout + /api/system/health). No-op when auth is off.
app.use(authGate);
+// Host-executing routes (lib/hostControlRoutes.js) additionally need operator
+// authority: a session, or a local connection on a password-free install.
+app.use(hostControlRouteGate);
// Body limit is set slightly above the 50MB combined base64 cap enforced by sendMessageSchema
// so the Zod validation (not the body parser) is the binding constraint for attachment payloads.
diff --git a/server/lib/README.md b/server/lib/README.md
index e5014615f1..50245bae0c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -622,6 +622,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `apiAccessPolicy.js` | Shared always-public path, gated non-`/api` prefix, and peer-credential federation surface (`PEER_API_SURFACE`, `isPeerApiRequestAllowed`) policy consumed by `authGate` and API discovery. |
| `apiCatalog.js` | Searchable projection of the Express route inventory (`getApiRouteCatalog()` from `apiRouteGraph.js`): domain, access, side-effect, contract coverage, summaries, and Express-to-OpenAPI path conversion. |
+| `hostControlRoutes.js` | The audited `HOST_CONTROL_ROUTES` list of HTTP routes that execute on the host (app lifecycle, CoS agent queueing, git, scaffold, standardize) plus `hostControlRouteFor` / `isHostControlRoute`; `authGate.js#hostControlRouteGate` applies `requireHostControl` to every entry. The socket twin is `HOST_CONTROL_SOCKET_EVENTS` in `services/socket.js`. |
| `apiRouteGraph.js` | Static scan of the mounted HTTP route graph — `server/index.js` `app.use('/api/…', router)` mounts → route-module imports → `router.use(prefix, child)` → `router.<method>('<path>')`, including aliased mounts, local subrouters, factory returns and composed `toolkit.routes.<x>` routers. `buildApiRouteCatalog({ repoRoot? })` → `{ derivedFrom, mounts, routes: [{ method, path, mountPath, sources }], stats }`; `getApiRouteCatalog()` derives it on first use and caches it for the process (read by the API Explorer, the internal OpenAPI document and `apiRouteParity.test.js`); `scanRouteGraph()` adds `declarationKeys` / `duplicateDeclarationKeys` (`routeDeclarationKey`) for the coverage guard in `apiRouteGraph.test.js`. Never committed — see "Generated manifests" in `server/AGENTS.md`. |
| `socketEventCatalog.js` | Searchable projection of the cached Socket.IO inventory: direction, domain, and runtime-schema coverage. |
| `sourceScan.js` | Lexer-assisted primitives shared by the whole-tree source-scan guard suites, so the timer rule and the socket rule cannot drift on what "owns its rejection" means. `blankLiterals(src)` blanks comment/string/template/regex CONTENT to spaces while preserving length, so a brace inside a literal cannot skew a bracket walk and a caller can still read a literal (a socket event name) out of the original string at the same offset; `matchBracket(src, open)` returns the index past the matching `)`/`]`/`}`; `parseCallbackAt(blanked, from, limit)` parses the function expression at `from` (`async`/`function`/either arrow spelling, skipping the parameter list as a unit so a `= {}` default is not mistaken for the body) and returns `{isAsync, start, text}`; `unguardedAwaits(body)` returns the awaited chains that neither sit inside a `try`/`catch` nor END in `.catch(…)`. `blankComments(src)` is the weaker LINE-based stripper the per-line `child_process` rule needs. `blankCommentBodies(src)` is the complement — comments blanked, literal TEXT kept — for a caller that reads a message string and must not see a marker written in a comment beside it. Callers: `childProcess.guards.test.js`, `server/timerCallbackConventions.test.js`, `server/logLevelConventions.test.js`, `server/sockets/asyncHandlerGuard.test.js`, `server/process-safety-net.test.js`. |
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
new file mode 100644
index 0000000000..5ca51a2ee9
--- /dev/null
+++ b/server/lib/hostControlRoutes.js
@@ -0,0 +1,124 @@
+/**
+ * The audited list of HTTP routes that execute on the host (#8716).
+ *
+ * Each one needs operator authority — `requireHostControl` in
+ * services/authGate.js, applied to every route here by `hostControlRouteGate`:
+ * an operator session when a password is set, or a local connection when none
+ * is. A peer credential (scoped token or legacy Basic) never qualifies, and a
+ * remote LAN/tailnet caller on a password-free install is refused (#8226).
+ * The socket twin is HOST_CONTROL_SOCKET_EVENTS in services/socket.js;
+ * `/api/commands/*` mounts `requireHostControl` per route in routes/commands.js.
+ *
+ * A route belongs here when it runs a process, git, npm, gh or a CoS agent on
+ * the host, or when it sets what one will run (a repo path, a start command, a
+ * task prompt, a shell job). Read-only GETs stay open. Mutating routes in the
+ * same families that are deliberately left OUT:
+ * - apps: delete/archive/unarchive, detect-icons, scope-adherence — they
+ * change only PortOS's own records or read files; nothing runs.
+ * - CoS: stop/pause/kill/terminate/delete and feedback — they reduce or
+ * annotate execution, never start it; task reorder/refresh/enhance,
+ * templates, challenge and goal-fidelity reports — records and LLM text
+ * only, and sub-agents call the latter from loopback anyway; job toggle —
+ * arms a job the operator authored through the gated create/update routes.
+ * - standardize/analyze — reads the repo; `apply` and `backup` are gated.
+ *
+ * Patterns are `METHOD /path`, with Express-style `:param` (one segment) and
+ * `*name` (the rest of the path). Matching is case-insensitive and ignores one
+ * trailing slash, exactly as Express routing does, so a request cannot reach a
+ * listed handler by a spelling this list does not match.
+ */
+
+export const HOST_CONTROL_ROUTES = Object.freeze([
+ // 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.
+ 'POST /api/apps',
+ 'PUT /api/apps/:id',
+ 'POST /api/apps/:id/start',
+ 'POST /api/apps/:id/stop',
+ 'POST /api/apps/:id/restart',
+ 'POST /api/apps/:id/build',
+ 'POST /api/apps/:id/native-launch',
+ 'POST /api/apps/:id/refresh-config',
+ 'POST /api/apps/:id/open-editor',
+ 'POST /api/apps/:id/open-claude',
+ 'POST /api/apps/:id/open-folder',
+ 'POST /api/apps/:id/open-xcode',
+ // Edits and commits inside the app's repo (git runs its hooks) or runs gh.
+ 'POST /api/apps/:id/upgrade-tls',
+ 'POST /api/apps/:id/fix-vite-hosts',
+ 'POST /api/apps/:id/xcode-scripts/install',
+ 'PUT /api/apps/:id/documents/*docPath',
+ 'POST /api/apps/:id/quality-snapshot',
+ 'POST /api/apps/:id/repository-sources/sync-fork',
+ 'POST /api/apps/:id/pull-requests/:number/resolve',
+ 'POST /api/apps/:id/pull-requests/:number/merge',
+ 'POST /api/apps/:id/pull-requests/:number/review',
+ 'POST /api/apps/:id/pull-requests/:number/do-review',
+ // Enable or queue CoS agent work against an app.
+ 'POST /api/apps/:id/launch-videos',
+ 'POST /api/apps/:id/quality-schedule/apply',
+ 'PUT /api/apps/bulk-task-type/:taskType',
+ 'PUT /api/apps/:id/task-types/all',
+ 'PUT /api/apps/:id/task-types/:taskType',
+
+ // CoS: queue, release or steer an agent that runs shell commands in a
+ // worktree, or a job that runs a shell command directly.
+ 'POST /api/cos/start',
+ 'POST /api/cos/resume',
+ 'POST /api/cos/evaluate',
+ 'POST /api/cos/tasks',
+ 'PUT /api/cos/tasks/:id',
+ 'POST /api/cos/tasks/slashdo',
+ 'POST /api/cos/tasks/jira-ticket',
+ 'POST /api/cos/tasks/:id/approve',
+ 'POST /api/cos/tasks/:id/spawn',
+ 'POST /api/cos/agents/:id/resume',
+ 'POST /api/cos/agents/:id/relaunch',
+ 'POST /api/cos/agents/:id/btw',
+ 'POST /api/cos/jobs',
+ 'PUT /api/cos/jobs/:id',
+ 'POST /api/cos/jobs/:id/trigger',
+ 'PUT /api/cos/schedule/task/:taskType',
+ 'POST /api/cos/schedule/trigger',
+ 'POST /api/cos/schedule/maintenance-runs',
+ 'POST /api/cos/schedule/maintenance-runs/:id/resume',
+ 'POST /api/cos/tools/call',
+
+ // Git in a caller-named directory. Every POST is gated, reads included: git
+ // runs repository-configured programs (hooks, fsmonitor) even for `status`.
+ 'POST /api/git/*rest',
+
+ // Scaffolding writes a new repo and runs git/npm in it.
+ 'POST /api/scaffold',
+ 'POST /api/scaffold/templates/create',
+
+ // HTTP twins of the gated `app:standardize` / `standardize:start` events.
+ 'POST /api/standardize/apply',
+ 'POST /api/standardize/backup',
+]);
+
+const escapeRegExp = (text) => text.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
+
+const compileSegment = (segment) => {
+ if (segment.startsWith(':')) return '[^/]+';
+ if (segment.startsWith('*')) return '.+';
+ return escapeRegExp(segment);
+};
+
+const compileRoute = (route) => {
+ const [method, path] = route.split(' ');
+ const body = path.split('/').slice(1).map(compileSegment).join('/');
+ return { route, method, pattern: new RegExp(`^/${body}/?$`, 'i') };
+};
+
+const COMPILED_ROUTES = HOST_CONTROL_ROUTES.map(compileRoute);
+
+/** The HOST_CONTROL_ROUTES entry that `method path` (an Express `req.method` / `req.path`) matches, or null. */
+export const hostControlRouteFor = (method, path) => {
+ if (typeof method !== 'string' || typeof path !== 'string') return null;
+ const verb = method.toUpperCase();
+ return COMPILED_ROUTES.find((entry) => entry.method === verb && entry.pattern.test(path))?.route ?? null;
+};
+
+/** Whether `method path` executes on the host. */
+export const isHostControlRoute = (method, path) => hostControlRouteFor(method, path) !== null;
diff --git a/server/lib/hostControlRoutes.test.js b/server/lib/hostControlRoutes.test.js
new file mode 100644
index 0000000000..72a2d5fb5e
--- /dev/null
+++ b/server/lib/hostControlRoutes.test.js
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import { getApiRouteCatalog } from './apiRouteGraph.js';
+import { HOST_CONTROL_ROUTES, hostControlRouteFor, isHostControlRoute } from './hostControlRoutes.js';
+
+describe('HOST_CONTROL_ROUTES (#8716)', () => {
+ it('names only mounted routes, so a rename cannot silently ungate one', () => {
+ // A catalog path keeps its `:param` / `*wildcard` tokens, which the
+ // compiled patterns accept as ordinary segment text.
+ const reached = new Set(getApiRouteCatalog().routes
+ .map(({ method, path }) => hostControlRouteFor(method, path))
+ .filter(Boolean));
+ expect(HOST_CONTROL_ROUTES.filter((route) => !reached.has(route))).toEqual([]);
+ });
+
+ it('matches the spellings Express routes to the same handler, and nothing wider', () => {
+ expect(isHostControlRoute('post', '/API/Apps/example-app/START/')).toBe(true);
+ expect(isHostControlRoute('POST', '/api/git/status')).toBe(true);
+ expect(isHostControlRoute('PUT', '/api/apps/example-app/documents/docs/example.md')).toBe(true);
+ // Read-only GETs and neighbouring paths stay open.
+ expect(isHostControlRoute('GET', '/api/apps/example-app/start')).toBe(false);
+ expect(isHostControlRoute('GET', '/api/git/submodules/status')).toBe(false);
+ expect(isHostControlRoute('POST', '/api/apps/example-app/start-example')).toBe(false);
+ expect(isHostControlRoute('POST', '/api/apps/example-app/archive')).toBe(false);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index cc4ff3c92e..423a30f92c 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -605,6 +605,7 @@ export * from './viteAllowedHosts.js';
export * from './apiAccessPolicy.js';
export * from './apiCatalog.js';
export * from './apiRouteGraph.js';
+export * from './hostControlRoutes.js';
export * from './socketEventCatalog.js';
export * from './sourceScan.js';
export * from './apiOperationContracts.js';
diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.js
index 8a414e9462..4f31834daf 100644
--- a/server/routes/apps/lifecycle.test.js
+++ b/server/routes/apps/lifecycle.test.js
@@ -10,6 +10,16 @@ import { join } from 'path';
// runner, which is why this suite passed locally and 400'd there.
const REAL_DIR = tmpdir();
import lifecycleRoutes from './lifecycle.js';
+import { authGate, hostControlRouteGate } from '../../services/authGate.js';
+import { errorMiddleware } from '../../lib/errorHandler.js';
+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../../lib/portosAuthCore.js';
+
+// The real authGate, pinned to a password-free install so the developer's own
+// settings cannot change what the host-control cases below observe.
+vi.mock('../../services/auth.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ isAuthEnabled: vi.fn().mockResolvedValue(false),
+}));
// Mock the services this router touches. appBuilder is intentionally NOT mocked
// so the build-command validation branch (INVALID_BUILD_COMMAND) runs for real.
@@ -525,3 +535,58 @@ describe('Apps Lifecycle Routes', () => {
});
});
});
+
+describe('host-control gate on app lifecycle (#8716)', () => {
+ const mockApp = {
+ id: 'app-001', name: 'Test App', repoPath: '/path/to/repo',
+ pm2ProcessNames: ['test-app'], startCommands: ['npm run dev'],
+ };
+
+ const buildGatedApp = (remoteAddress) => {
+ const gated = express();
+ gated.use((req, _res, next) => {
+ // Model the server's socket observation, never an HTTP header.
+ Object.defineProperty(req.socket, 'remoteAddress', { value: remoteAddress });
+ next();
+ });
+ gated.use(authGate);
+ gated.use(hostControlRouteGate);
+ gated.use(express.json());
+ gated.use('/api/apps', lifecycleRoutes);
+ gated.use(errorMiddleware);
+ return gated;
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.startWithCommand.mockResolvedValue({ success: true });
+ pm2Service.restartApp.mockResolvedValue({ success: true });
+ });
+
+ it('refuses a remote caller on a password-free install before PM2 runs anything', async () => {
+ const remote = buildGatedApp('192.0.2.10');
+ const local = buildGatedApp('127.0.0.1');
+ for (const action of ['start', 'restart']) {
+ for (const [app, headers] of [[remote, {}], [local, { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }]]) {
+ const pending = request(app).post(`/api/apps/app-001/${action}`);
+ for (const [key, value] of Object.entries(headers)) pending.set(key, value);
+ const response = await pending;
+ expect(response.status).toBe(403);
+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+ }
+ }
+ expect(appsService.getAppById).not.toHaveBeenCalled();
+ expect(pm2Service.startWithCommand).not.toHaveBeenCalled();
+ expect(pm2Service.restartApp).not.toHaveBeenCalled();
+ });
+
+ it('keeps a local caller, direct or through the dev proxy, able to start the app', async () => {
+ const local = buildGatedApp('127.0.0.1');
+ const direct = await request(local).post('/api/apps/app-001/start');
+ const proxied = await request(local).post('/api/apps/app-001/start')
+ .set(DEV_PROXY_CLIENT_ADDRESS_HEADER, '::ffff:127.0.0.1');
+ expect([direct.status, proxied.status]).toEqual([200, 200]);
+ expect(pm2Service.startWithCommand).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.js
index 3045915326..8bb1aaf93d 100644
--- a/server/routes/cosTaskRoutes.test.js
+++ b/server/routes/cosTaskRoutes.test.js
@@ -12,7 +12,7 @@
* assert a PERSISTED row rather than a mock call.
*/
-import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import express from 'express';
import { rmSync } from 'node:fs';
import { join } from 'node:path';
@@ -74,6 +74,7 @@ import { getAssignableInstances } from '../services/instances.js';
import { getAppById, getAppWorkTracker } from '../services/apps.js';
import { resolveManagedAppIssueTarget } from '../services/managedAppRepositories.js';
import cosTaskRoutes from './cosTaskRoutes.js';
+import { authGate, hostControlRouteGate } from '../services/authGate.js';
import { listUserActions } from '../services/userActions.js';
import { __resetInvestigationCircuit } from '../services/investigationTaskProducer.js';
import { clientInvestigationFingerprint } from '../lib/investigationTasks.js';
@@ -560,3 +561,61 @@ describe('POST /api/cos/goal-fidelity/false-positive', () => {
expect(res.body).toMatchObject({ queued: false, reason: expect.stringContaining('disabled') });
});
});
+
+describe('host-control gate on CoS task queueing (#8716)', () => {
+ // The real authGate over the temp data root: no password until a case sets one.
+ const buildGatedApp = (remoteAddress) => {
+ const app = express();
+ app.use((req, _res, next) => {
+ Object.defineProperty(req.socket, 'remoteAddress', { value: remoteAddress });
+ next();
+ });
+ app.use(authGate);
+ app.use(hostControlRouteGate);
+ app.use(express.json());
+ app.use('/api/cos', cosTaskRoutes);
+ app.use(errorMiddleware);
+ return app;
+ };
+
+ afterEach(async () => {
+ rmSync(join(tempRoot, 'settings.json'), { force: true });
+ rmSync(join(tempRoot, 'auth-sessions.json'), { force: true });
+ });
+
+ it('refuses a remote password-free caller without queueing or spawning a task', async () => {
+ const remote = buildGatedApp('192.0.2.10');
+ for (const [path, body] of [['/api/cos/tasks', { description: 'run a shell command' }], ['/api/cos/tasks/task-1/spawn', {}], ['/api/cos/tasks/task-1/approve', {}]]) {
+ const res = await request(remote).post(path).send(body);
+ expect(res.status).toBe(403);
+ expect(res.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+ }
+ expect(cos.addTask).not.toHaveBeenCalled();
+ expect(cos.forceSpawnTask).not.toHaveBeenCalled();
+ expect(cos.approveTask).not.toHaveBeenCalled();
+ });
+
+ it('keeps a local password-free caller able to queue a task', async () => {
+ const res = await request(buildGatedApp('127.0.0.1')).post('/api/cos/tasks').send({ description: 'local work' });
+ expect(res.status).toBe(200);
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('with a password set, Basic credentials are refused and an operator session is not', async () => {
+ const auth = await import('../services/auth.js');
+ const { token } = await auth.setPassword({ newPassword: 'example-instance-password' });
+ const remote = buildGatedApp('192.0.2.10');
+ const basic = await request(remote).post('/api/cos/tasks')
+ .set('Authorization', `Basic ${Buffer.from(':example-instance-password').toString('base64')}`)
+ .send({ description: 'peer work' });
+ expect(basic.status).toBe(403);
+ expect(basic.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+ expect(cos.addTask).not.toHaveBeenCalled();
+
+ const session = await request(remote).post('/api/cos/tasks')
+ .set('Authorization', `Bearer ${token}`)
+ .send({ description: 'operator work' });
+ expect(session.status).toBe(200);
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/services/authGate.js b/server/services/authGate.js
index 84e2a1838a..cb5fddaaae 100644
--- a/server/services/authGate.js
+++ b/server/services/authGate.js
@@ -13,6 +13,7 @@ import {
isPeerBasicBootstrapRequest,
} from '../lib/apiAccessPolicy.js';
import { sendErrorResponse, ServerError } from '../lib/errorHandler.js';
+import { isHostControlRoute } from '../lib/hostControlRoutes.js';
import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';
import { loadData as loadInstances } from './instanceIdentity.js';
@@ -256,6 +257,14 @@ export const requireHostControl = (req, res, next) => {
}));
};
+// Applies requireHostControl to every route in the audited
+// HOST_CONTROL_ROUTES list (lib/hostControlRoutes.js). Mounted once, right
+// after authGate, so the list — not each route file — is the one place that
+// says which HTTP routes execute on the host.
+export const hostControlRouteGate = (req, res, next) => (
+ isHostControlRoute(req.method, req.path) ? requireHostControl(req, res, next) : next()
+);
+
// 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
diff --git a/server/services/peerSocketRelayAuth.test.js b/server/services/peerSocketRelayAuth.test.js
index 8f8166e58f..79a0c465c7 100644
--- a/server/services/peerSocketRelayAuth.test.js
+++ b/server/services/peerSocketRelayAuth.test.js
@@ -86,6 +86,8 @@ const startServer = async () => {
});
socket.on('iterm:input', () => reached.push(['iterm:input']));
socket.on('app:update', () => reached.push(['app:update']));
+ // Stand-in for socket.js's error:recover, which queues a recovery agent (#8716).
+ socket.on('error:recover', () => reached.push(['error:recover']));
});
await new Promise((resolve) => httpServer.listen(0, resolve));
port = httpServer.address().port;
@@ -213,6 +215,10 @@ describe('host-control socket events need operator authority (#8708)', () => {
client.emit('app:update', { appId: 'example-app' });
expect(await updateRefused).toMatchObject({ code: 'HOST_CONTROL_FORBIDDEN', appId: 'example-app' });
+ const recoverRefused = waitFor(client, 'error:recover:error');
+ client.emit('error:recover', { code: 'EXAMPLE_ERROR' });
+ expect(await recoverRefused).toMatchObject({ code: 'HOST_CONTROL_FORBIDDEN' });
+
// Read-only subscriptions stay open, and the refusals did not disconnect.
const subscribed = waitFor(client, 'cos:subscribed');
client.emit('cos:subscribe');
diff --git a/server/services/socket.js b/server/services/socket.js
index 932bf93102..fa71d3b3cd 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -140,7 +140,9 @@ const PEER_RELAY_ALLOWED_EVENTS = new Set(['cos:subscribe', 'cos:unsubscribe']);
// 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']);
+// `error:recover` queues a recovery agent that runs shell commands (#8716).
+// The HTTP twin of this set is HOST_CONTROL_ROUTES in lib/hostControlRoutes.js.
+const HOST_CONTROL_SOCKET_EVENTS = new Set(['app:update', 'app:standardize', 'app:deploy', 'standardize:start', 'error:recover']);
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)));