@agent-corpus/policy-manager 0.4.0 → 0.6.0

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.
package/dist/flow.js CHANGED
@@ -1,8 +1,10 @@
1
+ import { accessSync, constants, statSync } from "node:fs";
1
2
  import { homedir } from "node:os";
2
- import { basename, join, resolve } from "node:path";
3
+ import { basename, isAbsolute, join, posix, resolve } from "node:path";
4
+ import { canonical, resolveWord, UNKNOWN_CWD } from "./evidence.js";
3
5
  import { BANNED_ENV, human, redirectDecision, simpleDecision, unwrap } from "./permissive.js";
4
6
  import { result } from "./policy.js";
5
- import { parseScript, SUBSTITUTION, } from "./script.js";
7
+ import { applyParamOp, parseScript, SUBSTITUTION, } from "./script.js";
6
8
  /**
7
9
  * Walks a parsed script and judges every command that could run. The state carried along is the
8
10
  * set of directories the next command could run in and the variables whose value is known. A
@@ -20,8 +22,26 @@ const MAX_JUDGEMENTS = 400;
20
22
  const SIMPLE_VALUE = /^[A-Za-z0-9_@%+=:,./-]+$/;
21
23
  const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
22
24
  const UNSUPPORTED = "Unsupported shell syntax; expansions and subshells need human review";
23
- const copy = (state) => ({ cwds: [...state.cwds], vars: new Map(state.vars) });
25
+ const MAX_CALL_DEPTH = 4;
26
+ /** Positional parameters: never from the environment, unknown unless `set --` or a call set them. */
27
+ const POSITIONAL = /^(?:[0-9]+|[@*])$/;
28
+ /** Prefix of an entry in an assigned-name set that stands for a function definition. */
29
+ const FUNCTION_MARK = "()";
30
+ const copy = (state) => ({
31
+ cwds: [...state.cwds],
32
+ ...(state.failed ? { failed: [...state.failed] } : {}),
33
+ vars: new Map(state.vars),
34
+ funcs: new Map(state.funcs),
35
+ });
36
+ /** The last `cd` may have failed: every directory it could have left the shell in is possible. */
37
+ function settle(state) {
38
+ if (state.failed)
39
+ state.cwds = [...new Set([...state.cwds, ...state.failed])];
40
+ delete state.failed;
41
+ }
42
+ /** Every directory either state could be in; neither input is changed. */
24
43
  function merge(a, b) {
44
+ const cwds = [...a.cwds, ...(a.failed ?? []), ...b.cwds, ...(b.failed ?? [])];
25
45
  const vars = new Map();
26
46
  for (const [name, left] of a.vars) {
27
47
  if (!b.vars.has(name))
@@ -30,11 +50,21 @@ function merge(a, b) {
30
50
  const union = left && right ? [...new Set([...left, ...right])] : null;
31
51
  vars.set(name, union && union.length <= MAX_VARIANTS ? union : null);
32
52
  }
33
- return { cwds: [...new Set([...a.cwds, ...b.cwds])], vars };
53
+ const funcs = new Map();
54
+ for (const name of new Set([...a.funcs.keys(), ...b.funcs.keys()])) {
55
+ const left = a.funcs.get(name);
56
+ funcs.set(name, left && left === b.funcs.get(name) ? left : null);
57
+ }
58
+ return { cwds: [...new Set(cwds)], vars, funcs };
34
59
  }
35
60
  function replace(target, source) {
36
61
  target.cwds = source.cwds;
62
+ if (source.failed)
63
+ target.failed = source.failed;
64
+ else
65
+ delete target.failed;
37
66
  target.vars = source.vars;
67
+ target.funcs = source.funcs;
38
68
  }
39
69
  // --- words ------------------------------------------------------------------------------------
40
70
  const isKnown = (values) => !!values?.length && values.every((v) => SIMPLE_VALUE.test(v));
@@ -60,22 +90,61 @@ const ENVIRONMENT_OK = new Set([
60
90
  "COLUMNS",
61
91
  "LINES",
62
92
  ]);
93
+ /**
94
+ * Programs whose output depends only on their literal arguments (and the directory), so a
95
+ * substitution of one can be computed: `$(dirname /a/b)` is `/a`. A function of the same name
96
+ * replaces the program, so a defined one makes the output unknown again.
97
+ */
98
+ const PURE = new Set(["dirname", "basename", "pwd"]);
99
+ const pureCache = new Map();
100
+ /** The single `dirname x`, `basename x [suffix]` or `pwd` command a substitution runs, if it is. */
101
+ function pureCommand(inner) {
102
+ let cached = pureCache.get(inner);
103
+ if (cached === undefined) {
104
+ const script = parseScript(inner);
105
+ const item = script?.items.length === 1 ? script.items[0] : undefined;
106
+ const node = item && !item.background && !item.node.rest.length ? item.node.first : undefined;
107
+ const stage = node && !node.negated && node.stages.length === 1 ? node.stages[0] : undefined;
108
+ const name = stage?.kind === "simple" ? plainText(stage.argv[0]) : undefined;
109
+ cached =
110
+ stage?.kind === "simple" &&
111
+ name !== undefined &&
112
+ PURE.has(name) &&
113
+ !stage.assigns.length &&
114
+ !stage.redirects.length &&
115
+ stage.argv.every((w) => !w.subs.length && !w.glob)
116
+ ? stage
117
+ : null;
118
+ if (pureCache.size > 256)
119
+ pureCache.clear();
120
+ pureCache.set(inner, cached);
121
+ }
122
+ return cached ?? undefined;
123
+ }
124
+ function wordNames(word, out) {
125
+ for (const part of word.parts)
126
+ if (typeof part === "object" && "name" in part)
127
+ out.add(part.name);
128
+ else if (typeof part === "object" && part.inner !== undefined) {
129
+ const pure = pureCommand(part.inner);
130
+ if (pure)
131
+ for (const w of pure.argv)
132
+ wordNames(w, out);
133
+ }
134
+ }
63
135
  function environmentRefs(ctx, words, state) {
136
+ const names = new Set();
64
137
  for (const word of words)
65
- for (const part of word.parts)
66
- if (typeof part === "object" &&
67
- "name" in part &&
68
- !state.vars.has(part.name) &&
69
- !ENVIRONMENT_OK.has(part.name))
70
- return human(ctx.request, "unknown", "An environment variable of unknown content requires human review");
138
+ wordNames(word, names);
139
+ for (const name of names)
140
+ if (!state.vars.has(name) && !ENVIRONMENT_OK.has(name) && !POSITIONAL.test(name))
141
+ return human(ctx.request, "unknown", "An environment variable of unknown content requires human review");
71
142
  return undefined;
72
143
  }
73
144
  function knownVariables(words, state) {
74
145
  const names = new Set();
75
146
  for (const word of words)
76
- for (const part of word.parts)
77
- if (typeof part === "object" && "name" in part)
78
- names.add(part.name);
147
+ wordNames(word, names);
79
148
  const known = [...names].filter((name) => isKnown(state.vars.get(name)));
80
149
  const size = (list) => list.reduce((n, k) => n * (state.vars.get(k)?.length ?? 1), 1);
81
150
  known.sort((a, b) => (state.vars.get(b)?.length ?? 0) - (state.vars.get(a)?.length ?? 0));
@@ -89,22 +158,54 @@ function combinations(known) {
89
158
  out = out.flatMap((env) => values.map((value) => ({ ...env, [name]: value })));
90
159
  return out;
91
160
  }
161
+ /** Output of a pure substitution for one choice of values, or undefined when it is unknown. */
162
+ function pureOutput(inner, known, env, state) {
163
+ const command = pureCommand(inner);
164
+ const name = command ? plainText(command.argv[0]) : undefined;
165
+ if (!command || name === undefined || state.funcs.has(name))
166
+ return undefined;
167
+ const args = [];
168
+ for (const word of command.argv.slice(1)) {
169
+ const { text } = instantiate(word, known, env, state);
170
+ if (!SIMPLE_VALUE.test(text) || text.startsWith("-"))
171
+ return undefined;
172
+ args.push(text);
173
+ }
174
+ let output;
175
+ if (name === "pwd")
176
+ output = args.length === 0 && state.cwds.length === 1 ? state.cwds[0] : "";
177
+ else if (name === "dirname" && args.length === 1)
178
+ output = posix.dirname(args[0]);
179
+ else if (name === "basename" && (args.length === 1 || args.length === 2)) {
180
+ const [path, suffix] = args;
181
+ const base = posix.basename(path);
182
+ output =
183
+ suffix && base !== suffix && base.endsWith(suffix) ? base.slice(0, -suffix.length) : base;
184
+ }
185
+ return output && SIMPLE_VALUE.test(output) ? output : undefined;
186
+ }
92
187
  /** Text of a word for one choice of variable values; unknown parts become SUBSTITUTION. */
93
- function instantiate(word, known, env) {
188
+ function instantiate(word, known, env, state) {
94
189
  let text = "";
95
190
  let loose = false;
96
191
  for (const part of word.parts) {
97
192
  if (typeof part === "string")
98
193
  text += part;
99
194
  else if ("unknown" in part) {
100
- text += SUBSTITUTION;
101
- loose ||= !part.quoted;
195
+ const output = state && part.inner !== undefined ? pureOutput(part.inner, known, env, state) : undefined;
196
+ if (output !== undefined)
197
+ text += output;
198
+ else {
199
+ text += SUBSTITUTION;
200
+ loose ||= !part.quoted;
201
+ }
102
202
  }
103
203
  else if (known.has(part.name))
104
- text += env[part.name] ?? "";
204
+ text += applyParamOp(env[part.name] ?? "", part.op);
105
205
  else {
106
206
  text += SUBSTITUTION;
107
- loose ||= !part.quoted;
207
+ // "$@" is one word per parameter even when quoted.
208
+ loose ||= !part.quoted || part.name === "@";
108
209
  }
109
210
  }
110
211
  return { text, loose };
@@ -154,11 +255,11 @@ function runRedirects(ctx, redirs, state) {
154
255
  for (const redir of redirs) {
155
256
  if (!redir.target)
156
257
  continue;
157
- const redirect = toRedirect(redir, instantiate(redir.target, known, env).text);
258
+ const redirect = toRedirect(redir, instantiate(redir.target, known, env, state).text);
158
259
  if (!redirect)
159
260
  continue;
160
261
  for (const cwd of state.cwds) {
161
- const check = redirectDecision(ctx.request, redirect, ctx.profile, cwd);
262
+ const check = redirectDecision(ctx.request, redirect, ctx.profile, cwd, fillFor(ctx, false));
162
263
  if (check)
163
264
  return check;
164
265
  }
@@ -221,14 +322,28 @@ function printTargets(args) {
221
322
  }
222
323
  return { names, unreadable: false };
223
324
  }
224
- function assignedInSimple(node, out) {
325
+ /** `$@` and `$*` are never stored, so they stay unknown (and `*` is the forget-everything mark). */
326
+ const POSITIONAL_NAMES = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
327
+ function assignedInSimple(node, out, funcs, seen) {
225
328
  if (!node.argv.length) {
226
329
  for (const a of node.assigns)
227
330
  out.add(a.name);
228
331
  return;
229
332
  }
230
- const name = basename(plainText(node.argv[0]) ?? "");
333
+ const literal = plainText(node.argv[0]);
334
+ const fn = literal === undefined ? undefined : funcs?.get(literal);
335
+ if (literal !== undefined && fn && !seen?.has(literal)) {
336
+ // A call runs the body in this shell, so what the body assigns is assigned here.
337
+ const visited = new Set([...(seen ?? []), literal]);
338
+ assignedInList(fn.body.body, out, funcs, visited);
339
+ }
340
+ else if (literal !== undefined && fn === null)
341
+ out.add("*");
342
+ const name = basename(literal ?? "");
231
343
  const args = node.argv.slice(1).map(plainText);
344
+ if (name === "set" || name === "shift")
345
+ for (const p of POSITIONAL_NAMES)
346
+ out.add(p);
232
347
  if (SPECIAL_BUILTINS.has(name))
233
348
  for (const a of node.assigns)
234
349
  out.add(a.name);
@@ -255,56 +370,72 @@ function assignedInSimple(node, out) {
255
370
  if (name === "read")
256
371
  out.add("REPLY");
257
372
  }
258
- function assignedInList(list, out) {
373
+ /**
374
+ * Names a list may assign, plus FUNCTION_MARK + name for each function it may define. With `funcs`,
375
+ * a call to a known function counts what its body assigns.
376
+ */
377
+ function assignedInList(list, out, funcs, seen) {
259
378
  for (const item of list.items) {
260
379
  const nodes = [item.node.first, ...item.node.rest.map((r) => r.node)];
261
380
  for (const node of nodes)
262
381
  for (const stage of node.stages)
263
- assignedInCommand(stage, out);
382
+ assignedInCommand(stage, out, funcs, seen);
264
383
  }
265
384
  }
266
- function assignedInCommand(command, out) {
385
+ function assignedInCommand(command, out, funcs, seen) {
386
+ const list = (l) => assignedInList(l, out, funcs, seen);
267
387
  switch (command.kind) {
268
388
  case "simple":
269
- assignedInSimple(command, out);
389
+ assignedInSimple(command, out, funcs, seen);
270
390
  return;
271
391
  case "subshell":
272
392
  case "group":
273
- assignedInList(command.body, out);
393
+ list(command.body);
274
394
  return;
275
395
  case "for":
276
396
  out.add(command.name);
277
- assignedInList(command.body, out);
397
+ list(command.body);
278
398
  return;
279
399
  case "while":
280
- assignedInList(command.cond, out);
281
- assignedInList(command.body, out);
400
+ list(command.cond);
401
+ list(command.body);
282
402
  return;
283
403
  case "if":
284
404
  for (const clause of command.clauses) {
285
- assignedInList(clause.cond, out);
286
- assignedInList(clause.body, out);
405
+ list(clause.cond);
406
+ list(clause.body);
287
407
  }
288
408
  if (command.otherwise)
289
- assignedInList(command.otherwise, out);
409
+ list(command.otherwise);
290
410
  return;
291
411
  case "case":
292
412
  for (const branch of command.branches)
293
- assignedInList(branch.body, out);
413
+ list(branch.body);
414
+ return;
415
+ case "function":
416
+ out.add(FUNCTION_MARK + command.name);
294
417
  return;
295
418
  }
296
419
  }
297
- /** An assignment to a name the analysis could not read (`*`) makes every variable unknown. */
420
+ /**
421
+ * An assignment to a name the analysis could not read (`*`) makes every variable unknown; a
422
+ * function that may have been redefined becomes uncertain.
423
+ */
298
424
  function forget(state, names) {
425
+ for (const name of names)
426
+ if (name.startsWith(FUNCTION_MARK))
427
+ state.funcs.set(name.slice(FUNCTION_MARK.length), null);
299
428
  if (names.has("*"))
300
429
  state.vars.clear();
301
430
  else
302
431
  for (const name of names)
303
- state.vars.set(name, null);
432
+ if (!name.startsWith(FUNCTION_MARK))
433
+ state.vars.set(name, null);
304
434
  }
305
435
  // --- simple commands --------------------------------------------------------------------------
306
436
  const STATEFUL = new Set([
307
437
  "cd",
438
+ "chdir",
308
439
  "pushd",
309
440
  "popd",
310
441
  "export",
@@ -363,7 +494,7 @@ function runSimple(ctx, node, state, stage, piped) {
363
494
  const build = (env) => {
364
495
  const loose = [];
365
496
  const argv = node.argv.map((word) => {
366
- const expanded = instantiate(word, known, env);
497
+ const expanded = instantiate(word, known, env, state);
367
498
  loose.push(expanded.loose);
368
499
  return expanded.text;
369
500
  });
@@ -371,7 +502,7 @@ function runSimple(ctx, node, state, stage, piped) {
371
502
  for (const redir of node.redirects) {
372
503
  if (!redir.target)
373
504
  continue;
374
- const redirect = toRedirect(redir, instantiate(redir.target, known, env).text);
505
+ const redirect = toRedirect(redir, instantiate(redir.target, known, env, state).text);
375
506
  if (redirect)
376
507
  redirects.push(redirect);
377
508
  }
@@ -383,9 +514,9 @@ function runSimple(ctx, node, state, stage, piped) {
383
514
  if (only?.op === "<<")
384
515
  stdin = only.body ?? "";
385
516
  else if (only?.op === "<<<" && only.target)
386
- stdin = `${instantiate(only.target, known, env).text}\n`;
517
+ stdin = `${instantiate(only.target, known, env, state).text}\n`;
387
518
  return {
388
- env: node.assigns.map((a) => [a.name, instantiate(a.value, known, env).text]),
519
+ env: node.assigns.map((a) => [a.name, instantiate(a.value, known, env, state).text]),
389
520
  argv,
390
521
  redirects,
391
522
  subs: [],
@@ -395,10 +526,38 @@ function runSimple(ctx, node, state, stage, piped) {
395
526
  };
396
527
  // A builtin the analysis must track can hide behind a variable (`X=cd; $X /etc`) or a wrapper
397
528
  // that runs it in the current shell (`command cd /etc`, `time cd /etc`).
529
+ // Likewise a function: `time f` and `X=f; $X` run it, and only a direct call is followed.
398
530
  for (const env of envs) {
399
- const effective = basename(unwrap(build(env).argv).argv[0] ?? "");
531
+ const argv = build(env).argv;
532
+ const effective = basename(unwrap(argv).argv[0] ?? "");
400
533
  if (STATEFUL.has(effective) && name !== effective)
401
534
  return human(request, "unknown", "A builtin behind a variable or wrapper requires human review");
535
+ if ((state.funcs.has(effective) && literal !== effective) ||
536
+ (state.funcs.has(argv[0] ?? "") && literal !== argv[0]))
537
+ return human(request, "unknown", "A function behind a variable or wrapper requires human review");
538
+ // `unset name` removes a function when no variable has that name, and zsh has its own
539
+ // removers, so a recorded function could stop shadowing the real program.
540
+ const args = unwrap(argv).argv.slice(1);
541
+ if (state.funcs.size &&
542
+ (UNDEFINES.has(effective) ||
543
+ // bash and sh read options only before the first name: `unset touch -v` removes `touch`.
544
+ (effective === "unset" &&
545
+ !(args[0] === "-v" && args.slice(1).every((a) => !a.startsWith("-"))))))
546
+ return human(request, "unknown", "Removing a definition after defining a function requires human review");
547
+ }
548
+ if (literal !== undefined && state.funcs.has(literal)) {
549
+ const fn = state.funcs.get(literal);
550
+ if (!fn)
551
+ return human(request, "unknown", "A function that may or may not be defined here requires human review");
552
+ return callFunction(ctx, node, fn, state, known, envs);
553
+ }
554
+ if (literal === "set" && plainText(node.argv[1]) === "--" && !node.assigns.length) {
555
+ const refusal = runRedirects(ctx, node.redirects, state);
556
+ if (refusal)
557
+ return refusal;
558
+ setPositional(ctx, state, node.argv.slice(2), known, envs);
559
+ ctx.box.last = result(request, "code-read", "Positional parameters", true);
560
+ return undefined;
402
561
  }
403
562
  if (!node.argv.length) {
404
563
  // Assignments on their own, or redirections with no command.
@@ -411,17 +570,17 @@ function runSimple(ctx, node, state, stage, piped) {
411
570
  for (const redir of node.redirects) {
412
571
  if (!redir.target)
413
572
  continue;
414
- const redirect = toRedirect(redir, instantiate(redir.target, known, env).text);
573
+ const redirect = toRedirect(redir, instantiate(redir.target, known, env, state).text);
415
574
  if (!redirect)
416
575
  continue;
417
576
  for (const cwd of state.cwds) {
418
- const check = redirectDecision(request, redirect, profile, cwd);
577
+ const check = redirectDecision(request, redirect, profile, cwd, fillFor(ctx, piped));
419
578
  if (check)
420
579
  return check;
421
580
  }
422
581
  }
423
582
  for (const a of node.assigns) {
424
- const texts = envs.map((env) => instantiate(a.value, known, env).text);
583
+ const texts = envs.map((env) => instantiate(a.value, known, env, state).text);
425
584
  if (texts.length && texts.every((t) => SIMPLE_VALUE.test(t))) {
426
585
  const set = [...new Set(texts)];
427
586
  if (set.length <= MAX_VARIANTS) {
@@ -439,17 +598,35 @@ function runSimple(ctx, node, state, stage, piped) {
439
598
  for (const cwd of state.cwds) {
440
599
  if (++ctx.box.calls > MAX_JUDGEMENTS)
441
600
  return human(request, "unknown", "Too many commands to verify");
442
- const decision = simpleDecision(request, command, profile, ctx.depth, stage, cwd);
601
+ const fill = fillFor(ctx, piped);
602
+ const decision = simpleDecision(request, command, profile, ctx.depth, stage, cwd, fill);
443
603
  if (decision.decision !== "approve")
444
604
  return decision;
445
605
  ctx.box.last = decision;
606
+ if (!symlinkFree(unwrap(command.argv).argv)) {
607
+ if (ctx.box.script.approved)
608
+ return human(request, "unknown", "A command that can create symlinks may run before an approved temp path");
609
+ ctx.box.script.tainted = true;
610
+ }
611
+ for (const dir of createdDirectories(unwrap(command.argv).argv)) {
612
+ if (cwd === UNKNOWN_CWD && !isAbsolute(dir))
613
+ continue;
614
+ ctx.box.created ??= new Set();
615
+ ctx.box.created.add(resolve(cwd, dir));
616
+ }
446
617
  }
447
618
  }
448
619
  // A prefix assignment before a special builtin outlives the command in some shells.
449
620
  if (name && SPECIAL_BUILTINS.has(name))
450
621
  for (const a of node.assigns)
451
622
  state.vars.set(a.name, null);
452
- if (name === "cd")
623
+ // `shift` moves every positional parameter down, and `set` with a non-option word (`set -e
624
+ // pipefail`) replaces them; only `set --` is tracked.
625
+ if (name === "shift" || name === "set")
626
+ for (const p of POSITIONAL_NAMES)
627
+ state.vars.set(p, null);
628
+ // zsh `chdir` is `cd`; in bash it fails, which leaves the starting directory possible anyway.
629
+ if (name === "cd" || name === "chdir")
453
630
  return changeDirectory(ctx, state, piped, envs, build);
454
631
  if (name === "export")
455
632
  return exportVariables(ctx, node, state, piped, known, envs);
@@ -474,11 +651,173 @@ function runSimple(ctx, node, state, stage, piped) {
474
651
  }
475
652
  return undefined;
476
653
  }
654
+ /** In a loop, a pipeline or a background job, a later command can run first. */
655
+ function fillFor(ctx, piped) {
656
+ return { script: ctx.box.script, reorder: ctx.loop > 0 || piped || !!ctx.reorder };
657
+ }
658
+ /**
659
+ * Programs that create no symlink: they read, print, or write regular files only. Shells are here
660
+ * because the script they run is judged with the same state.
661
+ */
662
+ const SYMLINK_FREE = new Set([
663
+ ...[":", "[", "test", "true", "false", "echo", "printf", "print", "pwd", "sleep", "date"],
664
+ ...["cd", "chdir", "export", "set", "shift", "unset", "read", "local"],
665
+ ...["cat", "head", "tail", "wc", "sort", "uniq", "cut", "tr", "paste", "diff", "cmp", "jq"],
666
+ ...["grep", "egrep", "fgrep", "rg", "sed", "ls", "stat", "file", "which", "type"],
667
+ ...["basename", "dirname", "realpath", "readlink", "mkdir", "touch", "tee"],
668
+ ...["rm", "rmdir", "unlink", "bash", "sh", "zsh", "dash"],
669
+ ...["seq", "mktemp", "chmod", "find", "curl", "du", "df", "tree", "column", "nl"],
670
+ ...["tac", "rev", "comm", "join", "fold", "od", "xxd", "shasum", "sha256sum", "md5sum", "md5"],
671
+ ...["whoami", "id", "uname", "hostname"],
672
+ ]);
673
+ /** git subcommands that leave the working tree as it is, or only add a fresh `.git`. */
674
+ const GIT_SYMLINK_FREE = new Set([
675
+ ...["status", "log", "diff", "show", "add", "commit", "init", "rev-parse", "ls-files"],
676
+ ...["branch", "config", "fetch", "remote", "describe", "push", "rev-list", "merge-base"],
677
+ ...["ls-remote", "cat-file", "for-each-ref", "symbolic-ref", "shortlog", "blame", "grep"],
678
+ ]);
679
+ /** git options that run another program. */
680
+ const GIT_RUNS = /^(?:-O|--open-files-in-pager|--upload-pack|--receive-pack|--exec|--ext-diff)/;
681
+ /** gh commands that only talk to GitHub or print: `api`, or a group with one of its verbs. */
682
+ const GH_SYMLINK_FREE = {
683
+ pr: new Set(["view", "list", "diff", "checks", "status", "create", "comment", "edit", "ready"]),
684
+ issue: new Set(["view", "list", "status", "create", "comment", "edit", "close", "reopen"]),
685
+ run: new Set(["view", "list", "watch", "rerun", "cancel"]),
686
+ repo: new Set(["view", "list"]),
687
+ release: new Set(["view", "list"]),
688
+ workflow: new Set(["view", "list"]),
689
+ label: new Set(["list"]),
690
+ auth: new Set(["status"]),
691
+ search: new Set(["prs", "issues", "repos", "code", "commits"]),
692
+ };
693
+ /**
694
+ * Whether a command is known to create no symlink. Anything else may plant one anywhere, so
695
+ * later temp paths in the script are no longer trusted. `cp` without options that copy links
696
+ * (`-R`, `-a`, `-P`, `-d`, long options) writes a regular file.
697
+ */
698
+ function symlinkFree(argv) {
699
+ const [path = "", ...args] = argv;
700
+ const program = basename(path);
701
+ if (program === "cp")
702
+ return args.every((arg) => !arg.startsWith("-") || /^-[finpv]+$/.test(arg));
703
+ if (program === "git") {
704
+ // `-c` can set a pager or other program for this one command.
705
+ let index = 0;
706
+ while (args[index] === "-C" || args[index] === "--no-pager")
707
+ index += args[index] === "-C" ? 2 : 1;
708
+ const sub = args[index] ?? "";
709
+ const rest = args.slice(index + 1);
710
+ if (rest.some((arg) => GIT_RUNS.test(arg)) || (sub === "ls-remote" && rest.includes("-u")))
711
+ return false;
712
+ return GIT_SYMLINK_FREE.has(sub) || (sub === "worktree" && rest[0] === "list");
713
+ }
714
+ if (program === "gh") {
715
+ const [group = "", verb = ""] = args;
716
+ return group === "api" || !!GH_SYMLINK_FREE[group]?.has(verb);
717
+ }
718
+ return SYMLINK_FREE.has(program);
719
+ }
720
+ /** Where a loop or pipeline starts, so its end can tell whether it started a background job. */
721
+ function reorderMark(ctx) {
722
+ return { approved: ctx.box.script.approved, jobs: ctx.box.script.jobs };
723
+ }
724
+ /**
725
+ * Once a foreground loop or pipeline ends, nothing in it can run after a later command, unless
726
+ * it started a background job, which may still be running.
727
+ */
728
+ function endReorder(ctx, mark) {
729
+ if (ctx.loop === 0 && !ctx.reorder && ctx.box.script.jobs === mark.jobs)
730
+ ctx.box.script.approved = mark.approved;
731
+ }
732
+ /** git clone options that take a separate value. */
733
+ const CLONE_VALUES = new Set([
734
+ "-b",
735
+ "--branch",
736
+ "-o",
737
+ "--origin",
738
+ "-c",
739
+ "--config",
740
+ "--depth",
741
+ "--reference",
742
+ "--separate-git-dir",
743
+ "-u",
744
+ "--upload-pack",
745
+ "--template",
746
+ "-j",
747
+ "--jobs",
748
+ "--filter",
749
+ "--shallow-since",
750
+ "--shallow-exclude",
751
+ ]);
752
+ /** Positional words of `args`, skipping options and the values of those in `values`. */
753
+ function positionals(args, values) {
754
+ const out = [];
755
+ for (let index = 0; index < args.length; index++) {
756
+ const word = args[index] ?? "";
757
+ if (word === "--")
758
+ return [...out, ...args.slice(index + 1)];
759
+ if (values.has(word))
760
+ index++;
761
+ else if (!word.startsWith("-"))
762
+ out.push(word);
763
+ }
764
+ return out;
765
+ }
766
+ /**
767
+ * Directories a command creates (as written, relative to its cwd): `mkdir` (with `-p`, every
768
+ * ancestor too), `git clone <url> [dir]`, `git worktree add <path>`, and the destination of `cp -r`
769
+ * or `mv`.
770
+ */
771
+ function createdDirectories(argv) {
772
+ const [program, ...args] = argv;
773
+ if (program === "mkdir") {
774
+ const parents = args.some((arg) => arg === "--parents" || /^-[^-]*p/.test(arg));
775
+ return positionals(args, new Set(["-m", "--mode"])).flatMap((dir) => {
776
+ if (!parents)
777
+ return [dir];
778
+ const parts = dir.split("/");
779
+ return parts.map((_, index) => parts.slice(0, index + 1).join("/") || "/");
780
+ });
781
+ }
782
+ if (program === "git" && args[0] === "clone") {
783
+ const [url, dir] = positionals(args.slice(1), CLONE_VALUES);
784
+ if (dir)
785
+ return [dir];
786
+ const name = url
787
+ ?.replace(/[\\/]+$/, "")
788
+ .split(/[/:]/)
789
+ .pop()
790
+ ?.replace(/\.git$/, "");
791
+ return name ? [name] : [];
792
+ }
793
+ if (program === "git" && args[0] === "worktree" && args[1] === "add") {
794
+ const [path] = positionals(args.slice(2), new Set(["-b", "-B", "--reason"]));
795
+ return path ? [path] : [];
796
+ }
797
+ if ((program === "cp" && args.some((arg) => /^-[^-]*[rRa]/.test(arg))) || program === "mv") {
798
+ const rest = positionals(args, new Set(["-t", "-S", "--suffix"]));
799
+ return rest.length > 1 ? [rest[rest.length - 1]] : [];
800
+ }
801
+ return [];
802
+ }
803
+ /** A relative `cd` target that does not start with `.`: CDPATH and CDABLE_VARS can redirect it. */
804
+ function bareName(word) {
805
+ return !isAbsolute(word) && !/^(?:\.{1,2}(?:[\\/]|$)|[\\/])/.test(word);
806
+ }
807
+ function isDirectory(path) {
808
+ try {
809
+ return statSync(path).isDirectory();
810
+ }
811
+ catch {
812
+ return false;
813
+ }
814
+ }
477
815
  function changeDirectory(ctx, state, piped, envs, build) {
478
816
  const { request } = ctx;
479
817
  if (piped || ctx.loop > 0)
480
818
  return human(request, "unknown", "Directory change in a loop or pipeline requires human review");
481
- let cwds = [...state.cwds];
819
+ settle(state);
820
+ let cwds = [];
482
821
  for (const env of envs) {
483
822
  const target = build(env)
484
823
  .argv.slice(1)
@@ -490,13 +829,43 @@ function changeDirectory(ctx, state, piped, envs, build) {
490
829
  !word ||
491
830
  word.includes(SUBSTITUTION) ||
492
831
  /^~|[*?[\]]/.test(word) ||
493
- word.startsWith("-"))
832
+ // `-N` and zsh `+N` pick directory-stack entries.
833
+ /^[+-]/.test(word) ||
834
+ // CDPATH (from the environment the shell inherited) redirects a relative name.
835
+ (process.env.CDPATH && bareName(word)))
836
+ return human(request, "unknown", "Directory change requires human review");
837
+ // bash and zsh `cd` is logical: `..` drops the last written component. In physical mode (`cd
838
+ // -P`, `set -P`, `setopt chase_links`) it leaves the symlink's target. When the two differ, which
839
+ // one the shell uses is unknown here, so a person decides.
840
+ let next;
841
+ try {
842
+ next = state.cwds.map((cwd) => {
843
+ const logical = resolve(cwd, word);
844
+ if (canonical(logical) !== canonical(resolveWord(cwd, raw)))
845
+ throw new Error("Logical and physical directories differ");
846
+ // A bare name that is not a directory, and that no earlier command creates, fails in a
847
+ // plain shell; options set in rc files (zsh CDABLE_VARS, a CDPATH set there) can still send
848
+ // it anywhere. The shell is then somewhere unknown, so nothing relative is approved there.
849
+ // `created` is recorded when a command is judged, not when it runs; with CDABLE_VARS a
850
+ // variable of the same name wins when the directory was not made.
851
+ if (bareName(word) &&
852
+ !isDirectory(logical) &&
853
+ (!ctx.box.created?.has(logical) ||
854
+ state.vars.has(word) ||
855
+ process.env[word] !== undefined))
856
+ return UNKNOWN_CWD;
857
+ return logical;
858
+ });
859
+ }
860
+ catch {
494
861
  return human(request, "unknown", "Directory change requires human review");
495
- // `cd` can fail, so the directory it started from stays possible.
496
- cwds = [...new Set([...cwds, ...state.cwds.map((cwd) => resolve(cwd, word))])];
862
+ }
863
+ cwds = [...new Set([...cwds, ...next])];
497
864
  }
498
- if (cwds.length > MAX_DIRECTORIES)
865
+ if (!cwds.length || cwds.length + state.cwds.length > MAX_DIRECTORIES)
499
866
  return human(request, "unknown", "Too many directory changes to verify");
867
+ // `cd` can fail, so the directory it started from stays possible unless `&&` follows.
868
+ state.failed = state.cwds;
500
869
  state.cwds = cwds;
501
870
  ctx.box.last = result(request, "code-read", "Directory change", true);
502
871
  return undefined;
@@ -517,7 +886,7 @@ function exportVariables(ctx, node, state, piped, known, envs) {
517
886
  }
518
887
  if (BANNED_ENV.test(assignment.name))
519
888
  return human(request, "unknown", "Environment override requires human review");
520
- const texts = envs.map((env) => instantiate(assignment.value, known, env).text);
889
+ const texts = envs.map((env) => instantiate(assignment.value, known, env, state).text);
521
890
  if (texts.length && texts.every((t) => SIMPLE_VALUE.test(t)))
522
891
  state.vars.set(assignment.name, [...new Set(texts)]);
523
892
  else
@@ -525,8 +894,309 @@ function exportVariables(ctx, node, state, piped, known, envs) {
525
894
  }
526
895
  return undefined;
527
896
  }
897
+ // --- positional parameters and functions ------------------------------------------------------
898
+ function clearPositional(state) {
899
+ const saved = new Map();
900
+ for (const [name, values] of state.vars)
901
+ if (/^[0-9]+$/.test(name)) {
902
+ saved.set(name, values);
903
+ state.vars.delete(name);
904
+ }
905
+ return saved;
906
+ }
907
+ /**
908
+ * The values each argument word gives, in order. A word that could split into a different number
909
+ * of words (an unquoted unknown, a glob) makes every later position unknown. Known values are
910
+ * single plain words, so bash and zsh (which does not split unquoted parameters) agree.
911
+ */
912
+ function argumentSlots(words, state, known, envs) {
913
+ const slots = [];
914
+ const add = (values) => slots.push(values.size <= MAX_VARIANTS && [...values].every((v) => SIMPLE_VALUE.test(v))
915
+ ? [...values]
916
+ : null);
917
+ for (const word of words) {
918
+ const texts = envs.map((env) => instantiate(word, known, env, state));
919
+ if (word.glob || texts.some((t) => t.loose))
920
+ return slots;
921
+ add(new Set(texts.map((t) => t.text)));
922
+ }
923
+ return slots;
924
+ }
925
+ /** Stores positional values; with tracking off (the script names zsh's `argv`) they are unknown. */
926
+ function bindPositional(ctx, state, slots) {
927
+ for (const [index, values] of slots.entries())
928
+ if (index < POSITIONAL_NAMES.length)
929
+ state.vars.set(String(index + 1), ctx.positional ? values : null);
930
+ }
931
+ function setPositional(ctx, state, words, known, envs) {
932
+ const slots = argumentSlots(words, state, known, envs);
933
+ clearPositional(state);
934
+ bindPositional(ctx, state, slots);
935
+ }
936
+ /**
937
+ * A call runs the body in this shell with the arguments as positional parameters; the caller's
938
+ * parameters come back afterwards. Words were already checked by the caller.
939
+ */
940
+ function callFunction(ctx, node, fn, state, known, envs) {
941
+ const { request } = ctx;
942
+ if (node.assigns.length)
943
+ return human(request, "unknown", "An assignment before a function call requires human review");
944
+ if (ctx.calls >= MAX_CALL_DEPTH)
945
+ return human(request, "unknown", "Function calls are nested too deeply");
946
+ const refusal = runRedirects(ctx, node.redirects, state);
947
+ if (refusal)
948
+ return refusal;
949
+ const slots = argumentSlots(node.argv.slice(1), state, known, envs);
950
+ const saved = clearPositional(state);
951
+ bindPositional(ctx, state, slots);
952
+ // `return` can stop the body anywhere, so the state after the call is any point in it: what the
953
+ // body assigns is unknown, and a directory change in between cannot be followed.
954
+ const returns = mayRun(fn.body.body, new Set(["return"]), state.funcs);
955
+ const moves = mayRun(fn.body.body, new Set(["cd", "chdir", "pushd", "popd"]), state.funcs);
956
+ const inner = { ...ctx, calls: ctx.calls + 1 };
957
+ const target = fn.body.kind === "subshell" ? copy(state) : state;
958
+ const body = runList(inner, fn.body.body, target);
959
+ if (body)
960
+ return body;
961
+ if (returns && moves && fn.body.kind === "group")
962
+ return human(request, "unknown", "A function that can return early and change directory requires human review");
963
+ if (returns) {
964
+ const changed = new Set();
965
+ assignedInList(fn.body.body, changed, state.funcs);
966
+ forget(state, changed);
967
+ }
968
+ clearPositional(state);
969
+ for (const [name, values] of saved)
970
+ state.vars.set(name, values);
971
+ return undefined;
972
+ }
973
+ /**
974
+ * True when a command named in `names`, or one whose name is not a literal, may run in the list,
975
+ * including in the bodies of known functions it calls. Substitutions run in a subshell and are
976
+ * not searched.
977
+ */
978
+ function mayRun(list, names, funcs, seen = new Set()) {
979
+ const lists = (ls) => ls.some((l) => mayRun(l, names, funcs, seen));
980
+ const command = (c) => {
981
+ switch (c.kind) {
982
+ case "simple": {
983
+ if (!c.argv.length)
984
+ return false;
985
+ const program = plainText(c.argv[0]);
986
+ if (program === undefined || names.has(basename(program)))
987
+ return true;
988
+ const fn = funcs.get(program);
989
+ if (fn === null)
990
+ return true;
991
+ if (fn && !seen.has(program)) {
992
+ seen.add(program);
993
+ return mayRun(fn.body.body, names, funcs, seen);
994
+ }
995
+ return c.argv.slice(1).some((w) => names.has(plainText(w) ?? ""));
996
+ }
997
+ // A function the body defines or redefines may be called later in it.
998
+ case "function":
999
+ return mayRun(c.body.body, names, funcs, seen);
1000
+ case "subshell":
1001
+ return false;
1002
+ case "group":
1003
+ return lists([c.body]);
1004
+ case "for":
1005
+ return lists([c.body]);
1006
+ case "while":
1007
+ return lists([c.cond, c.body]);
1008
+ case "if":
1009
+ return lists([
1010
+ ...c.clauses.flatMap((cl) => [cl.cond, cl.body]),
1011
+ ...(c.otherwise ? [c.otherwise] : []),
1012
+ ]);
1013
+ case "case":
1014
+ return lists(c.branches.map((b) => b.body));
1015
+ }
1016
+ };
1017
+ return list.items.some((item) =>
1018
+ // zsh runs a pipeline's last stage in this shell, so every stage is searched.
1019
+ [item.node.first, ...item.node.rest.map((r) => r.node)].some((p) => p.stages.some(command)));
1020
+ }
1021
+ /**
1022
+ * Names a shell may resolve before a function of the same name: zsh reserved words and precommand
1023
+ * modifiers, and other builtins that run or look up commands.
1024
+ */
1025
+ const NOT_A_FUNCTION = new Set([
1026
+ "time",
1027
+ "command",
1028
+ "builtin",
1029
+ "exec",
1030
+ "noglob",
1031
+ "nocorrect",
1032
+ "coproc",
1033
+ "nohup",
1034
+ "source",
1035
+ "eval",
1036
+ "type",
1037
+ "whence",
1038
+ "which",
1039
+ "hash",
1040
+ "enable",
1041
+ "disable",
1042
+ "autoload",
1043
+ "functions",
1044
+ "unfunction",
1045
+ "alias",
1046
+ ]);
1047
+ /** Builtins that can remove or replace a function definition. */
1048
+ const UNDEFINES = new Set(["unfunction", "unhash", "disable", "enable", "functions", "autoload"]);
1049
+ /**
1050
+ * Functions a shell runs with no call: zsh's special functions (zshmisc "Special Functions": the
1051
+ * hooks and TRAPxxx traps) and the not-found handlers of zsh and bash.
1052
+ */
1053
+ const SHELL_HOOK = /^(?:TRAP[A-Z0-9]+|chpwd|precmd|preexec|periodic|zshexit|zshaddhistory|command_not_found_handler|command_not_found_handle)$/;
1054
+ function defineFunction(ctx, node, state) {
1055
+ // sh and dash find a special builtin before a function, so the call would not be followed.
1056
+ if (SPECIAL_BUILTINS.has(node.name) ||
1057
+ STATEFUL.has(node.name) ||
1058
+ NOT_A_FUNCTION.has(node.name) ||
1059
+ BANNED_ENV.test(node.name))
1060
+ return human(ctx.request, "unknown", "A function named like a builtin requires human review");
1061
+ if (SHELL_HOOK.test(node.name))
1062
+ return human(ctx.request, "unknown", "A shell hook function requires human review");
1063
+ state.funcs.set(node.name, node);
1064
+ ctx.box.last = result(ctx.request, "code-read", "Function definition", true);
1065
+ return undefined;
1066
+ }
1067
+ /** Programs that never read standard input. */
1068
+ const NO_INPUT = new Set([
1069
+ "echo",
1070
+ "printf",
1071
+ "true",
1072
+ "false",
1073
+ "test",
1074
+ "[",
1075
+ ":",
1076
+ "basename",
1077
+ "dirname",
1078
+ "pwd",
1079
+ "sleep",
1080
+ "ls",
1081
+ "mkdir",
1082
+ ]);
1083
+ const GH_NO_INPUT = new Set([
1084
+ "pr view",
1085
+ "pr list",
1086
+ "pr checks",
1087
+ "pr diff",
1088
+ "issue view",
1089
+ "issue list",
1090
+ "run view",
1091
+ "run list",
1092
+ "repo view",
1093
+ "release view",
1094
+ "release list",
1095
+ ]);
1096
+ /**
1097
+ * True when nothing in the list can read the standard input it inherits. A loop body that reads
1098
+ * it would consume part of what `read` was going to see, so `read` could return any part of a line.
1099
+ */
1100
+ function readsNoInput(list, funcs) {
1101
+ const words = (w) => w.every((word) => word.subs.every((inner) => {
1102
+ const script = parseScript(inner);
1103
+ return !!script && readsNoInput(script, funcs);
1104
+ }));
1105
+ const ownInput = (redirs) => redirs.some((r) => r.fd === "0" && (r.op === "<" || r.op === "<<" || r.op === "<<<"));
1106
+ const command = (c) => {
1107
+ if (c.kind !== "function" && !words(c.redirects.flatMap((r) => (r.target ? [r.target] : []))))
1108
+ return false;
1109
+ switch (c.kind) {
1110
+ case "simple": {
1111
+ if (!words([...c.argv, ...c.assigns.map((a) => a.value)]))
1112
+ return false;
1113
+ if (!c.argv.length || ownInput(c.redirects))
1114
+ return true;
1115
+ const [program, first, second] = c.argv.slice(0, 3).map(plainText);
1116
+ if (program === undefined || funcs.has(program))
1117
+ return false;
1118
+ return NO_INPUT.has(program) || (program === "gh" && GH_NO_INPUT.has(`${first} ${second}`));
1119
+ }
1120
+ case "function":
1121
+ return true;
1122
+ case "for":
1123
+ return words(c.words) && (ownInput(c.redirects) || readsNoInput(c.body, funcs));
1124
+ case "case":
1125
+ return (words([c.word]) &&
1126
+ (ownInput(c.redirects) || c.branches.every((b) => readsNoInput(b.body, funcs))));
1127
+ case "if":
1128
+ return (ownInput(c.redirects) ||
1129
+ (c.clauses.every((cl) => readsNoInput(cl.cond, funcs) && readsNoInput(cl.body, funcs)) &&
1130
+ (!c.otherwise || readsNoInput(c.otherwise, funcs))));
1131
+ case "while":
1132
+ return (ownInput(c.redirects) || (readsNoInput(c.cond, funcs) && readsNoInput(c.body, funcs)));
1133
+ case "subshell":
1134
+ case "group":
1135
+ return ownInput(c.redirects) || readsNoInput(c.body, funcs);
1136
+ }
1137
+ };
1138
+ return list.items.every((item) => [item.node.first, ...item.node.rest.map((r) => r.node)].every((p) => p.stages.every(command)));
1139
+ }
1140
+ /**
1141
+ * `while read a b; do ...; done <<< 'literal'` (or a quoted heredoc): what `read` assigns for each
1142
+ * line of the input.
1143
+ */
1144
+ function readValues(node, state) {
1145
+ if (node.until || !readsNoInput(node.body, state.funcs))
1146
+ return undefined;
1147
+ const item = node.cond.items.length === 1 ? node.cond.items[0] : undefined;
1148
+ const pipeline = item && !item.background && !item.node.rest.length ? item.node.first : undefined;
1149
+ const stage = pipeline?.stages.length === 1 && !pipeline.negated ? pipeline.stages[0] : undefined;
1150
+ if (stage?.kind !== "simple" || stage.assigns.length || stage.redirects.length)
1151
+ return undefined;
1152
+ const args = stage.argv.map(plainText);
1153
+ if (args[0] !== "read")
1154
+ return undefined;
1155
+ const raw = args.includes("-r");
1156
+ const names = args.slice(1).filter((a) => a !== "-r");
1157
+ if (!names.length || names.some((n) => n === undefined || !NAME.test(n) || BANNED_ENV.test(n)))
1158
+ return undefined;
1159
+ const inputs = node.redirects.filter((r) => r.fd === "0");
1160
+ const input = inputs.length === 1 ? inputs[0] : undefined;
1161
+ let text;
1162
+ if (input?.op === "<<")
1163
+ text = `${input.body ?? ""}\n`;
1164
+ else if (input?.op === "<<<" && input.target) {
1165
+ const known = knownVariables([input.target], state);
1166
+ const envs = combinations(known);
1167
+ if (envs.length !== 1)
1168
+ return undefined;
1169
+ text = `${instantiate(input.target, known, envs[0], state).text}\n`;
1170
+ }
1171
+ if (text === undefined || text.includes(SUBSTITUTION) || (!raw && text.includes("\\")))
1172
+ return undefined;
1173
+ const lines = text.split("\n").slice(0, -1);
1174
+ if (!lines.length || lines.length > MAX_VARIANTS)
1175
+ return undefined;
1176
+ return lines.map((line) => {
1177
+ const out = new Map();
1178
+ let rest = line.replace(/^[ \t]+|[ \t]+$/g, "");
1179
+ for (const [index, name] of names.entries()) {
1180
+ let value = rest;
1181
+ if (index < names.length - 1) {
1182
+ const match = /^(\S*)[ \t]*(.*)$/.exec(rest);
1183
+ value = match[1];
1184
+ rest = match[2];
1185
+ }
1186
+ out.set(name, SIMPLE_VALUE.test(value) ? [value] : null);
1187
+ }
1188
+ return out;
1189
+ });
1190
+ }
528
1191
  // --- compound commands ------------------------------------------------------------------------
529
1192
  function runCommand(ctx, command, state, stage, piped) {
1193
+ // A compound command's redirections are opened before its body runs, in the directory it
1194
+ // started in; a `cd` inside the body cannot move them.
1195
+ if (command.kind !== "simple" && command.kind !== "function") {
1196
+ const early = runRedirects(ctx, command.redirects, copy(state));
1197
+ if (early)
1198
+ return early;
1199
+ }
530
1200
  switch (command.kind) {
531
1201
  case "simple":
532
1202
  return runSimple(ctx, command, state, stage, piped);
@@ -542,11 +1212,14 @@ function runCommand(ctx, command, state, stage, piped) {
542
1212
  return runIf(ctx, command, state);
543
1213
  case "case":
544
1214
  return runCase(ctx, command, state);
1215
+ case "function":
1216
+ return defineFunction(ctx, command, state);
545
1217
  }
546
1218
  }
547
1219
  function runFor(ctx, node, state) {
548
1220
  if (BANNED_ENV.test(node.name))
549
1221
  return human(ctx.request, "unknown", "Environment override requires human review");
1222
+ const mark = reorderMark(ctx);
550
1223
  const refusal = runSubs(ctx, node.words.flatMap((w) => w.subs), state);
551
1224
  if (refusal)
552
1225
  return refusal;
@@ -558,7 +1231,7 @@ function runFor(ctx, node, state) {
558
1231
  let unknown = false;
559
1232
  for (const env of combinations(known))
560
1233
  for (const word of node.words) {
561
- const text = instantiate(word, known, env).text;
1234
+ const text = instantiate(word, known, env, state).text;
562
1235
  if (SIMPLE_VALUE.test(text))
563
1236
  values.add(text);
564
1237
  else
@@ -567,26 +1240,47 @@ function runFor(ctx, node, state) {
567
1240
  if (!values.size || values.size > MAX_VARIANTS)
568
1241
  unknown = true;
569
1242
  const changed = new Set([node.name]);
570
- assignedInList(node.body, changed);
571
- const inner = copy(state);
572
- forget(inner, changed);
573
- inner.vars.set(node.name, unknown ? null : [...values]);
574
- const body = runList({ ...ctx, loop: ctx.loop + 1 }, node.body, inner);
575
- if (body)
576
- return body;
1243
+ assignedInList(node.body, changed, state.funcs);
1244
+ // Each pass is judged on its own, from a start where everything the body assigns is unknown, so
1245
+ // values that belong together (the words of one item) stay together.
1246
+ for (const value of unknown ? [null] : [...values]) {
1247
+ if (++ctx.box.calls > MAX_JUDGEMENTS)
1248
+ return human(ctx.request, "unknown", "Too many commands to verify");
1249
+ const inner = copy(state);
1250
+ forget(inner, changed);
1251
+ inner.vars.set(node.name, value === null ? null : [value]);
1252
+ const body = runList({ ...ctx, loop: ctx.loop + 1 }, node.body, inner);
1253
+ if (body)
1254
+ return body;
1255
+ }
1256
+ endReorder(ctx, mark);
577
1257
  forget(state, changed);
578
1258
  return runRedirects(ctx, node.redirects, state);
579
1259
  }
580
1260
  function runWhile(ctx, node, state) {
581
1261
  const changed = new Set();
582
- assignedInList(node.cond, changed);
583
- assignedInList(node.body, changed);
1262
+ assignedInList(node.cond, changed, state.funcs);
1263
+ assignedInList(node.body, changed, state.funcs);
584
1264
  const inner = copy(state);
585
1265
  forget(inner, changed);
1266
+ const mark = reorderMark(ctx);
586
1267
  const loop = { ...ctx, loop: ctx.loop + 1 };
587
- const refusal = runList(loop, node.cond, inner) ?? runList(loop, node.body, inner);
1268
+ const refusal = runList(loop, node.cond, inner);
588
1269
  if (refusal)
589
1270
  return refusal;
1271
+ // With literal input, each pass is judged with what `read` took from its line.
1272
+ for (const line of readValues(node, state) ?? [undefined]) {
1273
+ if (++ctx.box.calls > MAX_JUDGEMENTS)
1274
+ return human(ctx.request, "unknown", "Too many commands to verify");
1275
+ const pass = line ? copy(inner) : inner;
1276
+ if (line)
1277
+ for (const [name, values] of line)
1278
+ pass.vars.set(name, values);
1279
+ const body = runList(loop, node.body, pass);
1280
+ if (body)
1281
+ return body;
1282
+ }
1283
+ endReorder(ctx, mark);
590
1284
  forget(state, changed);
591
1285
  return runRedirects(ctx, node.redirects, state);
592
1286
  }
@@ -596,12 +1290,16 @@ function runIf(ctx, node, state) {
596
1290
  for (const [index, clause] of node.clauses.entries()) {
597
1291
  // The first condition always runs; later ones only when every earlier one failed.
598
1292
  const conditionState = index === 0 ? current : copy(current);
599
- const refusal = runList(ctx, clause.cond, conditionState);
1293
+ const outcome = {};
1294
+ const refusal = runList(ctx, clause.cond, conditionState, outcome);
600
1295
  if (refusal)
601
1296
  return refusal;
602
1297
  if (index > 0)
603
1298
  current = merge(current, conditionState);
604
- const taken = copy(current);
1299
+ // The body runs only when the condition succeeded: an `a && b` condition ran both, and a `cd`
1300
+ // that ends the condition did change directory. Earlier clauses are already merged in.
1301
+ const taken = copy(outcome.success ?? current);
1302
+ delete taken.failed;
605
1303
  const body = runList(ctx, clause.body, taken);
606
1304
  if (body)
607
1305
  return body;
@@ -641,43 +1339,113 @@ function runCase(ctx, node, state) {
641
1339
  return runRedirects(ctx, node.redirects, state);
642
1340
  }
643
1341
  // --- lists, pipelines and the entry point -----------------------------------------------------
644
- function runList(ctx, list, state) {
645
- for (const item of list.items) {
1342
+ /**
1343
+ * True when the pipeline always succeeds: `true`, `:`, or `cd` to an absolute directory that exists
1344
+ * and can be entered now. Only used to know that an `&&` chain goes on past it; the directory it
1345
+ * started from is still kept as possible.
1346
+ */
1347
+ function cannotFail(ctx, node, state) {
1348
+ const stage = node.stages.length === 1 && !node.negated ? node.stages[0] : undefined;
1349
+ if (stage?.kind !== "simple" || stage.assigns.length || stage.redirects.length)
1350
+ return false;
1351
+ const argv = stage.argv.map(plainText);
1352
+ const [program, target] = argv;
1353
+ if (program === undefined || state.funcs.has(program))
1354
+ return false;
1355
+ if ((program === "true" || program === ":") && argv.length === 1)
1356
+ return true;
1357
+ // An earlier command (`mv`, a background job) could remove the directory, so only the script's
1358
+ // first command is trusted. Another process can still change it before the script runs.
1359
+ if (program !== "cd" || argv.length !== 2 || target === undefined || node !== ctx.box.first)
1360
+ return false;
1361
+ const path = target === "~" || target.startsWith("~/") ? join(homedir(), target.slice(1)) : target;
1362
+ if (!path.startsWith("/") || /[*?[\]]/.test(path))
1363
+ return false;
1364
+ try {
1365
+ if (!statSync(path).isDirectory())
1366
+ return false;
1367
+ accessSync(path, constants.X_OK);
1368
+ return true;
1369
+ }
1370
+ catch {
1371
+ return false;
1372
+ }
1373
+ }
1374
+ /** With `outcome`, also reports the state when the list's exit status is success. */
1375
+ function runList(ctx, list, state, outcome) {
1376
+ for (const [index, item] of list.items.entries()) {
1377
+ const last = index === list.items.length - 1;
1378
+ // Each item runs whether or not the one before it succeeded.
1379
+ settle(state);
646
1380
  // A background job runs in a subshell of its own.
647
1381
  const target = item.background ? copy(state) : state;
648
1382
  const { first, rest } = item.node;
649
- const refusal = runPipeline(ctx, first, target);
1383
+ if (item.background)
1384
+ ctx.box.script.jobs++;
1385
+ const refusal = runPipeline(item.background ? { ...ctx, reorder: true } : ctx, first, target);
650
1386
  if (refusal)
651
1387
  return refusal;
652
- if (!rest.length)
1388
+ if (!rest.length) {
1389
+ if (last && outcome)
1390
+ outcome.success = copy(item.background ? state : target);
653
1391
  continue;
1392
+ }
654
1393
  // In `a && b || c` each later command runs only if the ones before it did, so it sees their
655
1394
  // effects, but the chain may stop after any of them: the state afterwards is every prefix's.
1395
+ // An all-`&&` chain cannot stop after a step that cannot fail, and succeeds only at the end.
1396
+ const chain = rest.every((r) => r.op === "&&");
656
1397
  let running = copy(target);
657
1398
  let possible = copy(target);
658
- for (const next of rest) {
1399
+ // Variables after the chain: the steps it can stop after. Directories always use `possible`.
1400
+ let assigned = chain && cannotFail(ctx, first, target) ? undefined : copy(target);
1401
+ // While every operator so far is `&&`, a command runs only if everything before it succeeded,
1402
+ // so a `cd` before it did change directory. After an `||` any earlier directory is possible.
1403
+ let onlyAnd = true;
1404
+ for (const [step, next] of rest.entries()) {
659
1405
  running = copy(running);
1406
+ onlyAnd &&= next.op === "&&";
1407
+ if (onlyAnd)
1408
+ delete running.failed;
1409
+ else {
1410
+ settle(running);
1411
+ running.cwds = [...new Set([...running.cwds, ...possible.cwds])];
1412
+ }
660
1413
  const skipped = runPipeline(ctx, next.node, running);
661
1414
  if (skipped)
662
1415
  return skipped;
663
1416
  possible = merge(possible, running);
1417
+ if (!chain || step === rest.length - 1 || !cannotFail(ctx, next.node, running))
1418
+ assigned = assigned ? merge(assigned, running) : copy(running);
664
1419
  if (possible.cwds.length > MAX_DIRECTORIES)
665
1420
  return human(ctx.request, "unknown", "Too many directory changes to verify");
666
1421
  }
1422
+ if (assigned) {
1423
+ possible.vars = assigned.vars;
1424
+ possible.funcs = assigned.funcs;
1425
+ }
1426
+ if (last && outcome)
1427
+ outcome.success = copy(item.background ? state : chain ? running : possible);
667
1428
  replace(target, possible);
668
1429
  }
669
1430
  return undefined;
670
1431
  }
671
1432
  function runPipeline(ctx, node, state) {
672
- if (node.stages.length === 1)
673
- return runCommand(ctx, node.stages[0], state, 0, false);
1433
+ if (node.stages.length === 1) {
1434
+ const refusal = runCommand(ctx, node.stages[0], state, 0, false);
1435
+ // `! cd x` succeeds exactly when the `cd` failed.
1436
+ if (node.negated)
1437
+ settle(state);
1438
+ return refusal;
1439
+ }
674
1440
  const changed = new Set();
1441
+ const mark = reorderMark(ctx);
675
1442
  for (const [index, stage] of node.stages.entries()) {
676
- assignedInCommand(stage, changed);
1443
+ assignedInCommand(stage, changed, state.funcs);
677
1444
  const refusal = runCommand(ctx, stage, copy(state), index, true);
678
1445
  if (refusal)
679
1446
  return refusal;
680
1447
  }
1448
+ endReorder(ctx, mark);
681
1449
  // The last stage may run in the current shell, so what the stages assign is unknown afterwards.
682
1450
  forget(state, changed);
683
1451
  return undefined;
@@ -687,12 +1455,24 @@ function runPipeline(ctx, node, state) {
687
1455
  * directory it could run in (before and after the `cd`, since `cd x || ...` may fail), so a command
688
1456
  * that only looks safe relative to the starting directory cannot hide behind a `cd`.
689
1457
  */
690
- export function commandDecision(request, command, profile, depth = 0, start = [request.cwd]) {
1458
+ export function commandDecision(request, command, profile, depth = 0, start = [request.cwd], fill) {
691
1459
  const script = parseScript(command);
692
1460
  if (!script)
693
1461
  return human(request, "unknown", UNSUPPORTED);
694
- const ctx = { request, profile, depth, loop: 0, box: { calls: 0 } };
695
- const refusal = runList(ctx, script, { cwds: [...start], vars: new Map() });
1462
+ const ctx = {
1463
+ request,
1464
+ profile,
1465
+ depth,
1466
+ loop: 0,
1467
+ calls: 0,
1468
+ positional: !/argv/.test(command),
1469
+ box: { calls: 0, script: fill?.script ?? { tainted: false, approved: false, jobs: 0 } },
1470
+ ...(fill?.reorder ? { reorder: true } : {}),
1471
+ };
1472
+ const opening = script.items[0];
1473
+ if (depth === 0 && opening && !opening.background)
1474
+ ctx.box.first = opening.node.first;
1475
+ const refusal = runList(ctx, script, { cwds: [...start], vars: new Map(), funcs: new Map() });
696
1476
  return refusal ?? ctx.box.last ?? human(request, "unknown", "Empty command");
697
1477
  }
698
1478
  //# sourceMappingURL=flow.js.map