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 host control for agent, loop, provider and policy writes (#8721)

[._.]/ Adam Eivy88d6542ff534
diff --git a/docs/API.md b/docs/API.md
index afd2d989a7..cfe89b5340 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -38,7 +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`
+- **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, feature agents, loops, GSD, local code review, provider execution config and runtime installs, autopilot start) — the execution-policy slices of `PUT /api/settings` and `PUT /api/cos/config`, 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 ee4b80f682..b1cd4b92d6 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, hostControlRouteGate, socketAuthGate } from './services/authGate.js';
+import { allowSocketRequest, authGate, hostControlBodyGate, hostControlRouteGate, socketAuthGate } from './services/authGate.js';
import telegramRoutes from './routes/telegram.js';
import updateRoutes from './routes/update.js';
import loopsRoutes from './routes/loops.js';
@@ -283,6 +283,8 @@ app.use(hostControlRouteGate);
// Every per-file upload cap is derived from this value — see lib/uploadLimits.js.
app.use(express.json({ limit: JSON_BODY_LIMIT }));
app.use(express.urlencoded({ limit: JSON_BODY_LIMIT, extended: true }));
+// …and the policy-store slices that change execution, which need the body.
+app.use(hostControlBodyGate);
// The viewer and vendored noVNC modules are outside /api so WKWebView can load
// them without persisting the user's PortOS password. The viewer URL itself is
diff --git a/server/lib/README.md b/server/lib/README.md
index a7cc828ea9..7023335637 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -623,7 +623,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`. |
+| `hostControlRoutes.js` | The audited `HOST_CONTROL_ROUTES` list of HTTP routes that execute on the host (app lifecycle, CoS agent queueing, git, scaffold, standardize, feature agents, loops, GSD, local review, provider execution config, autopilot start) plus `hostControlRouteFor` / `isHostControlRoute`; `authGate.js#hostControlRouteGate` applies `requireHostControl` to every entry. `hostControlBodyKeys` names the execution-policy keys of a `PUT /api/settings` / `PUT /api/cos/config` body (`HOST_CONTROL_SETTINGS_SLICES`, `HOST_CONTROL_OPEN_COS_CONFIG_KEYS`), gated by `authGate.js#hostControlBodyGate`. 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
index e95e5a1ca0..0013a578c1 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -20,6 +20,30 @@
* templates, challenge and goal-fidelity reports — records and LLM text
* only, and sub-agents call the latter from loopback anyway.
* - standardize/analyze — reads the repo; `apply` and `backup` are gated.
+ * - feature agents and loops: pause/stop/delete — they reduce execution.
+ * - code-review/cli-outcome — records a reviewer verdict; nothing runs.
+ * - providers (#8721): the gated writes choose the binary, its args, the
+ * endpoint and credentials a tool-running CLI harness talks to, or which
+ * harnesses and wrapper CLIs may run at all. Left open: DELETEs (a
+ * connection still in use is refused with a 409), fleet-host/stop and the
+ * Codex login cancel (they stop execution), the fleet key reveals (a read
+ * of a secret, not execution), binding create/edit/unlink (minted routes
+ * arrive disabled; unlink clones the endpoint the binding already had;
+ * link/preview only reads), the model-comparison import (records only),
+ * model pins/aliases, derive and status recovery (they choose among
+ * already-configured values), and test, vision, refresh-models and
+ * refresh-catalog (they run an already-configured provider on a fixed
+ * prompt, as every AI feature does).
+ * - pipeline and FableLoom: only autopilot start is gated — with gap filing
+ * or self-improvement on it queues CoS agents. Every other pipeline route
+ * generates text or media through an already-configured provider, the
+ * same as any AI feature; the caller never chooses what runs.
+ * - settings: feature toggles and the Eidoverse host bridge (they arm
+ * PortOS's own integrations or open a listener), orchestration profiles,
+ * AI assignments and credentials (they choose among configured providers
+ * or store a key). The `PUT /api/settings` and `PUT /api/cos/config`
+ * slices that change execution policy are gated per request body — see
+ * HOST_CONTROL_SETTINGS_SLICES and HOST_CONTROL_OPEN_COS_CONFIG_KEYS.
*
* Patterns are `METHOD /path`, with Express-style `:param` (one segment) and
* `*name` (the rest of the path). Matching is case-insensitive and ignores one
@@ -98,6 +122,86 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
// HTTP twins of the gated `app:standardize` / `standardize:start` events.
'POST /api/standardize/apply',
'POST /api/standardize/backup',
+
+ // Feature agents and loops (#8721): create/edit set the prompt, working
+ // directory and provider an agent runs with; the rest start one.
+ 'POST /api/feature-agents',
+ 'PUT /api/feature-agents/:id',
+ 'POST /api/feature-agents/:id/start',
+ 'POST /api/feature-agents/:id/resume',
+ 'POST /api/feature-agents/:id/trigger',
+ 'POST /api/loops',
+ 'PUT /api/loops/:id',
+ 'POST /api/loops/:id/resume',
+ 'POST /api/loops/:id/trigger',
+
+ // GSD: queue CoS agent work against an app, or write into its repo.
+ 'POST /api/cos/gsd/projects/:appId/concerns/tasks',
+ 'POST /api/cos/gsd/projects/:appId/phases/:phaseId/action',
+ 'PUT /api/cos/gsd/projects/:appId/documents/:docName',
+
+ // Runs the configured local or provider reviewer on a caller-supplied diff.
+ 'POST /api/code-review/local',
+
+ // Providers: which binary runs, with which args, against which endpoint and
+ // credentials; installing or launching runtimes; signing a CLI in or out.
+ // `PUT /api/providers/:id` also matches `/active` and `/bootstraps`.
+ 'POST /api/providers',
+ 'PUT /api/providers/:id',
+ 'POST /api/providers/:id/modes/tui',
+ 'PATCH /api/providers/routes/:providerId',
+ 'POST /api/providers/connections',
+ 'PATCH /api/providers/connections/:id',
+ 'POST /api/providers/services',
+ 'PATCH /api/providers/services/:slug',
+ 'POST /api/providers/bindings/:id/link',
+ 'PUT /api/providers/harnesses/:id',
+ 'POST /api/providers/presets',
+ 'POST /api/providers/codex/account/login',
+ 'POST /api/providers/codex/account/logout',
+ 'POST /api/providers/readiness/setup',
+ 'POST /api/providers/readiness/serve-model',
+ 'POST /api/providers/runtimes/install',
+ 'POST /api/providers/opencode/install',
+ 'POST /api/providers/fleet-host/setup',
+
+ // Autopilots and support requests that queue CoS agents.
+ 'POST /api/pipeline/series/:id/autopilot/start',
+ 'POST /api/fableloom/:id/editorial/autopilot/start',
+ 'POST /api/image-video/models/support-request',
+
+ // Eidoverse: clone and install a caller-named repo, or repoint it.
+ 'POST /api/settings/features/eidoverse/install',
+ 'PUT /api/settings/features/eidoverse/source',
+]);
+
+/**
+ * `PUT /api/settings` slices that set what runs or the guardrails around it:
+ * harness enablement and wrapper CLIs, the code-review chain, the untrusted
+ * content screen in front of agent work, scheduled self-update, and scheduled
+ * series autopilots. The store is polymorphic, so its other slices stay open.
+ */
+export const HOST_CONTROL_SETTINGS_SLICES = Object.freeze([
+ 'autoUpdate',
+ 'codeReview',
+ 'credentialBootstraps',
+ 'harnesses',
+ 'seriesAutopilot',
+ 'untrustedContent',
+]);
+
+/**
+ * The only `PUT /api/cos/config` keys a remote caller on a password-free
+ * install may change. Nearly all of CoS config is execution policy (autonomy,
+ * concurrency, MCP server commands, the Persistent Mind's capabilities), so
+ * this list is the inverse: an unlisted key, including one added later, is
+ * gated.
+ */
+export const HOST_CONTROL_OPEN_COS_CONFIG_KEYS = Object.freeze([
+ 'avatarStyle',
+ 'dynamicAvatar',
+ 'embeddingModel',
+ 'embeddingProviderId',
]);
const compileSegment = (segment) => {
@@ -114,6 +218,23 @@ const compileRoute = (route) => {
const COMPILED_ROUTES = HOST_CONTROL_ROUTES.map(compileRoute);
+const bodyKeys = (body) => (body && typeof body === 'object' && !Array.isArray(body) ? Object.keys(body) : []);
+
+// The two polymorphic policy stores, gated per body key rather than per route.
+// `hostControlBodyGate` in services/authGate.js applies these after the body
+// parser, since `hostControlRouteGate` runs before it.
+const COMPILED_BODY_ROUTES = [
+ ['PUT /api/settings', (body) => bodyKeys(body).filter((key) => HOST_CONTROL_SETTINGS_SLICES.includes(key))],
+ ['PUT /api/cos/config', (body) => bodyKeys(body).filter((key) => !HOST_CONTROL_OPEN_COS_CONFIG_KEYS.includes(key))],
+].map(([route, pick]) => ({ ...compileRoute(route), pick }));
+
+/** The host-control keys a request body names, for `method path` of a policy store; [] elsewhere. */
+export const hostControlBodyKeys = (method, path, body) => {
+ if (typeof method !== 'string' || typeof path !== 'string') return [];
+ const verb = method.toUpperCase();
+ return COMPILED_BODY_ROUTES.find((entry) => entry.method === verb && entry.pattern.test(path))?.pick(body) ?? [];
+};
+
/** 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;
diff --git a/server/lib/hostControlRoutes.test.js b/server/lib/hostControlRoutes.test.js
index 72a2d5fb5e..eabb3035b6 100644
--- a/server/lib/hostControlRoutes.test.js
+++ b/server/lib/hostControlRoutes.test.js
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { getApiRouteCatalog } from './apiRouteGraph.js';
-import { HOST_CONTROL_ROUTES, hostControlRouteFor, isHostControlRoute } from './hostControlRoutes.js';
+import { HOST_CONTROL_ROUTES, hostControlBodyKeys, hostControlRouteFor, isHostControlRoute } from './hostControlRoutes.js';
describe('HOST_CONTROL_ROUTES (#8716)', () => {
it('names only mounted routes, so a rename cannot silently ungate one', () => {
@@ -21,5 +21,9 @@ describe('HOST_CONTROL_ROUTES (#8716)', () => {
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);
+ // The policy-store body gate matches the same spellings (#8721).
+ expect(hostControlBodyKeys('put', '/API/Settings/', { harnesses: {}, location: {} })).toEqual(['harnesses']);
+ expect(hostControlBodyKeys('PUT', '/api/COS/config', { avatarStyle: 'svg', mcpServers: [] })).toEqual(['mcpServers']);
+ expect(hostControlBodyKeys('PUT', '/api/settings/credentials/example', { harnesses: {} })).toEqual([]);
});
});
diff --git a/server/routes/hostControlFamilies.test.js b/server/routes/hostControlFamilies.test.js
new file mode 100644
index 0000000000..af96917f8a
--- /dev/null
+++ b/server/routes/hostControlFamilies.test.js
@@ -0,0 +1,154 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express, { Router } from 'express';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { request } from '../lib/testHelper.js';
+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';
+
+// The real authGate and both host-control gates over the #8721 families,
+// pinned to a password-free install so the developer's own settings cannot
+// change what these cases observe.
+vi.mock('../services/auth.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ isAuthEnabled: vi.fn().mockResolvedValue(false),
+}));
+
+const featureAgents = vi.hoisted(() => ({
+ createFeatureAgent: vi.fn(),
+ activateFeatureAgent: vi.fn(),
+ triggerFeatureAgent: vi.fn(),
+ stopFeatureAgent: vi.fn(),
+}));
+vi.mock('../services/featureAgents.js', () => featureAgents);
+
+const loops = vi.hoisted(() => ({
+ createLoop: vi.fn(),
+ triggerLoop: vi.fn(),
+ stopLoop: vi.fn(),
+}));
+vi.mock('../services/loops.js', () => loops);
+
+const installer = vi.hoisted(() => ({
+ getProviderRuntime: vi.fn(),
+ getProviderRuntimeStatus: vi.fn(),
+ getProviderRuntimeStatuses: vi.fn(),
+ spawnRuntimeInstaller: vi.fn(),
+ stopRuntimeInstaller: vi.fn(),
+ describeRuntimeInstall: vi.fn(),
+ buildRuntimeActionCommand: vi.fn(),
+ RUNTIME_ACTIONS: ['install', 'update', 'uninstall'],
+}));
+vi.mock('../services/providerRuntimeInstaller.js', () => installer);
+
+import { authGate, hostControlBodyGate, hostControlRouteGate } from '../services/authGate.js';
+import featureAgentsRoutes from './featureAgents.js';
+import loopsRoutes from './loops.js';
+import { createPortOSProviderRoutes } from './providers.js';
+
+// Stand-ins for the two policy-store handlers: the gate, not the store, is
+// under test, and a handler that never runs is the proof nothing was written.
+const settingsWrite = vi.fn((req, res) => res.json({ saved: Object.keys(req.body) }));
+const cosConfigWrite = vi.fn((req, res) => res.json({ saved: Object.keys(req.body) }));
+
+// Mirrors the order server/index.js mounts them in.
+const buildGatedApp = (remoteAddress) => {
+ const app = express();
+ app.use((req, _res, next) => {
+ // Model the server's socket observation, never an HTTP header.
+ Object.defineProperty(req.socket, 'remoteAddress', { value: remoteAddress });
+ next();
+ });
+ app.use(authGate);
+ app.use(hostControlRouteGate);
+ app.use(express.json());
+ app.use(hostControlBodyGate);
+ app.use('/api/feature-agents', featureAgentsRoutes);
+ app.use('/api/loops', loopsRoutes);
+ app.use('/api/providers', createPortOSProviderRoutes({ services: { providers: {} }, routes: { providers: Router() } }));
+ app.put('/api/settings', settingsWrite);
+ app.put('/api/cos/config', cosConfigWrite);
+ app.use(errorMiddleware);
+ return app;
+};
+
+const remote = () => buildGatedApp('192.0.2.10');
+const local = () => buildGatedApp('127.0.0.1');
+
+// `proxyClient` is the address the Vite dev proxy reports for the browser it
+// forwarded, which is what makes a loopback socket a remote caller.
+const call = (app, [method, path, body = {}], proxyClient) => {
+ const pending = request(app)[method](path);
+ if (proxyClient) pending.set(DEV_PROXY_CLIENT_ADDRESS_HEADER, proxyClient);
+ return pending.send(body);
+};
+
+const expectRefused = (response) => {
+ expect(response.status).toBe(403);
+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+};
+
+const REFUSED_WRITES = [
+ ['post', '/api/feature-agents', { name: 'Example agent' }],
+ ['post', '/api/feature-agents/agent-1/start', {}],
+ ['post', '/api/feature-agents/agent-1/trigger', {}],
+ ['post', '/api/loops', { prompt: 'run the example', interval: '5m' }],
+ ['post', '/api/loops/loop-1/trigger', {}],
+ ['post', '/api/providers/runtimes/install?runtime=codex', {}],
+ ['put', '/api/settings', { harnesses: { claude: { enabled: true } } }],
+ ['put', '/api/cos/config', { avatarStyle: 'svg', maxConcurrentAgents: 9 }],
+];
+
+describe('host-control gate on agent, loop, provider and policy writes (#8721)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ featureAgents.activateFeatureAgent.mockResolvedValue({ id: 'agent-1', status: 'active' });
+ featureAgents.stopFeatureAgent.mockResolvedValue({ id: 'agent-1', status: 'stopped' });
+ loops.triggerLoop.mockResolvedValue({ id: 'loop-1' });
+ loops.stopLoop.mockResolvedValue({ id: 'loop-1', status: 'stopped' });
+ });
+
+ it('refuses a remote password-free caller, direct or proxied, before anything runs or is written', async () => {
+ for (const write of REFUSED_WRITES) {
+ expectRefused(await call(remote(), write));
+ expectRefused(await call(local(), write, '192.0.2.10'));
+ }
+ expect(featureAgents.createFeatureAgent).not.toHaveBeenCalled();
+ expect(featureAgents.activateFeatureAgent).not.toHaveBeenCalled();
+ expect(featureAgents.triggerFeatureAgent).not.toHaveBeenCalled();
+ expect(loops.createLoop).not.toHaveBeenCalled();
+ expect(loops.triggerLoop).not.toHaveBeenCalled();
+ expect(installer.getProviderRuntimeStatus).not.toHaveBeenCalled();
+ expect(installer.spawnRuntimeInstaller).not.toHaveBeenCalled();
+ expect(settingsWrite).not.toHaveBeenCalled();
+ expect(cosConfigWrite).not.toHaveBeenCalled();
+ });
+
+ it('leaves a remote caller the writes that only stop work or change no execution policy', async () => {
+ const statuses = [];
+ for (const write of [
+ ['post', '/api/feature-agents/agent-1/stop'],
+ ['post', '/api/loops/loop-1/stop'],
+ ['put', '/api/settings', { location: { lat: null, lon: null } }],
+ ['put', '/api/cos/config', { avatarStyle: 'svg' }],
+ ]) statuses.push((await call(remote(), write)).status);
+ expect(statuses).toEqual([200, 200, 200, 200]);
+ expect(featureAgents.stopFeatureAgent).toHaveBeenCalledTimes(1);
+ expect(loops.stopLoop).toHaveBeenCalledTimes(1);
+ expect([settingsWrite, cosConfigWrite].map((write) => write.mock.calls.length)).toEqual([1, 1]);
+ });
+
+ it('keeps a local caller, direct or through the dev proxy, able to run and configure everything', async () => {
+ for (const proxyClient of [undefined, '::ffff:127.0.0.1']) {
+ const statuses = [];
+ for (const write of [
+ ['post', '/api/feature-agents/agent-1/start'],
+ ['post', '/api/loops/loop-1/trigger'],
+ ['put', '/api/settings', { codeReview: { reviewers: ['claude'] } }],
+ ['put', '/api/cos/config', { maxConcurrentAgents: 2 }],
+ ]) statuses.push((await call(local(), write, proxyClient)).status);
+ expect(statuses).toEqual([200, 200, 200, 200]);
+ }
+ expect(featureAgents.activateFeatureAgent).toHaveBeenCalledTimes(2);
+ expect(loops.triggerLoop).toHaveBeenCalledTimes(2);
+ expect([settingsWrite, cosConfigWrite].map((write) => write.mock.calls.length)).toEqual([2, 2]);
+ });
+});
diff --git a/server/services/authGate.js b/server/services/authGate.js
index cb5fddaaae..6e5defb4c9 100644
--- a/server/services/authGate.js
+++ b/server/services/authGate.js
@@ -13,7 +13,7 @@ import {
isPeerBasicBootstrapRequest,
} from '../lib/apiAccessPolicy.js';
import { sendErrorResponse, ServerError } from '../lib/errorHandler.js';
-import { isHostControlRoute } from '../lib/hostControlRoutes.js';
+import { hostControlBodyKeys, isHostControlRoute } from '../lib/hostControlRoutes.js';
import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';
import { loadData as loadInstances } from './instanceIdentity.js';
@@ -265,6 +265,13 @@ export const hostControlRouteGate = (req, res, next) => (
isHostControlRoute(req.method, req.path) ? requireHostControl(req, res, next) : next()
);
+// The body-slice twin, mounted right after the JSON parser: the two
+// polymorphic policy stores (PUT /api/settings, PUT /api/cos/config) are
+// gated only when the body names a key that changes execution policy.
+export const hostControlBodyGate = (req, res, next) => (
+ hostControlBodyKeys(req.method, req.path, req.body).length > 0 ? 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