@node9/policy-engine 2.65.10 → 2.66.1

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-v43";
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 = "a60fbf5de2ecbdeb";
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-v43";
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 = "a60fbf5de2ecbdeb";
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,38 @@ 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
+ if (/^[/~]/.test(prefix)) {
4562
+ if (pattern.length > 2)
4563
+ out.push({ operation: "read", path: pattern, cwd: "", followFinal: true, glob: pattern });
4564
+ return;
4565
+ }
4566
+ for (const cwd of state.cwd)
4567
+ if (cwd)
4568
+ out.push({ operation: "read", path: pattern, cwd, followFinal: true, glob: pattern });
4569
+ }
4524
4570
  function fromWords(tokens, state, nested, depth) {
4525
4571
  const words = tokens.map((w) => w && !w.dynamic ? w.value : null);
4526
4572
  let head = unwrapCommandHead(words, true);
4527
4573
  if (base(words[head]) === "builtin" && ["cd", "pushd"].includes(base(words[head + 1]))) head++;
4528
4574
  const name = base(words[head]);
4575
+ if (jail) {
4576
+ const dir = envChdir(tokens, head);
4577
+ const next = dir ? enter(dir, state, nested) : null;
4578
+ if (next) {
4579
+ state = { ...clone(state), cwd: unique(next) };
4580
+ nested = { ...clone(nested), cwd: unique(next) };
4581
+ }
4582
+ }
4529
4583
  if (name === "find") {
4530
4584
  findActions2(tokens, words, head, state, nested, depth);
4531
4585
  return;
@@ -4536,9 +4590,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4536
4590
  if (args.some((w) => w === null || w.value === "-" || w.dynamic)) return;
4537
4591
  const home = nested.vars.get("HOME")?.[0] ?? "~";
4538
4592
  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}`);
4593
+ const next = enter(target, state, nested);
4594
+ if (!next) return;
4542
4595
  state.cwd = unique([...state.cwd, ...next]);
4543
4596
  state.onSuccess = unique(next);
4544
4597
  return;
@@ -4626,6 +4679,17 @@ function collectShellFileAccesses(command, context = {}, report) {
4626
4679
  }
4627
4680
  if (FS_READ_TOOLS.has(name) && name !== "dd") {
4628
4681
  for (const p of readerPaths(words, head)) add("read", locate(p), state);
4682
+ if (jail) {
4683
+ const MARK = "";
4684
+ const valueFlags = UNKNOWN_VALUE_FLAGS[name] ?? [];
4685
+ const marked = words.map(
4686
+ (w, i) => i > head && w === null && !(tokens[i]?.value ?? "").startsWith("-") && !valueFlags.includes(words[i - 1] ?? "") ? `${MARK}${i}` : w
4687
+ );
4688
+ for (const p of readerPaths(marked, head))
4689
+ if (p.startsWith(MARK)) addUnknownRead(tokens[Number(p.slice(1))], state);
4690
+ if (currentFed === null && words.slice(0, head).some((w) => base(w) === "xargs"))
4691
+ addUnknownRead(null, state);
4692
+ }
4629
4693
  }
4630
4694
  if (["ls", "tree", "dir", "vdir"].includes(name)) {
4631
4695
  for (const token of args) {
@@ -4660,6 +4724,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4660
4724
  );
4661
4725
  const linkOnly = name === "cp" && strings.some((s) => /^-[^-]*[sl]/.test(s) || s === "--symbolic-link" || s === "--link");
4662
4726
  const replaceDestLink = name === "mv" || name === "ln" || strings.includes("--remove-destination");
4727
+ const symbolicLink = strings.some((s) => s === "--symbolic" || /^-[^-]*s/.test(s));
4728
+ const relativeLink = strings.some((s) => s === "--relative" || /^-[^-]*r/.test(s));
4663
4729
  for (let i = 0; i < args.length; i++) {
4664
4730
  const token = args[i];
4665
4731
  if (!token) continue;
@@ -4705,6 +4771,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4705
4771
  add("remove", source, state, { recursive: true, followFinal: false, copy: true });
4706
4772
  else if (name !== "ln" && !linkOnly)
4707
4773
  add("read", source, state, { recursive, followFinal: !preserveSourceLink, copy: true });
4774
+ else if (name === "ln" && jail && (!symbolicLink || relativeLink || /^[/~]/.test(source.value)))
4775
+ add("read", source, state, { followFinal: false, copy: true });
4708
4776
  if (!noDirectory)
4709
4777
  add(
4710
4778
  "write",
@@ -4909,6 +4977,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4909
4977
  }
4910
4978
  }
4911
4979
  function call(cmd, state, depth) {
4980
+ const fed = currentFed;
4912
4981
  const nested = clone(state);
4913
4982
  assignments(cmd.Assigns, nested);
4914
4983
  const nodes = cmd.Args ?? [];
@@ -4926,6 +4995,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4926
4995
  alternatives = alternatives.flatMap((prefix) => (words.length ? words : [null]).map((w) => [...prefix, w])).slice(0, MAX_ALTERNATIVES);
4927
4996
  }
4928
4997
  for (const tokens of alternatives) {
4998
+ currentFed = fed;
4929
4999
  fromWords(tokens, state, nested, depth);
4930
5000
  inlineCall(tokens, state, depth);
4931
5001
  }
@@ -5198,6 +5268,7 @@ function collectShellFileAccesses(command, context = {}, report) {
5198
5268
  const fedText = stdinText(stmt);
5199
5269
  if (fedText !== null) nestedPayload(xargsPayload(stmt, fedText), clone(state), depth);
5200
5270
  currentStdin = fedText;
5271
+ currentFed = fedText ?? pipedStdin.get(stmt) ?? null;
5201
5272
  switch (cmd.kind) {
5202
5273
  case "CallExpr":
5203
5274
  call(cmd, state, depth);
@@ -8618,7 +8689,17 @@ function extractShellDestTokens(command) {
8618
8689
  }
8619
8690
  var FS_OP_CACHE_MAX = 5e3;
8620
8691
  var fsOpCache = /* @__PURE__ */ new Map();
8621
- function analyzeFsOperation(command) {
8692
+ function analyzeFsOperation(command, cwd) {
8693
+ const own = analyzeCommandFs(command);
8694
+ if (own?.verdict === "block" || !cwd || !isCredentialDir(cwd)) return own;
8695
+ const dir = cwd.replace(/\\/g, "/");
8696
+ return stricter(own, analyzeCommandFs(`cd '${dir.replace(/'/g, `'\\''`)}' && ${command}`));
8697
+ }
8698
+ function isCredentialDir(cwd) {
8699
+ if (!/^(?:\/|[A-Za-z]:[/\\])/.test(cwd)) return false;
8700
+ return matchSensitivePath(`${cwd.replace(/\\/g, "/").replace(/\/+$/, "")}/n9-any-name`) !== null;
8701
+ }
8702
+ function analyzeCommandFs(command) {
8622
8703
  const normalized = normalizeCommandForPolicy(command);
8623
8704
  const stdinShell = feedsShellStdin(command) || feedsShellStdin(normalized);
8624
8705
  const dotenvCli = DOTENV_CLI_PRESCREEN_RE.test(command) || DOTENV_CLI_PRESCREEN_RE.test(normalized);
@@ -8632,7 +8713,7 @@ function analyzeFsOperation(command) {
8632
8713
  }
8633
8714
  const changesDir = CHANGES_DIR_RE.test(command) || CHANGES_DIR_RE.test(normalized);
8634
8715
  const own = analyzeFsOperationImpl(command);
8635
- const direct = (stdinShell || changesDir) && own?.verdict !== "block" ? stricter(own, structuralJailRead(command)) : own ?? (INDIRECT_SHAPE_RE.test(command) ? structuralJailRead(command) : null);
8716
+ const direct = (stdinShell || changesDir) && own?.verdict !== "block" ? stricter(own, structuralJailRead(command)) : own ?? (INDIRECT_SHAPE_RE.test(command) || namesCredentialDirLate(command) ? structuralJailRead(command) : null);
8636
8717
  const withInline = direct?.verdict === "block" || !runsInlineInterpreter(command, normalized) ? direct : stricter(direct, inlineCodeJailRead(command, changesDir));
8637
8718
  const computed = withInline?.verdict === "block" || !dotenvCli ? withInline : stricter(withInline, dotenvCliJailRead(command));
8638
8719
  if (fsOpCache.size >= FS_OP_CACHE_MAX) {
@@ -9100,12 +9181,26 @@ function matchSensitivePath(p) {
9100
9181
  return null;
9101
9182
  }
9102
9183
  var INDIRECT_SHAPE_RE = /\b(?:for|while|until|find|xargs|set|source)\b|\$\{?PWD\b|[*?[]|(?:^|[;&|(\s])\.\s/;
9184
+ var CREDENTIAL_DIR_NAME_RE = /\.(?:ssh|aws)(?![\w.-])/;
9185
+ function namesCredentialDirLate(command) {
9186
+ if (!/[$`]/.test(command) || !CREDENTIAL_DIR_NAME_RE.test(command)) return false;
9187
+ for (const word of command.split(/[\s;&|<>]+/)) {
9188
+ const at = word.search(/\.(?:ssh|aws)\//);
9189
+ if (at >= 0 && /[$`]/.test(word.slice(at))) return true;
9190
+ }
9191
+ if (command.split("`").some((seg, i) => i % 2 === 1 && CREDENTIAL_DIR_NAME_RE.test(seg)))
9192
+ return true;
9193
+ return command.split(")").some((seg) => {
9194
+ const open = seg.lastIndexOf("$(");
9195
+ return open >= 0 && CREDENTIAL_DIR_NAME_RE.test(seg.slice(open));
9196
+ });
9197
+ }
9103
9198
  var STDIN_SHELL_WORD_RE = new RegExp(
9104
9199
  `(?:^|[\\s;&|(/\\\\])(?:${[...SHELL_INTERPRETERS].map((name) => name.replace(/[.*+?^\${}()|[\]\\]/g, "\\$&")).join("|")})(?=$|[\\s;&|)<])`,
9105
9200
  "i"
9106
9201
  );
9107
9202
  var feedsShellStdin = (command) => /\||<</.test(command) && STDIN_SHELL_WORD_RE.test(command);
9108
- var CHANGES_DIR_RE = /(?:^|[\s;&|({'"`])(?:cd|pushd)\s/;
9203
+ var CHANGES_DIR_RE = /(?:^|[\s;&|({'"`])(?:(?:cd|pushd)\s|env\s(?:[^;&|\n]*?\s)?(?:-C|--chdir))/;
9109
9204
  var SOURCES_FILE_RE = /(?:^|[;&|(\s])(?:source|\.)\s/;
9110
9205
  function printsEnvironment(words) {
9111
9206
  const [name, ...rest] = words;
@@ -9241,6 +9336,94 @@ function findOfJailedNames(stmt) {
9241
9336
  }
9242
9337
  return null;
9243
9338
  }
9339
+ function homeLedWord(word) {
9340
+ const literal = resolveWordLiteral(word);
9341
+ if (literal !== null) return literal;
9342
+ let parts = word?.Parts ?? [];
9343
+ if (parts.length === 1 && parts[0].kind === "DblQuoted") parts = parts[0].Parts ?? [];
9344
+ const first = parts[0];
9345
+ if (first?.kind !== "ParamExp" || first.Param?.Value !== "HOME") return null;
9346
+ if (first.Exp || first.Index || first.Length || first.Excl || first.Slice || first.Repl)
9347
+ return null;
9348
+ const rest = parts.length > 1 ? resolveWordLiteral({ Parts: parts.slice(1) }) : "";
9349
+ return rest === null ? null : `~${rest}`;
9350
+ }
9351
+ var PRIVATE_PROBE_NAMES = ["id_rsa", "id_ed25519", "id_ecdsa", "config", "credentials"];
9352
+ function credentialDirListing(stmt) {
9353
+ const cmd = stmt?.Cmd;
9354
+ if (cmd?.kind !== "CallExpr") return null;
9355
+ const words = (cmd.Args ?? []).map((a) => homeLedWord(a));
9356
+ const head = unwrapCommandHead(words);
9357
+ const name = baseWord(words[head]);
9358
+ const rest = words.slice(head + 1);
9359
+ let targets;
9360
+ if (name === "find") {
9361
+ for (let i = 0; i < rest.length; i++)
9362
+ if (rest[i] === "-type" && rest[i + 1] === "d") return null;
9363
+ const patterns = findNamePatterns(rest);
9364
+ const selectsPrivate = patterns.length === 0 || patterns.some(({ pattern, nocase }) => {
9365
+ try {
9366
+ const m = (0, import_picomatch.default)(shellGlob(pattern), { dot: true, nocase });
9367
+ return PRIVATE_PROBE_NAMES.some((n) => m(n));
9368
+ } catch {
9369
+ return true;
9370
+ }
9371
+ });
9372
+ if (!selectsPrivate) return null;
9373
+ targets = findStartPoints(words, head).starts;
9374
+ } else if (name === "ls") {
9375
+ targets = rest.filter((w) => w === null || !w.startsWith("-"));
9376
+ } else if (name === "fd" || name === "fdfind") {
9377
+ targets = rest.filter((w) => w === null || !w.startsWith("-")).slice(1);
9378
+ } else return null;
9379
+ for (const target of targets) {
9380
+ if (target === null) continue;
9381
+ const t = joinEntered(target, ".").replace(/[/\\]+$/, "");
9382
+ if (isPublicSshMaterial(t)) continue;
9383
+ if (GLOB_META.test(t)) {
9384
+ const hit2 = matchSensitiveGlob(t, name === "find");
9385
+ if (hit2?.verdict === "block") return hit2;
9386
+ continue;
9387
+ }
9388
+ const hit = matchSensitivePath(`${t}/n9-any-name`);
9389
+ if (hit?.verdict === "block") return { ...hit, path: `${t}/*` };
9390
+ }
9391
+ return null;
9392
+ }
9393
+ var listingVerdict = (stmt) => findOfJailedNames(stmt) ?? credentialDirListing(stmt);
9394
+ function listedNamesRead(command) {
9395
+ const f = parseShared(command);
9396
+ if (typeof f === "symbol") return null;
9397
+ const substVerdict = (node) => {
9398
+ let found = null;
9399
+ walk(node, (n) => {
9400
+ if (found) return false;
9401
+ if (n.kind !== "CmdSubst") return true;
9402
+ walk(n, (m) => {
9403
+ if (m?.Cmd) found ??= listingVerdict(m);
9404
+ return !found;
9405
+ });
9406
+ return false;
9407
+ });
9408
+ return found;
9409
+ };
9410
+ let hit = null;
9411
+ walk(f, (n) => {
9412
+ if (hit) return false;
9413
+ const node = n;
9414
+ if (node.kind === "CallExpr") {
9415
+ const words = callWords(node);
9416
+ if (isReaderWord(words[unwrapCommandHead(words)])) hit = substVerdict(node);
9417
+ } else if (node.kind === "ForClause") {
9418
+ const v = node.Loop?.Name?.Value;
9419
+ if (v && hasReader({ kind: "Block", Stmts: node.Do }, v)) {
9420
+ for (const item of node.Loop.Items ?? []) hit ??= substVerdict(item);
9421
+ }
9422
+ }
9423
+ return !hit;
9424
+ });
9425
+ return hit;
9426
+ }
9244
9427
  var pipeOps = lazy(
9245
9428
  () => new Set(
9246
9429
  ["a | b", "a |& b"].map((t) => {
@@ -9281,7 +9464,7 @@ function findPipedToReader(command) {
9281
9464
  }
9282
9465
  }
9283
9466
  for (let i = 0; i < stages.length - 1 && !hit; i++) {
9284
- const found = findOfJailedNames(stages[i]);
9467
+ const found = listingVerdict(stages[i]);
9285
9468
  if (found && stages.slice(i + 1).some(readsFedNames)) hit = found;
9286
9469
  }
9287
9470
  return !hit;
@@ -9442,18 +9625,33 @@ function matchSensitiveGlob(glob, dotGlob) {
9442
9625
  function underEnteredDir(a, name) {
9443
9626
  const dir = a.cwd ?? "";
9444
9627
  if (!dir || /^(?:[/\\~$]|[A-Za-z]:)/.test(name)) return name;
9445
- const rest = name.replace(/^(?:\.\/)+/, "");
9446
- return `${dir.replace(/[/\\]+$/, "")}/${rest}`;
9628
+ return joinEntered(dir, name);
9629
+ }
9630
+ function joinEntered(dir, name) {
9631
+ const out = [];
9632
+ for (const seg of `${dir}/${name}`.split(/[/\\]+/)) {
9633
+ if (seg === ".") continue;
9634
+ const last = out[out.length - 1];
9635
+ if (seg === ".." && last !== void 0 && last !== "" && last !== ".." && !/^[~$]/.test(last)) {
9636
+ out.pop();
9637
+ continue;
9638
+ }
9639
+ out.push(seg);
9640
+ }
9641
+ return out.join("/");
9642
+ }
9643
+ function judgeEntered(path, dotGlob = false) {
9644
+ return GLOB_META.test(path) ? matchSensitiveGlob(path, dotGlob) : matchSensitivePath(path);
9447
9645
  }
9448
9646
  function structuralJailRead(command) {
9449
9647
  let accesses;
9450
9648
  const report = { exhausted: false };
9451
9649
  try {
9452
- accesses = collectShellFileAccesses(command, {}, report);
9650
+ accesses = collectShellFileAccesses(command, { credentialJail: true }, report);
9453
9651
  } catch {
9454
9652
  return null;
9455
9653
  }
9456
- const piped = findPipedToReader(command);
9654
+ const piped = findPipedToReader(command) ?? listedNamesRead(command);
9457
9655
  if (piped) return piped;
9458
9656
  const sourcedHit = sourcedAndPrinted(command);
9459
9657
  if (sourcedHit?.verdict === "block") return sourcedHit;
@@ -9462,12 +9660,12 @@ function structuralJailRead(command) {
9462
9660
  for (const a of accesses) {
9463
9661
  if (a.copy && !a.listing && (a.operation === "read" || a.operation === "remove")) {
9464
9662
  const entered = underEnteredDir(a, a.path);
9465
- if (entered !== a.path) relativeCopy ??= copyVerdictOf(matchSensitivePath(entered));
9663
+ const viaDir = !!a.cwd && entered === a.path && a.path.startsWith(`${a.cwd}/`);
9664
+ if (entered !== a.path || viaDir) relativeCopy ??= copyVerdictOf(judgeEntered(entered));
9466
9665
  continue;
9467
9666
  }
9468
9667
  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));
9668
+ const hit = judgeEntered(underEnteredDir(a, a.glob ?? a.path), !!a.dotGlob);
9471
9669
  if (hit?.verdict === "block") return hit;
9472
9670
  review ??= hit;
9473
9671
  }
@@ -9489,9 +9687,9 @@ function inlineCodeJailRead(command, changesDir = false) {
9489
9687
  if (code === null) continue;
9490
9688
  for (const p of inlineReadPaths(language, code, call.preload)) {
9491
9689
  const relative = !/^(?:[/\\~$]|[A-Za-z]:)/.test(p);
9492
- const spellings = relative ? [p, ...dirs().map((d) => `${d}/${p}`)] : [p];
9690
+ const spellings = relative ? [p, ...dirs().map((d) => joinEntered(d, p))] : [p];
9493
9691
  for (const spelling of spellings) {
9494
- const hit = matchSensitivePath(spelling);
9692
+ const hit = spelling === p ? matchSensitivePath(spelling) : judgeEntered(spelling);
9495
9693
  if (hit?.verdict === "block") return hit;
9496
9694
  review ??= hit;
9497
9695
  }
@@ -9512,12 +9710,19 @@ function enteredDirs(command, depth = 0, out = []) {
9512
9710
  let head = unwrapCommandHead(words);
9513
9711
  if (baseWord(words[head]) === "builtin") head++;
9514
9712
  const name = baseWord(words[head]);
9515
- if (name !== "cd" && name !== "pushd") {
9713
+ const envAt = words.findIndex((w, i) => i < head && baseWord(w) === "env");
9714
+ const envDir = envAt < 0 ? null : words.slice(envAt + 1, head).reduce((found, w, i, rest) => {
9715
+ if (found !== null || w === null) return found;
9716
+ if (w === "-C" || w === "--chdir") return rest[i + 1] ?? null;
9717
+ if (w.startsWith("--chdir=")) return w.slice(8);
9718
+ return /^-C./.test(w) ? w.slice(2) : null;
9719
+ }, null);
9720
+ if (name !== "cd" && name !== "pushd" && envDir === null) {
9516
9721
  const payload = literalShellPayload(words, baseWord(words[0]));
9517
9722
  if (payload !== null) enteredDirs(payload, depth + 1, out);
9518
9723
  return true;
9519
9724
  }
9520
- const target = words.slice(head + 1).find((w) => w === null || !w.startsWith("-"));
9725
+ const target = envDir ?? words.slice(head + 1).find((w) => w === null || !w.startsWith("-"));
9521
9726
  if (!target) return true;
9522
9727
  const dir = target.replace(/[/\\]+$/, "");
9523
9728
  const rooted = /^(?:[/\\~]|[A-Za-z]:)/.test(dir);
@@ -19669,7 +19874,7 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
19669
19874
  const pipeVerdict = pipeChainVerdict(bashCommand, isTrustedHost, cv("data.pipe-chain"));
19670
19875
  if (pipeVerdict?.logged) noteLogged(pipeVerdict);
19671
19876
  else if (pipeVerdict) return pipeVerdict;
19672
- const fsVerdict = analyzeFsOperation(bashCommand);
19877
+ const fsVerdict = analyzeFsOperation(bashCommand, cwd);
19673
19878
  if (fsVerdict) {
19674
19879
  const isShieldRule = fsVerdict.ruleName.startsWith("shield:");
19675
19880
  const labelPrefix = isShieldRule ? "project-jail (AST)" : "Node9 (AST)";
@@ -21784,8 +21989,8 @@ function matchCanaryArgs(args, values) {
21784
21989
 
21785
21990
  // src/scan/canonical.ts
21786
21991
  var LONG_OUTPUT_THRESHOLD_BYTES = 100 * 1024;
21787
- var CANONICAL_EXTRACTOR_VERSION = "canonical-v41";
21788
- var CANONICAL_EXTRACTOR_HASH = "dbde5e7f06f3738a";
21992
+ var CANONICAL_EXTRACTOR_VERSION = "canonical-v43";
21993
+ var CANONICAL_EXTRACTOR_HASH = "a60fbf5de2ecbdeb";
21789
21994
  var DEDUPE_PREVIEW_LEN = 120;
21790
21995
  function extractCanonicalFindings(call, ctx) {
21791
21996
  const out = [];
@@ -21932,7 +22137,7 @@ function extractCanonicalFindings(call, ctx) {
21932
22137
  if (!isShell || command === null) {
21933
22138
  return out;
21934
22139
  }
21935
- const fsVerdict = analyzeFsOperation(command);
22140
+ const fsVerdict = analyzeFsOperation(command, ctx.cwd);
21936
22141
  if (fsVerdict) {
21937
22142
  const isShield = fsVerdict.ruleName.startsWith("shield:");
21938
22143
  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,38 @@ 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
+ if (/^[/~]/.test(prefix)) {
4292
+ if (pattern.length > 2)
4293
+ out.push({ operation: "read", path: pattern, cwd: "", followFinal: true, glob: pattern });
4294
+ return;
4295
+ }
4296
+ for (const cwd of state.cwd)
4297
+ if (cwd)
4298
+ out.push({ operation: "read", path: pattern, cwd, followFinal: true, glob: pattern });
4299
+ }
4254
4300
  function fromWords(tokens, state, nested, depth) {
4255
4301
  const words = tokens.map((w) => w && !w.dynamic ? w.value : null);
4256
4302
  let head = unwrapCommandHead(words, true);
4257
4303
  if (base(words[head]) === "builtin" && ["cd", "pushd"].includes(base(words[head + 1]))) head++;
4258
4304
  const name = base(words[head]);
4305
+ if (jail) {
4306
+ const dir = envChdir(tokens, head);
4307
+ const next = dir ? enter(dir, state, nested) : null;
4308
+ if (next) {
4309
+ state = { ...clone(state), cwd: unique(next) };
4310
+ nested = { ...clone(nested), cwd: unique(next) };
4311
+ }
4312
+ }
4259
4313
  if (name === "find") {
4260
4314
  findActions2(tokens, words, head, state, nested, depth);
4261
4315
  return;
@@ -4266,9 +4320,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4266
4320
  if (args.some((w) => w === null || w.value === "-" || w.dynamic)) return;
4267
4321
  const home = nested.vars.get("HOME")?.[0] ?? "~";
4268
4322
  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}`);
4323
+ const next = enter(target, state, nested);
4324
+ if (!next) return;
4272
4325
  state.cwd = unique([...state.cwd, ...next]);
4273
4326
  state.onSuccess = unique(next);
4274
4327
  return;
@@ -4356,6 +4409,17 @@ function collectShellFileAccesses(command, context = {}, report) {
4356
4409
  }
4357
4410
  if (FS_READ_TOOLS.has(name) && name !== "dd") {
4358
4411
  for (const p of readerPaths(words, head)) add("read", locate(p), state);
4412
+ if (jail) {
4413
+ const MARK = "";
4414
+ const valueFlags = UNKNOWN_VALUE_FLAGS[name] ?? [];
4415
+ const marked = words.map(
4416
+ (w, i) => i > head && w === null && !(tokens[i]?.value ?? "").startsWith("-") && !valueFlags.includes(words[i - 1] ?? "") ? `${MARK}${i}` : w
4417
+ );
4418
+ for (const p of readerPaths(marked, head))
4419
+ if (p.startsWith(MARK)) addUnknownRead(tokens[Number(p.slice(1))], state);
4420
+ if (currentFed === null && words.slice(0, head).some((w) => base(w) === "xargs"))
4421
+ addUnknownRead(null, state);
4422
+ }
4359
4423
  }
4360
4424
  if (["ls", "tree", "dir", "vdir"].includes(name)) {
4361
4425
  for (const token of args) {
@@ -4390,6 +4454,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4390
4454
  );
4391
4455
  const linkOnly = name === "cp" && strings.some((s) => /^-[^-]*[sl]/.test(s) || s === "--symbolic-link" || s === "--link");
4392
4456
  const replaceDestLink = name === "mv" || name === "ln" || strings.includes("--remove-destination");
4457
+ const symbolicLink = strings.some((s) => s === "--symbolic" || /^-[^-]*s/.test(s));
4458
+ const relativeLink = strings.some((s) => s === "--relative" || /^-[^-]*r/.test(s));
4393
4459
  for (let i = 0; i < args.length; i++) {
4394
4460
  const token = args[i];
4395
4461
  if (!token) continue;
@@ -4435,6 +4501,8 @@ function collectShellFileAccesses(command, context = {}, report) {
4435
4501
  add("remove", source, state, { recursive: true, followFinal: false, copy: true });
4436
4502
  else if (name !== "ln" && !linkOnly)
4437
4503
  add("read", source, state, { recursive, followFinal: !preserveSourceLink, copy: true });
4504
+ else if (name === "ln" && jail && (!symbolicLink || relativeLink || /^[/~]/.test(source.value)))
4505
+ add("read", source, state, { followFinal: false, copy: true });
4438
4506
  if (!noDirectory)
4439
4507
  add(
4440
4508
  "write",
@@ -4639,6 +4707,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4639
4707
  }
4640
4708
  }
4641
4709
  function call(cmd, state, depth) {
4710
+ const fed = currentFed;
4642
4711
  const nested = clone(state);
4643
4712
  assignments(cmd.Assigns, nested);
4644
4713
  const nodes = cmd.Args ?? [];
@@ -4656,6 +4725,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4656
4725
  alternatives = alternatives.flatMap((prefix) => (words.length ? words : [null]).map((w) => [...prefix, w])).slice(0, MAX_ALTERNATIVES);
4657
4726
  }
4658
4727
  for (const tokens of alternatives) {
4728
+ currentFed = fed;
4659
4729
  fromWords(tokens, state, nested, depth);
4660
4730
  inlineCall(tokens, state, depth);
4661
4731
  }
@@ -4928,6 +4998,7 @@ function collectShellFileAccesses(command, context = {}, report) {
4928
4998
  const fedText = stdinText(stmt);
4929
4999
  if (fedText !== null) nestedPayload(xargsPayload(stmt, fedText), clone(state), depth);
4930
5000
  currentStdin = fedText;
5001
+ currentFed = fedText ?? pipedStdin.get(stmt) ?? null;
4931
5002
  switch (cmd.kind) {
4932
5003
  case "CallExpr":
4933
5004
  call(cmd, state, depth);
@@ -8348,7 +8419,17 @@ function extractShellDestTokens(command) {
8348
8419
  }
8349
8420
  var FS_OP_CACHE_MAX = 5e3;
8350
8421
  var fsOpCache = /* @__PURE__ */ new Map();
8351
- function analyzeFsOperation(command) {
8422
+ function analyzeFsOperation(command, cwd) {
8423
+ const own = analyzeCommandFs(command);
8424
+ if (own?.verdict === "block" || !cwd || !isCredentialDir(cwd)) return own;
8425
+ const dir = cwd.replace(/\\/g, "/");
8426
+ return stricter(own, analyzeCommandFs(`cd '${dir.replace(/'/g, `'\\''`)}' && ${command}`));
8427
+ }
8428
+ function isCredentialDir(cwd) {
8429
+ if (!/^(?:\/|[A-Za-z]:[/\\])/.test(cwd)) return false;
8430
+ return matchSensitivePath(`${cwd.replace(/\\/g, "/").replace(/\/+$/, "")}/n9-any-name`) !== null;
8431
+ }
8432
+ function analyzeCommandFs(command) {
8352
8433
  const normalized = normalizeCommandForPolicy(command);
8353
8434
  const stdinShell = feedsShellStdin(command) || feedsShellStdin(normalized);
8354
8435
  const dotenvCli = DOTENV_CLI_PRESCREEN_RE.test(command) || DOTENV_CLI_PRESCREEN_RE.test(normalized);
@@ -8362,7 +8443,7 @@ function analyzeFsOperation(command) {
8362
8443
  }
8363
8444
  const changesDir = CHANGES_DIR_RE.test(command) || CHANGES_DIR_RE.test(normalized);
8364
8445
  const own = analyzeFsOperationImpl(command);
8365
- const direct = (stdinShell || changesDir) && own?.verdict !== "block" ? stricter(own, structuralJailRead(command)) : own ?? (INDIRECT_SHAPE_RE.test(command) ? structuralJailRead(command) : null);
8446
+ const direct = (stdinShell || changesDir) && own?.verdict !== "block" ? stricter(own, structuralJailRead(command)) : own ?? (INDIRECT_SHAPE_RE.test(command) || namesCredentialDirLate(command) ? structuralJailRead(command) : null);
8366
8447
  const withInline = direct?.verdict === "block" || !runsInlineInterpreter(command, normalized) ? direct : stricter(direct, inlineCodeJailRead(command, changesDir));
8367
8448
  const computed = withInline?.verdict === "block" || !dotenvCli ? withInline : stricter(withInline, dotenvCliJailRead(command));
8368
8449
  if (fsOpCache.size >= FS_OP_CACHE_MAX) {
@@ -8830,12 +8911,26 @@ function matchSensitivePath(p) {
8830
8911
  return null;
8831
8912
  }
8832
8913
  var INDIRECT_SHAPE_RE = /\b(?:for|while|until|find|xargs|set|source)\b|\$\{?PWD\b|[*?[]|(?:^|[;&|(\s])\.\s/;
8914
+ var CREDENTIAL_DIR_NAME_RE = /\.(?:ssh|aws)(?![\w.-])/;
8915
+ function namesCredentialDirLate(command) {
8916
+ if (!/[$`]/.test(command) || !CREDENTIAL_DIR_NAME_RE.test(command)) return false;
8917
+ for (const word of command.split(/[\s;&|<>]+/)) {
8918
+ const at = word.search(/\.(?:ssh|aws)\//);
8919
+ if (at >= 0 && /[$`]/.test(word.slice(at))) return true;
8920
+ }
8921
+ if (command.split("`").some((seg, i) => i % 2 === 1 && CREDENTIAL_DIR_NAME_RE.test(seg)))
8922
+ return true;
8923
+ return command.split(")").some((seg) => {
8924
+ const open = seg.lastIndexOf("$(");
8925
+ return open >= 0 && CREDENTIAL_DIR_NAME_RE.test(seg.slice(open));
8926
+ });
8927
+ }
8833
8928
  var STDIN_SHELL_WORD_RE = new RegExp(
8834
8929
  `(?:^|[\\s;&|(/\\\\])(?:${[...SHELL_INTERPRETERS].map((name) => name.replace(/[.*+?^\${}()|[\]\\]/g, "\\$&")).join("|")})(?=$|[\\s;&|)<])`,
8835
8930
  "i"
8836
8931
  );
8837
8932
  var feedsShellStdin = (command) => /\||<</.test(command) && STDIN_SHELL_WORD_RE.test(command);
8838
- var CHANGES_DIR_RE = /(?:^|[\s;&|({'"`])(?:cd|pushd)\s/;
8933
+ var CHANGES_DIR_RE = /(?:^|[\s;&|({'"`])(?:(?:cd|pushd)\s|env\s(?:[^;&|\n]*?\s)?(?:-C|--chdir))/;
8839
8934
  var SOURCES_FILE_RE = /(?:^|[;&|(\s])(?:source|\.)\s/;
8840
8935
  function printsEnvironment(words) {
8841
8936
  const [name, ...rest] = words;
@@ -8971,6 +9066,94 @@ function findOfJailedNames(stmt) {
8971
9066
  }
8972
9067
  return null;
8973
9068
  }
9069
+ function homeLedWord(word) {
9070
+ const literal = resolveWordLiteral(word);
9071
+ if (literal !== null) return literal;
9072
+ let parts = word?.Parts ?? [];
9073
+ if (parts.length === 1 && parts[0].kind === "DblQuoted") parts = parts[0].Parts ?? [];
9074
+ const first = parts[0];
9075
+ if (first?.kind !== "ParamExp" || first.Param?.Value !== "HOME") return null;
9076
+ if (first.Exp || first.Index || first.Length || first.Excl || first.Slice || first.Repl)
9077
+ return null;
9078
+ const rest = parts.length > 1 ? resolveWordLiteral({ Parts: parts.slice(1) }) : "";
9079
+ return rest === null ? null : `~${rest}`;
9080
+ }
9081
+ var PRIVATE_PROBE_NAMES = ["id_rsa", "id_ed25519", "id_ecdsa", "config", "credentials"];
9082
+ function credentialDirListing(stmt) {
9083
+ const cmd = stmt?.Cmd;
9084
+ if (cmd?.kind !== "CallExpr") return null;
9085
+ const words = (cmd.Args ?? []).map((a) => homeLedWord(a));
9086
+ const head = unwrapCommandHead(words);
9087
+ const name = baseWord(words[head]);
9088
+ const rest = words.slice(head + 1);
9089
+ let targets;
9090
+ if (name === "find") {
9091
+ for (let i = 0; i < rest.length; i++)
9092
+ if (rest[i] === "-type" && rest[i + 1] === "d") return null;
9093
+ const patterns = findNamePatterns(rest);
9094
+ const selectsPrivate = patterns.length === 0 || patterns.some(({ pattern, nocase }) => {
9095
+ try {
9096
+ const m = picomatch(shellGlob(pattern), { dot: true, nocase });
9097
+ return PRIVATE_PROBE_NAMES.some((n) => m(n));
9098
+ } catch {
9099
+ return true;
9100
+ }
9101
+ });
9102
+ if (!selectsPrivate) return null;
9103
+ targets = findStartPoints(words, head).starts;
9104
+ } else if (name === "ls") {
9105
+ targets = rest.filter((w) => w === null || !w.startsWith("-"));
9106
+ } else if (name === "fd" || name === "fdfind") {
9107
+ targets = rest.filter((w) => w === null || !w.startsWith("-")).slice(1);
9108
+ } else return null;
9109
+ for (const target of targets) {
9110
+ if (target === null) continue;
9111
+ const t = joinEntered(target, ".").replace(/[/\\]+$/, "");
9112
+ if (isPublicSshMaterial(t)) continue;
9113
+ if (GLOB_META.test(t)) {
9114
+ const hit2 = matchSensitiveGlob(t, name === "find");
9115
+ if (hit2?.verdict === "block") return hit2;
9116
+ continue;
9117
+ }
9118
+ const hit = matchSensitivePath(`${t}/n9-any-name`);
9119
+ if (hit?.verdict === "block") return { ...hit, path: `${t}/*` };
9120
+ }
9121
+ return null;
9122
+ }
9123
+ var listingVerdict = (stmt) => findOfJailedNames(stmt) ?? credentialDirListing(stmt);
9124
+ function listedNamesRead(command) {
9125
+ const f = parseShared(command);
9126
+ if (typeof f === "symbol") return null;
9127
+ const substVerdict = (node) => {
9128
+ let found = null;
9129
+ walk(node, (n) => {
9130
+ if (found) return false;
9131
+ if (n.kind !== "CmdSubst") return true;
9132
+ walk(n, (m) => {
9133
+ if (m?.Cmd) found ??= listingVerdict(m);
9134
+ return !found;
9135
+ });
9136
+ return false;
9137
+ });
9138
+ return found;
9139
+ };
9140
+ let hit = null;
9141
+ walk(f, (n) => {
9142
+ if (hit) return false;
9143
+ const node = n;
9144
+ if (node.kind === "CallExpr") {
9145
+ const words = callWords(node);
9146
+ if (isReaderWord(words[unwrapCommandHead(words)])) hit = substVerdict(node);
9147
+ } else if (node.kind === "ForClause") {
9148
+ const v = node.Loop?.Name?.Value;
9149
+ if (v && hasReader({ kind: "Block", Stmts: node.Do }, v)) {
9150
+ for (const item of node.Loop.Items ?? []) hit ??= substVerdict(item);
9151
+ }
9152
+ }
9153
+ return !hit;
9154
+ });
9155
+ return hit;
9156
+ }
8974
9157
  var pipeOps = lazy(
8975
9158
  () => new Set(
8976
9159
  ["a | b", "a |& b"].map((t) => {
@@ -9011,7 +9194,7 @@ function findPipedToReader(command) {
9011
9194
  }
9012
9195
  }
9013
9196
  for (let i = 0; i < stages.length - 1 && !hit; i++) {
9014
- const found = findOfJailedNames(stages[i]);
9197
+ const found = listingVerdict(stages[i]);
9015
9198
  if (found && stages.slice(i + 1).some(readsFedNames)) hit = found;
9016
9199
  }
9017
9200
  return !hit;
@@ -9172,18 +9355,33 @@ function matchSensitiveGlob(glob, dotGlob) {
9172
9355
  function underEnteredDir(a, name) {
9173
9356
  const dir = a.cwd ?? "";
9174
9357
  if (!dir || /^(?:[/\\~$]|[A-Za-z]:)/.test(name)) return name;
9175
- const rest = name.replace(/^(?:\.\/)+/, "");
9176
- return `${dir.replace(/[/\\]+$/, "")}/${rest}`;
9358
+ return joinEntered(dir, name);
9359
+ }
9360
+ function joinEntered(dir, name) {
9361
+ const out = [];
9362
+ for (const seg of `${dir}/${name}`.split(/[/\\]+/)) {
9363
+ if (seg === ".") continue;
9364
+ const last = out[out.length - 1];
9365
+ if (seg === ".." && last !== void 0 && last !== "" && last !== ".." && !/^[~$]/.test(last)) {
9366
+ out.pop();
9367
+ continue;
9368
+ }
9369
+ out.push(seg);
9370
+ }
9371
+ return out.join("/");
9372
+ }
9373
+ function judgeEntered(path2, dotGlob = false) {
9374
+ return GLOB_META.test(path2) ? matchSensitiveGlob(path2, dotGlob) : matchSensitivePath(path2);
9177
9375
  }
9178
9376
  function structuralJailRead(command) {
9179
9377
  let accesses;
9180
9378
  const report = { exhausted: false };
9181
9379
  try {
9182
- accesses = collectShellFileAccesses(command, {}, report);
9380
+ accesses = collectShellFileAccesses(command, { credentialJail: true }, report);
9183
9381
  } catch {
9184
9382
  return null;
9185
9383
  }
9186
- const piped = findPipedToReader(command);
9384
+ const piped = findPipedToReader(command) ?? listedNamesRead(command);
9187
9385
  if (piped) return piped;
9188
9386
  const sourcedHit = sourcedAndPrinted(command);
9189
9387
  if (sourcedHit?.verdict === "block") return sourcedHit;
@@ -9192,12 +9390,12 @@ function structuralJailRead(command) {
9192
9390
  for (const a of accesses) {
9193
9391
  if (a.copy && !a.listing && (a.operation === "read" || a.operation === "remove")) {
9194
9392
  const entered = underEnteredDir(a, a.path);
9195
- if (entered !== a.path) relativeCopy ??= copyVerdictOf(matchSensitivePath(entered));
9393
+ const viaDir = !!a.cwd && entered === a.path && a.path.startsWith(`${a.cwd}/`);
9394
+ if (entered !== a.path || viaDir) relativeCopy ??= copyVerdictOf(judgeEntered(entered));
9196
9395
  continue;
9197
9396
  }
9198
9397
  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));
9398
+ const hit = judgeEntered(underEnteredDir(a, a.glob ?? a.path), !!a.dotGlob);
9201
9399
  if (hit?.verdict === "block") return hit;
9202
9400
  review ??= hit;
9203
9401
  }
@@ -9219,9 +9417,9 @@ function inlineCodeJailRead(command, changesDir = false) {
9219
9417
  if (code === null) continue;
9220
9418
  for (const p of inlineReadPaths(language, code, call.preload)) {
9221
9419
  const relative = !/^(?:[/\\~$]|[A-Za-z]:)/.test(p);
9222
- const spellings = relative ? [p, ...dirs().map((d) => `${d}/${p}`)] : [p];
9420
+ const spellings = relative ? [p, ...dirs().map((d) => joinEntered(d, p))] : [p];
9223
9421
  for (const spelling of spellings) {
9224
- const hit = matchSensitivePath(spelling);
9422
+ const hit = spelling === p ? matchSensitivePath(spelling) : judgeEntered(spelling);
9225
9423
  if (hit?.verdict === "block") return hit;
9226
9424
  review ??= hit;
9227
9425
  }
@@ -9242,12 +9440,19 @@ function enteredDirs(command, depth = 0, out = []) {
9242
9440
  let head = unwrapCommandHead(words);
9243
9441
  if (baseWord(words[head]) === "builtin") head++;
9244
9442
  const name = baseWord(words[head]);
9245
- if (name !== "cd" && name !== "pushd") {
9443
+ const envAt = words.findIndex((w, i) => i < head && baseWord(w) === "env");
9444
+ const envDir = envAt < 0 ? null : words.slice(envAt + 1, head).reduce((found, w, i, rest) => {
9445
+ if (found !== null || w === null) return found;
9446
+ if (w === "-C" || w === "--chdir") return rest[i + 1] ?? null;
9447
+ if (w.startsWith("--chdir=")) return w.slice(8);
9448
+ return /^-C./.test(w) ? w.slice(2) : null;
9449
+ }, null);
9450
+ if (name !== "cd" && name !== "pushd" && envDir === null) {
9246
9451
  const payload = literalShellPayload(words, baseWord(words[0]));
9247
9452
  if (payload !== null) enteredDirs(payload, depth + 1, out);
9248
9453
  return true;
9249
9454
  }
9250
- const target = words.slice(head + 1).find((w) => w === null || !w.startsWith("-"));
9455
+ const target = envDir ?? words.slice(head + 1).find((w) => w === null || !w.startsWith("-"));
9251
9456
  if (!target) return true;
9252
9457
  const dir = target.replace(/[/\\]+$/, "");
9253
9458
  const rooted = /^(?:[/\\~]|[A-Za-z]:)/.test(dir);
@@ -19399,7 +19604,7 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
19399
19604
  const pipeVerdict = pipeChainVerdict(bashCommand, isTrustedHost, cv("data.pipe-chain"));
19400
19605
  if (pipeVerdict?.logged) noteLogged(pipeVerdict);
19401
19606
  else if (pipeVerdict) return pipeVerdict;
19402
- const fsVerdict = analyzeFsOperation(bashCommand);
19607
+ const fsVerdict = analyzeFsOperation(bashCommand, cwd);
19403
19608
  if (fsVerdict) {
19404
19609
  const isShieldRule = fsVerdict.ruleName.startsWith("shield:");
19405
19610
  const labelPrefix = isShieldRule ? "project-jail (AST)" : "Node9 (AST)";
@@ -21514,8 +21719,8 @@ function matchCanaryArgs(args, values) {
21514
21719
 
21515
21720
  // src/scan/canonical.ts
21516
21721
  var LONG_OUTPUT_THRESHOLD_BYTES = 100 * 1024;
21517
- var CANONICAL_EXTRACTOR_VERSION = "canonical-v41";
21518
- var CANONICAL_EXTRACTOR_HASH = "dbde5e7f06f3738a";
21722
+ var CANONICAL_EXTRACTOR_VERSION = "canonical-v43";
21723
+ var CANONICAL_EXTRACTOR_HASH = "a60fbf5de2ecbdeb";
21519
21724
  var DEDUPE_PREVIEW_LEN = 120;
21520
21725
  function extractCanonicalFindings(call, ctx) {
21521
21726
  const out = [];
@@ -21662,7 +21867,7 @@ function extractCanonicalFindings(call, ctx) {
21662
21867
  if (!isShell || command === null) {
21663
21868
  return out;
21664
21869
  }
21665
- const fsVerdict = analyzeFsOperation(command);
21870
+ const fsVerdict = analyzeFsOperation(command, ctx.cwd);
21666
21871
  if (fsVerdict) {
21667
21872
  const isShield = fsVerdict.ruleName.startsWith("shield:");
21668
21873
  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.1",
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",