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: gate settings keys that pick an executable behind host control (#8751)
[._.]/ Adam Eivy4d34bce8a31f
diff --git a/server/lib/README.md b/server/lib/README.mdindex 7023335637..f8fd201cd6 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, 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`. |+| `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`), and `hostControlSettingsPathsIn` / `changedHostControlSettingsPaths` the nested settings keys that pick an executable (`HOST_CONTROL_SETTINGS_PATHS`, gated only when the value changes), all 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.jsindex 0013a578c1..06e493c1ba 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -43,7 +43,10 @@* 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.+ * HOST_CONTROL_SETTINGS_SLICES and HOST_CONTROL_OPEN_COS_CONFIG_KEYS —+ * and so are the nested settings keys that pick an executable or disarm+ * a shell guard (HOST_CONTROL_SETTINGS_PATHS), but only when the body+ * CHANGES the stored value (#8751).** Patterns are `METHOD /path`, with Express-style `:param` (one segment) and* `*name` (the rest of the path). Matching is case-insensitive and ignores one@@ -51,6 +54,7 @@* listed handler by a spelling this list does not match.*/+import { isPlainObject } from './objects.js';import { escapeRegExp } from './textUtils.js';export const HOST_CONTROL_ROUTES = Object.freeze([@@ -190,6 +194,26 @@ export const HOST_CONTROL_SETTINGS_SLICES = Object.freeze(['untrustedContent',]);+/**+ * Nested `PUT /api/settings` keys, as dotted paths, that choose a binary+ * PortOS spawns (the image-gen CLIs and the Python interpreter every local+ * media lane runs) or turn the Layered Intelligence `cmd` sources into a+ * full shell (#8751). Their parent slices stay open, so each is gated per+ * CHANGED value rather than per presence: the Image Gen tab resends the whole+ * slice, stored paths included, on every save, and a remote caller changing+ * only an aspect ratio must still be able to save it. A body that omits or+ * clears one (`''`, `null`, `false`) reverts it to the built-in default —+ * the shallow settings merge drops an omitted key, and every reader treats a+ * cleared value as unset — so neither is gated.+ */+export const HOST_CONTROL_SETTINGS_PATHS = Object.freeze([+ 'imageGen.agy.agyPath',+ 'imageGen.codex.codexPath',+ 'imageGen.grok.grokPath',+ 'imageGen.local.pythonPath',+ 'layeredIntelligence.trustShellSources',+]);+/*** 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,@@ -235,6 +259,29 @@ export const hostControlBodyKeys = (method, path, body) => {return COMPILED_BODY_ROUTES.find((entry) => entry.method === verb && entry.pattern.test(path))?.pick(body) ?? [];};+const valueAt = (object, path) => path.split('.').reduce(+ (node, key) => (isPlainObject(node) && Object.hasOwn(node, key) ? node[key] : undefined),+ object,+);++// Each listed key's readers fall back to the built-in default on any of these.+const isUnset = (value) => value === undefined || value === null || value === '' || value === false;++const SETTINGS_WRITE = compileRoute('PUT /api/settings');++/** The HOST_CONTROL_SETTINGS_PATHS a `method path` body sets to a non-default value, for `PUT /api/settings`; [] elsewhere. */+export const hostControlSettingsPathsIn = (method, path, body) => (+ typeof method === 'string' && typeof path === 'string'+ && method.toUpperCase() === SETTINGS_WRITE.method && SETTINGS_WRITE.pattern.test(path)+ ? HOST_CONTROL_SETTINGS_PATHS.filter((key) => !isUnset(valueAt(body, key)))+ : []+);++/** Of `paths`, the ones whose value in `body` differs from the stored `current` settings. */+export const changedHostControlSettingsPaths = (paths, body, current) => (+ paths.filter((key) => !Object.is(valueAt(body, key), valueAt(current, key)))+);+/** 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/routes/hostControlFamilies.test.js b/server/routes/hostControlFamilies.test.jsindex af96917f8a..0fd121790f 100644--- a/server/routes/hostControlFamilies.test.js+++ b/server/routes/hostControlFamilies.test.js@@ -12,6 +12,13 @@ vi.mock('../services/auth.js', async (importOriginal) => ({isAuthEnabled: vi.fn().mockResolvedValue(false),}));+// The stored settings the executable-path gate compares a body against.+const settingsStore = vi.hoisted(() => ({ current: {} }));+vi.mock('../services/settings.js', async (importOriginal) => ({+ ...await importOriginal(),+ getSettings: vi.fn(async () => settingsStore.current),+}));+const featureAgents = vi.hoisted(() => ({createFeatureAgent: vi.fn(),activateFeatureAgent: vi.fn(),@@ -152,3 +159,51 @@ describe('host-control gate on agent, loop, provider and policy writes (#8721)',expect([settingsWrite, cosConfigWrite].map((write) => write.mock.calls.length)).toEqual([2, 2]);});});++describe('host-control gate on settings keys that pick an executable (#8751)', () => {+ const STORED = {+ imageGen: {+ grok: { enabled: true, grokPath: '/opt/example/bin/grok', aspectRatio: '1:1' },+ agy: { enabled: true, agyPath: '/opt/example/bin/agy' },+ local: { pythonPath: '/opt/example/.venv/bin/python3' },+ },+ layeredIntelligence: { trustShellSources: false },+ };+ const CHANGES = [+ { imageGen: { ...STORED.imageGen, grok: { ...STORED.imageGen.grok, grokPath: '/bin/bash' } } },+ { imageGen: { agy: { agyPath: '/bin/sh' } } },+ { imageGen: { codex: { codexPath: '/usr/bin/env' } } },+ { imageGen: { local: { pythonPath: '/opt/example/other/python3' } } },+ { layeredIntelligence: { trustShellSources: true } },+ ];++ beforeEach(() => {+ vi.clearAllMocks();+ settingsStore.current = STORED;+ });++ it('refuses a remote password-free caller that changes one, before anything is written', async () => {+ for (const body of CHANGES) {+ expectRefused(await call(remote(), ['put', '/api/settings', body]));+ expectRefused(await call(local(), ['put', '/api/settings', body], '192.0.2.10'));+ }+ expect(settingsWrite).not.toHaveBeenCalled();+ });++ it('lets a remote caller resave the stored values, or clear one, while changing an open key', async () => {+ const statuses = [];+ for (const body of [+ { imageGen: { ...STORED.imageGen, grok: { ...STORED.imageGen.grok, aspectRatio: '16:9' } } },+ { layeredIntelligence: { trustShellSources: false } },+ { imageGen: { grok: { enabled: false, grokPath: '' } } },+ ]) statuses.push((await call(remote(), ['put', '/api/settings', body])).status);+ expect(statuses).toEqual([200, 200, 200]);+ expect(settingsWrite).toHaveBeenCalledTimes(3);+ });++ it('keeps a local caller able to change every one', async () => {+ const statuses = [];+ for (const body of CHANGES) statuses.push((await call(local(), ['put', '/api/settings', body])).status);+ expect(statuses).toEqual(CHANGES.map(() => 200));+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 081f6b0bf5..0c53b35b4d 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -18,7 +18,8 @@ import { getCredentialInventory } from '../services/credentialInventory.js';import { installEidoverse } from '../services/eidoverse.js';import { ensureEidoverseHost } from '../services/eidoverseHost.js';import { isGitHubRepoUrl } from '../lib/repoUrl.js';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { isAllowedPython } from '../lib/pythonSetup.js';import { isPlainObject } from '../lib/objects.js';import { resolveBackupConfig } from '../lib/backupConfig.js';import { storableAutoUpdateConfig } from '../lib/sharedSchemas.js';@@ -546,6 +547,16 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.imageGen?.agy !== undefined) {validateRequest(imageGenAgySettingsSchema.partial(), req.body.imageGen.agy);}+ // Every local media lane spawns this interpreter (and image gen spawns the+ // `mflux-generate` beside it), so hold it to the guard the setup routes use:+ // a python basename, never an arbitrary binary (#8751). A cleared value+ // (`''`/`null`) falls back to interpreter discovery, so it stays allowed.+ const localPython = req.body?.imageGen?.local?.pythonPath;+ if (localPython != null && localPython !== '' && !isAllowedPython(localPython)) {+ throw new ServerError('imageGen.local.pythonPath must be a python interpreter (basename python/python3/python3.NN)', {+ status: 400, code: 'INVALID_PYTHON_PATH',+ });+ }// Per-surface render defaults (#3231) — validate when present so a typo'd// target key or a non-enum backend can't persist a slice the render-target// resolver would then silently ignore (or worse, hand an invalid model iddiff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex badb5f980d..113e3e4771 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -775,6 +775,31 @@ describe('Settings routes — imageGen.agy slice', () => {});});+describe('Settings routes — imageGen.local.pythonPath (#8751)', () => {+ beforeEach(() => {+ store = {};+ vi.clearAllMocks();+ });++ it('refuses a pythonPath that is not a python interpreter, persisting nothing', async () => {+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ imageGen: { local: { pythonPath: '/bin/sh' } } });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('INVALID_PYTHON_PATH');+ expect(store.imageGen).toBeUndefined();+ });++ it('accepts a venv interpreter and a cleared value', async () => {+ for (const pythonPath of ['/opt/example/.venv/bin/python3.12', '']) {+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ imageGen: { local: { pythonPath } } });+ expect(res.status).toBe(200);+ }+ });+});+describe('Settings routes — renderDefaults slice (#3231)', () => {beforeEach(() => {store = {};diff --git a/server/services/authGate.js b/server/services/authGate.jsindex 6e5defb4c9..e68d9fa57e 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -13,7 +13,9 @@ import {isPeerBasicBootstrapRequest,} from '../lib/apiAccessPolicy.js';import { sendErrorResponse, ServerError } from '../lib/errorHandler.js';-import { hostControlBodyKeys, isHostControlRoute } from '../lib/hostControlRoutes.js';+import {+ changedHostControlSettingsPaths, hostControlBodyKeys, hostControlSettingsPathsIn, isHostControlRoute,+} from '../lib/hostControlRoutes.js';import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';import { loadData as loadInstances } from './instanceIdentity.js';@@ -267,10 +269,18 @@ export const hostControlRouteGate = (req, res, 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()-);+// gated only when the body names a key that changes execution policy, or+// changes the stored value of a nested settings key that picks an executable+// (HOST_CONTROL_SETTINGS_PATHS). The settings read is skipped when the caller+// already holds host control, since the answer could not change.+export const hostControlBodyGate = async (req, res, next) => {+ if (hostControlBodyKeys(req.method, req.path, req.body).length > 0) return requireHostControl(req, res, next);+ const named = hostControlSettingsPathsIn(req.method, req.path, req.body);+ if (named.length === 0+ || hasHostControl(req.portosAuthContext, isLocalConnection(req.socket?.remoteAddress, req.headers))) return next();+ const changed = changedHostControlSettingsPaths(named, req.body, await getSettings());+ return changed.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