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 unattended commands at the subcommand level, not just the binary (#5808)
Adam Eivy3a030814f1c0
diff --git a/server/lib/README.md b/server/lib/README.mdindex d6c188e279..22b80f4c0b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -277,7 +277,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. || `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. || `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.-| `commandSecurity.js` | Two allowlists, one parser. `validateCommand(cmd)` gates the OPERATOR-driven runner against `ALLOWED_COMMANDS` (+ `validatePm2Command(args)`, which rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateUnattendedCommand(cmd)` gates the UNATTENDED lane (Layered Intelligence `cmd` sources) against the far narrower `UNATTENDED_READONLY_COMMANDS` — read-only inspection binaries only, no `npx`/`node`/`python`/`pip`/`curl`/`wget`/`brew`, since those execute network code with no shell metacharacter. Both share one parse + `DANGEROUS_SHELL_CHARS` body. Mirrored by the `agentGuard/` PATH shim for agentic paths. |+| `commandSecurity.js` | Two allowlists, one parser. `validateCommand(cmd)` gates the OPERATOR-driven runner against `ALLOWED_COMMANDS` (+ `validatePm2Command(args)`, which rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateUnattendedCommand(cmd)` gates the UNATTENDED lane (Layered Intelligence `cmd` sources) against the far narrower `UNATTENDED_READONLY_COMMANDS` — read-only inspection binaries only, no `npx`/`node`/`python`/`pip`/`curl`/`wget`/`brew`, since those execute network code with no shell metacharacter — then applies a per-binary SUBCOMMAND gate to the multi-purpose survivors, so `git reset --hard` / `git commit`, `find -delete` / `-exec`, and `gh`/`glab` writes (`api -X POST`, `pr merge`) are rejected while `git log`, `find -name` and `gh pr list` pass. Both share one parse + `DANGEROUS_SHELL_CHARS` body. Mirrored by the `agentGuard/` PATH shim for agentic paths. || `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows has no double-fork (plain-spawn fallback), so its handle's `kill` delegates to `killProcessTree` (`taskkill /T /F`) — a cancel there takes the runner's children with it. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. || `execGit.js` | `execGit(args, cwd, options)` utility imported by `git.js` + worktree manager. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |diff --git a/server/lib/commandSecurity.js b/server/lib/commandSecurity.jsindex 71c8fb6c9d..65b4f78112 100644--- a/server/lib/commandSecurity.js+++ b/server/lib/commandSecurity.js@@ -24,12 +24,14 @@ export const ALLOWED_COMMANDS_SORTED = Array.from(ALLOWED_COMMANDS).sort();// `npx <pkg>` / `pip install <pkg>` / `curl -o <path> <url>` contain no shell// metacharacter, so the metacharacter filter alone does NOT stop them.//-// Scope: this gate is binary-level, not subcommand-level. Every admitted binary-// is one whose *documented* use here is inspection, but a few are multi-purpose-// (`git commit`, `find -delete`, `gh api -X POST`) and are NOT rejected. That is-// a deliberately smaller step than subcommand gating: it removes remote-code-// fetch/exec from the unattended lane, which is the class that turns hostile-// config into arbitrary RCE. Subcommand gating is tracked separately.+// Scope: membership here is necessary but NOT sufficient. Four of these binaries+// are multi-purpose — `git`, `find`, `gh` and `glab` all accept destructive or+// mutating verbs (`git reset --hard`, `find . -delete`, `gh api -X POST`) that+// carry no shell metacharacter. Those are rejected a second time by the+// per-binary subcommand gate below (`UNATTENDED_SUBCOMMAND_VALIDATORS`, wired+// into `validateUnattendedCommand`). The remaining entries (`ls`, `cat`, `head`,+// `tail`, `grep`, `wc`, `pwd`, `echo`) have no write mode at all and stay+// binary-level.export const UNATTENDED_READONLY_COMMANDS = new Set(['git', 'gh', 'glab','ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc',@@ -100,6 +102,132 @@ export function validatePm2Command(args) {return { valid: true };}+// ---------------------------------------------------------------------------+// Unattended subcommand gate (#5808)+//+// `UNATTENDED_READONLY_COMMANDS` admits four multi-purpose binaries whose+// destructive verbs contain no shell metacharacter, so the allowlist and the+// metacharacter filter both wave them through. These validators run only on the+// unattended lane, keyed off the base command exactly the way `validateCommand`+// keys the pm2 check off its own base command. The operator lane is untouched:+// a human triggers and watches it, and `git commit` there is legitimate.+// ---------------------------------------------------------------------------++// Read-only git verbs. Allowlist, not denylist — git grows verbs, and an unknown+// verb must fail closed rather than inherit a permission nobody reviewed.+const UNATTENDED_GIT_SUBCOMMANDS = new Set([+ 'log', 'show', 'status', 'diff', 'blame', 'describe', 'rev-parse',+ 'branch', 'tag', 'remote', 'config', 'ls-files', 'shortlog',+]);++// `git config` only reads when asked to read; a bare `git config a.b c` writes.+const GIT_CONFIG_READ_FLAGS = new Set(['--get', '--get-all', '--get-regexp', '--get-urlmatch', '--list', '-l']);++// The three listing verbs above still expose a small mutating flag surface+// (`git branch -D`, `git tag -d`, `git remote remove`). Their listing forms stay+// allowed; these forms do not.+const GIT_BRANCH_MUTATING_FLAGS = new Set(['-d', '-D', '--delete', '-m', '-M', '--move', '-c', '-C', '--copy', '--set-upstream-to', '-u', '--unset-upstream', '--edit-description']);+const GIT_TAG_MUTATING_FLAGS = new Set(['-d', '--delete', '-a', '--annotate', '-s', '--sign', '-f', '--force', '-m', '--message', '-F', '--file']);+// `git branch <name>` / `git tag <name>` CREATE a ref; the same verbs only read+// when the positional is a filter for an explicit list mode. So a positional is+// admitted only alongside one of these.+const GIT_LIST_MODE_FLAGS = new Set(['-l', '--list', '--contains', '--no-contains', '--points-at', '--merged', '--no-merged']);+const GIT_REMOTE_READ_VERBS = new Set(['show', 'get-url']);++// `find` action flags: `-delete` removes files and `-exec`/`-ok` family runs+// arbitrary binaries, which would defeat the allowlist entirely. `-f*print*`+// writes attacker-chosen files. Everything else (`-name`, `-type`, `-maxdepth`,+// `-print`) only inspects.+const FIND_ACTION_FLAGS = new Set([+ '-delete', '-exec', '-execdir', '-ok', '-okdir',+ '-fls', '-fprint', '-fprint0', '-fprintf',+]);++// gh/glab write verbs are authenticated mutations against the tracker using the+// operator's own credentials, so only `<noun> list`, `<noun> view` and read-only+// `api` calls are admitted.+const GH_READ_VERBS = new Set(['list', 'view']);+const GH_METHOD_FLAGS = new Set(['-X', '--method']);+// gh/glab switch `api` to POST implicitly when a field flag is present, so a+// method check alone is not enough.+const GH_FIELD_FLAGS = new Set(['-f', '-F', '--field', '--raw-field', '--input']);++const deny = (error) => ({ valid: false, error });++// True when `git branch` / `git tag` args only list refs: no mutating flag, and+// no bare positional unless an explicit list-mode flag makes it a filter.+function isGitRefListing(sub, rest) {+ const mutating = sub === 'branch' ? GIT_BRANCH_MUTATING_FLAGS : GIT_TAG_MUTATING_FLAGS;+ if (rest.some(a => mutating.has(a))) return false;+ const hasPositional = rest.some(a => !a.startsWith('-'));+ return !hasPositional || rest.some(a => GIT_LIST_MODE_FLAGS.has(a));+}++function validateUnattendedGit(args) {+ const sub = args[0];+ if (!sub) return deny("'git' needs a read-only subcommand on the unattended lane.");+ if (!UNATTENDED_GIT_SUBCOMMANDS.has(sub)) {+ return deny(`'git ${sub}' is not allowed on the unattended lane — only read-only inspection subcommands are: ${[...UNATTENDED_GIT_SUBCOMMANDS].sort().join(', ')}.`);+ }+ const rest = args.slice(1);+ if (sub === 'config' && !rest.some(a => GIT_CONFIG_READ_FLAGS.has(a))) {+ return deny("'git config' is only allowed in its read form on the unattended lane (e.g. 'git config --get <key>').");+ }+ if ((sub === 'branch' || sub === 'tag') && !isGitRefListing(sub, rest)) {+ return deny(`'git ${sub}' is only allowed in its listing form on the unattended lane — naming a ref (or a delete/move flag) writes to the repo.`);+ }+ if (sub === 'remote' && rest.length && !GIT_REMOTE_READ_VERBS.has(rest[0]) && !rest[0].startsWith('-')) {+ return deny("'git remote' is only allowed in its listing form on the unattended lane (e.g. 'git remote -v', 'git remote show <name>').");+ }+ return { valid: true };+}++function validateUnattendedFind(args) {+ const action = args.find(a => FIND_ACTION_FLAGS.has(a));+ if (action) {+ return deny(`'find ${action}' is not allowed on the unattended lane — it deletes, writes, or executes. Use inspection predicates ('-name', '-type', '-maxdepth', '-print') instead.`);+ }+ return { valid: true };+}++function validateUnattendedGhLike(base, args) {+ const sub = args[0];+ if (!sub) return deny(`'${base}' needs a read-only subcommand on the unattended lane.`);+ if (sub === 'api') {+ const rest = args.slice(1);+ for (let i = 0; i < rest.length; i += 1) {+ const arg = rest[i];+ // `?? ''` keeps a trailing `-X` with no value from crashing here — and a+ // methodless `-X` is malformed anyway, so failing closed is correct.+ const method = GH_METHOD_FLAGS.has(arg) ? (rest[i + 1] ?? '')+ : arg.startsWith('--method=') ? arg.slice('--method='.length)+ : null;+ if (method !== null && method.toUpperCase() !== 'GET') {+ return deny(`'${base} api' is limited to GET on the unattended lane — '${method}' is an authenticated write.`);+ }+ if (GH_FIELD_FLAGS.has(arg) || arg.startsWith('--field=') || arg.startsWith('--raw-field=')) {+ return deny(`'${base} api ${arg}' is not allowed on the unattended lane — a field flag makes the request a POST.`);+ }+ }+ return { valid: true };+ }+ const verb = args[1];+ if (!GH_READ_VERBS.has(verb)) {+ return deny(`'${base} ${sub}${verb ? ` ${verb}` : ''}' is not allowed on the unattended lane — only '${base} <noun> list', '${base} <noun> view' and read-only '${base} api' are.`);+ }+ return { valid: true };+}++// Keyed by base command; a binary with no entry is accepted on membership alone.+// A Map, not an object literal — the key comes from the parsed command string,+// and a Map has no prototype chain for `constructor`/`__proto__` to resolve into.+const UNATTENDED_SUBCOMMAND_VALIDATORS = new Map([+ ['git', validateUnattendedGit],+ ['find', validateUnattendedFind],+ ['gh', (args) => validateUnattendedGhLike('gh', args)],+ ['glab', (args) => validateUnattendedGhLike('glab', args)],+]);+/*** Shared shape/metacharacter/allowlist gate. Both public validators route* through this so the two lanes can never disagree about parsing or about@@ -143,12 +271,18 @@ export function validateCommand(command) {* string that lives in persistent, attacker-reachable config with no human in* the loop. Same parsing and metacharacter rules as `validateCommand`, but only* `UNATTENDED_READONLY_COMMANDS` are admitted, so a config that lands `npx`,- * `curl` or `pip install` cannot reach a spawn. No pm2 sub-check is needed —- * pm2 is not on the list at all.+ * `curl` or `pip install` cannot reach a spawn. Multi-purpose binaries then get+ * a per-binary subcommand check (`git`, `find`, `gh`, `glab`), so `git reset+ * --hard`, `find . -delete` and `gh api -X POST` are rejected too. No pm2+ * sub-check is needed — pm2 is not on the list at all.* Returns { valid, error?, baseCommand?, args? }*/export function validateUnattendedCommand(command) {- return validateAgainst(command, UNATTENDED_READONLY_COMMANDS, UNATTENDED_READONLY_COMMANDS_SORTED);+ const check = validateAgainst(command, UNATTENDED_READONLY_COMMANDS, UNATTENDED_READONLY_COMMANDS_SORTED);+ if (!check.valid) return check;+ const subCheck = UNATTENDED_SUBCOMMAND_VALIDATORS.get(check.baseCommand)?.(check.args);+ if (subCheck && !subCheck.valid) return subCheck;+ return check;}// Patterns matching sensitive env var values in command outputdiff --git a/server/lib/commandSecurity.test.js b/server/lib/commandSecurity.test.jsindex 7d786224e2..2f926b6cd6 100644--- a/server/lib/commandSecurity.test.js+++ b/server/lib/commandSecurity.test.js@@ -356,4 +356,123 @@ describe('commandSecurity', () => {expect(validateCommand('pip install requests').valid).toBe(true)})})++ describe('validateUnattendedCommand subcommand gate (#5808)', () => {+ // Allowlist membership is necessary but not sufficient: `git`, `find`, `gh`+ // and `glab` all accept destructive verbs that carry no shell metacharacter,+ // so the binary-level list and the metacharacter filter both wave them past.+ it.each([+ ['git reset --hard destroys uncommitted work in the app repo', 'git reset --hard'],+ ['git checkout . discards local edits', 'git checkout .'],+ ['git clean -fd removes untracked files', 'git clean -fd'],+ ['git push writes to the remote', 'git push'],+ ['git commit writes history', 'git commit -m "x"'],+ ['git stash is not on the read-only verb allowlist', 'git stash'],+ ['an unknown-to-the-allowlist verb fails closed', 'git rebase --continue'],+ ['a bare git has no read-only verb at all', 'git'],+ ])('rejects %s', (_label, cmd) => {+ expect(validateUnattendedCommand(cmd).valid).toBe(false)+ })++ it.each([+ 'git log --oneline -20',+ 'git status --short',+ 'git diff --stat', // NB: `git diff HEAD~1` is already rejected upstream — `~` is a DANGEROUS_SHELL_CHAR+ 'git show --name-only',+ 'git blame README.md',+ 'git rev-parse --abbrev-ref HEAD',+ 'git shortlog -sn',+ 'git ls-files',+ 'git describe --tags',+ 'git branch -a',+ 'git tag -l v1',+ 'git remote -v',+ 'git remote show origin',+ 'git config --get user.name',+ ])('accepts read-only git form %s', (cmd) => {+ expect(validateUnattendedCommand(cmd).valid).toBe(true)+ })++ it.each([+ ['git branch -D deletes a branch', 'git branch -D main'],+ ['git branch <name> creates one', 'git branch newbranch'],+ ['git tag <name> creates a tag', 'git tag v9.9.9'],+ ['git tag -d deletes one', 'git tag -d v1'],+ ['git remote add rewrites remotes', 'git remote add evil https://example.com'],+ ['git config <key> <value> writes config', 'git config user.email [email protected]'],+ ])('rejects the mutating form of a listing verb: %s', (_label, cmd) => {+ expect(validateUnattendedCommand(cmd).valid).toBe(false)+ })++ it.each([+ ['-delete removes files', 'find . -delete'],+ // The `{}` / `;` form is already caught by the metacharacter filter, so this+ // uses the `+` terminator — it reaches the new check and proves it works.+ ['-exec runs an arbitrary binary', 'find . -exec rm -f -- +'],+ ['-execdir runs an arbitrary binary', 'find . -execdir rm -f -- +'],+ ['-fprint writes an attacker-chosen file', 'find . -fprint /tmp/out'],+ ])('rejects find action flag: %s', (_label, cmd) => {+ const result = validateUnattendedCommand(cmd)+ expect(result.valid).toBe(false)+ expect(result.error).toMatch(/not allowed on the unattended lane/)+ })++ it.each([+ 'find . -name README.md',+ 'find . -type f -maxdepth 2 -print',+ ])('accepts find inspection form %s', (cmd) => {+ expect(validateUnattendedCommand(cmd).valid).toBe(true)+ })++ it.each([+ ['gh api -X POST is an authenticated write', 'gh api -X POST /repos/x/y/issues'],+ ['gh api --method DELETE is an authenticated write', 'gh api --method DELETE /repos/x/y/issues/1'],+ ['gh api --method=PATCH is an authenticated write', 'gh api --method=PATCH /repos/x/y/issues/1'],+ ['a field flag makes gh api an implicit POST', 'gh api /repos/x/y/issues -f title=hi'],+ ['gh pr merge merges with operator credentials', 'gh pr merge 1'],+ ['gh issue close mutates the tracker', 'gh issue close 1'],+ ['gh pr create mutates the tracker', 'gh pr create --fill'],+ ['glab mr merge merges with operator credentials', 'glab mr merge 1'],+ ['glab api -X POST is an authenticated write', 'glab api -X POST /projects'],+ ['a bare gh has no read-only verb at all', 'gh'],+ ['a methodless -X is malformed and fails closed', 'gh api -X'],+ ])('rejects %s', (_label, cmd) => {+ expect(validateUnattendedCommand(cmd).valid).toBe(false)+ })++ it.each([+ 'gh pr list',+ 'gh issue list --limit 20',+ 'gh issue view 1',+ 'gh api /rate_limit',+ 'gh api -X GET /rate_limit',+ 'glab mr list',+ 'glab issue view 1',+ ])('accepts read-only tracker command %s', (cmd) => {+ expect(validateUnattendedCommand(cmd).valid).toBe(true)+ })++ it('still returns the parsed base command and args on accept', () => {+ const result = validateUnattendedCommand('git log --oneline -5')+ expect(result).toEqual({ valid: true, baseCommand: 'git', args: ['log', '--oneline', '-5'] })+ })++ it.each([+ 'ls -la',+ 'cat README.md',+ 'grep -rn TODO src',+ 'echo hello',+ 'wc -l README.md',+ ])('leaves single-purpose binaries binary-level: %s', (cmd) => {+ expect(validateUnattendedCommand(cmd).valid).toBe(true)+ })++ it('does not touch the operator lane', () => {+ // POST /api/commands/execute stays byte-identical — a human triggers and+ // watches it, and `git commit` / `gh pr merge` are legitimate there.+ for (const cmd of ['git commit -m "x"', 'gh pr merge 1', 'git reset --hard', 'find . -delete']) {+ expect(validateCommand(cmd).valid).toBe(true)+ }+ })+ })})