Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Manual mode: the look-only shell allowlist takes only options known to look (#3975)
Niko1221f681b9ad62b3
diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.mdindex b05bebcf2..5afd94c11 100644--- a/apps/host/server/agent/README.md+++ b/apps/host/server/agent/README.md@@ -61,7 +61,7 @@ The chat's Mode menu is real Harness behaviour. Each turn the page sends the cha| Bypass | `strata-bypass` | `danger-full-access` | `never` | Full access without prompts, as before. |- Manual relies on the gate, so a Manual turn does not start unless the bridge has confirmed the gate is loaded (`/strata-gate` command): without it Manual would be an open sandbox that nobody asks about.-- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked; MCP and unknown tools ask.+- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked, each only with the options listed for it in `strata-gate.mjs` (an unknown option, or one that writes, runs a program, sets something or never ends, asks); MCP and unknown tools ask.- Web search and web pages (`web_search`, `web_fetch`) ask once per chat in Manual, not once per call. The gate asks through the approval service itself (`webDecision`: "The assistant wants to search the web for: ... Search words go to <service>." / "... open the web page ..."), remembers a yes for the chat (a helper agent shares its chat's answer, and two searches started together share one card), and on a no gives the model `WEB_REFUSAL` ("The person did not allow web access ... Go on without it and say so."). Plan and Bypass are unchanged. Settings -> Tools has a switch, "Let the assistant search the web without asking" (off by default, `webWithoutAsking` in `tools-settings.mjs`, passed to the gate as `config.web.skipAsk`), that skips the question in Manual. A scheduled task has nobody at the card, so its web call is answered no unless that switch is on. Tests: `tests/web-ask.test.mjs`.- The mode is read once per turn; an unknown or missing value is Manual.diff --git a/apps/host/server/agent/plugins/strata-gate.mjs b/apps/host/server/agent/plugins/strata-gate.mjsindex 96e592213..098ceea89 100644--- a/apps/host/server/agent/plugins/strata-gate.mjs+++ b/apps/host/server/agent/plugins/strata-gate.mjs@@ -48,25 +48,196 @@ export const READ_ONLY_TOOLS = new Set([const SHELL_TOOLS = new Set(['pwsh', 'bash']);-/** Commands that only look. Matched against the first word of every pipeline segment. */-const SAFE_COMMANDS = new Set([- // PowerShell- 'get-childitem', 'gci', 'ls', 'dir', 'get-content', 'gc', 'cat', 'type', 'get-item', 'gi', 'get-location', 'pwd', 'gl',- 'select-string', 'sls', 'measure-object', 'measure', 'select-object', 'select', 'where-object', 'where', 'sort-object', 'sort',- 'format-table', 'ft', 'format-list', 'fl', 'out-string', 'test-path', 'resolve-path', 'get-filehash', 'get-date', 'get-command',- 'get-process', 'get-itemproperty', 'write-output', 'echo', 'hostname', 'whoami', 'get-host', 'get-psdrive', 'get-help',- 'group-object', 'group', 'convertto-json', 'convertfrom-json', 'select-xml', 'compare-object', 'get-unique', 'tee-object-none',- // POSIX- 'head', 'tail', 'wc', 'grep', 'rg', 'egrep', 'fgrep', 'stat', 'file', 'du', 'df', 'uname', 'which', 'basename', 'dirname',- 'realpath', 'readlink', 'sort', 'uniq', 'cut', 'tr', 'less', 'more', 'date', 'id', 'env-none', 'tree',-]);+/**+ * Which shell commands run without a card in Manual mode, and with which options. Safe by construction (#3975): a command is on the list WITH the+ * options that are known to only look. Every other option, long or short, abbreviated or attached, makes the command ask. So a write mode+ * (`sort -o`, `tree -o`, `uniq in out`), a program-execution mode (`sort --compress-program`, `rg --pre`, `git grep -O`), a setting mode+ * (`date -s`) or one that never ends (`tail -f`) cannot slip in, and a word added to the list later starts with no options at all.+ *+ * A spec says what one command accepts:+ * f short options without a value (letters, so `-la` is `-l -a`) v short options that need a value (`-k2`, `-k 2`)+ * vn the same, and the value must be a number o short options with an optional value that must be attached (`-Iseconds`)+ * n a bare `-5` is allowed l long options (`--name`, `--name=value`), spelled in full+ * lv long options that need a value (`--name=value`, `--name value`) ps PowerShell parameter names, lower case, spelled in full+ * max how many operands (files, patterns) are allowed op a check for each operand+ * post a last check from the options seen and the operand count+ */+const words = (text) => (text ? text.trim().split(/\s+/) : []);+const spec = ({ f = '', v = '', vn = '', o = '', n = false, l = '', lv = '', ps = '', max = Infinity, op = null, post = null }) =>+ ({ f, v, vn, o, n, l: new Set(words(l)), lv: new Set(words(lv)), ps: ps ? new Set([...words(ps), ...PS_COMMON]) : null, max, op, post });+/** Parameters every cmdlet has that only change how errors and warnings show. (-Debug asks a question and -OutVariable sets one: not listed.) */+const PS_COMMON = ['erroraction', 'ea', 'warningaction', 'wa', 'informationaction', 'ia', 'verbose', 'vb'];+const NUMBER = /^[+-]?\d+[A-Za-z]{0,3}$/;++/** What `ls`, `dir`, `gci` and `Get-ChildItem` take. */+const LS = { f: 'aAbBcdDFgGhHiklLmnNopqQrRsStuUvxX1CZ', v: 'ITw', ps: 'path literalpath filter include exclude recurse depth name force file directory hidden readonly system attributes',+ l: 'all almost-all human-readable recursive directory classify reverse size inode dereference color group-directories-first sort time time-style block-size indicator-style si numeric-uid-gid no-group literal hide ignore quote-name escape author file-type full-time width tabsize' };+/** What `cat`, `type`, `gc` and `Get-Content` take. (-Wait never ends, so it is not here.) */+const CAT = { f: 'AbeEnstTuv', ps: 'path literalpath totalcount tail head raw encoding readcount force filter include exclude delimiter stream asbytestream',+ l: 'show-all number-nonblank show-ends number squeeze-blank show-tabs show-nonprinting' };+const MEASURE = { ps: 'property sum average maximum minimum line word character ignorewhitespace inputobject standarddeviation allstats' };+const SELECT = { ps: 'first last skip skiplast property expandproperty unique index excludeproperty inputobject' };+const WHERE = { ps: 'property value inputobject eq ne gt lt ge le like notlike match notmatch contains notcontains in notin is isnot ceq cne cgt clt cge cle clike cnotlike cmatch cnotmatch ccontains cnotcontains cin cnotin' };+const GROUP = { ps: 'property noelement ashashtable asstring casesensitive inputobject culture' };+const FT = { ps: 'property autosize wrap hidetableheaders groupby view force expand repeatheader displayerror showerror inputobject' };+const FL = { ps: 'property view groupby expand force displayerror showerror inputobject' };+const SLS = { ps: 'pattern path literalpath simplematch casesensitive context list notmatch quiet allmatches include exclude encoding raw inputobject culture noemphasis' };+const GETITEM = { ps: 'path literalpath name filter include exclude force stream' };+const GETLOC = { ps: 'psprovider psdrive stack stackname' };+const ECHO = { f: 'neE', ps: 'inputobject noenumerate' };+/** The GNU/BSD grep family. */+const GREP = { f: 'aiIlLcnvwHhEFGPqrRsTUyzZbxo', v: 'efdD', vn: 'ABCm', n: true,+ l: 'extended-regexp fixed-strings basic-regexp perl-regexp ignore-case no-ignore-case word-regexp line-regexp invert-match count color colour files-with-matches files-without-match max-count only-matching quiet silent no-messages byte-offset with-filename no-filename label line-buffered initial-tab null after-context before-context context text recursive dereference-recursive include exclude exclude-dir binary-files line-number null-data no-group-separator group-separator regexp file directories devices binary' };++/** Commands that only look, each with the options that are known to be harmless. Matched against the first word of every pipeline segment. */+const SPECS = new Map();+const add = (names, s) => { for (const name of words(names)) SPECS.set(name, spec(s)); };+// PowerShell+add('get-childitem gci', { ps: LS.ps });+add('ls dir', LS);+add('get-content gc', { ps: CAT.ps });+add('cat type', CAT);+add('get-item gi get-itemproperty', GETITEM);+add('get-location gl', GETLOC);+add('pwd', { ...GETLOC, f: 'LP' });+add('select-string sls', SLS);+add('measure-object measure', MEASURE);+add('select-object select', SELECT);+add('where-object where', WHERE);+add('sort-object', { ps: 'property descending unique top bottom casesensitive culture stable inputobject' });+add('format-table ft', FT);+add('format-list fl', FL);+add('out-string', { ps: 'stream width inputobject' });+add('test-path', { ps: 'path literalpath pathtype isvalid filter include exclude olderthan newerthan' });+add('resolve-path', { ps: 'path literalpath relative relativebasepath force' });+add('get-filehash', { ps: 'path literalpath algorithm' });+add('get-date', { ps: 'format uformat date asutc displayhint year month day hour minute second millisecond' });+add('get-command', { ps: 'name commandtype module all syntax listimported totalcount noun verb fullyqualifiedmodule parametername parametertype' });+add('get-process', { ps: 'name id includeusername module fileversioninfo inputobject' });+add('write-output', { ps: ECHO.ps });+add('echo', ECHO);+add('get-host', { ps: '' });+add('get-psdrive', { ps: 'name psprovider scope literalname' });+add('get-help', { ps: 'name full detailed examples parameter category component functionality role' });+add('group-object group', GROUP);+add('convertto-json', { ps: 'depth compress enumsasstrings inputobject asarray escapehandling' });+add('convertfrom-json', { ps: 'ashashtable depth inputobject noenumerate' });+add('select-xml', { ps: 'xml path literalpath xpath content namespace' });+add('compare-object', { ps: 'referenceobject differenceobject property includeequal excludedifferent passthru syncwindow casesensitive culture' });+add('get-unique', { ps: 'inputobject asstring caseinsensitive onetype' });+// POSIX. `sort` and `date` take no PowerShell names here: `sort -o FILE` writes, `date -s` sets the clock, and a PowerShell-looking `-Second` or `-Top`+// must not be read by a real sort or date as one of those. (Sort-Object and Get-Date above are the PowerShell forms.)+add('head', { f: 'qvz', vn: 'nc', n: true, l: 'quiet silent verbose zero-terminated lines bytes' });+add('tail', { f: 'qvz', vn: 'nc', n: true, l: 'quiet silent verbose zero-terminated lines bytes' }); // no -f, -F, --follow, --retry, --pid, -s: those never end+add('wc', { f: 'lwcmL', l: 'lines words bytes chars max-line-length' });+add('grep egrep fgrep', GREP);+add('rg', { // no --pre, --pre-glob, --hostname-bin (they run a program) and no -z/--search-zip (it runs decompressors)+ f: 'iIsSnNHlcwFxvUoLaquhVpbP', v: 'efgtTr', vn: 'ABCjdMm',+ l: 'ignore-case no-ignore-case smart-case case-sensitive fixed-strings word-regexp line-regexp invert-match count count-matches files-with-matches files-without-match files type-list hidden no-ignore no-ignore-vcs no-ignore-parent no-ignore-dot no-ignore-global no-ignore-messages follow line-number no-line-number with-filename no-filename column heading no-heading null only-matching quiet text multiline multiline-dotall pcre2 no-messages json stats trim unrestricted binary no-config vimgrep pretty byte-offset passthru crlf one-file-system no-unicode regexp file glob iglob type type-not max-count max-depth maxdepth context after-context before-context color replace threads sort sortr max-filesize max-columns path-separator encoding engine ignore-file glob-case-insensitive no-glob-case-insensitive' });+add('stat', { f: 'LtxlnqrsFf', v: 'c', l: 'dereference file-system terse format printf' });+add('file', { f: 'bhikLnNrvI', l: 'brief dereference no-dereference mime mime-type mime-encoding keep-going no-pad no-buffer raw' }); // no -C, -m, -f, -P (they write or read other files), no -z/-s/-p (they run decompressors, read devices, reset times)+add('du', { f: 'abchHklmsxLPSD0', v: 'tB', vn: 'd', l: 'all apparent-size bytes total dereference-args human-readable si summarize one-file-system dereference no-dereference separate-dirs count-links inodes null max-depth threshold block-size time time-style exclude' });+add('df', { f: 'ahHiklmPTv', v: 'txB', l: 'all human-readable si inodes local portability print-type total sync no-sync output block-size type exclude-type' });+add('uname', { f: 'asnrvmpio', max: 0, l: 'all kernel-name nodename kernel-release kernel-version machine processor hardware-platform operating-system' });+add('which', { f: 'as', l: 'all' });+add('basename', { f: 'az', v: 's', l: 'multiple zero suffix' });+add('dirname', { f: 'z', l: 'zero' });+add('realpath', { f: 'emsqzLP', l: 'canonicalize-existing canonicalize-missing no-symlinks quiet zero strip logical physical relative-to relative-base' });+add('readlink', { f: 'femnqsvz', l: 'canonicalize canonicalize-existing canonicalize-missing no-newline quiet silent verbose zero' });+add('sort', { f: 'bdfghiMnRrsuVzmcC', v: 'kt', l: 'ignore-leading-blanks dictionary-order ignore-case general-numeric-sort human-numeric-sort ignore-nonprinting month-sort numeric-sort random-sort reverse stable unique version-sort zero-terminated check merge sort field-separator key' });+// uniq's second operand is its OUTPUT file, so it takes at most one.+add('uniq', { f: 'cdDuiz', vn: 'fsw', max: 1, l: 'count repeated all-repeated unique ignore-case skip-fields skip-chars check-chars zero-terminated group' });+add('cut', { f: 'snz', v: 'bcfd', l: 'complement only-delimited zero-terminated bytes characters fields delimiter output-delimiter' });+add('tr', { f: 'cCdst', max: 2 });+add('date', { f: 'uR', o: 'I', v: 'dr', lv: 'date reference', l: 'utc universal rfc-email rfc-2822 iso-8601 rfc-3339',+ op: (word) => word.startsWith('+') }); // a bare operand like 1026120026 SETS the clock; only +FORMAT is a format+add('id', { f: 'ugGnrazZ', l: 'user group groups name real context zero' });+add('hostname', { f: 'sfiIdaAyv', max: 0 }); // `hostname NAME` renames the machine+add('whoami', { l: 'help version', op: (word) => /^\/(all|user|groups|priv|upn|fqdn|logonid|nh)$/i.test(word) });+add('tree', { f: 'adfilpsugDFqNQrtvxCnASUchJX', v: 'LPIHT', vn: '', l: 'help version filelimit charset sort timefmt noreport dirsfirst filesfirst prune du si gitignore matchdirs ignore-case inodes device nolinks' }); // no -o, no -R+// `less` and `more` are not here: they wait for keys, and `less` can run commands.++/** The names that run without a card (for the tests). */+export const readOnlyCommandNames = () => [...SPECS.keys()];++/** git subcommands that only read, with the options they may take. */+const GIT_VIEW = 'oneline graph decorate no-decorate all branches tags remotes stat shortstat numstat dirstat name-only name-status patch no-patch raw summary compact-summary abbrev-commit no-abbrev-commit abbrev reverse follow no-merges merges first-parent full-history simplify-by-decoration simplify-merges ancestry-path left-right left-only right-only cherry-pick cherry-mark cherry topo-order date-order author-date-order relative-date all-match invert-grep regexp-ignore-case extended-regexp fixed-strings perl-regexp no-color color color-words word-diff word-diff-regex minimal patience histogram diff-algorithm check exit-code quiet cached staged merge-base no-index no-ext-diff no-textconv find-renames find-copies find-copies-harder no-renames ignore-space-change ignore-all-space ignore-space-at-eol ignore-blank-lines ignore-cr-at-eol function-context show-function unified inter-hunk-context src-prefix dst-prefix no-prefix full-index binary text source use-mailmap mailmap no-mailmap log-size notes no-notes show-signature diff-merges boundary children parents no-walk sparse date format pretty author committer grep since until after before max-count skip min-parents max-parents diff-filter encoding stat-width stat-name-width stat-graph-width stat-count count';+const LISTING = ['l', 'list', 'contains', 'no-contains', 'merged', 'no-merged', 'points-at'];+const GIT = new Map(Object.entries({+ status: spec({ f: 'sbvz', o: 'u', l: 'short branch porcelain long ignored untracked-files ignore-submodules renames no-renames find-renames show-stash ahead-behind no-ahead-behind column no-column verbose null' }),+ log: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }),+ diff: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }),+ show: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }),+ 'rev-list': spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }),+ shortlog: spec({ f: 'sneciw', n: false, l: `${GIT_VIEW} summary numbered email committer group` }),+ // Listing forms only. A name with no list option would CREATE a branch or a tag, and the options that change things are not here.+ branch: spec({ f: 'avri', l: 'list all remotes verbose show-current ignore-case contains no-contains merged no-merged points-at sort format abbrev no-abbrev color no-color column no-column omit-empty',+ post: (seen, count) => count === 0 || LISTING.some(name => seen.has(name)) }),+ tag: spec({ f: 'li', o: 'n', l: 'list sort contains no-contains merged no-merged points-at format column no-column ignore-case omit-empty color no-color',+ post: (seen, count) => count === 0 || LISTING.some(name => seen.has(name)) }),+ remote: spec({ f: 'v', l: 'verbose', max: 0 }),+ // `git config KEY` reads and `git config KEY VALUE` writes, so a key is only taken with --get; no --edit, --add, --unset, --file.+ config: spec({ f: 'lz', l: 'list get get-all get-regexp show-origin show-scope local global system worktree bool int bool-or-int path expiry-date type null name-only includes no-includes', lv: 'default',+ post: (seen, count) => (count > 0 ? ['get', 'get-all', 'get-regexp'].some(name => seen.has(name)) : seen.has('list') || seen.has('l')) }),+ 'rev-parse': spec({ f: 'q', l: 'show-toplevel git-dir git-common-dir absolute-git-dir abbrev-ref symbolic symbolic-full-name short verify is-inside-work-tree is-inside-git-dir is-bare-repository is-shallow-repository show-prefix show-cdup show-superproject-working-tree all branches tags remotes quiet revs-only no-revs flags no-flags local-env-vars show-object-format path-format', lv: 'default git-path' }),+ 'ls-files': spec({ f: 'cdmoiskuzvtfD', l: 'cached deleted modified others ignored stage directory unmerged killed no-empty-directory error-unmatch exclude-standard exclude full-name eol deduplicate recurse-submodules sparse abbrev resolve-undo format' }),+ 'ls-tree': spec({ f: 'rtdlz', l: 'name-only name-status long full-name full-tree object-only abbrev format' }),+ blame: spec({ f: 'wMCespltbfnc', v: 'L', l: 'porcelain line-porcelain incremental show-email show-name show-number date root abbrev' }),+ describe: spec({ l: 'all tags always long dirty broken contains abbrev match exclude first-parent exact-match candidates' }),+ 'cat-file': spec({ f: 'tsep', l: 'batch batch-check batch-all-objects allow-unknown-type buffer unordered follow-symlinks mailmap use-mailmap' }), // no --textconv, --filters+ // No -O / --open-files-in-pager: they run a program on the matches.+ grep: spec({ f: 'aiIlLcnvwHhEFGPqpWrzUo', v: 'e', vn: 'ABCm', n: true, l: 'no-index untracked cached no-exclude-standard exclude-standard recurse-submodules text ignore-case word-regexp invert-match full-name extended-regexp basic-regexp perl-regexp fixed-strings line-number column files-with-matches name-only files-without-match count null only-matching quiet no-color color break heading show-function function-context all-match and or not max-depth max-count threads after-context before-context context recursive no-recursive' }),+}));++/**+ * One command's words against its spec: every option has to be one the spec knows (anything else is not understood, so it asks).+ * @param {ReturnType<typeof spec>} sp+ * @param {{t:string,q:boolean}[]} args the words after the command; q marks a quoted text, which is data and never an option+ */+function argumentsAreSafe(sp, args) {+ const seen = new Set();+ let operands = 0, ended = false;+ const operand = (arg) => { operands++; return operands <= sp.max && (!sp.op || sp.op(arg.t, arg.q)); };+ const valueOf = (i, numeric) => { // the next word as an option's value; it can be a quoted text, a number, or a word that is not an option+ const arg = args[i + 1];+ if (!arg) return false;+ return numeric ? NUMBER.test(arg.t) : arg.q || !arg.t.startsWith('-') || NUMBER.test(arg.t);+ };+ for (let i = 0; i < args.length; i++) {+ const { t, q } = args[i];+ if (q || ended || t === '-' || t[0] !== '-') { if (!operand(args[i])) return false; continue; }+ if (t === '--') { ended = true; continue; }+ if (t.startsWith('--')) {+ const eq = t.indexOf('=');+ const name = eq < 0 ? t.slice(2) : t.slice(2, eq);+ if (sp.l.has(name)) { seen.add(name); continue; }+ if (sp.lv.has(name)) { seen.add(name); if (eq < 0) { if (!valueOf(i, false)) return false; i++; } continue; }+ return false;+ }+ if (sp.ps) {+ const named = /^-([A-Za-z][A-Za-z0-9]*)(?::|$)/.exec(t);+ if (named && sp.ps.has(named[1].toLowerCase())) { seen.add(named[1].toLowerCase()); continue; }+ }+ if (sp.n && /^-\d+$/.test(t)) continue;+ for (let j = 1; j < t.length; j++) {+ const c = t[j];+ if (sp.f.includes(c)) { seen.add(c); continue; }+ if (sp.o.includes(c)) { seen.add(c); break; }+ const numeric = sp.vn.includes(c);+ if (!numeric && !sp.v.includes(c)) return false;+ seen.add(c);+ const rest = t.slice(j + 1);+ if (rest) { if (numeric && !NUMBER.test(rest)) return false; } else { if (!valueOf(i, numeric)) return false; i++; }+ break;+ }+ }+ return sp.post ? sp.post(seen, operands) : true;+}-/** git subcommands that only read. */-const SAFE_GIT = new Set(['status', 'log', 'diff', 'show', 'branch', 'rev-parse', 'ls-files', 'blame', 'describe', 'remote', 'tag', 'shortlog', 'rev-list', 'cat-file', 'grep', 'ls-tree', 'config']);const SAFE_VERSION = /^(node|python|python3|py|npm|pnpm|git|dotnet|cargo|rustc|go|java|pip|pip3)\s+(--version|-v|-version|version)$/i;-/** Anything that can chain, redirect, expand or start something else is not read-only. */-const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd-content\b|\binvoke-|\biex\b|\bstart-|\bnew-|\bremove-|\bcopy-|\bmove-|\brename-|\bclear-|\bset-|\bpush-|\bexpand-|\bsave-|\binstall-|\bcurl\b|\bwget\b|\bsudo\b|\bsh\b|\bbash\b|\bpwsh\b|\bpowershell\b|\bcmd\b|-exec\b|-delete\b|-execdir\b/i;+/** Anything that can chain, redirect, expand or start something else is not read-only. (`sh` as a word, not inside an option like `du -sh`.) */+const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd-content\b|\binvoke-|\biex\b|\bstart-|\bnew-|\bremove-|\bcopy-|\bmove-|\brename-|\bclear-|\bset-|\bpush-|\bexpand-|\bsave-|\binstall-|\bcurl\b|\bwget\b|\bsudo\b|(?<![-\w])sh(?![-\w])|\bbash\b|\bpwsh\b|\bpowershell\b|\bcmd\b|-exec\b|-delete\b|-execdir\b/i;/*** The command with every quoted text replaced by a plain stand-in, or null when it cannot be read safely. What is inside quotes is data@@ -74,9 +245,10 @@ const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd* inside double quotes a $ or a backtick expands (a variable, a sub-command), and an unterminated quote means the text was not understood.* Either one gives null, and the command asks as before.* @param {string} text+ * @param {string[]} [quoted] when given, receives the text inside each quote, in order (the checks on operands read it)* @returns {string|null}*/-export function maskQuotes(text) {+export function maskQuotes(text, quoted) {let out = '';for (let i = 0; i < text.length; i++) {const c = text[i];@@ -91,13 +263,14 @@ export function maskQuotes(text) {const before = text[i - 1], after = text[end + 1];if ((before !== undefined && !/[\s|]/.test(before)) || (after !== undefined && !/[\s|]/.test(after)) || text[i + 1] === '-') return null;out += '"_"';+ quoted?.push(text.slice(i + 1, end));i = end;}return out;}/**- * Whether a shell command only reads. Conservative by design: one unrecognised word and the answer is no.+ * Whether a shell command only reads. Conservative by design: one unrecognised word or option and the answer is no.* Quoted text is data and is looked at after it has been set aside (maskQuotes): Get-ChildItem "C:\Users\x\Q&A" only lists.* @param {string} command* @returns {boolean}@@ -106,24 +279,21 @@ export function isReadOnlyShell(command) {const text = String(command ?? '').trim();if (!text || text.length > 600) return false;if (SAFE_VERSION.test(text)) return true;- const masked = maskQuotes(text);+ const quoted = [];+ const masked = maskQuotes(text, quoted);if (masked === null || UNSAFE_SYNTAX.test(masked)) return false;- const segments = masked.split('|').map(s => s.trim());- return segments.every((segment) => {- if (!segment) return false;- const words = segment.split(/\s+/);- const first = words[0].toLowerCase().replace(/^\.\\/, '');+ let next = 0;+ const tokens = masked.split('|').map(segment => segment.trim()).map(segment => words(segment).map(w => (w === '"_"' ? { t: quoted[next++] ?? '', q: true } : { t: w, q: false })));+ return tokens.every((segment) => {+ if (!segment.length || segment[0].q) return false;+ const first = segment[0].t.toLowerCase().replace(/^\.\\/, '');if (first === 'git') {- // `git config` and `git tag`/`branch`/`remote` can write when given a value; only the bare listing forms are safe.- const sub = (words[1] ?? '').toLowerCase();- if (!SAFE_GIT.has(sub)) return false;- if (['config', 'tag', 'branch', 'remote'].includes(sub)) {- const rest = words.slice(2).filter(w => !w.startsWith('-') || /^(-l|-a|-v|-vv|--list|--all|--show-current|--get|--get-all)$/i.test(w));- return rest.length === 0 || (sub === 'config' && words[2] === '--get') || (sub === 'remote' && words[2] === '-v');- }- return !words.some(w => /^--(output|ext-diff|textconv)\b/i.test(w));+ const sub = segment[1];+ const sp = sub && !sub.q ? GIT.get(sub.t) : null;+ return !!sp && argumentsAreSafe(sp, segment.slice(2));}- return SAFE_COMMANDS.has(first) && !words.some(w => /^-(delete|exec|execdir|fprint|fls|ok)$/i.test(w));+ const sp = SPECS.get(first);+ return !!sp && argumentsAreSafe(sp, segment.slice(1));});}diff --git a/apps/host/tests/gate-readonly.test.mjs b/apps/host/tests/gate-readonly.test.mjsnew file mode 100644index 000000000..5fd9d8e8f--- /dev/null+++ b/apps/host/tests/gate-readonly.test.mjs@@ -0,0 +1,148 @@+// #3975 (P0): Manual mode's "read-only" shell allowlist must be safe by construction. A command without a card may only use options that are known to+// look and nothing else. The first block is what the issue reported (write and program-execution modes of allowlisted commands), the rest is the+// same class: options, operands, spellings and quoting. The last block is the commands people really type, which must keep running unasked.+import test from 'node:test';+import assert from 'node:assert/strict';+import { isReadOnlyShell, maskQuotes, readOnlyCommandNames } from '../server/agent/plugins/strata-gate.mjs';++const denied = (list) => { for (const c of list) assert.equal(isReadOnlyShell(c), false, `must ask: ${c}`); };+const allowed = (list) => { for (const c of list) assert.equal(isReadOnlyShell(c), true, `must run unasked: ${c}`); };++test('#3975: the five confirmed cases and the rest of the issue table now ask', () => {+ denied([+ 'sort --compress-program=sh a.txt', 'sort --compress-program sh a.txt', 'sort -o out.txt a.txt', 'sort --output=out.txt a.txt',+ 'rg --pre sh pattern', 'rg --pre=sh pattern',+ 'git grep -Osh pattern', 'git grep -O sh pattern', 'git grep --open-files-in-pager=sh pattern',+ 'uniq in.txt out.txt',+ 'tree -o out.txt', 'file -C -m x', 'date -s 12:00', 'date --set=12:00', 'tail -f app.log',+ ]);+});++test('#3975: other spellings of the same options (attached, clustered, abbreviated, repeated) ask', () => {+ denied([+ 'sort -oout.txt a.txt', 'sort -ro out.txt a.txt', 'sort -nro out.txt a.txt', 'sort --out=out.txt a.txt', 'sort --outp out.txt a.txt',+ 'sort --comp=sh a.txt', 'sort -T /tmp a.txt', 'sort --files0-from=list a.txt', 'sort -n -u -o out a',+ 'rg --pre-glob "*" x', 'rg --hostname-bin=sh x', 'rg -z x', 'rg --search-zip x', 'rg -uz x', 'rg --pre sh --files',+ 'git grep -O"sh" x', 'git grep -nOsh x', 'git grep -O x', 'git grep --open x', 'git grep -l --open-files-in-pager=sh x',+ 'uniq - out.txt', 'uniq -c in.txt out.txt', 'uniq -i -u in out',+ 'tree -oout.txt', 'tree -a -o out.txt', 'tree -R', 'tree --output=out',+ 'file -C', 'file --compile x', 'file -m magic x', 'file -f list', 'file -bC x', 'file --magic-file=x y',+ 'date -sMonth', 'date -u -s now', 'date --set now', 'date 102612002026', 'date -u 1026', 'date -d now 1026',+ 'tail -F app.log', 'tail --follow app.log', 'tail --follow=name app.log', 'tail -fn5 app.log', 'tail -n 1 -f app.log', 'tail --retry x', 'tail -f -n 1 x',+ 'tail --pid=1 -f x', 'tail -s 1 x',+ 'head -f x', 'wc --files0-from=list', 'du --files0-from=list', 'du -X file', 'stat --foo x', 'ls --foo', 'ls -@', 'cat -@ x', 'grep --foo x y',+ 'hostname newname', 'hostname -F file', 'uname -n box', 'uname box',+ ]);+});++test('#3975: git subcommands that write or run something when given the right option ask', () => {+ denied([+ 'git diff --output=out.txt', 'git diff --out=out.txt', 'git log --output=out.txt', 'git show --output out HEAD', 'git log --ext-diff', 'git diff --ext-diff',+ 'git diff --textconv', 'git log --textconv', 'git grep --textconv x', 'git cat-file --textconv HEAD:a', 'git cat-file --filters HEAD:a', 'git log --exec=sh',+ 'git config -e', 'git config --edit', 'git config --global --edit', 'git config --global user.name x', 'git config user.name x', 'git config --unset user.name',+ 'git config --add a.b c', 'git config --replace-all a.b c', 'git config --file x --list', 'git config --get', 'git config --get a --edit',+ 'git branch --set-upstream-to=origin/main', 'git branch --unset-upstream', 'git branch -u origin/main', 'git branch -d x', 'git branch -D x', 'git branch -m new',+ 'git branch --edit-description', 'git branch newbranch', 'git branch -a newbranch', 'git branch --track x origin/x',+ 'git tag v1', 'git tag -a v1', 'git tag -d v1', 'git tag -s v1', 'git tag -v v1', 'git tag -a -m msg v1', 'git tag --edit',+ 'git remote add o u', 'git remote show origin', 'git remote update', 'git remote prune origin', 'git remote set-url o u', 'git remote rename a b',+ 'git -c core.pager=sh log', 'git --paginate log', 'git -C x status', 'git --git-dir=x log', 'git -p log',+ 'git commit', 'git push', 'git checkout x', 'git stash', 'git reset', 'git clean -n', 'git fetch', 'git pull', 'git rev-parse --parseopt', 'git ls-files -x',+ 'git status --foo', 'git log --foo', 'git blame --contents=x a', 'git diff -O orderfile', 'git diff --no-pager',+ ]);+});++test('#3975: PowerShell commands: parameters that wait forever, reach other machines or open windows ask', () => {+ denied([+ 'Get-Content a.txt -Wait', 'gc a.txt -Wait', 'type a.txt -Wait', 'Get-Process -ComputerName other', 'Get-Help Get-ChildItem -Online', 'Get-Help Get-ChildItem -ShowWindow',+ 'Select-String -Pattern x -Foo', 'Get-ChildItem -Rec', 'Get-ChildItem -Debug', 'Get-ChildItem -OutVariable x', 'Get-ChildItem -ErrorVariable x',+ 'Sort-Object -Foo', 'Get-Date -Foo', 'Get-FileHash a.txt -InputStream x',+ ]);+});++test('#3975: pagers and anything not on the list ask', () => {+ denied(['less a.txt', 'more a.txt', 'less -o log a.txt', 'find . -name x', 'xargs ls', 'awk 1 a', 'sed s/a/b/ a', 'env', 'tee a', 'printenv', 'mv a b', 'cp a b', 'touch a', 'mkdir a', 'dd if=a of=b']);+});++test('#3975: quoting cannot hide an option or an operand', () => {+ denied([+ 'sort "--output=out" a', 'sort --out"put"=out a', 'sort --"output"=out a', "sort '-o' out a", 'sort -"o" out a', 'sort -o"out" a', 'sort --compress-program="sh" a',+ 'rg --pre "sh" x', "rg --pre 'sh' x", 'git grep -O"sh" x', 'git grep "-Osh" x',+ 'uniq a "b"', 'uniq "a" "b"', "uniq 'a' 'b'", 'date "1026120026"', "date '1026'", 'date "-s" now', 'date "-s now"',+ 'tail "-f" x', "tail '-f' x", 'tail -n 1 "-f" x',+ 'tree "-o" x', 'file "-C" x', 'git diff "--output=out.txt"', 'git "diff" --output=x',+ // a quoted dash value is never taken for a value of a flag that wants a number+ 'head -n "-f" x',+ ]);+});++test('#3975: operands that would write or set something ask (uniq output file, date setting, hostname)', () => {+ denied(['uniq a b', 'uniq a b c', 'date 1231', 'date 12311200', 'hostname a', 'whoami /foo', 'tr a b c', 'git tag v1.0', 'git branch topic']);+});++test('#3975: every command on the list asks for an unknown option, long or short', () => {+ const names = readOnlyCommandNames();+ assert.ok(names.length > 40, 'the list is not empty');+ for (const name of names) {+ assert.equal(isReadOnlyShell(`${name} -@`), false, `${name} -@`);+ assert.equal(isReadOnlyShell(`${name} --zz-no-such-option`), false, `${name} --zz-no-such-option`);+ assert.equal(isReadOnlyShell(`${name} --zz-no-such-option=1 x`), false, `${name} --zz-no-such-option=1 x`);+ assert.equal(isReadOnlyShell(`Get-ChildItem | ${name} -@`), false, `piped ${name} -@`);+ }+ for (const sub of ['status', 'log', 'diff', 'show', 'branch', 'rev-parse', 'ls-files', 'blame', 'describe', 'remote', 'tag', 'shortlog', 'rev-list', 'cat-file', 'grep', 'ls-tree', 'config']) {+ assert.equal(isReadOnlyShell(`git ${sub} --zz-no-such-option`), false, `git ${sub} --zz-no-such-option`);+ assert.equal(isReadOnlyShell(`git ${sub} -@`), false, `git ${sub} -@`);+ }+});++test('#3975: commands people really type still run without a card', () => {+ allowed([+ // sort, uniq, head, tail, wc, cut, tr+ 'sort a.txt', 'sort -r a.txt', 'sort -n -k 2 a.txt', 'sort -u -t, -k2,2 a.txt', 'sort -nr a.txt', 'sort -k2,2nr a.txt', 'sort --reverse --numeric-sort a.txt',+ 'uniq', 'uniq -c', 'uniq -c a.txt', 'uniq -d a.txt', 'uniq -f 1 a.txt', 'sort a.txt | uniq -c | sort -nr | head -5',+ 'head a.txt', 'head -5 a.txt', 'head -n 5 a.txt', 'head -n5 a.txt', 'head -n -5 a.txt', 'head -c 100 a.txt', 'tail a.txt', 'tail -20 a.txt', 'tail -n 20 a.txt', 'tail -n +5 a.txt', 'tail -c 100 a.txt',+ 'wc -l a.txt', 'wc -w a.txt', 'cat a.txt | wc -l', 'cut -d, -f1,3 a.txt', 'cut -c1-10 a.txt', 'tr a-z A-Z', 'tr -d "\\r"', 'tr -s " "',+ // grep family and rg+ 'grep foo a.txt', 'grep -rn foo src', 'grep -c foo a.txt', 'grep -E "a|b" a.txt', 'grep -A 3 foo a.txt', 'grep -i -v foo a.txt', 'grep -rl --include "*.js" foo .', 'egrep -n foo a.txt', 'fgrep -x foo a.txt',+ 'rg foo', 'rg -n -i foo src', 'rg -l --type js foo', 'rg --files -g "*.md"', 'rg -C 3 foo', "rg foo -g '!node_modules'", 'rg -e foo -e bar', 'rg --hidden --no-ignore foo', 'rg --count-matches foo', 'rg -w -F "a.b"', 'rg --json foo',+ // tree, file, stat, du, df, ls, dir+ 'tree', 'tree -L 2', 'tree -a -I node_modules', 'tree -d src', 'tree -L 2 -d',+ 'file a.bin', 'file -b --mime-type a.bin', 'file -i a.bin', 'file -L a.bin',+ 'stat a.txt', 'stat -c %s a.txt', 'du -sh .', 'du -h --max-depth=1', 'du -ah -d 1', 'df -h', 'df -hT', 'df .',+ 'ls', 'ls -la', 'ls -la src', 'ls -lh', 'ls -R', 'ls -1 --color=never', 'ls -lt | head -5', 'dir', 'dir /s',+ // small ones+ 'date', 'date -u', 'date +%s', 'date -u +%Y-%m-%dT%H:%M:%SZ', 'date -I', 'date -Iseconds', 'date -d @0', 'date --utc', 'date "+%Y-%m-%d"', "date '+%Y-%m-%d %H:%M'",+ 'uname', 'uname -a', 'uname -m', 'hostname', 'hostname -s', 'whoami', 'whoami /groups', 'id', 'id -u', 'id -un', 'pwd', 'which node', 'which -a node',+ 'basename a/b.txt', 'basename a/b.txt .txt', 'dirname a/b', 'realpath .', 'readlink -f a', 'echo hello', 'echo -n hello', 'cat a.txt', 'cat -n a.txt',+ // git+ 'git status', 'git status -s', 'git status --porcelain', 'git status -sb', 'git status --short --branch', 'git log', 'git log --oneline', 'git log --oneline -5', 'git log --oneline -n 5',+ 'git log --stat -n 3', 'git log -p -1', 'git log --graph --oneline --decorate --all', 'git log --format=%H -1', 'git log --author=alice --since=2.weeks', 'git log -- a.txt', 'git log --follow -p a.txt',+ 'git log main..HEAD', 'git log --oneline --no-merges origin/main..HEAD', 'git diff', 'git diff --stat', 'git diff --cached', 'git diff --name-only', 'git diff --name-status HEAD~1', 'git diff HEAD~1 -- a.txt',+ 'git diff -U5', 'git diff --no-ext-diff', 'git diff main...HEAD', 'git diff -w', 'git show', 'git show HEAD', 'git show HEAD --stat', 'git show HEAD:a.txt', 'git show -s --format=%H HEAD',+ 'git branch', 'git branch -a', 'git branch -v', 'git branch -vv', 'git branch -r', 'git branch --show-current', 'git branch --list', 'git branch --list "feat*"', 'git branch --contains HEAD', 'git branch --merged main',+ 'git tag', 'git tag -l', 'git tag --list', 'git tag -l "v*"', 'git tag --sort=-creatordate', 'git tag --contains HEAD', 'git tag -n',+ 'git remote', 'git remote -v', 'git config --get user.name', 'git config --list', 'git config --global --get user.email', 'git config -l', 'git config --get-all remote.origin.fetch', 'git config --show-origin --list',+ 'git rev-parse HEAD', 'git rev-parse --abbrev-ref HEAD', 'git rev-parse --show-toplevel', 'git rev-parse --short HEAD', 'git rev-parse --is-inside-work-tree', 'git rev-parse --git-dir',+ 'git ls-files', 'git ls-files --others --exclude-standard', 'git ls-files -m', 'git ls-files -s', 'git blame a.txt', 'git blame -L 1,10 a.txt', 'git describe --tags', 'git describe --always --dirty',+ 'git shortlog -sn', 'git shortlog -s -n --all', 'git rev-list --count HEAD', 'git rev-list HEAD~5..HEAD', 'git cat-file -p HEAD', 'git cat-file -t HEAD', 'git ls-tree HEAD', 'git ls-tree -r --name-only HEAD',+ 'git grep foo', 'git grep -n foo', 'git grep -n -i foo -- src', 'git grep -l foo', 'git grep -e foo --and -e bar', 'git grep -c foo', 'git grep -w -F "a.b"', 'git grep --no-index foo',+ // PowerShell+ 'Get-ChildItem', 'Get-ChildItem -Recurse src | Select-Object -First 5', 'Get-ChildItem -Path . -Recurse -Filter *.mjs | Select-Object -First 5 FullName', 'Get-ChildItem -Force -ErrorAction SilentlyContinue',+ 'ls -Recurse', 'ls -Force', 'gci -Recurse -File', 'dir -Name', 'Get-ChildItem -Directory -Depth 2', 'Get-Content a.txt', 'Get-Content a.txt -Raw', 'Get-Content a.txt -Tail 5', 'Get-Content a.txt -TotalCount 5',+ 'Get-Content -Path a.txt', 'gc a.txt | Select-Object -First 3', 'cat a.txt | Select-String needle', 'type a.txt', 'Select-String -Path *.txt -Pattern foo -CaseSensitive', 'sls foo a.txt', 'Select-String -Pattern foo -Path a.txt -Context 2',+ 'Get-Content a.txt | Measure-Object -Line', 'Measure-Object -Property Length -Sum', 'Get-ChildItem | Where-Object Length -gt 100', 'Get-ChildItem | Sort-Object Length -Descending', 'Get-ChildItem | Group-Object Extension',+ 'Get-ChildItem | Select-Object Name, Length | Format-Table -AutoSize', 'Get-ChildItem | Format-List', 'Get-ChildItem | Out-String', 'Test-Path a.txt', 'Test-Path a.txt -PathType Leaf', 'Resolve-Path .',+ 'Get-FileHash a.txt', 'Get-FileHash a.txt -Algorithm SHA256', 'Get-Date', 'Get-Date -Format yyyy-MM-dd', 'Get-Command node', 'Get-Command -Name node -All', 'Get-Process', 'Get-Process -Name node', 'Get-Item a.txt', 'gi a.txt',+ 'Get-ItemProperty a.txt', 'Get-Location', 'pwd', 'Get-Help Get-ChildItem', 'Get-Help Get-ChildItem -Examples', 'Write-Output hello', 'hostname', 'whoami', 'Get-Host', 'Get-PSDrive', 'Get-PSDrive -Name C',+ 'Get-Content a.json | ConvertFrom-Json', 'Get-Content a.json | ConvertFrom-Json | ConvertTo-Json -Depth 3', 'Compare-Object a b', 'Get-Content a | Get-Unique',+ // versions+ 'node --version', 'node -v', 'python --version', 'git --version', 'dotnet --version', 'java -version', 'npm -v',+ ]);+});++test('#3975: maskQuotes still returns the quoted text to the caller, without changing what it returned before', () => {+ const quoted = [];+ assert.equal(maskQuotes('date "+%Y" \'a b\'', quoted), 'date "_" "_"');+ assert.deepEqual(quoted, ['+%Y', 'a b']);+ assert.equal(maskQuotes('Get-ChildItem "C:\\Q&A" | Select-Object Name'), 'Get-ChildItem "_" | Select-Object Name');+ assert.equal(maskQuotes('echo "$HOME"'), null);+});diff --git a/docs/SAFETY.md b/docs/SAFETY.mdindex 6145c4487..e377f355a 100644--- a/docs/SAFETY.md+++ b/docs/SAFETY.md@@ -164,7 +164,9 @@ In **Manual**:- **These ask:** writing or editing a file, any command that is not on a short list of look-only commands, and every toolyou connect. In the browser tool, opening a page, clicking and typing ask.- **These do not ask:** reading files, listing and searching folders, and look-only commands such as `ls`, `cat` and- `git status`. A command with a redirect, a chain (`;`, `&&`), a variable or anything else the check does not recognise asks.+ `git status`. Each of those commands runs unasked only with options that just look: `sort -o FILE`, `rg --pre PROGRAM`,+ `tail -f`, `date -s` and `git grep -O` ask, as does any option the check does not know. A command with a redirect, a+ chain (`;`, `&&`), a variable or anything else the check does not recognise asks.- **Web search and opening web pages ask once per chat.** The first one in a chat shows a card with the search words and theservice they go to, or with the address of the page. **Approve** covers the rest of that chat. **Deny** tells the assistantyou did not allow the web, and it carries on without it. Plan and Bypass do not ask. The model picks the search words and