@node9/policy-engine 2.32.0 → 2.33.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.js CHANGED
@@ -111,6 +111,7 @@ __export(src_exports, {
111
111
  detectDangerousShellExec: () => detectDangerousShellExec,
112
112
  detectInlineExec: () => detectInlineExec,
113
113
  detectPii: () => detectPii,
114
+ entryDisplay: () => entryDisplay,
114
115
  evaluateEgress: () => evaluateEgress,
115
116
  evaluateLoopWindow: () => evaluateLoopWindow,
116
117
  evaluatePolicy: () => evaluatePolicy,
@@ -134,18 +135,23 @@ __export(src_exports, {
134
135
  getCompiledRegex: () => getCompiledRegex,
135
136
  getNestedValue: () => getNestedValue,
136
137
  gitRepoPath: () => gitRepoPath,
138
+ hashDestination: () => hashDestination,
137
139
  hostMatches: () => hostMatches,
138
140
  incompleteFileVerdict: () => incompleteFileVerdict,
139
141
  inspectArgumentSecrets: () => inspectArgumentSecrets,
142
+ inspectionEntry: () => inspectionEntry,
143
+ inspectionLayers: () => inspectionLayers,
140
144
  isAgentInstructionPath: () => isAgentInstructionPath,
141
145
  isBashTool: () => isBashTool,
142
146
  isDestructiveToolName: () => isDestructiveToolName,
147
+ isHashedEntry: () => isHashedEntry,
143
148
  isIgnoredTool: () => isIgnoredTool,
144
149
  isInside: () => isInside,
145
150
  isKnobGoverned: () => isKnobGoverned,
146
151
  isLegacySystemPath: () => isLegacySystemPath,
147
152
  isLockedCheck: () => isLockedCheck,
148
153
  isLoopbackHost: () => isLoopbackHost,
154
+ isMaskedKind: () => isMaskedKind,
149
155
  isPasswordHashPath: () => isPasswordHashPath,
150
156
  isPrivateHost: () => isPrivateHost,
151
157
  isProtectedHomePath: () => isProtectedHomePath,
@@ -153,16 +159,24 @@ __export(src_exports, {
153
159
  isShieldVerdict: () => isShieldVerdict,
154
160
  isStrictGatedTier: () => isStrictGatedTier,
155
161
  isVerdict: () => isVerdict,
162
+ maskDestination: () => maskDestination,
163
+ maskPersonalData: () => maskPersonalData,
164
+ maskPersonalValue: () => maskPersonalValue,
156
165
  matchCanary: () => matchCanary,
157
166
  matchCanaryArgs: () => matchCanaryArgs,
158
167
  matchSensitivePath: () => matchSensitivePath2,
159
168
  matchesPattern: () => matchesPattern,
169
+ matchesTrustedEntry: () => matchesTrustedEntry,
170
+ matchesTrustedList: () => matchesTrustedList,
160
171
  narrativeRuleLabel: () => narrativeRuleLabel,
161
172
  normalizeCommandForPolicy: () => normalizeCommandForPolicy,
173
+ normalizeDestination: () => normalizeDestination,
162
174
  normalizeFilePath: () => normalizeFilePath,
163
175
  normalizeForScan: () => normalizeForScan,
164
176
  normalizeIpLiteral: () => normalizeIpLiteral,
165
177
  normalizePyPiName: () => normalizePyPiName,
178
+ normalizeRecipient: () => normalizeRecipient,
179
+ normalizeTrustedEntry: () => normalizeTrustedEntry,
166
180
  parseAllSshHostsFromCommand: () => parseAllSshHostsFromCommand,
167
181
  parseDestHost: () => parseDestHost,
168
182
  patternShapeOf: () => patternShapeOf,
@@ -196,6 +210,7 @@ __export(src_exports, {
196
210
  toScanFinding: () => toScanFinding,
197
211
  toolMatchesRule: () => toolMatchesRule,
198
212
  truncateBlastPath: () => truncateBlastPath,
213
+ trustedEntryOf: () => trustedEntryOf,
199
214
  tuningFromLegacyPolicy: () => tuningFromLegacyPolicy,
200
215
  tuningToLegacyPolicy: () => tuningToLegacyPolicy,
201
216
  unwrapCommandHead: () => unwrapCommandHead,
@@ -4727,36 +4742,129 @@ var BASH_TOOL_NAMES = /* @__PURE__ */ new Set([
4727
4742
  "shell",
4728
4743
  "exec_command"
4729
4744
  ]);
4730
- var MCP_EXECUTORS = /* @__PURE__ */ new Set([...BASH_TOOL_NAMES, "exec", "run_command", "terminal"]);
4745
+ var MCP_EXECUTORS = /* @__PURE__ */ new Set([
4746
+ ...BASH_TOOL_NAMES,
4747
+ "exec",
4748
+ "run_command",
4749
+ "terminal",
4750
+ "execute_command",
4751
+ "execute_shell",
4752
+ "execute_shell_command",
4753
+ "shell_execute",
4754
+ "run_shell",
4755
+ "run_terminal_command",
4756
+ "start_process"
4757
+ ]);
4758
+ var BUILTIN_FIELDS = ["command", "cmd", "script"];
4759
+ var ARGV_FIELDS = ["args", "argv"];
4760
+ var BARE_WORD = /^[A-Za-z0-9_./+:@%,-]+$/;
4761
+ var MAX_ARGV_CHARACTERS = 262144;
4731
4762
  function isBashTool(tool) {
4732
4763
  return BASH_TOOL_NAMES.has(tool.toLowerCase());
4733
4764
  }
4734
- function inspectionEntry(tool, inspection = {}) {
4765
+ function inspectionLayers(policy) {
4766
+ return { trusted: policy.toolInspection, project: policy.projectToolInspection };
4767
+ }
4768
+ function isShellEntry(value) {
4769
+ return typeof value === "object" && value !== null && value.kind === "shell" && typeof value.field === "string" && Object.keys(value).length === 2;
4770
+ }
4771
+ function isInspectionLayers(input) {
4772
+ const trusted = input.trusted;
4773
+ return typeof trusted === "object" && trusted !== null && !isShellEntry(trusted);
4774
+ }
4775
+ function layersOf(input) {
4776
+ return isInspectionLayers(input) ? { trusted: input.trusted, project: input.project ?? {} } : { trusted: input, project: {} };
4777
+ }
4778
+ function entryOf(tool, inspection) {
4735
4779
  const pattern = Object.keys(inspection).find((p) => matchesPattern(tool, p));
4736
4780
  return pattern === void 0 ? void 0 : inspection[pattern];
4737
4781
  }
4782
+ function inspectionEntry(tool, inspection = {}) {
4783
+ const { trusted, project } = layersOf(inspection);
4784
+ return entryOf(tool, trusted) ?? entryOf(tool, project);
4785
+ }
4786
+ function executorName(tool) {
4787
+ const name = tool.toLowerCase();
4788
+ if (!name.startsWith("mcp__")) return name;
4789
+ const at = name.lastIndexOf("__");
4790
+ return at >= "mcp__".length ? name.slice(at + 2) : name;
4791
+ }
4792
+ function entryFields(entry) {
4793
+ if (typeof entry === "object") return [entry.field];
4794
+ return entry === "command" ? ["command"] : null;
4795
+ }
4738
4796
  function shellFields(tool, inspection) {
4739
4797
  if (isBashTool(tool)) return ["command"];
4740
- const entry = inspectionEntry(tool, inspection);
4741
- if (typeof entry === "object") return [entry.field];
4742
- if (entry !== void 0) return entry === "command" ? [entry] : null;
4743
- const name = tool.toLowerCase().replace(/^mcp__[a-z0-9_-]+?__/, "");
4744
- return MCP_EXECUTORS.has(name) ? ["command", "cmd", "script"] : null;
4798
+ const { trusted, project } = layersOf(inspection);
4799
+ const trustedEntry = entryOf(tool, trusted);
4800
+ if (trustedEntry !== void 0) return entryFields(trustedEntry);
4801
+ const builtin = MCP_EXECUTORS.has(executorName(tool)) ? BUILTIN_FIELDS : null;
4802
+ const projectEntry = entryOf(tool, project);
4803
+ if (projectEntry === void 0) return builtin;
4804
+ const added = entryFields(projectEntry);
4805
+ if (!builtin) return added;
4806
+ if (!added) return builtin;
4807
+ return [.../* @__PURE__ */ new Set([...builtin, ...added])];
4745
4808
  }
4746
4809
  function isShellShapedTool(tool, inspection = {}) {
4747
4810
  return shellFields(tool, inspection) !== null;
4748
4811
  }
4812
+ function shellWord(word) {
4813
+ if (BARE_WORD.test(word)) return word;
4814
+ return word === "" ? "''" : `'${word.replace(/'/g, `'\\''`)}'`;
4815
+ }
4816
+ function isStringArray(value) {
4817
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
4818
+ }
4819
+ function commandLine(args, fieldPath, value, native) {
4820
+ const missing = { reason: "Shell command field is missing or is not a string" };
4821
+ const unreadable = { reason: "Shell command arguments could not be read" };
4822
+ if (typeof value !== "string" && (native || !Array.isArray(value))) return missing;
4823
+ const dot = fieldPath.lastIndexOf(".");
4824
+ const parent = dot === -1 ? args : getNestedValue(args, fieldPath.slice(0, dot));
4825
+ const siblings = ARGV_FIELDS.map((key) => ({
4826
+ key,
4827
+ value: parent && typeof parent === "object" ? parent[key] : void 0
4828
+ })).filter(({ value: value2 }) => value2 !== void 0 && value2 !== null);
4829
+ let argv = siblings[0];
4830
+ if (native) argv = siblings.find(({ value: v }) => isStringArray(v));
4831
+ else if (siblings.length === 2 && JSON.stringify(siblings[0].value) !== JSON.stringify(siblings[1].value))
4832
+ return { reason: "Shell command arguments disagree" };
4833
+ let command;
4834
+ let source = fieldPath;
4835
+ if (Array.isArray(value)) {
4836
+ if (argv || !value.length || !isStringArray(value)) return unreadable;
4837
+ command = value.map(shellWord).join(" ");
4838
+ } else if (!argv) {
4839
+ return { command: value, fieldPath };
4840
+ } else {
4841
+ if (!isStringArray(argv.value)) return unreadable;
4842
+ if (!argv.value.length) return { command: value, fieldPath };
4843
+ command = `${value} ${argv.value.map(shellWord).join(" ")}`;
4844
+ source = `${fieldPath}+${argv.key}`;
4845
+ }
4846
+ if (command.length > MAX_ARGV_CHARACTERS)
4847
+ return { reason: "Shell command arguments exceed the inspectable size" };
4848
+ return { command, fieldPath: source };
4849
+ }
4749
4850
  function resolveShellInput(tool, args, inspection = {}) {
4750
4851
  const fields = shellFields(tool, inspection);
4751
4852
  if (!fields) return { kind: "not-shell" };
4752
4853
  const values = fields.map((fieldPath) => ({ fieldPath, value: getNestedValue(args, fieldPath) })).filter(({ value }) => value !== void 0 && value !== null && value !== "");
4753
- if (!values.length || values.some(({ value }) => typeof value !== "string")) {
4854
+ if (!values.length) {
4754
4855
  return { kind: "uninspectable", reason: "Shell command field is missing or is not a string" };
4755
4856
  }
4756
- if (new Set(values.map(({ value }) => value)).size !== 1) {
4857
+ const native = isBashTool(tool);
4858
+ const lines = values.map(({ fieldPath, value }) => commandLine(args, fieldPath, value, native));
4859
+ const failed = lines.find((line) => "reason" in line);
4860
+ if (failed) return { kind: "uninspectable", reason: failed.reason };
4861
+ const commands = lines.filter(
4862
+ (line) => "command" in line
4863
+ );
4864
+ if (new Set(commands.map(({ command }) => command)).size !== 1) {
4757
4865
  return { kind: "uninspectable", reason: "Multiple shell command fields disagree" };
4758
4866
  }
4759
- return { kind: "shell", command: values[0].value, fieldPath: values[0].fieldPath };
4867
+ return { kind: "shell", ...commands[0] };
4760
4868
  }
4761
4869
  function shellRuleArgs(tool, args, ruleTool, inspection = {}) {
4762
4870
  if (!ruleTool || !matchesPattern("bash", ruleTool) || matchesPattern(tool, ruleTool)) return args;
@@ -7641,20 +7749,26 @@ var BIP39_PUBLIC_VECTORS = /* @__PURE__ */ new Set([
7641
7749
  var indices = new Map(BIP39_ENGLISH.map((word, i) => [word, i]));
7642
7750
  var lengths = [24, 21, 18, 15, 12];
7643
7751
  var hash = (value) => (0, import_node_crypto.createHash)("sha256").update(value).digest();
7644
- function findMnemonic(text, budget = { candidates: 0, reasons: /* @__PURE__ */ new Set() }) {
7645
- const words = [...text.matchAll(/[a-zA-Z]+/g)];
7752
+ var MAX_MNEMONIC_HASHES = 25e3;
7753
+ function findMnemonic(text, budget = { hashes: 0, reasons: /* @__PURE__ */ new Set() }) {
7646
7754
  let run = [];
7755
+ let runIndex = [];
7647
7756
  let previousEnd = 0;
7648
7757
  const rejected = /* @__PURE__ */ new Set();
7649
7758
  const inspect = () => {
7759
+ if (run.length < 12) return false;
7760
+ const ascending = new Array(run.length).fill(0);
7761
+ for (let i = 1; i < run.length; i++)
7762
+ ascending[i] = ascending[i - 1] + (runIndex[i] > runIndex[i - 1] ? 1 : 0);
7650
7763
  for (let start = 0; start + 12 <= run.length; start++) {
7651
7764
  for (const count of lengths) {
7652
7765
  if (start + count > run.length) continue;
7766
+ if (ascending[start + count - 1] - ascending[start] === count - 1) continue;
7653
7767
  const candidate = run.slice(start, start + count);
7654
7768
  const sentence = candidate.join(" ");
7655
7769
  if (rejected.has(sentence)) continue;
7656
- if (++budget.candidates > 1024) {
7657
- budget.reasons.add("mnemonic-candidates");
7770
+ if (++budget.hashes > MAX_MNEMONIC_HASHES) {
7771
+ budget.reasons.add("mnemonic-budget");
7658
7772
  return false;
7659
7773
  }
7660
7774
  if (BIP39_PUBLIC_VECTORS.has(hash(sentence).toString("hex"))) {
@@ -7672,13 +7786,18 @@ function findMnemonic(text, budget = { candidates: 0, reasons: /* @__PURE__ */ n
7672
7786
  }
7673
7787
  return false;
7674
7788
  };
7675
- for (const word of words) {
7676
- if (!indices.has(word[0]) || run.length && !/^\s+$/.test(text.slice(previousEnd, word.index))) {
7789
+ for (const word of text.matchAll(/[a-zA-Z]+/g)) {
7790
+ const index = indices.get(word[0]);
7791
+ if (index === void 0 || run.length && !/^\s+$/.test(text.slice(previousEnd, word.index))) {
7677
7792
  if (inspect()) return true;
7678
- if (budget.reasons.has("mnemonic-candidates")) return false;
7793
+ if (budget.reasons.has("mnemonic-budget")) return false;
7679
7794
  run = [];
7795
+ runIndex = [];
7796
+ }
7797
+ if (index !== void 0) {
7798
+ run.push(word[0]);
7799
+ runIndex.push(index);
7680
7800
  }
7681
- if (indices.has(word[0])) run.push(word[0]);
7682
7801
  previousEnd = word.index + word[0].length;
7683
7802
  }
7684
7803
  return inspect();
@@ -7921,6 +8040,10 @@ function validateCask(raw) {
7921
8040
 
7922
8041
  // src/dlp/normalize.ts
7923
8042
  var INVISIBLE_RE = /[­͏؜᠎​-‏‪-‮⁠-⁤-︀-️]|[\u{E0000}-\u{E007F}]/gu;
8043
+ function isInvisibleChar(char) {
8044
+ return INVISIBLE_ONE.test(char);
8045
+ }
8046
+ var INVISIBLE_ONE = new RegExp(`^(?:${INVISIBLE_RE.source.split("|")[0]})$`, "u");
7924
8047
  function stripInvisible(text) {
7925
8048
  return text.replace(INVISIBLE_RE, "");
7926
8049
  }
@@ -8096,7 +8219,7 @@ function scanInjection(text, ctx = {}) {
8096
8219
  }
8097
8220
  }
8098
8221
  if (matched.length === 0) return null;
8099
- const untrusted = !!ctx.tool && UNTRUSTED_TOOLS.test(ctx.tool);
8222
+ const untrusted = ctx.untrusted ?? (!!ctx.tool && UNTRUSTED_TOOLS.test(ctx.tool));
8100
8223
  const score = matched.length + (untrusted ? 1 : 0);
8101
8224
  const confidence = score >= 3 ? "high" : score === 2 ? "medium" : "low";
8102
8225
  return { signals: untrusted ? [...matched, "untrusted-origin"] : matched, confidence };
@@ -8884,6 +9007,46 @@ function matchArgumentText(text, fieldPath, budget) {
8884
9007
  }
8885
9008
  return best;
8886
9009
  }
9010
+ var BATCH_SEPARATOR = "\n";
9011
+ function matchArgumentBatch(fragments, fieldPath, budget) {
9012
+ if (!fragments.length) return null;
9013
+ const text = fragments.join(BATCH_SEPARATOR);
9014
+ const lower2 = text.toLowerCase();
9015
+ let best = null;
9016
+ for (const pattern of DLP_PATTERNS) {
9017
+ if (pattern.keywords && !pattern.keywords.some((kw) => lower2.includes(kw.toLowerCase())))
9018
+ continue;
9019
+ const flags = pattern.regex.flags.replace(/[gmy]/g, "");
9020
+ if (!new RegExp(pattern.regex.source, flags + "m").test(text)) continue;
9021
+ for (const fragment of fragments) {
9022
+ if (firstAcceptedMatch(pattern, fragment) === null) continue;
9023
+ const severity = pattern.contextBoost && isAssignmentContext(fragment) ? "block" : pattern.severity;
9024
+ if (severity === "block")
9025
+ return {
9026
+ patternName: pattern.name,
9027
+ fieldPath,
9028
+ redactedSample: "[encoded secret]",
9029
+ severity
9030
+ };
9031
+ best ??= {
9032
+ patternName: pattern.name,
9033
+ fieldPath,
9034
+ redactedSample: "[encoded secret]",
9035
+ severity
9036
+ };
9037
+ if (!pattern.contextBoost) break;
9038
+ }
9039
+ }
9040
+ if (findMnemonic(text, budget)) {
9041
+ return {
9042
+ patternName: "BIP-39 Recovery Phrase",
9043
+ fieldPath,
9044
+ redactedSample: "[recovery phrase]",
9045
+ severity: "block"
9046
+ };
9047
+ }
9048
+ return best;
9049
+ }
8887
9050
  function scanArgs(args, depth = 0, fieldPath = "args") {
8888
9051
  if (depth > MAX_DEPTH2 || args === null || args === void 0) return null;
8889
9052
  if (Array.isArray(args)) {
@@ -10342,12 +10505,23 @@ function ssrfDestinationFloor(toolName, args, opts = {}) {
10342
10505
 
10343
10506
  // src/dlp/secret-views.ts
10344
10507
  var SECRET_VIEW_LIMITS = {
10508
+ /** A decoded text that itself decodes is followed this many layers; a deeper layer is reviewed. */
10345
10509
  maxDepth: 4,
10346
- maxViewsPerLeaf: 64,
10347
- maxViews: 256,
10348
- maxDerivedBytes: 1048576,
10349
- maxCandidates: 4096
10510
+ /** Nested views per parent view, and nested text per call; past either the call is reviewed. */
10511
+ maxNestedViewsPerLeaf: 64,
10512
+ maxNestedBytes: 1048576,
10513
+ /** Joined hostname-label text per call; past it the call is reviewed. */
10514
+ maxJoinedLabelBytes: 1048576,
10515
+ /** Decoded fragments are matched in batches of about this many characters. */
10516
+ batchCharacters: 65536,
10517
+ /** Only a valid DNS name has its labels joined. */
10518
+ maxHostLength: 253,
10519
+ maxLabelLength: 63,
10520
+ maxLabels: 127
10350
10521
  };
10522
+ function newSecretViewBudget() {
10523
+ return { hashes: 0, nestedBytes: 0, joinedLabelBytes: 0, reasons: /* @__PURE__ */ new Set() };
10524
+ }
10351
10525
  function textBytes(buf) {
10352
10526
  if (buf.length < 16) return null;
10353
10527
  const text = buf.toString("utf8");
@@ -10366,13 +10540,41 @@ function percentOnce(text) {
10366
10540
  }
10367
10541
  });
10368
10542
  }
10543
+ function* wrappedBase64(text) {
10544
+ if (!text.includes("\n")) return;
10545
+ const word = /^[A-Za-z0-9+/_-]+={0,2}$/;
10546
+ let run = [];
10547
+ let width = 0;
10548
+ const flush = function* () {
10549
+ if (run.length >= 2) yield run.join("");
10550
+ run = [];
10551
+ width = 0;
10552
+ };
10553
+ for (const raw of text.split("\n")) {
10554
+ const line = raw.trim();
10555
+ const full = line.length >= 16 && word.test(line) && !line.includes("=");
10556
+ if (full && (!run.length || line.length === width)) {
10557
+ run.push(line);
10558
+ width = line.length;
10559
+ continue;
10560
+ }
10561
+ if (run.length && word.test(line) && line.length >= 2 && line.length <= width) {
10562
+ run.push(line);
10563
+ yield* flush();
10564
+ continue;
10565
+ }
10566
+ yield* flush();
10567
+ if (full) {
10568
+ run.push(line);
10569
+ width = line.length;
10570
+ }
10571
+ }
10572
+ yield* flush();
10573
+ }
10369
10574
  function* encodedRegions(text, budget) {
10370
10575
  yield [text, false];
10576
+ for (const block of wrappedBase64(text)) yield [block, false];
10371
10577
  for (const match of text.matchAll(/(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,30}:\/\/[^\s<>"']+/gi)) {
10372
- if (++budget.candidates > SECRET_VIEW_LIMITS.maxCandidates) {
10373
- budget.reasons.add("decode-candidates");
10374
- return;
10375
- }
10376
10578
  try {
10377
10579
  new URL(match[0]);
10378
10580
  } catch {
@@ -10392,6 +10594,8 @@ function* encodedRegions(text, budget) {
10392
10594
  ];
10393
10595
  for (const region of regions) if (region) yield [region, false];
10394
10596
  const labels = host2.split(".");
10597
+ if (host2.length > SECRET_VIEW_LIMITS.maxHostLength || labels.length > SECRET_VIEW_LIMITS.maxLabels || !labels.every((l) => l.length >= 1 && l.length <= SECRET_VIEW_LIMITS.maxLabelLength))
10598
+ continue;
10395
10599
  for (let start = 0; start < labels.length; start++) {
10396
10600
  let joined = labels[start];
10397
10601
  for (let end = start + 1; end < Math.min(labels.length, start + 8); end++) {
@@ -10399,11 +10603,13 @@ function* encodedRegions(text, budget) {
10399
10603
  if (!run.every((s) => /^[a-f0-9]{2,}$/i.test(s)) && !run.every((s) => /^[A-Z2-7]{4,}$/i.test(s)))
10400
10604
  break;
10401
10605
  joined += labels[end];
10402
- if (++budget.candidates > SECRET_VIEW_LIMITS.maxCandidates) {
10403
- budget.reasons.add("decode-candidates");
10606
+ if (joined.length < 16) continue;
10607
+ budget.joinedLabelBytes += joined.length;
10608
+ if (budget.joinedLabelBytes > SECRET_VIEW_LIMITS.maxJoinedLabelBytes) {
10609
+ budget.reasons.add("decode-labels");
10404
10610
  return;
10405
10611
  }
10406
- if (joined.length >= 16 && joined.length <= 253) yield [joined, true];
10612
+ yield [joined, true];
10407
10613
  }
10408
10614
  }
10409
10615
  }
@@ -10440,10 +10646,6 @@ function* decodedCandidates(text, budget) {
10440
10646
  if (joined) yield ["dns-labels", region];
10441
10647
  for (const [kind, re] of families) {
10442
10648
  for (const match of region.matchAll(re)) {
10443
- if (++budget.candidates > SECRET_VIEW_LIMITS.maxCandidates) {
10444
- budget.reasons.add("decode-candidates");
10445
- return;
10446
- }
10447
10649
  const raw = match[0];
10448
10650
  let buf;
10449
10651
  if (kind === "base64") {
@@ -10466,37 +10668,47 @@ function* decodedCandidates(text, budget) {
10466
10668
  }
10467
10669
  }
10468
10670
  }
10469
- function* secretViews(text, budget) {
10671
+ function secretViews(text, budget) {
10470
10672
  const seen = /* @__PURE__ */ new Set([text]);
10471
- const queue = [{ text, transforms: [] }];
10472
- for (let i = 0; i < queue.length; i++) {
10473
- const view = queue[i];
10474
- yield view;
10475
- for (const [kind, decoded] of decodedCandidates(view.text, budget)) {
10476
- if (seen.has(decoded)) continue;
10477
- if (view.transforms.length >= SECRET_VIEW_LIMITS.maxDepth) {
10478
- budget.reasons.add("decode-depth");
10479
- continue;
10480
- }
10481
- const bytes = Buffer.byteLength(decoded);
10482
- if (queue.length >= SECRET_VIEW_LIMITS.maxViewsPerLeaf || budget.views >= SECRET_VIEW_LIMITS.maxViews || budget.bytes + bytes > SECRET_VIEW_LIMITS.maxDerivedBytes) {
10483
- budget.reasons.add("decode-budget");
10484
- return;
10673
+ const out = [];
10674
+ let frontier = [{ text, transforms: [] }];
10675
+ for (let depth = 1; depth <= SECRET_VIEW_LIMITS.maxDepth; depth++) {
10676
+ const next = [];
10677
+ for (const parent of frontier) {
10678
+ let perLeaf = 0;
10679
+ for (const [kind, decoded] of decodedCandidates(parent.text, budget)) {
10680
+ if (seen.has(decoded)) continue;
10681
+ seen.add(decoded);
10682
+ const normalizing = kind === "invisibles" || kind === "percent";
10683
+ if (depth >= 2 && !normalizing) {
10684
+ budget.nestedBytes += Buffer.byteLength(decoded);
10685
+ if (++perLeaf > SECRET_VIEW_LIMITS.maxNestedViewsPerLeaf || budget.nestedBytes > SECRET_VIEW_LIMITS.maxNestedBytes) {
10686
+ budget.reasons.add("decode-nested");
10687
+ return out;
10688
+ }
10689
+ }
10690
+ const view = { text: decoded, transforms: [...parent.transforms, kind] };
10691
+ out.push(view);
10692
+ next.push(view);
10485
10693
  }
10486
- seen.add(decoded);
10487
- budget.views++;
10488
- budget.bytes += bytes;
10489
- queue.push({ text: decoded, transforms: [...view.transforms, kind] });
10490
10694
  }
10491
- if (budget.candidates > SECRET_VIEW_LIMITS.maxCandidates) return;
10695
+ frontier = next;
10696
+ if (!frontier.length) return out;
10492
10697
  }
10698
+ for (const view of frontier) {
10699
+ if (!decodedCandidates(view.text, budget).next().done) {
10700
+ budget.reasons.add("decode-nested");
10701
+ break;
10702
+ }
10703
+ }
10704
+ return out;
10493
10705
  }
10494
10706
 
10495
10707
  // src/dlp/arguments.ts
10496
10708
  var ARGUMENT_SCAN_LIMITS = {
10497
10709
  maxDepth: 12,
10498
10710
  maxNodes: 16384,
10499
- /** Raw text is matched in windows of this size; decoding views use the first window. */
10711
+ /** Text is matched and decoded in windows of this size. */
10500
10712
  maxStringCharacters: 1e5,
10501
10713
  /** Windows overlap by this much so a token on a window edge is still seen whole. */
10502
10714
  windowOverlap: 4096,
@@ -10506,17 +10718,46 @@ var ARGUMENT_SCAN_LIMITS = {
10506
10718
  maxTailBytes: 4194304,
10507
10719
  maxJsonCharacters: 1e4
10508
10720
  };
10721
+ var RUN_CHAR = /[A-Za-z0-9+/=_%\\.-]/;
10722
+ var runChar = (value, index) => {
10723
+ const char = value[index] ?? "";
10724
+ return RUN_CHAR.test(char) || char !== "" && isInvisibleChar(char);
10725
+ };
10726
+ function batches(views) {
10727
+ const out = [];
10728
+ let current = [];
10729
+ let size = 0;
10730
+ for (const { text } of views) {
10731
+ if (current.length && size + text.length > SECRET_VIEW_LIMITS.batchCharacters) {
10732
+ out.push(current);
10733
+ current = [];
10734
+ size = 0;
10735
+ }
10736
+ current.push(text);
10737
+ size += text.length;
10738
+ }
10739
+ if (current.length) out.push(current);
10740
+ return out;
10741
+ }
10509
10742
  function inspectArgumentSecrets(args) {
10510
- const budget = { views: 0, bytes: 0, candidates: 0, reasons: /* @__PURE__ */ new Set() };
10743
+ const budget = newSecretViewBudget();
10511
10744
  const ancestors = /* @__PURE__ */ new Set();
10512
10745
  let nodes = 0;
10513
10746
  let sourceBytes = 0;
10514
10747
  let tailBytes = 0;
10515
10748
  let best = null;
10749
+ const blocked = () => best?.severity === "block";
10516
10750
  const accept = (match) => {
10517
10751
  if (match && (!best || best.severity !== "block" && match.severity === "block")) best = match;
10518
10752
  };
10753
+ const decodeSegment = (segment, fieldPath) => {
10754
+ for (const batch of batches(secretViews(segment, budget))) {
10755
+ accept(matchArgumentBatch(batch, fieldPath, budget));
10756
+ if (blocked()) return;
10757
+ }
10758
+ };
10519
10759
  const visit = (value, depth, fieldPath) => {
10760
+ if (blocked()) return;
10520
10761
  if (++nodes > ARGUMENT_SCAN_LIMITS.maxNodes) {
10521
10762
  budget.reasons.add("argument-nodes");
10522
10763
  return;
@@ -10558,14 +10799,11 @@ function inspectArgumentSecrets(args) {
10558
10799
  }
10559
10800
  sourceBytes += Math.min(bytes, Math.max(0, remaining));
10560
10801
  if (!text) return;
10561
- for (const view of secretViews(text, budget)) {
10562
- const hit = matchArgumentText(view.text, fieldPath, budget);
10563
- if (hit)
10564
- accept(view.transforms.length ? { ...hit, redactedSample: "[encoded secret]" } : hit);
10565
- }
10802
+ accept(matchArgumentText(text, fieldPath, budget));
10803
+ let scannedEnd = text.length;
10566
10804
  if (!truncated && value.length > window) {
10567
- budget.reasons.add("decode-window");
10568
10805
  for (let start = window - overlap; start < value.length; start += window - overlap) {
10806
+ if (blocked()) return;
10569
10807
  const chunk = value.slice(start, start + window);
10570
10808
  const chunkBytes = Buffer.byteLength(chunk);
10571
10809
  if (tailBytes + chunkBytes > ARGUMENT_SCAN_LIMITS.maxTailBytes) {
@@ -10574,9 +10812,16 @@ function inspectArgumentSecrets(args) {
10574
10812
  }
10575
10813
  tailBytes += chunkBytes;
10576
10814
  accept(matchArgumentText(chunk, fieldPath, budget));
10815
+ scannedEnd = start + chunk.length;
10577
10816
  if (start + window >= value.length) break;
10578
10817
  }
10579
10818
  }
10819
+ for (let start = 0; start < scannedEnd && !blocked(); ) {
10820
+ let end = Math.min(start + window, scannedEnd);
10821
+ while (end < scannedEnd && runChar(value, end - 1) && runChar(value, end)) end++;
10822
+ decodeSegment(value.slice(start, end), fieldPath);
10823
+ start = end;
10824
+ }
10580
10825
  const trimmed = text.trim();
10581
10826
  if (value.length < ARGUMENT_SCAN_LIMITS.maxJsonCharacters && (trimmed.startsWith("{") || trimmed.startsWith("["))) {
10582
10827
  try {
@@ -10595,7 +10840,7 @@ function inspectArgumentSecrets(args) {
10595
10840
  function scanArgumentSecrets(args) {
10596
10841
  const result = inspectArgumentSecrets(args);
10597
10842
  if (result.match) return result.match;
10598
- return result.reasons.some((reason) => reason.startsWith("argument-")) ? {
10843
+ return result.coverage === "incomplete" ? {
10599
10844
  patternName: "Argument inspection incomplete",
10600
10845
  fieldPath: "args",
10601
10846
  redactedSample: "[uninspected content]",
@@ -10630,18 +10875,13 @@ function tokenize2(toolName) {
10630
10875
  return toolName.toLowerCase().split(/[_.\-\s]+/).filter(Boolean);
10631
10876
  }
10632
10877
  function extractShellCommand(toolName, args, toolInspection) {
10633
- const patterns = Object.keys(toolInspection);
10634
- const matchingPattern = patterns.find((p) => matchesPattern(toolName, p));
10635
- if (!matchingPattern) return null;
10636
- const fieldPath = toolInspection[matchingPattern];
10878
+ const fieldPath = inspectionEntry(toolName, toolInspection);
10879
+ if (fieldPath === void 0) return null;
10637
10880
  const value = getNestedValue(args, typeof fieldPath === "string" ? fieldPath : fieldPath.field);
10638
10881
  return typeof value === "string" ? value : null;
10639
10882
  }
10640
10883
  function isSqlTool(toolName, toolInspection) {
10641
- const patterns = Object.keys(toolInspection);
10642
- const matchingPattern = patterns.find((p) => matchesPattern(toolName, p));
10643
- if (!matchingPattern) return false;
10644
- const fieldName = toolInspection[matchingPattern];
10884
+ const fieldName = inspectionEntry(toolName, toolInspection);
10645
10885
  return fieldName === "sql" || fieldName === "query";
10646
10886
  }
10647
10887
  var SQL_DML_KEYWORDS = /* @__PURE__ */ new Set(["select", "insert", "update", "delete", "merge", "upsert"]);
@@ -10718,9 +10958,10 @@ function egressPolicyVerdict(eg) {
10718
10958
  }
10719
10959
  async function evaluatePolicy(config, toolName, args, context = {}, hooks = {}) {
10720
10960
  let protectedVerdict = null;
10961
+ const layers = inspectionLayers(config.policy);
10721
10962
  if (context.agent !== "Terminal") {
10722
10963
  try {
10723
- const accesses = context.accesses ?? collectFileAccesses(toolName, args, context, config.policy.toolInspection);
10964
+ const accesses = context.accesses ?? collectFileAccesses(toolName, args, context, layers);
10724
10965
  protectedVerdict = evaluateProtectedFileAccess(accesses, context, catalogSettings(config));
10725
10966
  } catch {
10726
10967
  protectedVerdict = incompleteFileVerdict();
@@ -10755,7 +10996,7 @@ async function evaluatePolicy(config, toolName, args, context = {}, hooks = {})
10755
10996
  hooks
10756
10997
  );
10757
10998
  if (result.decision === "block") return result;
10758
- if (context.agent !== "Terminal" && resolveShellInput(toolName, args, config.policy.toolInspection).kind === "uninspectable") {
10999
+ if (context.agent !== "Terminal" && resolveShellInput(toolName, args, layers).kind === "uninspectable") {
10759
11000
  return {
10760
11001
  decision: "review",
10761
11002
  ruleName: "shell-inspection-incomplete",
@@ -10771,13 +11012,14 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
10771
11012
  const { agent, cwd, activeEnvironment } = context;
10772
11013
  const { checkProvenance, isTrustedHost } = hooks;
10773
11014
  const settingsView = catalogSettings(config);
11015
+ const layers = inspectionLayers(config.policy);
10774
11016
  const cv = (id) => checkValue(settingsView, id);
10775
11017
  let loggedFinding;
10776
11018
  const noteLogged = (v) => {
10777
11019
  if (v?.logged && !loggedFinding) loggedFinding = v;
10778
11020
  };
10779
11021
  const allowed = () => loggedFinding ?? { decision: "allow" };
10780
- const shellInput = resolveShellInput(toolName, args, config.policy.toolInspection);
11022
+ const shellInput = resolveShellInput(toolName, args, layers);
10781
11023
  const wouldBeIgnored = matchesPattern(toolName, config.policy.ignoredTools);
10782
11024
  {
10783
11025
  const dest = ssrfDestinationFloor(toolName, args, {
@@ -10882,13 +11124,10 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
10882
11124
  return { id, value: cv(id) };
10883
11125
  };
10884
11126
  const matches = config.policy.smartRules.filter((rule) => {
10885
- if (!toolMatchesRule(toolName, rule.tool, config.policy.toolInspection)) return false;
11127
+ if (!toolMatchesRule(toolName, rule.tool, layers)) return false;
10886
11128
  if (astSuppressed(rule)) return false;
10887
11129
  if (rmCleanupWaiver && rule.name === "review-rm" && rule.verdict === "review") return false;
10888
- if (!evaluateSmartConditions(
10889
- shellRuleArgs(toolName, args, rule.tool, config.policy.toolInspection),
10890
- rule
10891
- ))
11130
+ if (!evaluateSmartConditions(shellRuleArgs(toolName, args, rule.tool, layers), rule))
10892
11131
  return false;
10893
11132
  const check = ruleCheck(rule);
10894
11133
  if (check?.value === "off") return false;
@@ -10935,7 +11174,7 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
10935
11174
  let allTokens = [];
10936
11175
  let pathTokens = [];
10937
11176
  if (pendingToolEgress) return pendingToolEgress;
10938
- const shellCommand = shellInput.kind === "shell" ? shellInput.command : shellInput.kind === "not-shell" ? extractShellCommand(toolName, args, config.policy.toolInspection) : null;
11177
+ const shellCommand = shellInput.kind === "shell" ? shellInput.command : shellInput.kind === "not-shell" ? extractShellCommand(toolName, args, layers) : null;
10939
11178
  if (shellCommand) {
10940
11179
  const analyzed = analyzeShellCommand(shellCommand);
10941
11180
  allTokens = analyzed.allTokens;
@@ -11012,7 +11251,7 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
11012
11251
  if (["ssh", "scp", "rsync"].includes(firstToken)) {
11013
11252
  const rawTokens = shellCommand.trim().split(/\s+/);
11014
11253
  const sshHosts = extractAllSshHosts(rawTokens.slice(1));
11015
- allTokens.push(...sshHosts);
11254
+ allTokens = allTokens.concat(sshHosts);
11016
11255
  }
11017
11256
  if (firstToken && firstToken.startsWith("/") && checkProvenance) {
11018
11257
  const prov = checkProvenance(firstToken, cwd);
@@ -11041,7 +11280,7 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
11041
11280
  };
11042
11281
  }
11043
11282
  }
11044
- if (isSqlTool(toolName, config.policy.toolInspection)) {
11283
+ if (isSqlTool(toolName, layers)) {
11045
11284
  allTokens = allTokens.filter((t) => !SQL_DML_KEYWORDS.has(t.toLowerCase()));
11046
11285
  }
11047
11286
  } else {
@@ -11049,7 +11288,7 @@ async function evaluatePolicyCore(config, toolName, args, context = {}, hooks =
11049
11288
  if (args && typeof args === "object") {
11050
11289
  const flattenedArgs = JSON.stringify(args).toLowerCase();
11051
11290
  const extraTokens = flattenedArgs.split(/[^a-zA-Z0-9]+/).filter((t) => t.length > 1);
11052
- allTokens.push(...extraTokens);
11291
+ allTokens = allTokens.concat(extraTokens);
11053
11292
  }
11054
11293
  }
11055
11294
  const isManual = agent === "Terminal";
@@ -11305,6 +11544,264 @@ function isDestructiveToolName(bareTool) {
11305
11544
  return DESTRUCTIVE_VERB_RE.test(bareTool);
11306
11545
  }
11307
11546
 
11547
+ // src/exposure/mask.ts
11548
+ var import_crypto2 = require("crypto");
11549
+
11550
+ // src/scan/pii.ts
11551
+ var PII_EMAIL_RE = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/;
11552
+ var PII_SSN_RE = /\b\d{3}-\d{2}-\d{4}\b/;
11553
+ var PII_PHONE_RE = /\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b/;
11554
+ var PII_CC16_RE = /\b(?:4\d{3}|5[1-5]\d{2}|6\d{3})[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/;
11555
+ var PII_CC15_RE = /\b3[47]\d{2}[-\s]?\d{6}[-\s]?\d{5}\b/;
11556
+ var PII_IBAN_RE = /\b[A-Z]{2}\d{2}(?:[A-Z0-9]|[ -][A-Z0-9]){11,30}\b/;
11557
+ function* validCardRuns(text, base2) {
11558
+ const re = new RegExp(base2.source, "g");
11559
+ let m;
11560
+ while ((m = re.exec(text)) !== null) {
11561
+ const digits = m[0].replace(/\D/g, "");
11562
+ if (!isDecimalFraction(text, m.index, digits.length === m[0].length) && validateLuhn(digits)) {
11563
+ yield { index: m.index, length: m[0].length, digits };
11564
+ } else {
11565
+ re.lastIndex = m.index + 1;
11566
+ }
11567
+ }
11568
+ }
11569
+ function hasValidCard(text) {
11570
+ for (const base2 of [PII_CC16_RE, PII_CC15_RE]) {
11571
+ if (!validCardRuns(text, base2).next().done) return true;
11572
+ }
11573
+ return false;
11574
+ }
11575
+ function replaceValidCards(text, replace) {
11576
+ let out = text;
11577
+ for (const base2 of [PII_CC16_RE, PII_CC15_RE]) {
11578
+ let res = "";
11579
+ let last = 0;
11580
+ for (const run of validCardRuns(out, base2)) {
11581
+ res += out.slice(last, run.index) + replace(run.digits);
11582
+ last = run.index + run.length;
11583
+ }
11584
+ out = res + out.slice(last);
11585
+ }
11586
+ return out;
11587
+ }
11588
+ var NUMBER_LEAD_RE = /[\s:=;([{"'+-]/;
11589
+ function isDecimalFraction(text, index, unseparated) {
11590
+ if (!unseparated) return false;
11591
+ const sep = text[index - 1];
11592
+ const a = text[index - 2];
11593
+ if (sep === ".") {
11594
+ if (a !== void 0 && a >= "0" && a <= "9") return true;
11595
+ return a === void 0 || NUMBER_LEAD_RE.test(a);
11596
+ }
11597
+ if (sep === "," && a === "0") {
11598
+ const b = text[index - 3];
11599
+ return b === void 0 || NUMBER_LEAD_RE.test(b);
11600
+ }
11601
+ return false;
11602
+ }
11603
+ function hasValidIban(text) {
11604
+ const re = new RegExp(PII_IBAN_RE.source, "g");
11605
+ let m;
11606
+ while ((m = re.exec(text)) !== null) {
11607
+ if (validateIban(m[0])) return true;
11608
+ re.lastIndex = m.index + 1;
11609
+ }
11610
+ return false;
11611
+ }
11612
+ function detectPii(text) {
11613
+ const found = /* @__PURE__ */ new Set();
11614
+ if (/@/.test(text) && PII_EMAIL_RE.test(text)) found.add("Email");
11615
+ if (/-/.test(text) && PII_SSN_RE.test(text)) found.add("SSN");
11616
+ if (PII_PHONE_RE.test(text)) found.add("Phone");
11617
+ if (hasValidCard(text)) found.add("Credit Card");
11618
+ if (hasValidIban(text)) found.add("IBAN");
11619
+ return [...found];
11620
+ }
11621
+ var REALTIME_PII_PATTERNS = ["SSN", "Credit Card", "IBAN"];
11622
+ var MAX_PII_SCAN_BYTES = 1e5;
11623
+ function* stringLeaves(v, depth = 0) {
11624
+ if (depth > 6) return;
11625
+ if (typeof v === "string") {
11626
+ if (v.length > 0) yield v;
11627
+ return;
11628
+ }
11629
+ if (typeof v === "number") {
11630
+ if (Number.isFinite(v)) yield String(v);
11631
+ return;
11632
+ }
11633
+ if (!v || typeof v !== "object") return;
11634
+ if (Array.isArray(v)) {
11635
+ for (const x of v) yield* stringLeaves(x, depth + 1);
11636
+ return;
11637
+ }
11638
+ for (const x of Object.values(v)) yield* stringLeaves(x, depth + 1);
11639
+ }
11640
+ function detectArgsPii(args) {
11641
+ if (args === null || args === void 0) return [];
11642
+ const found = /* @__PURE__ */ new Set();
11643
+ let budget = MAX_PII_SCAN_BYTES;
11644
+ try {
11645
+ for (const leaf of stringLeaves(args)) {
11646
+ if (budget <= 0) break;
11647
+ const t = leaf.length > budget ? leaf.slice(0, budget) : leaf;
11648
+ budget -= t.length;
11649
+ for (const p of detectPii(t)) {
11650
+ if (REALTIME_PII_PATTERNS.includes(p)) found.add(p);
11651
+ }
11652
+ }
11653
+ } catch {
11654
+ return [];
11655
+ }
11656
+ return [...found];
11657
+ }
11658
+
11659
+ // src/exposure/mask.ts
11660
+ var MASKED_KINDS = /* @__PURE__ */ new Set(["email", "iban", "account"]);
11661
+ var ENTRY_RE = /^(email|iban|account):([^#\s]{1,200}(?: [^#\s]{1,40}){0,4})#sha256:([0-9a-f]{64})$/;
11662
+ function split(dest) {
11663
+ const i = dest.indexOf(":");
11664
+ if (i <= 0) return null;
11665
+ return { kind: dest.slice(0, i).toLowerCase(), value: dest.slice(i + 1) };
11666
+ }
11667
+ function normalizeDestination(dest) {
11668
+ const p = split(dest.trim());
11669
+ if (!p) return dest.trim();
11670
+ if (p.kind === "iban" || p.kind === "account")
11671
+ return `${p.kind}:${p.value.replace(/\s+/g, "").toUpperCase()}`;
11672
+ return `${p.kind}:${p.value.toLowerCase()}`;
11673
+ }
11674
+ function maskEmailValue(address) {
11675
+ const at = address.lastIndexOf("@");
11676
+ if (at <= 0) return "***";
11677
+ return `${address[0]}***@${address.slice(at + 1)}`;
11678
+ }
11679
+ function maskDestination(dest) {
11680
+ const n = normalizeDestination(dest);
11681
+ const p = split(n);
11682
+ if (!p || !MASKED_KINDS.has(p.kind)) return n;
11683
+ if (p.kind === "iban") return `iban:${p.value.slice(0, 4)} **** **** ${p.value.slice(-4)}`;
11684
+ if (p.kind === "account") return `account:****${p.value.slice(-4)}`;
11685
+ return `email:${maskEmailValue(p.value)}`;
11686
+ }
11687
+ function isMaskedKind(dest) {
11688
+ const p = split(dest);
11689
+ return !!p && MASKED_KINDS.has(p.kind);
11690
+ }
11691
+ function hashDestination(dest) {
11692
+ return (0, import_crypto2.createHash)("sha256").update(normalizeDestination(dest), "utf8").digest("hex");
11693
+ }
11694
+ function isHashedEntry(entry) {
11695
+ return ENTRY_RE.test(entry);
11696
+ }
11697
+ function trustedEntryOf(dest) {
11698
+ const n = normalizeDestination(dest);
11699
+ if (!isMaskedKind(n)) return n;
11700
+ return `${maskDestination(n)}#sha256:${hashDestination(n)}`;
11701
+ }
11702
+ function matchesTrustedEntry(dest, entry) {
11703
+ const m = ENTRY_RE.exec(entry);
11704
+ if (m) return hashDestination(dest) === m[3];
11705
+ return normalizeDestination(dest) === normalizeDestination(entry);
11706
+ }
11707
+ function matchesTrustedList(dest, entries) {
11708
+ if (entries.length === 0) return false;
11709
+ const plain = normalizeDestination(dest);
11710
+ let hash2;
11711
+ for (const entry of entries) {
11712
+ const m = ENTRY_RE.exec(entry);
11713
+ if (m) {
11714
+ hash2 ??= hashDestination(dest);
11715
+ if (hash2 === m[3]) return true;
11716
+ } else if (plain === normalizeDestination(entry)) return true;
11717
+ }
11718
+ return false;
11719
+ }
11720
+ function normalizeRecipient(raw) {
11721
+ if (typeof raw !== "string") return null;
11722
+ const v = raw.trim();
11723
+ if (!v || v.length > 512) return null;
11724
+ const acct = /^account:([A-Za-z0-9 ]{8,40})$/i.exec(v);
11725
+ if (acct) {
11726
+ const n = acct[1].replace(/\s+/g, "").toUpperCase();
11727
+ return n.length >= 8 && n.length <= 34 ? `account:${n}` : null;
11728
+ }
11729
+ if (/^(email|host|iban):/i.test(v)) {
11730
+ const i = v.indexOf(":");
11731
+ const kind = v.slice(0, i).toLowerCase();
11732
+ const inner = normalizeRecipient(v.slice(i + 1));
11733
+ return inner && inner.startsWith(`${kind}:`) ? inner : null;
11734
+ }
11735
+ const found = extractArgDestinations({ to: v });
11736
+ return found.length === 1 ? found[0] : null;
11737
+ }
11738
+ function normalizeTrustedEntry(raw) {
11739
+ if (typeof raw !== "string") return null;
11740
+ const v = raw.trim().replace(/#sha256:([0-9A-Fa-f]{64})$/, (_m, h) => `#sha256:${h.toLowerCase()}`);
11741
+ if (v.includes("#")) return isHashedEntry(v) ? v : null;
11742
+ const full = normalizeRecipient(v);
11743
+ return full === null ? null : trustedEntryOf(full);
11744
+ }
11745
+ function entryDisplay(entry) {
11746
+ const i = entry.indexOf("#sha256:");
11747
+ return i > 0 ? entry.slice(0, i) : entry;
11748
+ }
11749
+ var IBAN_TEXT_RE = /\b[A-Z]{2}\d{2}(?:[ -]?[A-Z0-9]{4}){2,7}(?:[ -]?[A-Z0-9]{1,4})?\b/gi;
11750
+ var EMAIL_TEXT_RE = /[\p{L}\p{N}._%+-]+@[\p{L}\p{N}](?:[\p{L}\p{N}-]*[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]*[\p{L}\p{N}])?)*\.\p{L}{2,}/gu;
11751
+ var ACCOUNT_KEY_RE = /("(?:iban|account|account_number|accountNumber)"\s*:\s*")([A-Za-z0-9 .-]{6,40})(")/g;
11752
+ var ACCOUNT_VALUE_RE = /"([A-Z]{2}\d{2}[A-Z0-9]{11,30})"/g;
11753
+ function maskPersonalData(text) {
11754
+ if (!text) return text;
11755
+ try {
11756
+ let out = text;
11757
+ out = out.replace(IBAN_TEXT_RE, (m) => {
11758
+ const v = m.replace(/[ -]/g, "").toUpperCase();
11759
+ return validateIban(v) ? `${v.slice(0, 4)} **** **** ${v.slice(-4)}` : m;
11760
+ });
11761
+ out = replaceValidCards(out, (digits) => `**** **** **** ${digits.slice(-4)}`);
11762
+ out = out.replace(
11763
+ ACCOUNT_VALUE_RE,
11764
+ (m, v) => IBAN_LENGTH[v.slice(0, 2).toUpperCase()] === v.length ? `"****${v.slice(-4)}"` : m
11765
+ );
11766
+ out = out.replace(ACCOUNT_KEY_RE, (m, a, v, b) => {
11767
+ const compact = v.replace(/[ .-]/g, "");
11768
+ const digits = compact.replace(/\D/g, "").length;
11769
+ return digits >= 6 && digits * 2 >= compact.length ? `${a}****${compact.slice(-4)}${b}` : m;
11770
+ });
11771
+ if (out.includes("@")) out = out.replace(EMAIL_TEXT_RE, (m) => maskEmailValue(m));
11772
+ return out;
11773
+ } catch {
11774
+ return text;
11775
+ }
11776
+ }
11777
+ var MAX_MASK_DEPTH = 64;
11778
+ function maskPersonalValue(value) {
11779
+ return maskLeaf(value, "", 0);
11780
+ }
11781
+ function maskLeaf(value, key, depth) {
11782
+ if (depth > MAX_MASK_DEPTH) return "[REDACTED]";
11783
+ if (typeof value === "string") {
11784
+ try {
11785
+ const json = `{${JSON.stringify(key)}:${JSON.stringify(value)}}`;
11786
+ return Object.values(JSON.parse(maskPersonalData(json)))[0];
11787
+ } catch {
11788
+ return "[REDACTED]";
11789
+ }
11790
+ }
11791
+ if (typeof value === "number") {
11792
+ const text = String(value);
11793
+ const masked = maskPersonalData(text);
11794
+ return masked === text ? value : masked;
11795
+ }
11796
+ if (Array.isArray(value)) return value.map((v) => maskLeaf(v, key, depth + 1));
11797
+ if (value && typeof value === "object") {
11798
+ return Object.fromEntries(
11799
+ Object.entries(value).map(([k, v]) => [maskPersonalData(k), maskLeaf(v, k, depth + 1)])
11800
+ );
11801
+ }
11802
+ return value;
11803
+ }
11804
+
11308
11805
  // src/exposure/shell.ts
11309
11806
  var import_mvdan_sh4 = __toESM(require("mvdan-sh"));
11310
11807
  var { syntax: syntax4 } = import_mvdan_sh4.default;
@@ -11785,11 +12282,11 @@ function safeMessage(value, max = 300) {
11785
12282
  }
11786
12283
 
11787
12284
  // src/loop/index.ts
11788
- var import_crypto2 = __toESM(require("crypto"));
12285
+ var import_crypto3 = __toESM(require("crypto"));
11789
12286
  var LOOP_MAX_RECORDS = 500;
11790
12287
  function computeArgsHash(args) {
11791
12288
  const str = JSON.stringify(args ?? "");
11792
- return import_crypto2.default.createHash("sha256").update(str).digest("hex").slice(0, 16);
12289
+ return import_crypto3.default.createHash("sha256").update(str).digest("hex").slice(0, 16);
11793
12290
  }
11794
12291
  function evaluateLoopWindow(records, tool, args, threshold, windowMs, now) {
11795
12292
  const hash2 = computeArgsHash(args);
@@ -12084,88 +12581,6 @@ var FILE_TOOLS = /* @__PURE__ */ new Set([
12084
12581
  "list_files"
12085
12582
  ]);
12086
12583
 
12087
- // src/scan/pii.ts
12088
- var PII_EMAIL_RE = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/;
12089
- var PII_SSN_RE = /\b\d{3}-\d{2}-\d{4}\b/;
12090
- var PII_PHONE_RE = /\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b/;
12091
- var PII_CC16_RE = /\b(?:4\d{3}|5[1-5]\d{2}|6\d{3})[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/;
12092
- var PII_CC15_RE = /\b3[47]\d{2}[-\s]?\d{6}[-\s]?\d{5}\b/;
12093
- var PII_IBAN_RE = /\b[A-Z]{2}\d{2}(?:[A-Z0-9]|[ -][A-Z0-9]){11,30}\b/;
12094
- function hasValidCard(text) {
12095
- for (const base2 of [PII_CC16_RE, PII_CC15_RE]) {
12096
- const re = new RegExp(base2.source, "g");
12097
- let m;
12098
- while ((m = re.exec(text)) !== null) {
12099
- const digits = m[0].replace(/\D/g, "");
12100
- if (!isDecimalFraction(text, m.index, digits.length === m[0].length)) {
12101
- if (validateLuhn(digits)) return true;
12102
- }
12103
- re.lastIndex = m.index + 1;
12104
- }
12105
- }
12106
- return false;
12107
- }
12108
- function isDecimalFraction(text, index, unseparated) {
12109
- if (!unseparated || text[index - 1] !== ".") return false;
12110
- const before = text.charCodeAt(index - 2);
12111
- return before >= 48 && before <= 57;
12112
- }
12113
- function hasValidIban(text) {
12114
- const re = new RegExp(PII_IBAN_RE.source, "g");
12115
- let m;
12116
- while ((m = re.exec(text)) !== null) {
12117
- if (validateIban(m[0])) return true;
12118
- re.lastIndex = m.index + 1;
12119
- }
12120
- return false;
12121
- }
12122
- function detectPii(text) {
12123
- const found = /* @__PURE__ */ new Set();
12124
- if (/@/.test(text) && PII_EMAIL_RE.test(text)) found.add("Email");
12125
- if (/-/.test(text) && PII_SSN_RE.test(text)) found.add("SSN");
12126
- if (PII_PHONE_RE.test(text)) found.add("Phone");
12127
- if (hasValidCard(text)) found.add("Credit Card");
12128
- if (hasValidIban(text)) found.add("IBAN");
12129
- return [...found];
12130
- }
12131
- var REALTIME_PII_PATTERNS = ["SSN", "Credit Card", "IBAN"];
12132
- var MAX_PII_SCAN_BYTES = 1e5;
12133
- function* stringLeaves(v, depth = 0) {
12134
- if (depth > 6) return;
12135
- if (typeof v === "string") {
12136
- if (v.length > 0) yield v;
12137
- return;
12138
- }
12139
- if (typeof v === "number") {
12140
- if (Number.isFinite(v)) yield String(v);
12141
- return;
12142
- }
12143
- if (!v || typeof v !== "object") return;
12144
- if (Array.isArray(v)) {
12145
- for (const x of v) yield* stringLeaves(x, depth + 1);
12146
- return;
12147
- }
12148
- for (const x of Object.values(v)) yield* stringLeaves(x, depth + 1);
12149
- }
12150
- function detectArgsPii(args) {
12151
- if (args === null || args === void 0) return [];
12152
- const found = /* @__PURE__ */ new Set();
12153
- let budget = MAX_PII_SCAN_BYTES;
12154
- try {
12155
- for (const leaf of stringLeaves(args)) {
12156
- if (budget <= 0) break;
12157
- const t = leaf.length > budget ? leaf.slice(0, budget) : leaf;
12158
- budget -= t.length;
12159
- for (const p of detectPii(t)) {
12160
- if (REALTIME_PII_PATTERNS.includes(p)) found.add(p);
12161
- }
12162
- }
12163
- } catch {
12164
- return [];
12165
- }
12166
- return [...found];
12167
- }
12168
-
12169
12584
  // src/dlp/canary.ts
12170
12585
  var CANARY_MIN_LENGTH = 16;
12171
12586
  var MAX_TEXT = 1e5;
@@ -12337,8 +12752,8 @@ function matchCanaryArgs(args, values) {
12337
12752
 
12338
12753
  // src/scan/canonical.ts
12339
12754
  var LONG_OUTPUT_THRESHOLD_BYTES = 100 * 1024;
12340
- var CANONICAL_EXTRACTOR_VERSION = "canonical-v25";
12341
- var CANONICAL_EXTRACTOR_HASH = "48ef4af5dd89198d";
12755
+ var CANONICAL_EXTRACTOR_VERSION = "canonical-v27";
12756
+ var CANONICAL_EXTRACTOR_HASH = "a358f47eacca6e14";
12342
12757
  var DEDUPE_PREVIEW_LEN = 120;
12343
12758
  function extractCanonicalFindings(call, ctx) {
12344
12759
  const out = [];
@@ -12790,6 +13205,7 @@ var ENGINE_VERSION = "1.4.0";
12790
13205
  detectDangerousShellExec,
12791
13206
  detectInlineExec,
12792
13207
  detectPii,
13208
+ entryDisplay,
12793
13209
  evaluateEgress,
12794
13210
  evaluateLoopWindow,
12795
13211
  evaluatePolicy,
@@ -12813,18 +13229,23 @@ var ENGINE_VERSION = "1.4.0";
12813
13229
  getCompiledRegex,
12814
13230
  getNestedValue,
12815
13231
  gitRepoPath,
13232
+ hashDestination,
12816
13233
  hostMatches,
12817
13234
  incompleteFileVerdict,
12818
13235
  inspectArgumentSecrets,
13236
+ inspectionEntry,
13237
+ inspectionLayers,
12819
13238
  isAgentInstructionPath,
12820
13239
  isBashTool,
12821
13240
  isDestructiveToolName,
13241
+ isHashedEntry,
12822
13242
  isIgnoredTool,
12823
13243
  isInside,
12824
13244
  isKnobGoverned,
12825
13245
  isLegacySystemPath,
12826
13246
  isLockedCheck,
12827
13247
  isLoopbackHost,
13248
+ isMaskedKind,
12828
13249
  isPasswordHashPath,
12829
13250
  isPrivateHost,
12830
13251
  isProtectedHomePath,
@@ -12832,16 +13253,24 @@ var ENGINE_VERSION = "1.4.0";
12832
13253
  isShieldVerdict,
12833
13254
  isStrictGatedTier,
12834
13255
  isVerdict,
13256
+ maskDestination,
13257
+ maskPersonalData,
13258
+ maskPersonalValue,
12835
13259
  matchCanary,
12836
13260
  matchCanaryArgs,
12837
13261
  matchSensitivePath,
12838
13262
  matchesPattern,
13263
+ matchesTrustedEntry,
13264
+ matchesTrustedList,
12839
13265
  narrativeRuleLabel,
12840
13266
  normalizeCommandForPolicy,
13267
+ normalizeDestination,
12841
13268
  normalizeFilePath,
12842
13269
  normalizeForScan,
12843
13270
  normalizeIpLiteral,
12844
13271
  normalizePyPiName,
13272
+ normalizeRecipient,
13273
+ normalizeTrustedEntry,
12845
13274
  parseAllSshHostsFromCommand,
12846
13275
  parseDestHost,
12847
13276
  patternShapeOf,
@@ -12875,6 +13304,7 @@ var ENGINE_VERSION = "1.4.0";
12875
13304
  toScanFinding,
12876
13305
  toolMatchesRule,
12877
13306
  truncateBlastPath,
13307
+ trustedEntryOf,
12878
13308
  tuningFromLegacyPolicy,
12879
13309
  tuningToLegacyPolicy,
12880
13310
  unwrapCommandHead,