@phren/agent 0.3.58 → 0.3.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,17 +9,12 @@
9
9
  * understand (redirection into a file, substitution, a leading variable
10
10
  * assignment, background `&`) is not auto-approvable.
11
11
  */
12
- /** Commands that only read. */
13
- const READ_ONLY = new Set([
14
- "ls", "cat", "head", "tail", "wc", "grep", "egrep", "fgrep", "rg", "pwd", "echo", "printf", "which", "type",
15
- "file", "stat", "du", "df", "tree", "diff", "cmp", "sort", "uniq", "cut", "tr", "basename", "dirname", "realpath",
16
- "readlink", "date", "true", "false", "test", "[", "jq", "nl", "column", "sha256sum", "shasum", "md5sum", "whoami",
17
- "uname", "hostname", "cd", "find", "sed",
18
- ]);
19
- /** Build, test and type-check tools, and the subcommands of multi-command tools that read, build or test. */
12
+ import { GIT_GLOBAL_SAFE, GIT_SPECS, optionArg, own, parseFind, parsedPaths, parseOptions, parseSed, READ_ONLY_SPECS } from "./shell-options.js";
13
+ /** Build, test and type-check tools, and the subcommands of multi-command tools that build or test. Their
14
+ * options are not listed one by one (they run the project's own code anyway); the ones that rewrite sources
15
+ * (`--fix`, `--write`) are refused. Read-only commands and git take only their listed options (shell-options.ts). */
20
16
  const RUNNERS = new Set(["tsc", "vitest", "jest", "mocha", "pytest", "mypy", "pyright"]);
21
17
  const SUBCOMMANDS = {
22
- git: new Set(["status", "diff", "log", "show", "rev-parse", "ls-files", "blame", "grep", "describe", "shortlog"]),
23
18
  npm: new Set(["test", "t", "run", "ls", "view", "outdated"]),
24
19
  pnpm: new Set(["test", "t", "run", "lint", "build", "typecheck", "ls", "list", "why", "outdated"]),
25
20
  yarn: new Set(["test", "run", "lint", "build", "typecheck", "list", "why"]),
@@ -31,112 +26,429 @@ const SUBCOMMANDS = {
31
26
  eslint: new Set(),
32
27
  biome: new Set(["check", "lint", "ci"]),
33
28
  };
34
- /** Arguments that turn a read-only command into one that writes or runs things. */
35
- const WRITING_ARGS = {
36
- find: /^-(exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls)$/,
37
- // -i edits in place; a script's w command writes a file and e runs one.
38
- sed: /^(-i|--in-place)|(^|[;{}\n]|\/[gpIiMm0-9]*)\s*[we](\s|$)/,
39
- eslint: /^--fix/,
40
- // git grep -O / --open-files-in-pager runs a program on the matches.
41
- git: /^(-o|--output|-[A-Za-z]*O|--open-files-in-pager)/,
42
- // sort -o writes its output file, also inside a cluster (-ro); --compress-program runs one.
43
- sort: /^(-[A-Za-z]*o|--output|--compress-program)/,
44
- tree: /^-[A-Za-z]*o/,
45
- // rg --pre runs a program on every file it searches.
46
- rg: /^--pre(=|$)/,
47
- };
48
- /**
49
- * git options before the subcommand that set config (core.fsmonitor and
50
- * diff.external run programs), swap git's own executables, or point it at
51
- * another repository: `git -c… status` is not `git status`.
52
- */
53
- const GIT_GLOBAL_UNSAFE = /^(-c|-C|--config-env|--exec-path|--git-dir|--work-tree)/;
54
- /** uniq options whose value is the next argument, not a file. */
55
- const UNIQ_VALUE_OPTION = /^(-f|-s|-w|--skip-fields|--skip-chars|--check-chars)$/;
29
+ /** Build and lint options that rewrite the project's sources. */
30
+ const FIXING_ARG = /^--(fix|write|apply|unsafe)(-[\w-]+)?(=|$)/;
31
+ /** git's options before the subcommand, and the subcommand, or null when an option there is not one of the
32
+ * few that keep it `git <subcommand>` (-c sets config that runs programs, -C and --git-dir switch repositories). */
33
+ function gitSubcommand(args) {
34
+ let i = 0;
35
+ while (i < args.length && args[i].startsWith("-")) {
36
+ if (!GIT_GLOBAL_SAFE.has(args[i]))
37
+ return null;
38
+ i++;
39
+ }
40
+ return i < args.length ? { sub: args[i], rest: args.slice(i + 1) } : null;
41
+ }
56
42
  function gitGlobalOptionsUnsafe(args) {
57
43
  for (const a of args) {
58
44
  if (!a.startsWith("-"))
59
45
  return false;
60
- if (GIT_GLOBAL_UNSAFE.test(a))
46
+ if (!GIT_GLOBAL_SAFE.has(a))
61
47
  return true;
62
48
  }
63
49
  return false;
64
50
  }
51
+ /**
52
+ * The files a simple command reads, as its own options parser sees them, or null when this reader has no
53
+ * spec for it or its arguments don't parse (an unlisted option). Search patterns, jq's filter and echo's
54
+ * words are not paths; a pattern given by -e makes every operand one.
55
+ */
56
+ export function commandPaths(tokens) {
57
+ const [binary, ...args] = tokens;
58
+ if (!binary || binary.includes("/"))
59
+ return null;
60
+ if (binary === "find")
61
+ return parseFind(args);
62
+ if (binary === "sed")
63
+ return parseSed(args);
64
+ if (binary === "git") {
65
+ const git = gitSubcommand(args);
66
+ const spec = git ? own(GIT_SPECS, git.sub) : undefined;
67
+ const parsed = git && spec && parseOptions(git.rest, spec);
68
+ // A `REV:PATH` operand's path is relative to the repository's top: gitRead's `blobs` has it.
69
+ return parsed && spec ? parsedPaths(parsed, spec).filter((p) => blobPath(p) === undefined) : null;
70
+ }
71
+ const spec = own(READ_ONLY_SPECS, binary);
72
+ const parsed = spec && parseOptions(args, spec);
73
+ return parsed && spec ? parsedPaths(parsed, spec) : null;
74
+ }
75
+ /** grep's options that choose which files a recursive grep reads. */
76
+ const GREP_SELECT = new Set(["-r", "-R", "--recursive", "--dereference-recursive", "-d", "--directories", "-D", "--devices",
77
+ "--include", "--exclude", "--exclude-dir", "--exclude-from", "-I", "-a", "--text", "--binary-files"]);
78
+ /** rg's options that change which files it reads, short and long. */
79
+ const RG_FILTERS = new Set(["-u", "-.", "-L", "-g", "-t", "-T", "-d", "--hidden", "--no-ignore", "--no-ignore-vcs", "--no-ignore-parent",
80
+ "--no-ignore-dot", "--unrestricted", "--follow", "--glob", "--iglob", "--glob-case-insensitive", "--type", "--type-not", "--type-add",
81
+ "--ignore-file", "--max-depth", "--no-config"]);
82
+ /** Where a command reads every file below a directory (grep -r, rg, diff -r, git grep, git diff --no-index),
83
+ * or null when it reads only the files named. The caller looks below each for a secret file, since no
84
+ * operand names it. */
85
+ export function recursiveReads(tokens) {
86
+ const [binary, ...args] = tokens;
87
+ if (!binary)
88
+ return null;
89
+ const parse = (spec, rest) => {
90
+ const parsed = spec && parseOptions(rest, spec);
91
+ return parsed && spec ? { parsed, paths: parsedPaths(parsed, spec) } : null;
92
+ };
93
+ const named = (options, ...names) => options.some((o) => names.includes(o.name));
94
+ if (binary === "grep" || binary === "egrep" || binary === "fgrep") {
95
+ const read = parse(own(READ_ONLY_SPECS, binary), args);
96
+ if (!read)
97
+ return null;
98
+ const { options } = read.parsed;
99
+ const follow = named(options, "-R", "--dereference-recursive");
100
+ // Any -d value but an exact `read` or `skip` may recurse (GNU takes `rec`, BSD `RECURSE`).
101
+ const directories = (o) => o.name === "-d" || o.name === "--directories";
102
+ const recursing = (o) => directories(o) && o.value !== "read" && o.value !== "skip";
103
+ const recurse = follow || named(options, "-r", "--recursive") || options.some(recursing);
104
+ if (!recurse)
105
+ return null;
106
+ // grep itself says which files its selection reads; the operands it names (not the -f/--exclude-from files) start it.
107
+ const patternGiven = named(options, "-e", "--regexp", "-f", "--file");
108
+ const roots = patternGiven ? read.parsed.operands : read.parsed.operands.slice(1);
109
+ // The listing recurses with -r whatever the run spelled: the grep here may not take that spelling (GNU refuses
110
+ // `-d RECURSE`, BSD takes it), and a listing that fails to recurse would see none of the files below.
111
+ const listArgs = options.filter((o) => GREP_SELECT.has(o.name) && !directories(o)).map(optionArg);
112
+ if (options.some(recursing))
113
+ listArgs.unshift("-r");
114
+ return { roots: roots.length ? roots : ["."], follow, scope: "grep", listArgs };
115
+ }
116
+ if (binary === "rg") {
117
+ const read = parse(own(READ_ONLY_SPECS, "rg"), args);
118
+ if (!read)
119
+ return null;
120
+ const { options } = read.parsed;
121
+ const listArgs = options.filter((o) => RG_FILTERS.has(o.name))
122
+ .flatMap((o) => (o.value === undefined ? [o.name] : o.name.startsWith("--") ? [`${o.name}=${o.value}`] : [o.name, o.value]));
123
+ return { roots: read.paths, follow: named(options, "-L", "--follow"), scope: "rg", listArgs };
124
+ }
125
+ if (binary === "diff") {
126
+ const read = parse(own(READ_ONLY_SPECS, "diff"), args);
127
+ return read && named(read.parsed.options, "-r", "--recursive") ? { roots: read.paths, follow: true, scope: "all" } : null;
128
+ }
129
+ if (binary === "git") {
130
+ const git = gitSubcommand(args);
131
+ const spec = git ? own(GIT_SPECS, git.sub) : undefined;
132
+ const read = git && spec ? parse(spec, git.rest) : null;
133
+ if (!git || !read)
134
+ return null;
135
+ const { options } = read.parsed;
136
+ // Two directories compared (`--no-index`, or by git itself when a path is outside the work tree), the
137
+ // files on one side only printed whole: every directory operand is read through.
138
+ if (git.sub === "diff")
139
+ return { roots: read.paths, follow: true, scope: "all" };
140
+ if (git.sub !== "grep")
141
+ return null;
142
+ const everything = named(options, "--untracked", "--no-index", "--no-exclude-standard", "--recurse-submodules");
143
+ // It searches the pathspecs it is given, else everything below cwd.
144
+ const roots = read.paths.length ? read.paths : ["."];
145
+ return { roots, follow: false, scope: everything ? "all" : "tracked" };
146
+ }
147
+ return null;
148
+ }
149
+ /** The file a `REV:PATH` (or index `:PATH`, `:N:PATH`) operand names, or undefined for a plain revision. A
150
+ * colon inside a reflog date (`main@{2026-10-01 10:00}`) is part of the revision. */
151
+ export function blobPath(operand) {
152
+ const plain = operand.replace(/@\{[^}]*\}/g, "");
153
+ const at = plain.indexOf(":");
154
+ if (at === -1)
155
+ return undefined;
156
+ const rest = plain.slice(at + 1);
157
+ return at === 0 && /^[0-3]:/.test(rest) ? rest.slice(2) : rest;
158
+ }
159
+ /** git options that print file contents as a patch (a `git log` without them prints none). `--binary` implies a patch. */
160
+ const GIT_PATCH_OPTIONS = new Set(["-p", "-u", "-U", "-W", "--patch", "--patch-with-stat", "--word-diff", "--color-words",
161
+ "--function-context", "--unified", "--binary"]);
162
+ /** The pickaxe: commits chosen by what their diffs contain, which textconv may compute. */
163
+ const GIT_PICKAXE = new Set(["-S", "-G"]);
164
+ /** git options whose output is computed from file contents (a diffstat), so textconv runs for them too. */
165
+ const GIT_STAT_OPTIONS = new Set(["--stat", "--numstat", "--shortstat", "--dirstat", "--cumulative", "--check", "--summary"]);
166
+ /** The options of a diff that choose what is compared (not how it prints). */
167
+ const GIT_DIFF_SELECT = new Set(["--cached", "--staged", "--merge-base", "--diff-filter", "-S", "-G", "--ignore-submodules"]);
168
+ /** The options of a log or show that choose its commits. */
169
+ const GIT_LOG_SELECT = new Set(["-NUM", "-n", "--max-count", "--skip", "--since", "--after", "--until", "--before", "--author",
170
+ "--committer", "--grep", "--all", "--branches", "--tags", "--remotes", "--merges", "--no-merges", "--first-parent", "--min-parents",
171
+ "--max-parents", "--regexp-ignore-case", "--all-match", "--invert-grep", "--ancestry-path", "--cherry-pick", "--cherry-mark",
172
+ "--left-right", "--full-history", "--simplify-by-decoration", "--follow", "-S", "-G", "--diff-filter", "--no-walk", "--mailmap",
173
+ "--use-mailmap", "--boundary"]);
174
+ export function gitRead(tokens) {
175
+ if (tokens[0] !== "git")
176
+ return null;
177
+ const git = gitSubcommand(tokens.slice(1));
178
+ const spec = git ? own(GIT_SPECS, git.sub) : undefined;
179
+ const parsed = git && spec ? parseOptions(git.rest, spec) : null;
180
+ if (!git || !parsed)
181
+ return null;
182
+ const has = (set) => parsed.options.some((o) => set.has(o.name));
183
+ const names = ["--name-only", "-z", "--no-renames", "--no-ext-diff", "--no-textconv"];
184
+ // Revisions and blobs come before a `--`; after it every operand is a pathspec.
185
+ const end = parsed.dashdash ?? parsed.operands.length;
186
+ const named = parsed.operands.slice(0, end), pathspecs = parsed.operands.slice(end);
187
+ const blobs = ["diff", "show"].includes(git.sub) ? named.flatMap((o) => blobPath(o) ?? []) : [];
188
+ const ask = parsed.options.filter((o) => o.name === "-C").length > 1;
189
+ switch (git.sub) {
190
+ case "diff":
191
+ // --no-index compares directories, which the recursive-read walk covers.
192
+ if (has(new Set(["--no-index"])))
193
+ return { helpers: ["diff", "filter"], blobs, ask };
194
+ return { helpers: ["diff", "filter"], blobs, ask, exposure: ["diff", ...names, ...listingOf(parsed, GIT_DIFF_SELECT)] };
195
+ case "log": {
196
+ const patch = has(GIT_PATCH_OPTIONS);
197
+ return { helpers: ["format", ...(patch || has(GIT_STAT_OPTIONS) || has(GIT_PICKAXE) ? ["diff"] : [])], blobs, ask,
198
+ ...(patch ? { exposure: ["log", ...names, "--format=", "-m", ...listingOf(parsed, GIT_LOG_SELECT)] } : {}) };
199
+ }
200
+ case "show": {
201
+ // A `REV:PATH` operand is a blob (`blobs`); the commits shown are the others (HEAD when nothing is named).
202
+ // Only blobs named: no commit's patch is shown.
203
+ const revs = named.filter((o) => blobPath(o) === undefined);
204
+ if (named.length && !revs.length)
205
+ return { helpers: ["diff", "format"], blobs, ask };
206
+ const shown = { options: parsed.options, operands: [...(revs.length ? revs : ["HEAD"]), ...pathspecs],
207
+ ...(parsed.dashdash !== undefined ? { dashdash: revs.length || 1 } : {}) };
208
+ return { helpers: ["diff", "format"], blobs, ask,
209
+ exposure: ["log", "--no-walk", ...names, "--format=", "-m", ...listingOf(shown, GIT_LOG_SELECT)] };
210
+ }
211
+ case "blame": return { helpers: ["diff", "filter"], blobs };
212
+ // `-v` prints the staged patch, `-vv` the unstaged one too: every change against HEAD.
213
+ case "status":
214
+ return has(new Set(["-v", "--verbose"])) ? { helpers: ["diff", "filter"], blobs, exposure: ["diff", ...names, "HEAD"] } : { helpers: ["filter"], blobs };
215
+ case "grep": return { helpers: ["filter"], blobs };
216
+ case "shortlog": return { helpers: ["format"], blobs };
217
+ default: return { helpers: [], blobs };
218
+ }
219
+ }
220
+ /** The arguments a listing keeps from the run: its selecting options, revisions and pathspecs (after a `--`
221
+ * where it had one). */
222
+ function listingOf(parsed, select) {
223
+ const before = parsed.dashdash === undefined ? parsed.operands : parsed.operands.slice(0, parsed.dashdash);
224
+ const after = parsed.dashdash === undefined ? [] : parsed.operands.slice(parsed.dashdash);
225
+ return [...parsed.options.filter((o) => select.has(o.name)).map(optionArg), ...before, ...(after.length ? ["--", ...after] : [])];
226
+ }
227
+ /**
228
+ * Whether a printf format only prints: every `%` directive is a known conversion (or `%%`), never `%n`, which
229
+ * stores a count in a variable (`printf '%n' PATH` empties PATH), and every backslash escape is a plain one
230
+ * (an octal or hex escape could spell a `%` this check didn't read).
231
+ */
232
+ export function printfFormatIsPlain(format) {
233
+ for (let i = 0; i < format.length; i++) {
234
+ const c = format[i];
235
+ if (c === "\\") {
236
+ if (!/["'\\abefnrtv]/.test(format[i + 1] ?? ""))
237
+ return false;
238
+ i++;
239
+ continue;
240
+ }
241
+ if (c !== "%")
242
+ continue;
243
+ if (format[i + 1] === "%") {
244
+ i++;
245
+ continue;
246
+ }
247
+ const directive = /^%[-+ #0']*(\*|\d+)?(\.(\*|\d+)?)?(\([^()%]*\)T|[diouxXfFeEgGaAcsbq])/.exec(format.slice(i));
248
+ if (!directive)
249
+ return false;
250
+ i += directive[0].length - 1;
251
+ }
252
+ return true;
253
+ }
254
+ /** Whether a jq program starts with a module directive (`import "x" as $d;`, `include "x";`, `module {…};`),
255
+ * which reads files no check here sees. Directives come only before the program's body; a field `.import` or
256
+ * a string "include" is not one. */
257
+ export function jqHasModuleDirective(program) {
258
+ let rest = program;
259
+ for (;;) {
260
+ rest = rest.replace(/^\s+/, "");
261
+ if (!rest.startsWith("#"))
262
+ break;
263
+ // Ended at either line break, so a comment jq ends sooner never hides a directive from this check.
264
+ const end = rest.search(/[\r\n]/);
265
+ rest = end === -1 ? "" : rest.slice(end + 1);
266
+ }
267
+ return /^(import|include|module)(?![\w$])/.test(rest);
268
+ }
269
+ /** Whether a read-only command or a git read takes only its listed options (and date only +FORMAT). */
270
+ function readOnlyIsSafe(name, args) {
271
+ if (name === "find")
272
+ return parseFind(args) !== null;
273
+ if (name === "sed")
274
+ return parseSed(args) !== null;
275
+ if (name === "git") {
276
+ const git = gitSubcommand(args);
277
+ const spec = git ? own(GIT_SPECS, git.sub) : undefined;
278
+ const parsed = git && spec ? parseOptions(git.rest, spec) : null;
279
+ if (!parsed)
280
+ return false;
281
+ // `%G…` placeholders verify signatures, which runs gpg.program.
282
+ if (parsed.options.some((o) => (o.name === "--format" || o.name === "--pretty") && o.value?.includes("%G")))
283
+ return false;
284
+ // Pathspec magic (`:/`, `:(top)`) and `..` reach past where the search below cwd was looked at.
285
+ if (git.sub === "grep" && parsed.operands.some((o) => o.startsWith(":") || o.split("/").includes("..")))
286
+ return false;
287
+ return true;
288
+ }
289
+ const spec = own(READ_ONLY_SPECS, name);
290
+ if (!spec)
291
+ return undefined;
292
+ if (name === "printf") {
293
+ // `printf -v NAME` and a `%n` directive assign a variable (`printf -v PATH .` changes what the next command runs).
294
+ if (args[0]?.startsWith("-v"))
295
+ return false;
296
+ const format = args[0] === "--" ? args[1] : args[0];
297
+ return format === undefined || printfFormatIsPlain(format);
298
+ }
299
+ const parsed = parseOptions(args, spec);
300
+ if (!parsed)
301
+ return false;
302
+ // A bare date operand sets the clock.
303
+ if (name === "date" && parsed.operands.some((o) => !o.startsWith("+")))
304
+ return false;
305
+ // A jq program's `import "x" as $d` and `include` read files (searching paths it names) no check here sees.
306
+ if (name === "jq" && jqHasModuleDirective(parsed.operands[0] ?? ""))
307
+ return false;
308
+ return true;
309
+ }
65
310
  /** Package scripts that `npm run` and friends may run unprompted. */
66
311
  const SAFE_SCRIPT = /^(test|build|lint|check|typecheck|type-check|tsc|compile)(:[\w:-]+)?$/;
312
+ /** A script variant that rewrites sources or snapshots (`lint:fix`, `test:update`). */
313
+ const REWRITING_SCRIPT = /fix|write|format|apply|update|snapshot/i;
67
314
  const SCRIPT_RUNNERS = new Set(["npm", "pnpm", "yarn", "bun"]);
68
315
  /** Multi-command tools whose allowlist entries are scoped to the subcommand. */
69
316
  export const MULTI_COMMAND_TOOLS = new Set([
70
317
  "git", "npm", "pnpm", "yarn", "bun", "npx", "cargo", "go", "docker", "kubectl", "gh", "pip", "pip3", "uv", "poetry",
71
318
  "brew", "dotnet", "mvn", "gradle", "terraform", "helm", "systemctl", "apt", "apt-get", "ruff", "biome",
72
319
  ]);
320
+ const GLOB = /[*?]|\[[^\]]*\]|\{[^{}]*(,|\.\.)[^{}]*\}/;
73
321
  /** A command line split into its simple commands, or null when it has constructs this reader won't vouch for. */
74
322
  export function splitCommandLine(command) {
323
+ return splitCommandWords(command)?.map((segment) => segment.words) ?? null;
324
+ }
325
+ /** As splitCommandLine, with which words the shell would expand. */
326
+ export function splitCommandWords(command) {
75
327
  const segments = [];
76
328
  let tokens = [];
329
+ let globbed = [];
330
+ let home = [];
77
331
  let current = "";
332
+ // The token's unquoted, unescaped characters: only these can glob.
333
+ let bare = "";
334
+ // Whether the token's first character was neither quoted nor escaped (undefined before it has one).
335
+ let firstBare;
336
+ const begin = (plain) => { if (!inToken)
337
+ firstBare = plain; inToken = true; };
338
+ // A `$NAME` or `${…}` outside single quotes: the word is whatever the variable holds. `$'…'` and `$"…"`
339
+ // too: bash decodes their escapes (`$'\056env'` is `.env`, `$'\055o'` is `-o`) where no check here looks.
340
+ let expands = false;
78
341
  let inToken = false;
79
342
  let quote = null;
80
343
  const endToken = () => {
81
- if (inToken)
344
+ // A leading `~` bash expands: unquoted, and the word is `~` or goes on with an unquoted `/`.
345
+ const homeTilde = firstBare === true && (current === "~" ? bare === "~" : current.startsWith("~/") && bare.startsWith("~/"));
346
+ // An unquoted `~name`, `~+` or `~-` at the start is a home directory or $PWD/$OLDPWD, never what the word
347
+ // says; one after `=` or `:` (`a=~/x`, an assignment-looking word) is expanded too, where no check looks.
348
+ const tilde = (firstBare === true && bare.startsWith("~") && !homeTilde) || /[=:]~/.test(bare);
349
+ if (inToken) {
82
350
  tokens.push(current);
351
+ globbed.push(expands || tilde || GLOB.test(bare));
352
+ home.push(homeTilde);
353
+ }
83
354
  current = "";
355
+ bare = "";
356
+ expands = false;
84
357
  inToken = false;
358
+ firstBare = undefined;
85
359
  };
86
- const endSegment = () => {
360
+ // Inside double quotes `$"` is a `$` before the closing quote, and `$'` a `$` before a quote character.
361
+ // `$[…]` is bash's old arithmetic, which assigns (`"$[PATH=0]"`), quoted or not.
362
+ const variable = (i, quoted = false) => command[i] === "$"
363
+ && (quoted ? /[A-Za-z_{0-9@*#?$![-]/ : /[A-Za-z_{0-9@*#?$!'"[-]/).test(command[i + 1] ?? "");
364
+ // The operator before the segment being read, and the one that ends it.
365
+ let before = "";
366
+ const endSegment = (after = "") => {
87
367
  endToken();
88
- if (tokens.length > 0)
89
- segments.push(tokens);
368
+ if (tokens.length === 0) {
369
+ // An empty segment (`a &&⏎ b`) keeps the operator before it, unless this one is a pipe.
370
+ if (after === "|" || after === "||")
371
+ before = after;
372
+ return;
373
+ }
374
+ segments.push({ words: tokens, globbed, home, before, after });
375
+ before = after;
90
376
  tokens = [];
377
+ globbed = [];
378
+ home = [];
91
379
  };
92
380
  for (let i = 0; i < command.length; i++) {
93
381
  const c = command[i];
382
+ // A line continuation: bash drops the backslash and newline and joins the word (`sec\⏎rets.json`), which this
383
+ // reader would keep as two characters, so it isn't vouched for (outside single quotes, where it is literal).
384
+ if (c === "\\" && command[i + 1] === "\n" && quote !== "'")
385
+ return null;
94
386
  if (quote) {
387
+ // Inside double quotes a backslash escapes `"`, `\`, `$` and a backquote: `"a\" b"` is one word, and
388
+ // reading `\"` as the closing quote would put the rest of the line outside it.
389
+ if (quote === '"' && c === "\\" && /["\\$`]/.test(command[i + 1] ?? "")) {
390
+ current += command[++i];
391
+ continue;
392
+ }
95
393
  if (c === quote)
96
394
  quote = null;
97
395
  else if (quote === '"' && (c === "`" || (c === "$" && command[i + 1] === "(")))
98
396
  return null;
99
- else
397
+ else {
398
+ if (quote === '"' && variable(i, true))
399
+ expands = true;
100
400
  current += c;
401
+ }
101
402
  continue;
102
403
  }
404
+ if (variable(i))
405
+ expands = true;
406
+ // A comment: bash ignores the rest of the line, quotes in it included, which this reader would not.
407
+ if (c === "#" && !inToken)
408
+ return null;
103
409
  if (c === "'" || c === '"') {
104
410
  quote = c;
105
- inToken = true;
411
+ begin(false);
106
412
  continue;
107
413
  }
108
414
  if (c === "\\") {
109
415
  current += command[i + 1] ?? "";
110
- inToken = true;
416
+ begin(false);
111
417
  i++;
112
418
  continue;
113
419
  }
114
420
  if (c === "`" || (c === "$" && command[i + 1] === "(") || c === "<" && command[i + 1] === "(")
115
421
  return null;
116
422
  if (c === "&" && command[i + 1] === "&") {
117
- endSegment();
423
+ endSegment("&&");
118
424
  i++;
119
425
  continue;
120
426
  }
121
427
  if (c === "|") {
122
- endSegment();
123
- if (command[i + 1] === "|")
428
+ if (command[i + 1] === "|") {
429
+ endSegment("||");
124
430
  i++;
431
+ }
432
+ else
433
+ endSegment("|");
125
434
  continue;
126
435
  }
127
436
  if (c === ";" || c === "\n") {
128
- endSegment();
437
+ endSegment(";");
129
438
  continue;
130
439
  }
131
440
  if (c === "&" || c === ">" || c === "<") {
132
- // Only the harmless redirections: stderr into stdout, output thrown away.
441
+ // Only the harmless redirections: stderr into stdout, output thrown away. The whole target must be that
442
+ // descriptor or /dev/null (`>&1pwned` writes the file 1pwned).
133
443
  const rest = command.slice(i);
134
- const harmless = /^(?:>&[12]|>\s*\/dev\/null|&>\s*\/dev\/null)/.exec(rest);
444
+ const harmless = /^(?:>&[12]|>[ \t]*\/dev\/null|&>[ \t]*\/dev\/null)(?=$|[ \t\n;|&])/.exec(rest);
135
445
  const fd = current === "1" || current === "2" ? current : null;
136
446
  if (!harmless || (inToken && !fd))
137
447
  return null;
138
448
  current = "";
449
+ bare = "";
139
450
  inToken = false;
451
+ firstBare = undefined;
140
452
  i += harmless[0].length - 1;
141
453
  continue;
142
454
  }
@@ -144,39 +456,33 @@ export function splitCommandLine(command) {
144
456
  endToken();
145
457
  continue;
146
458
  }
459
+ begin(true);
147
460
  current += c;
148
- inToken = true;
461
+ bare += c;
149
462
  }
150
463
  if (quote)
151
464
  return null;
152
465
  endSegment();
153
466
  return segments;
154
467
  }
155
- function segmentIsSafe(tokens) {
468
+ function segmentIsSafe({ words: tokens, globbed }) {
156
469
  const [binary, ...args] = tokens;
157
470
  // A leading assignment (PATH=… cmd) can change what runs.
158
471
  if (!binary || /^[A-Za-z_][A-Za-z0-9_]*=/.test(binary))
159
472
  return false;
160
- const name = binary.includes("/") ? "" : binary;
161
- // After `--` every argument is an operand, never an option (find's
162
- // expression and sed's script are checked whole).
163
- const end = name === "find" || name === "sed" ? -1 : args.indexOf("--");
164
- const options = end === -1 ? args : args.slice(0, end);
165
- const writing = WRITING_ARGS[name];
166
- if (writing && options.some((a) => writing.test(a)))
473
+ // A word the shell expands into file names is not what any check here read.
474
+ if (globbed.some(Boolean))
167
475
  return false;
168
- // uniq IN OUT overwrites OUT.
169
- if (name === "uniq") {
170
- const operands = options.filter((a, i) => !a.startsWith("-") && !UNIQ_VALUE_OPTION.test(options[i - 1] ?? "")).length
171
- + (end === -1 ? 0 : args.length - end - 1);
172
- if (operands > 1)
173
- return false;
174
- }
175
- if (name === "git" && gitGlobalOptionsUnsafe(args))
476
+ const name = binary.includes("/") ? "" : binary;
477
+ const readOnly = readOnlyIsSafe(name, args);
478
+ if (readOnly !== undefined)
479
+ return readOnly;
480
+ // Past `--` too: `npm run lint -- --fix` hands --fix on to the script's own tool.
481
+ if (args.some((a) => FIXING_ARG.test(a)))
176
482
  return false;
177
- if (READ_ONLY.has(name) || RUNNERS.has(name))
483
+ if (RUNNERS.has(name))
178
484
  return true;
179
- const subs = SUBCOMMANDS[name];
485
+ const subs = own(SUBCOMMANDS, name);
180
486
  if (!subs)
181
487
  return false;
182
488
  if (subs.size === 0)
@@ -186,13 +492,14 @@ function segmentIsSafe(tokens) {
186
492
  if (sub === undefined || !subs.has(sub))
187
493
  return false;
188
494
  // `npm run deploy` runs whatever the package says; only the usual check scripts pass.
189
- if (sub === "run" && SCRIPT_RUNNERS.has(name))
190
- return positional[1] !== undefined && SAFE_SCRIPT.test(positional[1]);
495
+ if (sub === "run" && SCRIPT_RUNNERS.has(name)) {
496
+ return positional[1] !== undefined && SAFE_SCRIPT.test(positional[1]) && !REWRITING_SCRIPT.test(positional[1]);
497
+ }
191
498
  return true;
192
499
  }
193
500
  /** True when every part of the command line only reads, builds or tests. */
194
501
  export function isAutoApprovableCommand(command) {
195
- const segments = splitCommandLine(command);
502
+ const segments = splitCommandWords(command);
196
503
  return segments !== null && segments.length > 0 && segments.every(segmentIsSafe);
197
504
  }
198
505
  /** The allowlist pattern for one simple command: the binary, plus the subcommand for multi-command tools. */