@node9/policy-engine 2.65.10 → 2.66.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/index.d.mts CHANGED
@@ -184,6 +184,13 @@ interface FileAccessContext {
184
184
  cwd?: string;
185
185
  homeDirs?: string[];
186
186
  accesses?: FileAccess[];
187
+ /**
188
+ * Readings only the credential jail asks for: a reader operand whose name is
189
+ * not known until the command runs (read as `*` in each directory the command
190
+ * entered), a `cd` to a glob, `env -C DIR`, and a hard link's source. Off for
191
+ * every other user of the walk, whose accesses stay as they were.
192
+ */
193
+ credentialJail?: boolean;
187
194
  }
188
195
  /** The names, as a regex source without anchors, for the copies that are regexes. */
189
196
  declare const PUBLIC_SSH_NAME_SOURCE: string;
@@ -766,7 +773,16 @@ interface ShellDestToken {
766
773
  * ADDRESS has no false-positive surface, because that comparison is exact.
767
774
  */
768
775
  declare function extractShellDestTokens(command: string): ShellDestToken[];
769
- declare function analyzeFsOperation(command: string): FsOpVerdict | null;
776
+ /**
777
+ * `cwd` is the directory the agent's shell is in when the command runs (the
778
+ * hook payload's cwd). Claude Code keeps a `cd` inside its working directories
779
+ * between calls, so an agent started in $HOME can enter ~/.ssh with one call
780
+ * and run `cat id_rsa` with the next. When that directory is itself a
781
+ * credential directory, the command is also read as `cd DIR && COMMAND` and the
782
+ * stricter verdict wins. Any other directory, the case of every ordinary
783
+ * session, changes nothing; a cwd that is not absolute is not used.
784
+ */
785
+ declare function analyzeFsOperation(command: string, cwd?: string): FsOpVerdict | null;
770
786
  /**
771
787
  * One representative command per copy verb, for a gate test that DERIVES its
772
788
  * rows from COPY_VERBS instead of keeping a second hand list (the trap the
@@ -2487,7 +2503,7 @@ declare const LONG_OUTPUT_THRESHOLD_BYTES: number;
2487
2503
  * and fails CI when the hash drifts without a version bump — forgetting
2488
2504
  * is loud, not silent.
2489
2505
  */
2490
- declare const CANONICAL_EXTRACTOR_VERSION = "canonical-v41";
2506
+ declare const CANONICAL_EXTRACTOR_VERSION = "canonical-v42";
2491
2507
  /**
2492
2508
  * SHA-256 prefix of the detector-source files
2493
2509
  * (canonical.ts + pii.ts + destructive-regex.ts).
@@ -2498,7 +2514,7 @@ declare const CANONICAL_EXTRACTOR_VERSION = "canonical-v41";
2498
2514
  * files changed, this hash must change too, and you must consciously
2499
2515
  * decide whether to bump CANONICAL_EXTRACTOR_VERSION."
2500
2516
  */
2501
- declare const CANONICAL_EXTRACTOR_HASH = "dbde5e7f06f3738a";
2517
+ declare const CANONICAL_EXTRACTOR_HASH = "3e74a6cffd82db82";
2502
2518
  declare function extractCanonicalFindings(call: ToolCallEntry, ctx: ExtractContext): CanonicalFinding[];
2503
2519
  declare function extractSessionLevelFindings(calls: ReadonlyArray<SessionToolCall>, ctx: SessionExtractContext): CanonicalFinding[];
2504
2520
  /**
package/dist/index.d.ts CHANGED
@@ -184,6 +184,13 @@ interface FileAccessContext {
184
184
  cwd?: string;
185
185
  homeDirs?: string[];
186
186
  accesses?: FileAccess[];
187
+ /**
188
+ * Readings only the credential jail asks for: a reader operand whose name is
189
+ * not known until the command runs (read as `*` in each directory the command
190
+ * entered), a `cd` to a glob, `env -C DIR`, and a hard link's source. Off for
191
+ * every other user of the walk, whose accesses stay as they were.
192
+ */
193
+ credentialJail?: boolean;
187
194
  }
188
195
  /** The names, as a regex source without anchors, for the copies that are regexes. */
189
196
  declare const PUBLIC_SSH_NAME_SOURCE: string;
@@ -766,7 +773,16 @@ interface ShellDestToken {
766
773
  * ADDRESS has no false-positive surface, because that comparison is exact.
767
774
  */
768
775
  declare function extractShellDestTokens(command: string): ShellDestToken[];
769
- declare function analyzeFsOperation(command: string): FsOpVerdict | null;
776
+ /**
777
+ * `cwd` is the directory the agent's shell is in when the command runs (the
778
+ * hook payload's cwd). Claude Code keeps a `cd` inside its working directories
779
+ * between calls, so an agent started in $HOME can enter ~/.ssh with one call
780
+ * and run `cat id_rsa` with the next. When that directory is itself a
781
+ * credential directory, the command is also read as `cd DIR && COMMAND` and the
782
+ * stricter verdict wins. Any other directory, the case of every ordinary
783
+ * session, changes nothing; a cwd that is not absolute is not used.
784
+ */
785
+ declare function analyzeFsOperation(command: string, cwd?: string): FsOpVerdict | null;
770
786
  /**
771
787
  * One representative command per copy verb, for a gate test that DERIVES its
772
788
  * rows from COPY_VERBS instead of keeping a second hand list (the trap the
@@ -2487,7 +2503,7 @@ declare const LONG_OUTPUT_THRESHOLD_BYTES: number;
2487
2503
  * and fails CI when the hash drifts without a version bump — forgetting
2488
2504
  * is loud, not silent.
2489
2505
  */
2490
- declare const CANONICAL_EXTRACTOR_VERSION = "canonical-v41";
2506
+ declare const CANONICAL_EXTRACTOR_VERSION = "canonical-v42";
2491
2507
  /**
2492
2508
  * SHA-256 prefix of the detector-source files
2493
2509
  * (canonical.ts + pii.ts + destructive-regex.ts).
@@ -2498,7 +2514,7 @@ declare const CANONICAL_EXTRACTOR_VERSION = "canonical-v41";
2498
2514
  * files changed, this hash must change too, and you must consciously
2499
2515
  * decide whether to bump CANONICAL_EXTRACTOR_VERSION."
2500
2516
  */
2501
- declare const CANONICAL_EXTRACTOR_HASH = "dbde5e7f06f3738a";
2517
+ declare const CANONICAL_EXTRACTOR_HASH = "3e74a6cffd82db82";
2502
2518
  declare function extractCanonicalFindings(call: ToolCallEntry, ctx: ExtractContext): CanonicalFinding[];
2503
2519
  declare function extractSessionLevelFindings(calls: ReadonlyArray<SessionToolCall>, ctx: SessionExtractContext): CanonicalFinding[];
2504
2520
  /**
package/dist/index.js CHANGED
@@ -4422,6 +4422,31 @@ function wordValues(word, state) {
4422
4422
  if (!dynamic) return out.map(asWord);
4423
4423
  return out.filter((piece) => piece.value !== "").map((piece) => ({ value: piece.value, pattern: piece.pattern + "*", dynamic: true }));
4424
4424
  }
4425
+ var UNKNOWN_VALUE_FLAGS = {
4426
+ head: ["-n", "-c", "--lines", "--bytes"],
4427
+ tail: ["-n", "-c", "--lines", "--bytes", "-s", "--sleep-interval", "--pid"],
4428
+ cut: ["-d", "-f", "-c", "-b", "--delimiter", "--fields", "--characters", "--bytes"],
4429
+ sort: ["-k", "-t", "-S", "-o", "--key", "--field-separator", "--buffer-size"],
4430
+ uniq: ["-f", "-s", "-w", "--skip-fields", "--skip-chars", "--check-chars"],
4431
+ od: ["-N", "-j", "-t", "-A", "-w", "--read-bytes", "--skip-bytes", "--format"],
4432
+ xxd: ["-l", "-s", "-c", "-g", "-o", "-cols", "-len", "-seek"],
4433
+ hexdump: ["-n", "-s", "-e", "-f"],
4434
+ base64: ["-w", "--wrap"],
4435
+ fold: ["-w", "--width"],
4436
+ nl: ["-b", "-n", "-s", "-v", "-w", "-i"]
4437
+ };
4438
+ function envChdir(tokens, head) {
4439
+ const at = tokens.findIndex((t, i) => i < head && base(t?.value ?? "") === "env");
4440
+ if (at < 0) return null;
4441
+ for (let i = at + 1; i < head; i++) {
4442
+ const t = tokens[i];
4443
+ if (!t || t.dynamic) continue;
4444
+ if (t.value === "-C" || t.value === "--chdir") return tokens[i + 1] ?? null;
4445
+ if (t.value.startsWith("--chdir=")) return { ...t, value: t.value.slice(8) };
4446
+ if (/^-C./.test(t.value)) return { ...t, value: t.value.slice(2) };
4447
+ }
4448
+ return null;
4449
+ }
4425
4450
  function sedSubstitutions(script) {
4426
4451
  const out = [];
4427
4452
  for (const raw of script.split(/\r?\n|;/)) {
@@ -4462,6 +4487,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4462
4487
  const seenCalls = /* @__PURE__ */ new Set();
4463
4488
  const pipedStdin = /* @__PURE__ */ new WeakMap();
4464
4489
  let currentStdin = null;
4490
+ let currentFed = null;
4491
+ const jail = !!context.credentialJail;
4465
4492
  let callWalks2 = MAX_CALL_WALKS;
4466
4493
  const initial = {
4467
4494
  cwd: [context.cwd ?? ""],
@@ -4521,11 +4548,33 @@ function collectShellFileAccesses(command, context = {}, report) {
4521
4548
  return true;
4522
4549
  });
4523
4550
  }
4551
+ function enter(target, state, nested) {
4552
+ if (!target.value || target.dynamic || target.pattern && !jail) return null;
4553
+ const home = nested.vars.get("HOME")?.[0] ?? "~";
4554
+ const expanded = target.value === "~" || target.value.startsWith("~/") ? home + target.value.slice(1) : target.value;
4555
+ return expanded.startsWith("/") || expanded.startsWith("~") ? [expanded] : state.cwd.map((cwd) => `${cwd}/${expanded}`);
4556
+ }
4557
+ function addUnknownRead(token, state) {
4558
+ const prefix = token?.value ?? "";
4559
+ if (/^[/~$]|^[A-Za-z]:/.test(prefix)) return;
4560
+ const pattern = `${prefix.slice(0, prefix.lastIndexOf("/") + 1)}*`;
4561
+ for (const cwd of state.cwd)
4562
+ if (cwd)
4563
+ out.push({ operation: "read", path: pattern, cwd, followFinal: true, glob: pattern });
4564
+ }
4524
4565
  function fromWords(tokens, state, nested, depth) {
4525
4566
  const words = tokens.map((w) => w && !w.dynamic ? w.value : null);
4526
4567
  let head = unwrapCommandHead(words, true);
4527
4568
  if (base(words[head]) === "builtin" && ["cd", "pushd"].includes(base(words[head + 1]))) head++;
4528
4569
  const name = base(words[head]);
4570
+ if (jail) {
4571
+ const dir = envChdir(tokens, head);
4572
+ const next = dir ? enter(dir, state, nested) : null;
4573
+ if (next) {
4574
+ state = { ...clone(state), cwd: unique(next) };
4575
+ nested = { ...clone(nested), cwd: unique(next) };
4576
+ }
4577
+ }
4529
4578
  if (name === "find") {
4530
4579
  findActions2(tokens, words, head, state, nested, depth);
4531
4580
  return;
@@ -4536,9 +4585,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4536
4585
  if (args.some((w) => w === null || w.value === "-" || w.dynamic)) return;
4537
4586
  const home = nested.vars.get("HOME")?.[0] ?? "~";
4538
4587
  const target = args.find((w) => w && !w.value.startsWith("-")) ?? { value: home };
4539
- if (!target.value || target.pattern || target.dynamic) return;
4540
- const expanded = target.value === "~" || target.value.startsWith("~/") ? home + target.value.slice(1) : target.value;
4541
- const next = expanded.startsWith("/") || expanded.startsWith("~") ? [expanded] : state.cwd.map((cwd) => `${cwd}/${expanded}`);
4588
+ const next = enter(target, state, nested);
4589
+ if (!next) return;
4542
4590
  state.cwd = unique([...state.cwd, ...next]);
4543
4591
  state.onSuccess = unique(next);
4544
4592
  return;
@@ -4626,6 +4674,17 @@ function collectShellFileAccesses(command, context = {}, report) {
4626
4674
  }
4627
4675
  if (FS_READ_TOOLS.has(name) && name !== "dd") {
4628
4676
  for (const p of readerPaths(words, head)) add("read", locate(p), state);
4677
+ if (jail) {
4678
+ const MARK = "";
4679
+ const valueFlags = UNKNOWN_VALUE_FLAGS[name] ?? [];
4680
+ const marked = words.map(
4681
+ (w, i) => i > head && w === null && !(tokens[i]?.value ?? "").startsWith("-") && !valueFlags.includes(words[i - 1] ?? "") ? `${MARK}${i}` : w
4682
+ );
4683
+ for (const p of readerPaths(marked, head))
4684
+ if (p.startsWith(MARK)) addUnknownRead(tokens[Number(p.slice(1))], state);
4685
+ if (currentFed === null && words.slice(0, head).some((w) => base(w) === "xargs"))
4686
+ addUnknownRead(null, state);
4687
+ }
4629
4688
  }
4630
4689
  if (["ls", "tree", "dir", "vdir"].includes(name)) {
4631
4690
  for (const token of args) {
@@ -4660,6 +4719,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4660
4719
  );
4661
4720
  const linkOnly = name === "cp" && strings.some((s) => /^-[^-]*[sl]/.test(s) || s === "--symbolic-link" || s === "--link");
4662
4721
  const replaceDestLink = name === "mv" || name === "ln" || strings.includes("--remove-destination");
4722
+ const symbolicLink = strings.some((s) => s === "--symbolic" || /^-[^-]*s/.test(s));
4723
+ const relativeLink = strings.some((s) => s === "--relative" || /^-[^-]*r/.test(s));
4663
4724
  for (let i = 0; i < args.length; i++) {
4664
4725
  const token = args[i];
4665
4726
  if (!token) continue;
@@ -4705,6 +4766,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4705
4766
  add("remove", source, state, { recursive: true, followFinal: false, copy: true });
4706
4767
  else if (name !== "ln" && !linkOnly)
4707
4768
  add("read", source, state, { recursive, followFinal: !preserveSourceLink, copy: true });
4769
+ else if (name === "ln" && jail && (!symbolicLink || relativeLink || /^[/~]/.test(source.value)))
4770
+ add("read", source, state, { followFinal: false, copy: true });
4708
4771
  if (!noDirectory)
4709
4772
  add(
4710
4773
  "write",
@@ -4909,6 +4972,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4909
4972
  }
4910
4973
  }
4911
4974
  function call(cmd, state, depth) {
4975
+ const fed = currentFed;
4912
4976
  const nested = clone(state);
4913
4977
  assignments(cmd.Assigns, nested);
4914
4978
  const nodes = cmd.Args ?? [];
@@ -4926,6 +4990,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4926
4990
  alternatives = alternatives.flatMap((prefix) => (words.length ? words : [null]).map((w) => [...prefix, w])).slice(0, MAX_ALTERNATIVES);
4927
4991
  }
4928
4992
  for (const tokens of alternatives) {
4993
+ currentFed = fed;
4929
4994
  fromWords(tokens, state, nested, depth);
4930
4995
  inlineCall(tokens, state, depth);
4931
4996
  }
@@ -5198,6 +5263,7 @@ function collectShellFileAccesses(command, context = {}, report) {
5198
5263
  const fedText = stdinText(stmt);
5199
5264
  if (fedText !== null) nestedPayload(xargsPayload(stmt, fedText), clone(state), depth);
5200
5265
  currentStdin = fedText;
5266
+ currentFed = fedText ?? pipedStdin.get(stmt) ?? null;
5201
5267
  switch (cmd.kind) {
5202
5268
  case "CallExpr":
5203
5269
  call(cmd, state, depth);
@@ -8618,7 +8684,17 @@ function extractShellDestTokens(command) {
8618
8684
  }
8619
8685
  var FS_OP_CACHE_MAX = 5e3;
8620
8686
  var fsOpCache = /* @__PURE__ */ new Map();
8621
- function analyzeFsOperation(command) {
8687
+ function analyzeFsOperation(command, cwd) {
8688
+ const own = analyzeCommandFs(command);
8689
+ if (own?.verdict === "block" || !cwd || !isCredentialDir(cwd)) return own;
8690
+ const dir = cwd.replace(/\\/g, "/");
8691
+ return stricter(own, analyzeCommandFs(`cd '${dir.replace(/'/g, `'\\''`)}' && ${command}`));
8692
+ }
8693
+ function isCredentialDir(cwd) {
8694
+ if (!/^(?:\/|[A-Za-z]:[/\\])/.test(cwd)) return false;
8695
+ return matchSensitivePath(`${cwd.replace(/\\/g, "/").replace(/\/+$/, "")}/n9-any-name`) !== null;
8696
+ }
8697
+ function analyzeCommandFs(command) {
8622
8698
  const normalized = normalizeCommandForPolicy(command);
8623
8699
  const stdinShell = feedsShellStdin(command) || feedsShellStdin(normalized);
8624
8700
  const dotenvCli = DOTENV_CLI_PRESCREEN_RE.test(command) || DOTENV_CLI_PRESCREEN_RE.test(normalized);
@@ -9105,7 +9181,7 @@ var STDIN_SHELL_WORD_RE = new RegExp(
9105
9181
  "i"
9106
9182
  );
9107
9183
  var feedsShellStdin = (command) => /\||<</.test(command) && STDIN_SHELL_WORD_RE.test(command);
9108
- var CHANGES_DIR_RE = /(?:^|[\s;&|({'"`])(?:cd|pushd)\s/;
9184
+ var CHANGES_DIR_RE = /(?:^|[\s;&|({'"`])(?:(?:cd|pushd)\s|env\s(?:[^;&|\n]*?\s)?(?:-C|--chdir))/;
9109
9185
  var SOURCES_FILE_RE = /(?:^|[;&|(\s])(?:source|\.)\s/;
9110
9186
  function printsEnvironment(words) {
9111
9187
  const [name, ...rest] = words;
@@ -9442,14 +9518,29 @@ function matchSensitiveGlob(glob, dotGlob) {
9442
9518
  function underEnteredDir(a, name) {
9443
9519
  const dir = a.cwd ?? "";
9444
9520
  if (!dir || /^(?:[/\\~$]|[A-Za-z]:)/.test(name)) return name;
9445
- const rest = name.replace(/^(?:\.\/)+/, "");
9446
- return `${dir.replace(/[/\\]+$/, "")}/${rest}`;
9521
+ return joinEntered(dir, name);
9522
+ }
9523
+ function joinEntered(dir, name) {
9524
+ const out = [];
9525
+ for (const seg of `${dir}/${name}`.split(/[/\\]+/)) {
9526
+ if (seg === ".") continue;
9527
+ const last = out[out.length - 1];
9528
+ if (seg === ".." && last !== void 0 && last !== "" && last !== ".." && !/^[~$]/.test(last)) {
9529
+ out.pop();
9530
+ continue;
9531
+ }
9532
+ out.push(seg);
9533
+ }
9534
+ return out.join("/");
9535
+ }
9536
+ function judgeEntered(path, dotGlob = false) {
9537
+ return GLOB_META.test(path) ? matchSensitiveGlob(path, dotGlob) : matchSensitivePath(path);
9447
9538
  }
9448
9539
  function structuralJailRead(command) {
9449
9540
  let accesses;
9450
9541
  const report = { exhausted: false };
9451
9542
  try {
9452
- accesses = collectShellFileAccesses(command, {}, report);
9543
+ accesses = collectShellFileAccesses(command, { credentialJail: true }, report);
9453
9544
  } catch {
9454
9545
  return null;
9455
9546
  }
@@ -9462,12 +9553,12 @@ function structuralJailRead(command) {
9462
9553
  for (const a of accesses) {
9463
9554
  if (a.copy && !a.listing && (a.operation === "read" || a.operation === "remove")) {
9464
9555
  const entered = underEnteredDir(a, a.path);
9465
- if (entered !== a.path) relativeCopy ??= copyVerdictOf(matchSensitivePath(entered));
9556
+ const viaDir = !!a.cwd && entered === a.path && a.path.startsWith(`${a.cwd}/`);
9557
+ if (entered !== a.path || viaDir) relativeCopy ??= copyVerdictOf(judgeEntered(entered));
9466
9558
  continue;
9467
9559
  }
9468
9560
  if (a.operation !== "read" || a.listing || a.recursive) continue;
9469
- const glob = a.glob ?? (GLOB_META.test(a.path) ? a.path : void 0);
9470
- const hit = glob ? matchSensitiveGlob(underEnteredDir(a, glob), !!a.dotGlob) : matchSensitivePath(underEnteredDir(a, a.path));
9561
+ const hit = judgeEntered(underEnteredDir(a, a.glob ?? a.path), !!a.dotGlob);
9471
9562
  if (hit?.verdict === "block") return hit;
9472
9563
  review ??= hit;
9473
9564
  }
@@ -9489,9 +9580,9 @@ function inlineCodeJailRead(command, changesDir = false) {
9489
9580
  if (code === null) continue;
9490
9581
  for (const p of inlineReadPaths(language, code, call.preload)) {
9491
9582
  const relative = !/^(?:[/\\~$]|[A-Za-z]:)/.test(p);
9492
- const spellings = relative ? [p, ...dirs().map((d) => `${d}/${p}`)] : [p];
9583
+ const spellings = relative ? [p, ...dirs().map((d) => joinEntered(d, p))] : [p];
9493
9584
  for (const spelling of spellings) {
9494
- const hit = matchSensitivePath(spelling);
9585
+ const hit = spelling === p ? matchSensitivePath(spelling) : judgeEntered(spelling);
9495
9586
  if (hit?.verdict === "block") return hit;
9496
9587
  review ??= hit;
9497
9588
  }
@@ -9512,12 +9603,19 @@ function enteredDirs(command, depth = 0, out = []) {
9512
9603
  let head = unwrapCommandHead(words);
9513
9604
  if (baseWord(words[head]) === "builtin") head++;
9514
9605
  const name = baseWord(words[head]);
9515
- if (name !== "cd" && name !== "pushd") {
9606
+ const envAt = words.findIndex((w, i) => i < head && baseWord(w) === "env");
9607
+ const envDir = envAt < 0 ? null : words.slice(envAt + 1, head).reduce((found, w, i, rest) => {
9608
+ if (found !== null || w === null) return found;
9609
+ if (w === "-C" || w === "--chdir") return rest[i + 1] ?? null;
9610
+ if (w.startsWith("--chdir=")) return w.slice(8);
9611
+ return /^-C./.test(w) ? w.slice(2) : null;
9612
+ }, null);
9613
+ if (name !== "cd" && name !== "pushd" && envDir === null) {
9516
9614
  const payload = literalShellPayload(words, baseWord(words[0]));
9517
9615
  if (payload !== null) enteredDirs(payload, depth + 1, out);
9518
9616
  return true;
9519
9617
  }
9520
- const target = words.slice(head + 1).find((w) => w === null || !w.startsWith("-"));
9618
+ const target = envDir ?? words.slice(head + 1).find((w) => w === null || !w.startsWith("-"));
9521
9619
  if (!target) return true;
9522
9620
  const dir = target.replace(/[/\\]+$/, "");
9523
9621
  const rooted = /^(?:[/\\~]|[A-Za-z]:)/.test(dir);
@@ -19669,7 +19767,7 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
19669
19767
  const pipeVerdict = pipeChainVerdict(bashCommand, isTrustedHost, cv("data.pipe-chain"));
19670
19768
  if (pipeVerdict?.logged) noteLogged(pipeVerdict);
19671
19769
  else if (pipeVerdict) return pipeVerdict;
19672
- const fsVerdict = analyzeFsOperation(bashCommand);
19770
+ const fsVerdict = analyzeFsOperation(bashCommand, cwd);
19673
19771
  if (fsVerdict) {
19674
19772
  const isShieldRule = fsVerdict.ruleName.startsWith("shield:");
19675
19773
  const labelPrefix = isShieldRule ? "project-jail (AST)" : "Node9 (AST)";
@@ -21784,8 +21882,8 @@ function matchCanaryArgs(args, values) {
21784
21882
 
21785
21883
  // src/scan/canonical.ts
21786
21884
  var LONG_OUTPUT_THRESHOLD_BYTES = 100 * 1024;
21787
- var CANONICAL_EXTRACTOR_VERSION = "canonical-v41";
21788
- var CANONICAL_EXTRACTOR_HASH = "dbde5e7f06f3738a";
21885
+ var CANONICAL_EXTRACTOR_VERSION = "canonical-v42";
21886
+ var CANONICAL_EXTRACTOR_HASH = "3e74a6cffd82db82";
21789
21887
  var DEDUPE_PREVIEW_LEN = 120;
21790
21888
  function extractCanonicalFindings(call, ctx) {
21791
21889
  const out = [];
@@ -21932,7 +22030,7 @@ function extractCanonicalFindings(call, ctx) {
21932
22030
  if (!isShell || command === null) {
21933
22031
  return out;
21934
22032
  }
21935
- const fsVerdict = analyzeFsOperation(command);
22033
+ const fsVerdict = analyzeFsOperation(command, ctx.cwd);
21936
22034
  if (fsVerdict) {
21937
22035
  const isShield = fsVerdict.ruleName.startsWith("shield:");
21938
22036
  out.push(
package/dist/index.mjs CHANGED
@@ -4152,6 +4152,31 @@ function wordValues(word, state) {
4152
4152
  if (!dynamic) return out.map(asWord);
4153
4153
  return out.filter((piece) => piece.value !== "").map((piece) => ({ value: piece.value, pattern: piece.pattern + "*", dynamic: true }));
4154
4154
  }
4155
+ var UNKNOWN_VALUE_FLAGS = {
4156
+ head: ["-n", "-c", "--lines", "--bytes"],
4157
+ tail: ["-n", "-c", "--lines", "--bytes", "-s", "--sleep-interval", "--pid"],
4158
+ cut: ["-d", "-f", "-c", "-b", "--delimiter", "--fields", "--characters", "--bytes"],
4159
+ sort: ["-k", "-t", "-S", "-o", "--key", "--field-separator", "--buffer-size"],
4160
+ uniq: ["-f", "-s", "-w", "--skip-fields", "--skip-chars", "--check-chars"],
4161
+ od: ["-N", "-j", "-t", "-A", "-w", "--read-bytes", "--skip-bytes", "--format"],
4162
+ xxd: ["-l", "-s", "-c", "-g", "-o", "-cols", "-len", "-seek"],
4163
+ hexdump: ["-n", "-s", "-e", "-f"],
4164
+ base64: ["-w", "--wrap"],
4165
+ fold: ["-w", "--width"],
4166
+ nl: ["-b", "-n", "-s", "-v", "-w", "-i"]
4167
+ };
4168
+ function envChdir(tokens, head) {
4169
+ const at = tokens.findIndex((t, i) => i < head && base(t?.value ?? "") === "env");
4170
+ if (at < 0) return null;
4171
+ for (let i = at + 1; i < head; i++) {
4172
+ const t = tokens[i];
4173
+ if (!t || t.dynamic) continue;
4174
+ if (t.value === "-C" || t.value === "--chdir") return tokens[i + 1] ?? null;
4175
+ if (t.value.startsWith("--chdir=")) return { ...t, value: t.value.slice(8) };
4176
+ if (/^-C./.test(t.value)) return { ...t, value: t.value.slice(2) };
4177
+ }
4178
+ return null;
4179
+ }
4155
4180
  function sedSubstitutions(script) {
4156
4181
  const out = [];
4157
4182
  for (const raw of script.split(/\r?\n|;/)) {
@@ -4192,6 +4217,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4192
4217
  const seenCalls = /* @__PURE__ */ new Set();
4193
4218
  const pipedStdin = /* @__PURE__ */ new WeakMap();
4194
4219
  let currentStdin = null;
4220
+ let currentFed = null;
4221
+ const jail = !!context.credentialJail;
4195
4222
  let callWalks2 = MAX_CALL_WALKS;
4196
4223
  const initial = {
4197
4224
  cwd: [context.cwd ?? ""],
@@ -4251,11 +4278,33 @@ function collectShellFileAccesses(command, context = {}, report) {
4251
4278
  return true;
4252
4279
  });
4253
4280
  }
4281
+ function enter(target, state, nested) {
4282
+ if (!target.value || target.dynamic || target.pattern && !jail) return null;
4283
+ const home = nested.vars.get("HOME")?.[0] ?? "~";
4284
+ const expanded = target.value === "~" || target.value.startsWith("~/") ? home + target.value.slice(1) : target.value;
4285
+ return expanded.startsWith("/") || expanded.startsWith("~") ? [expanded] : state.cwd.map((cwd) => `${cwd}/${expanded}`);
4286
+ }
4287
+ function addUnknownRead(token, state) {
4288
+ const prefix = token?.value ?? "";
4289
+ if (/^[/~$]|^[A-Za-z]:/.test(prefix)) return;
4290
+ const pattern = `${prefix.slice(0, prefix.lastIndexOf("/") + 1)}*`;
4291
+ for (const cwd of state.cwd)
4292
+ if (cwd)
4293
+ out.push({ operation: "read", path: pattern, cwd, followFinal: true, glob: pattern });
4294
+ }
4254
4295
  function fromWords(tokens, state, nested, depth) {
4255
4296
  const words = tokens.map((w) => w && !w.dynamic ? w.value : null);
4256
4297
  let head = unwrapCommandHead(words, true);
4257
4298
  if (base(words[head]) === "builtin" && ["cd", "pushd"].includes(base(words[head + 1]))) head++;
4258
4299
  const name = base(words[head]);
4300
+ if (jail) {
4301
+ const dir = envChdir(tokens, head);
4302
+ const next = dir ? enter(dir, state, nested) : null;
4303
+ if (next) {
4304
+ state = { ...clone(state), cwd: unique(next) };
4305
+ nested = { ...clone(nested), cwd: unique(next) };
4306
+ }
4307
+ }
4259
4308
  if (name === "find") {
4260
4309
  findActions2(tokens, words, head, state, nested, depth);
4261
4310
  return;
@@ -4266,9 +4315,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4266
4315
  if (args.some((w) => w === null || w.value === "-" || w.dynamic)) return;
4267
4316
  const home = nested.vars.get("HOME")?.[0] ?? "~";
4268
4317
  const target = args.find((w) => w && !w.value.startsWith("-")) ?? { value: home };
4269
- if (!target.value || target.pattern || target.dynamic) return;
4270
- const expanded = target.value === "~" || target.value.startsWith("~/") ? home + target.value.slice(1) : target.value;
4271
- const next = expanded.startsWith("/") || expanded.startsWith("~") ? [expanded] : state.cwd.map((cwd) => `${cwd}/${expanded}`);
4318
+ const next = enter(target, state, nested);
4319
+ if (!next) return;
4272
4320
  state.cwd = unique([...state.cwd, ...next]);
4273
4321
  state.onSuccess = unique(next);
4274
4322
  return;
@@ -4356,6 +4404,17 @@ function collectShellFileAccesses(command, context = {}, report) {
4356
4404
  }
4357
4405
  if (FS_READ_TOOLS.has(name) && name !== "dd") {
4358
4406
  for (const p of readerPaths(words, head)) add("read", locate(p), state);
4407
+ if (jail) {
4408
+ const MARK = "";
4409
+ const valueFlags = UNKNOWN_VALUE_FLAGS[name] ?? [];
4410
+ const marked = words.map(
4411
+ (w, i) => i > head && w === null && !(tokens[i]?.value ?? "").startsWith("-") && !valueFlags.includes(words[i - 1] ?? "") ? `${MARK}${i}` : w
4412
+ );
4413
+ for (const p of readerPaths(marked, head))
4414
+ if (p.startsWith(MARK)) addUnknownRead(tokens[Number(p.slice(1))], state);
4415
+ if (currentFed === null && words.slice(0, head).some((w) => base(w) === "xargs"))
4416
+ addUnknownRead(null, state);
4417
+ }
4359
4418
  }
4360
4419
  if (["ls", "tree", "dir", "vdir"].includes(name)) {
4361
4420
  for (const token of args) {
@@ -4390,6 +4449,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4390
4449
  );
4391
4450
  const linkOnly = name === "cp" && strings.some((s) => /^-[^-]*[sl]/.test(s) || s === "--symbolic-link" || s === "--link");
4392
4451
  const replaceDestLink = name === "mv" || name === "ln" || strings.includes("--remove-destination");
4452
+ const symbolicLink = strings.some((s) => s === "--symbolic" || /^-[^-]*s/.test(s));
4453
+ const relativeLink = strings.some((s) => s === "--relative" || /^-[^-]*r/.test(s));
4393
4454
  for (let i = 0; i < args.length; i++) {
4394
4455
  const token = args[i];
4395
4456
  if (!token) continue;
@@ -4435,6 +4496,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4435
4496
  add("remove", source, state, { recursive: true, followFinal: false, copy: true });
4436
4497
  else if (name !== "ln" && !linkOnly)
4437
4498
  add("read", source, state, { recursive, followFinal: !preserveSourceLink, copy: true });
4499
+ else if (name === "ln" && jail && (!symbolicLink || relativeLink || /^[/~]/.test(source.value)))
4500
+ add("read", source, state, { followFinal: false, copy: true });
4438
4501
  if (!noDirectory)
4439
4502
  add(
4440
4503
  "write",
@@ -4639,6 +4702,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4639
4702
  }
4640
4703
  }
4641
4704
  function call(cmd, state, depth) {
4705
+ const fed = currentFed;
4642
4706
  const nested = clone(state);
4643
4707
  assignments(cmd.Assigns, nested);
4644
4708
  const nodes = cmd.Args ?? [];
@@ -4656,6 +4720,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4656
4720
  alternatives = alternatives.flatMap((prefix) => (words.length ? words : [null]).map((w) => [...prefix, w])).slice(0, MAX_ALTERNATIVES);
4657
4721
  }
4658
4722
  for (const tokens of alternatives) {
4723
+ currentFed = fed;
4659
4724
  fromWords(tokens, state, nested, depth);
4660
4725
  inlineCall(tokens, state, depth);
4661
4726
  }
@@ -4928,6 +4993,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4928
4993
  const fedText = stdinText(stmt);
4929
4994
  if (fedText !== null) nestedPayload(xargsPayload(stmt, fedText), clone(state), depth);
4930
4995
  currentStdin = fedText;
4996
+ currentFed = fedText ?? pipedStdin.get(stmt) ?? null;
4931
4997
  switch (cmd.kind) {
4932
4998
  case "CallExpr":
4933
4999
  call(cmd, state, depth);
@@ -8348,7 +8414,17 @@ function extractShellDestTokens(command) {
8348
8414
  }
8349
8415
  var FS_OP_CACHE_MAX = 5e3;
8350
8416
  var fsOpCache = /* @__PURE__ */ new Map();
8351
- function analyzeFsOperation(command) {
8417
+ function analyzeFsOperation(command, cwd) {
8418
+ const own = analyzeCommandFs(command);
8419
+ if (own?.verdict === "block" || !cwd || !isCredentialDir(cwd)) return own;
8420
+ const dir = cwd.replace(/\\/g, "/");
8421
+ return stricter(own, analyzeCommandFs(`cd '${dir.replace(/'/g, `'\\''`)}' && ${command}`));
8422
+ }
8423
+ function isCredentialDir(cwd) {
8424
+ if (!/^(?:\/|[A-Za-z]:[/\\])/.test(cwd)) return false;
8425
+ return matchSensitivePath(`${cwd.replace(/\\/g, "/").replace(/\/+$/, "")}/n9-any-name`) !== null;
8426
+ }
8427
+ function analyzeCommandFs(command) {
8352
8428
  const normalized = normalizeCommandForPolicy(command);
8353
8429
  const stdinShell = feedsShellStdin(command) || feedsShellStdin(normalized);
8354
8430
  const dotenvCli = DOTENV_CLI_PRESCREEN_RE.test(command) || DOTENV_CLI_PRESCREEN_RE.test(normalized);
@@ -8835,7 +8911,7 @@ var STDIN_SHELL_WORD_RE = new RegExp(
8835
8911
  "i"
8836
8912
  );
8837
8913
  var feedsShellStdin = (command) => /\||<</.test(command) && STDIN_SHELL_WORD_RE.test(command);
8838
- var CHANGES_DIR_RE = /(?:^|[\s;&|({'"`])(?:cd|pushd)\s/;
8914
+ var CHANGES_DIR_RE = /(?:^|[\s;&|({'"`])(?:(?:cd|pushd)\s|env\s(?:[^;&|\n]*?\s)?(?:-C|--chdir))/;
8839
8915
  var SOURCES_FILE_RE = /(?:^|[;&|(\s])(?:source|\.)\s/;
8840
8916
  function printsEnvironment(words) {
8841
8917
  const [name, ...rest] = words;
@@ -9172,14 +9248,29 @@ function matchSensitiveGlob(glob, dotGlob) {
9172
9248
  function underEnteredDir(a, name) {
9173
9249
  const dir = a.cwd ?? "";
9174
9250
  if (!dir || /^(?:[/\\~$]|[A-Za-z]:)/.test(name)) return name;
9175
- const rest = name.replace(/^(?:\.\/)+/, "");
9176
- return `${dir.replace(/[/\\]+$/, "")}/${rest}`;
9251
+ return joinEntered(dir, name);
9252
+ }
9253
+ function joinEntered(dir, name) {
9254
+ const out = [];
9255
+ for (const seg of `${dir}/${name}`.split(/[/\\]+/)) {
9256
+ if (seg === ".") continue;
9257
+ const last = out[out.length - 1];
9258
+ if (seg === ".." && last !== void 0 && last !== "" && last !== ".." && !/^[~$]/.test(last)) {
9259
+ out.pop();
9260
+ continue;
9261
+ }
9262
+ out.push(seg);
9263
+ }
9264
+ return out.join("/");
9265
+ }
9266
+ function judgeEntered(path2, dotGlob = false) {
9267
+ return GLOB_META.test(path2) ? matchSensitiveGlob(path2, dotGlob) : matchSensitivePath(path2);
9177
9268
  }
9178
9269
  function structuralJailRead(command) {
9179
9270
  let accesses;
9180
9271
  const report = { exhausted: false };
9181
9272
  try {
9182
- accesses = collectShellFileAccesses(command, {}, report);
9273
+ accesses = collectShellFileAccesses(command, { credentialJail: true }, report);
9183
9274
  } catch {
9184
9275
  return null;
9185
9276
  }
@@ -9192,12 +9283,12 @@ function structuralJailRead(command) {
9192
9283
  for (const a of accesses) {
9193
9284
  if (a.copy && !a.listing && (a.operation === "read" || a.operation === "remove")) {
9194
9285
  const entered = underEnteredDir(a, a.path);
9195
- if (entered !== a.path) relativeCopy ??= copyVerdictOf(matchSensitivePath(entered));
9286
+ const viaDir = !!a.cwd && entered === a.path && a.path.startsWith(`${a.cwd}/`);
9287
+ if (entered !== a.path || viaDir) relativeCopy ??= copyVerdictOf(judgeEntered(entered));
9196
9288
  continue;
9197
9289
  }
9198
9290
  if (a.operation !== "read" || a.listing || a.recursive) continue;
9199
- const glob = a.glob ?? (GLOB_META.test(a.path) ? a.path : void 0);
9200
- const hit = glob ? matchSensitiveGlob(underEnteredDir(a, glob), !!a.dotGlob) : matchSensitivePath(underEnteredDir(a, a.path));
9291
+ const hit = judgeEntered(underEnteredDir(a, a.glob ?? a.path), !!a.dotGlob);
9201
9292
  if (hit?.verdict === "block") return hit;
9202
9293
  review ??= hit;
9203
9294
  }
@@ -9219,9 +9310,9 @@ function inlineCodeJailRead(command, changesDir = false) {
9219
9310
  if (code === null) continue;
9220
9311
  for (const p of inlineReadPaths(language, code, call.preload)) {
9221
9312
  const relative = !/^(?:[/\\~$]|[A-Za-z]:)/.test(p);
9222
- const spellings = relative ? [p, ...dirs().map((d) => `${d}/${p}`)] : [p];
9313
+ const spellings = relative ? [p, ...dirs().map((d) => joinEntered(d, p))] : [p];
9223
9314
  for (const spelling of spellings) {
9224
- const hit = matchSensitivePath(spelling);
9315
+ const hit = spelling === p ? matchSensitivePath(spelling) : judgeEntered(spelling);
9225
9316
  if (hit?.verdict === "block") return hit;
9226
9317
  review ??= hit;
9227
9318
  }
@@ -9242,12 +9333,19 @@ function enteredDirs(command, depth = 0, out = []) {
9242
9333
  let head = unwrapCommandHead(words);
9243
9334
  if (baseWord(words[head]) === "builtin") head++;
9244
9335
  const name = baseWord(words[head]);
9245
- if (name !== "cd" && name !== "pushd") {
9336
+ const envAt = words.findIndex((w, i) => i < head && baseWord(w) === "env");
9337
+ const envDir = envAt < 0 ? null : words.slice(envAt + 1, head).reduce((found, w, i, rest) => {
9338
+ if (found !== null || w === null) return found;
9339
+ if (w === "-C" || w === "--chdir") return rest[i + 1] ?? null;
9340
+ if (w.startsWith("--chdir=")) return w.slice(8);
9341
+ return /^-C./.test(w) ? w.slice(2) : null;
9342
+ }, null);
9343
+ if (name !== "cd" && name !== "pushd" && envDir === null) {
9246
9344
  const payload = literalShellPayload(words, baseWord(words[0]));
9247
9345
  if (payload !== null) enteredDirs(payload, depth + 1, out);
9248
9346
  return true;
9249
9347
  }
9250
- const target = words.slice(head + 1).find((w) => w === null || !w.startsWith("-"));
9348
+ const target = envDir ?? words.slice(head + 1).find((w) => w === null || !w.startsWith("-"));
9251
9349
  if (!target) return true;
9252
9350
  const dir = target.replace(/[/\\]+$/, "");
9253
9351
  const rooted = /^(?:[/\\~]|[A-Za-z]:)/.test(dir);
@@ -19399,7 +19497,7 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
19399
19497
  const pipeVerdict = pipeChainVerdict(bashCommand, isTrustedHost, cv("data.pipe-chain"));
19400
19498
  if (pipeVerdict?.logged) noteLogged(pipeVerdict);
19401
19499
  else if (pipeVerdict) return pipeVerdict;
19402
- const fsVerdict = analyzeFsOperation(bashCommand);
19500
+ const fsVerdict = analyzeFsOperation(bashCommand, cwd);
19403
19501
  if (fsVerdict) {
19404
19502
  const isShieldRule = fsVerdict.ruleName.startsWith("shield:");
19405
19503
  const labelPrefix = isShieldRule ? "project-jail (AST)" : "Node9 (AST)";
@@ -21514,8 +21612,8 @@ function matchCanaryArgs(args, values) {
21514
21612
 
21515
21613
  // src/scan/canonical.ts
21516
21614
  var LONG_OUTPUT_THRESHOLD_BYTES = 100 * 1024;
21517
- var CANONICAL_EXTRACTOR_VERSION = "canonical-v41";
21518
- var CANONICAL_EXTRACTOR_HASH = "dbde5e7f06f3738a";
21615
+ var CANONICAL_EXTRACTOR_VERSION = "canonical-v42";
21616
+ var CANONICAL_EXTRACTOR_HASH = "3e74a6cffd82db82";
21519
21617
  var DEDUPE_PREVIEW_LEN = 120;
21520
21618
  function extractCanonicalFindings(call, ctx) {
21521
21619
  const out = [];
@@ -21662,7 +21760,7 @@ function extractCanonicalFindings(call, ctx) {
21662
21760
  if (!isShell || command === null) {
21663
21761
  return out;
21664
21762
  }
21665
- const fsVerdict = analyzeFsOperation(command);
21763
+ const fsVerdict = analyzeFsOperation(command, ctx.cwd);
21666
21764
  if (fsVerdict) {
21667
21765
  const isShield = fsVerdict.ruleName.startsWith("shield:");
21668
21766
  out.push(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@node9/policy-engine",
3
- "version": "2.65.10",
3
+ "version": "2.66.0",
4
4
  "description": "Shared policy evaluation engine for node9 — DLP, smart rules, AST shell parsing, shields, loop detection. Pure functions, no I/O. Used by both node9-proxy and the node9 SaaS firewall.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://node9.ai",