@exorcist-98/mcp-server 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4142,7 +4142,7 @@ var require_code = __commonJS({
4142
4142
  };
4143
4143
  exports._CodeOrName = _CodeOrName;
4144
4144
  exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
4145
- var Name2 = class extends _CodeOrName {
4145
+ var Name3 = class extends _CodeOrName {
4146
4146
  constructor(s) {
4147
4147
  super();
4148
4148
  if (!exports.IDENTIFIER.test(s))
@@ -4159,7 +4159,7 @@ var require_code = __commonJS({
4159
4159
  return { [this.str]: 1 };
4160
4160
  }
4161
4161
  };
4162
- exports.Name = Name2;
4162
+ exports.Name = Name3;
4163
4163
  var _Code = class extends _CodeOrName {
4164
4164
  constructor(code) {
4165
4165
  super();
@@ -4181,7 +4181,7 @@ var require_code = __commonJS({
4181
4181
  get names() {
4182
4182
  var _a;
4183
4183
  return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => {
4184
- if (c instanceof Name2)
4184
+ if (c instanceof Name3)
4185
4185
  names[c.str] = (names[c.str] || 0) + 1;
4186
4186
  return names;
4187
4187
  }, {});
@@ -4215,7 +4215,7 @@ var require_code = __commonJS({
4215
4215
  function addCodeArg(code, arg) {
4216
4216
  if (arg instanceof _Code)
4217
4217
  code.push(...arg._items);
4218
- else if (arg instanceof Name2)
4218
+ else if (arg instanceof Name3)
4219
4219
  code.push(arg);
4220
4220
  else
4221
4221
  code.push(interpolate(arg));
@@ -4241,7 +4241,7 @@ var require_code = __commonJS({
4241
4241
  if (a === '""')
4242
4242
  return b;
4243
4243
  if (typeof a == "string") {
4244
- if (b instanceof Name2 || a[a.length - 1] !== '"')
4244
+ if (b instanceof Name3 || a[a.length - 1] !== '"')
4245
4245
  return;
4246
4246
  if (typeof b != "string")
4247
4247
  return `${a.slice(0, -1)}${b}"`;
@@ -4249,7 +4249,7 @@ var require_code = __commonJS({
4249
4249
  return a.slice(0, -1) + b.slice(1);
4250
4250
  return;
4251
4251
  }
4252
- if (typeof b == "string" && b[0] === '"' && !(a instanceof Name2))
4252
+ if (typeof b == "string" && b[0] === '"' && !(a instanceof Name3))
4253
4253
  return `"${a}${b.slice(1)}`;
4254
4254
  return;
4255
4255
  }
@@ -11548,6 +11548,24 @@ var init_canary = __esm({
11548
11548
  }
11549
11549
  });
11550
11550
 
11551
+ // ../core/src/severity-paths.ts
11552
+ function keepsFullSeverity(rel, role) {
11553
+ const norm = rel.replace(/\\/g, "/");
11554
+ return NEVER_LOWERED_ROLES.has(role) || AGENT_PATH.test(norm);
11555
+ }
11556
+ function lowersSeverity(def, rel, role) {
11557
+ if (!def.low_severity_paths || keepsFullSeverity(rel, role)) return false;
11558
+ return def.low_severity_paths.some((p) => new RegExp(p, "i").test(rel));
11559
+ }
11560
+ var NEVER_LOWERED_ROLES, AGENT_PATH;
11561
+ var init_severity_paths = __esm({
11562
+ "../core/src/severity-paths.ts"() {
11563
+ "use strict";
11564
+ NEVER_LOWERED_ROLES = /* @__PURE__ */ new Set(["instruction", "memory", "hook", "mcp-config", "tool-result", "power"]);
11565
+ AGENT_PATH = /(^|\/)(\.kiro|\.claude|\.cursor)\/|(^|\/)\.github\/(?:[^/]*instructions[^/]*|instructions|prompts)(\/|$)/i;
11566
+ }
11567
+ });
11568
+
11551
11569
  // ../core/src/walker.ts
11552
11570
  import { opendir, stat, open } from "node:fs/promises";
11553
11571
  import { join as join4, relative as relative2, extname, basename as basename2 } from "node:path";
@@ -11584,6 +11602,23 @@ async function isBinary(filePath) {
11584
11602
  async function* walkRepo(root, maxFileSize = MAX_FILE_SIZE) {
11585
11603
  yield* walkDir(root, root, maxFileSize);
11586
11604
  }
11605
+ async function* walkPaths(root) {
11606
+ yield* walkPathsIn(root, root);
11607
+ }
11608
+ async function* walkPathsIn(root, dir) {
11609
+ const dh = await opendir(dir);
11610
+ for await (const entry of dh) {
11611
+ const absPath = join4(dir, entry.name);
11612
+ const rel = relative2(root, absPath).replace(/\\/g, "/");
11613
+ if (entry.isDirectory()) {
11614
+ if (SKIP_DIRS.has(entry.name)) continue;
11615
+ yield { rel, isDirectory: true };
11616
+ yield* walkPathsIn(root, absPath);
11617
+ } else {
11618
+ yield { rel, isDirectory: false };
11619
+ }
11620
+ }
11621
+ }
11587
11622
  async function* walkDir(root, dir, maxFileSize) {
11588
11623
  const dh = await opendir(dir);
11589
11624
  for await (const entry of dh) {
@@ -11616,6 +11651,7 @@ var MAX_FILE_SIZE, AGENT_FILE_HARD_LIMIT, AGENT_FACING_ROLES, LOCKFILE_NAMES, BI
11616
11651
  var init_walker = __esm({
11617
11652
  "../core/src/walker.ts"() {
11618
11653
  "use strict";
11654
+ init_severity_paths();
11619
11655
  MAX_FILE_SIZE = 1048576;
11620
11656
  AGENT_FILE_HARD_LIMIT = 10 * 1048576;
11621
11657
  AGENT_FACING_ROLES = /* @__PURE__ */ new Set(["instruction", "memory", "hook", "config", "mcp-config", "tool-result", "power"]);
@@ -11823,7 +11859,7 @@ function locateQuote(text, quote) {
11823
11859
  const viaMask = tryIn(masked);
11824
11860
  return viaMask ? { ...viaMask, shown: masked.slice(viaMask.index, viaMask.end) } : null;
11825
11861
  }
11826
- function positionOf(text, needle) {
11862
+ function positionOf2(text, needle) {
11827
11863
  const idx = text.indexOf(needle);
11828
11864
  if (idx === -1) return null;
11829
11865
  const before = text.slice(0, idx);
@@ -11917,9 +11953,9 @@ function decodesToText(v) {
11917
11953
  if (/^[A-Za-z0-9+\/]{16,}={0,2}$/.test(v) && v.length % 4 === 0) bytes = Buffer.from(v, "base64");
11918
11954
  else if (/^(?:[0-9a-f]{2}){12,}$/i.test(v)) bytes = Buffer.from(v, "hex");
11919
11955
  if (!bytes || bytes.length < 12) return false;
11920
- let printable2 = 0;
11921
- for (const b of bytes) if (b >= 32 && b < 127 || b === 10) printable2++;
11922
- return printable2 / bytes.length > 0.9 && /[A-Za-z]{3,}\s+[A-Za-z]{2,}/.test(bytes.toString("latin1"));
11956
+ let printable3 = 0;
11957
+ for (const b of bytes) if (b >= 32 && b < 127 || b === 10) printable3++;
11958
+ return printable3 / bytes.length > 0.9 && /[A-Za-z]{3,}\s+[A-Za-z]{2,}/.test(bytes.toString("latin1"));
11923
11959
  }
11924
11960
  function unquote(v) {
11925
11961
  const q = v[0];
@@ -12047,7 +12083,7 @@ async function judgeWholeFile(file, norm, client, maskedRuns = 0) {
12047
12083
  if (start >= text.length) break;
12048
12084
  const v = await judgeText(text.slice(start, start + MAX_JUDGED_CHARS), file.rel, client, maskedRuns);
12049
12085
  if (!v) continue;
12050
- const pos = positionOf(text, v.span);
12086
+ const pos = positionOf2(text, v.span);
12051
12087
  if (!pos) continue;
12052
12088
  return [{
12053
12089
  source: "heuristic",
@@ -22381,7 +22417,7 @@ var StdioServerTransport = class {
22381
22417
 
22382
22418
  // src/index.ts
22383
22419
  init_zod();
22384
- import { homedir as homedir2 } from "node:os";
22420
+ import { homedir as homedir3 } from "node:os";
22385
22421
  import { delimiter } from "node:path";
22386
22422
 
22387
22423
  // src/tools.ts
@@ -22454,7 +22490,18 @@ var PolicySchema = external_exports.object({
22454
22490
  * which ordinary use rarely does, and then a single question is cheap next
22455
22491
  * to a leaked key. `mode: monitor` makes it monitor too.
22456
22492
  */
22457
- sessionGuard: external_exports.enum(["hold", "block", "monitor", "off"]).default("hold")
22493
+ sessionGuard: external_exports.enum(["hold", "block", "monitor", "off"]).default("hold"),
22494
+ /**
22495
+ * Who may release a call that Session Guard (EX-027) is holding:
22496
+ * `os`: the operating system confirms the owner (Touch ID or login
22497
+ * password on macOS). A forged `cli.json` release no longer works.
22498
+ * Falls back to `terminal` when the OS check is unavailable;
22499
+ * `terminal`: a release recorded by `exorcist approve` from a terminal,
22500
+ * as before.
22501
+ * Optional with no default: when absent the Shield picks `os` if it is
22502
+ * available, else `terminal`. Older Shields reject this key.
22503
+ */
22504
+ sessionRelease: external_exports.enum(["os", "terminal"]).optional()
22458
22505
  }).strict();
22459
22506
 
22460
22507
  // ../shield/src/state.ts
@@ -22603,7 +22650,7 @@ function requireSnippet() {
22603
22650
  if (hasRequiredSnippet) return snippet;
22604
22651
  hasRequiredSnippet = 1;
22605
22652
  const common2 = requireCommon();
22606
- function getLine(buffer, lineStart, lineEnd, position2, maxLineLength) {
22653
+ function getLine(buffer, lineStart, lineEnd2, position2, maxLineLength) {
22607
22654
  let head = "";
22608
22655
  let tail = "";
22609
22656
  const maxHalfLength = Math.floor(maxLineLength / 2) - 1;
@@ -22611,12 +22658,12 @@ function requireSnippet() {
22611
22658
  head = " ... ";
22612
22659
  lineStart = position2 - maxHalfLength + head.length;
22613
22660
  }
22614
- if (lineEnd - position2 > maxHalfLength) {
22661
+ if (lineEnd2 - position2 > maxHalfLength) {
22615
22662
  tail = " ...";
22616
- lineEnd = position2 + maxHalfLength - tail.length;
22663
+ lineEnd2 = position2 + maxHalfLength - tail.length;
22617
22664
  }
22618
22665
  return {
22619
- str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
22666
+ str: head + buffer.slice(lineStart, lineEnd2).replace(/\t/g, "\u2192") + tail,
22620
22667
  pos: position2 - lineStart + head.length
22621
22668
  // relative position
22622
22669
  };
@@ -25619,6 +25666,13 @@ var MatchSchema = external_exports.object({
25619
25666
  // matching this regex (words such as "never", "such as", "injection"), is
25620
25667
  // being quoted as an example or warned against, not given as an order.
25621
25668
  quoted_example_cues: external_exports.string().optional(),
25669
+ // A phrase that the text itself forbids is a defence, not an attack ("it
25670
+ // must not attempt to tell the agent to ignore earlier instructions",
25671
+ // "users cannot bypass the prompt"). Checked against the text from the
25672
+ // start of the sentence up to the match (at most 200 characters), anchored
25673
+ // at its end with `$`, so the negation has to govern the phrase and not
25674
+ // merely appear somewhere before it (m7-precision).
25675
+ negated_cues: external_exports.string().optional(),
25622
25676
  // Matches separated only by line breaks, quotes, commas or `+` are one
25623
25677
  // encoded blob: one finding, checked as a whole.
25624
25678
  merge_adjacent: external_exports.boolean().optional(),
@@ -25639,18 +25693,28 @@ var MatchSchema = external_exports.object({
25639
25693
  // capabilities.yaml). The signature engine skips such rules.
25640
25694
  // `detonation` is the Detonation Chamber (EX-024, m5-detonation): a
25641
25695
  // sandboxed model run, only with `--detonate`.
25642
- analysis: external_exports.enum(["trifecta", "detonation"]).optional(),
25696
+ // `path-names` checks the names of every walked path (EX-029, path-names.ts).
25697
+ analysis: external_exports.enum(["trifecta", "detonation", "path-names"]).optional(),
25698
+ // Text an element hides from a person by its style (EX-028, hidden-text.ts):
25699
+ // reported only when the hidden text addresses the AI or asks for actions.
25700
+ hidden_text: external_exports.boolean().optional(),
25701
+ // unicode_class only: a single U+200B directly after `@` and before a name
25702
+ // is the way changelogs stop GitHub from notifying the person. Reported at
25703
+ // `severity` and not counted toward the escalation of many short runs.
25704
+ mention_guard: external_exports.object({
25705
+ severity: external_exports.enum(["critical", "high", "medium", "low"])
25706
+ }).optional(),
25643
25707
  minor_run: external_exports.object({
25644
25708
  max_length: external_exports.number().int().min(1),
25645
25709
  classes: external_exports.array(external_exports.string()).min(1),
25646
25710
  severity: external_exports.enum(["critical", "high", "medium", "low"])
25647
25711
  }).optional()
25648
25712
  }).superRefine((val, ctx2) => {
25649
- const hasAny = val.regex !== void 0 || val.unicode_class !== void 0 && val.unicode_class.length > 0 || val.json_path !== void 0 || val.analysis !== void 0;
25713
+ const hasAny = val.regex !== void 0 || val.unicode_class !== void 0 && val.unicode_class.length > 0 || val.json_path !== void 0 || val.hidden_text === true || val.analysis !== void 0;
25650
25714
  if (!hasAny) {
25651
25715
  ctx2.addIssue({
25652
25716
  code: external_exports.ZodIssueCode.custom,
25653
- message: "match must contain at least one of: regex, unicode_class, json_path, analysis"
25717
+ message: "match must contain at least one of: regex, unicode_class, json_path, analysis, hidden_text"
25654
25718
  });
25655
25719
  }
25656
25720
  if (val.value_regex !== void 0 && val.json_path === void 0) {
@@ -25662,7 +25726,7 @@ var MatchSchema = external_exports.object({
25662
25726
  if ((val.exclude_regex !== void 0 || val.validate !== void 0) && val.regex === void 0 && val.json_path === void 0) {
25663
25727
  ctx2.addIssue({ code: external_exports.ZodIssueCode.custom, message: "match.exclude_regex and match.validate need match.regex or match.json_path" });
25664
25728
  }
25665
- for (const key of ["regex", "value_regex", "exclude_regex", "file_regex", "quoted_example_cues", "decoded_flag_regex"]) {
25729
+ for (const key of ["regex", "value_regex", "exclude_regex", "file_regex", "quoted_example_cues", "negated_cues", "decoded_flag_regex"]) {
25666
25730
  const pattern = val[key];
25667
25731
  if (pattern !== void 0 && !compiles(pattern)) {
25668
25732
  ctx2.addIssue({
@@ -25683,6 +25747,10 @@ var VirusDefinitionSchema = external_exports.object({
25683
25747
  enabled: external_exports.boolean().optional().default(true),
25684
25748
  // Repo-relative paths (regexes) this rule never looks at, e.g. lockfiles.
25685
25749
  skip_paths: external_exports.array(external_exports.string().refine(compiles, "skip_paths entries must be valid regular expressions")).optional(),
25750
+ // Repo-relative paths (regexes) where this rule reports at low severity
25751
+ // instead of its own (test and eval folders). Never applied to a file an
25752
+ // agent reads: see keepsFullSeverity in walker.ts.
25753
+ low_severity_paths: external_exports.array(external_exports.string().refine(compiles, "low_severity_paths entries must be valid regular expressions")).optional(),
25686
25754
  // Rules in the same group that report the same line of the same file are
25687
25755
  // one problem: only the most severe of them is kept.
25688
25756
  same_line_group: external_exports.string().min(1).optional()
@@ -25867,6 +25935,9 @@ function flagTagOffsets(text) {
25867
25935
  }
25868
25936
  return out;
25869
25937
  }
25938
+ function isHiddenCodePoint(cp) {
25939
+ return CP_TO_CLASS.has(cp);
25940
+ }
25870
25941
  function findHiddenUnicode(text) {
25871
25942
  const hits = [];
25872
25943
  const flagTags = flagTagOffsets(text);
@@ -26571,6 +26642,118 @@ function decodeHidden(text) {
26571
26642
  return out.slice(0, MAX_HIDDEN_RUNS);
26572
26643
  }
26573
26644
 
26645
+ // ../core/src/hidden-text.ts
26646
+ var MAX_HIDDEN_ELEMENT = 2e3;
26647
+ var VOID_TAGS = /* @__PURE__ */ new Set(["img", "input", "br", "hr", "meta", "link", "area", "base", "col", "embed", "source", "track", "wbr"]);
26648
+ var AI_NAME_UPPER = /\bAI\b/;
26649
+ var AI_WORDS = /\b(?:assistants?|agents?|llms?|kiro|claude|copilot|chatgpt|gemini|cursor|language\s+models?|(?:the|this)\s+model)\b/i;
26650
+ var ACTION_VERB = "(?:write|rewrite|edit|modify|overwrite|run|execute|fetch|download|send|upload|start|launch|add|append|install|delete|remove|exfiltrate|forward|email)";
26651
+ var ACTION_OBJECT = "(?:files?|config(?:uration)?s?|servers?|commands?|scripts?|mcp|credentials?|secrets?|tokens?|api\\s+keys?|\\.env|\\S*\\.json|~\\/\\S+)";
26652
+ var ACTION = new RegExp(`\\b${ACTION_VERB}\\b[^.\\n!?]{0,60}?(?:\\b${ACTION_OBJECT}(?![\\w-])|${"~\\/"}|\\.env\\b)`, "i");
26653
+ var OVERRIDE = /\b(?:ignore|disregard|forget)\s+(?:all\s+|any\s+|the\s+)?(?:previous|prior|above|earlier)\b/i;
26654
+ function addressesAi(text) {
26655
+ if (text.length === 0) return false;
26656
+ return AI_NAME_UPPER.test(text) || AI_WORDS.test(text) || OVERRIDE.test(text) || ACTION.test(text);
26657
+ }
26658
+ function parseColour(raw) {
26659
+ const v = raw.trim().toLowerCase().replace(/\s*!important$/, "");
26660
+ if (v === "white") return [255, 255, 255];
26661
+ if (v === "black") return [0, 0, 0];
26662
+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/.exec(v);
26663
+ if (hex) {
26664
+ const h = hex[1];
26665
+ const f = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
26666
+ return [parseInt(f.slice(0, 2), 16), parseInt(f.slice(2, 4), 16), parseInt(f.slice(4, 6), 16)];
26667
+ }
26668
+ const rgb = /^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*(?:[,/]\s*[\d.]+%?\s*)?\)$/.exec(v);
26669
+ if (rgb) return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])];
26670
+ return null;
26671
+ }
26672
+ function distance(a, b) {
26673
+ return Math.max(Math.abs(a[0] - b[0]), Math.abs(a[1] - b[1]), Math.abs(a[2] - b[2]));
26674
+ }
26675
+ function px(raw) {
26676
+ const m = /^(-?\d*\.?\d+)\s*(px|pt|em|rem|%|vw|vh)?$/.exec(raw.trim().toLowerCase());
26677
+ if (!m) return null;
26678
+ const n = Number(m[1]);
26679
+ const unit = m[2] ?? "";
26680
+ if (n === 0) return 0;
26681
+ if (unit === "px" || unit === "") return n;
26682
+ if (unit === "pt") return n * 1.333;
26683
+ if (unit === "em" || unit === "rem") return n * 16;
26684
+ return null;
26685
+ }
26686
+ function parseStyle(style) {
26687
+ const out = /* @__PURE__ */ new Map();
26688
+ for (const part of style.split(";")) {
26689
+ const i = part.indexOf(":");
26690
+ if (i < 1) continue;
26691
+ out.set(part.slice(0, i).trim().toLowerCase(), part.slice(i + 1).trim().replace(/\s*!important$/i, ""));
26692
+ }
26693
+ return out;
26694
+ }
26695
+ function hidingMethod(style) {
26696
+ const css = parseStyle(style);
26697
+ if (css.get("display")?.toLowerCase() === "none") return "display-none";
26698
+ if (css.get("visibility")?.toLowerCase() === "hidden") return "visibility-hidden";
26699
+ const opacity = css.get("opacity");
26700
+ if (opacity !== void 0 && /^0*\.?0+%?$/.test(opacity.trim())) return "opacity-zero";
26701
+ const size = css.get("font-size");
26702
+ if (size !== void 0) {
26703
+ const n = px(size);
26704
+ if (n !== null && n <= 2) return "font-size";
26705
+ }
26706
+ for (const key of ["left", "top", "right", "bottom", "text-indent", "margin-left"]) {
26707
+ const v = css.get(key);
26708
+ if (v !== void 0) {
26709
+ const n = px(v);
26710
+ if (n !== null && n <= -999) return "off-screen";
26711
+ }
26712
+ }
26713
+ const w = css.get("width");
26714
+ const h = css.get("height");
26715
+ const clipped = /^(hidden|clip)$/i.test(css.get("overflow") ?? "");
26716
+ if (clipped && (w !== void 0 && px(w) === 0 || h !== void 0 && px(h) === 0)) return "zero-box";
26717
+ const colour = css.get("color");
26718
+ if (colour !== void 0) {
26719
+ const c = parseColour(colour);
26720
+ if (c) {
26721
+ const bg = parseColour(css.get("background-color") ?? css.get("background") ?? "");
26722
+ if (bg ? distance(c, bg) <= 8 : distance(c, [255, 255, 255]) <= 5) return "colour";
26723
+ }
26724
+ }
26725
+ return null;
26726
+ }
26727
+ var OPEN_TAG = /<([a-zA-Z][a-zA-Z0-9-]*)\b([^<>]*?)\bstyle\s*=\s*(?:"([^"]*)"|'([^']*)')[^<>]*>/g;
26728
+ function plainElementText(html) {
26729
+ return html.replace(/<[^>]*>/g, " ").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/\s+/g, " ").trim();
26730
+ }
26731
+ function findHiddenText(text) {
26732
+ const out = [];
26733
+ OPEN_TAG.lastIndex = 0;
26734
+ let lastEnd = -1;
26735
+ let m;
26736
+ while ((m = OPEN_TAG.exec(text)) !== null) {
26737
+ const name = m[1].toLowerCase();
26738
+ if (VOID_TAGS.has(name) || m.index < lastEnd) continue;
26739
+ const method = hidingMethod(m[3] ?? m[4] ?? "");
26740
+ if (method === null) continue;
26741
+ const start = m.index + m[0].length;
26742
+ const window = text.slice(start, start + MAX_HIDDEN_ELEMENT);
26743
+ const close = window.toLowerCase().indexOf(`</${name}`);
26744
+ const inner = close === -1 ? window : window.slice(0, close);
26745
+ const body = plainElementText(inner);
26746
+ if (!addressesAi(body)) continue;
26747
+ const end = start + inner.length;
26748
+ out.push({ index: m.index, length: end - m.index, method, text: body });
26749
+ lastEnd = end;
26750
+ }
26751
+ return out;
26752
+ }
26753
+
26754
+ // ../core/src/scanner/signature-engine.ts
26755
+ init_severity_paths();
26756
+
26574
26757
  // ../core/src/known-packages.ts
26575
26758
  var KNOWN_MCP_PACKAGES = [
26576
26759
  "@modelcontextprotocol/server-filesystem",
@@ -26733,7 +26916,7 @@ var EXEC_KEYS = /* @__PURE__ */ new Set([
26733
26916
  ]);
26734
26917
  var KEY_AT_LINE_START = /^\s*[{[,]?\s*(?:-\s*)?["']?([A-Za-z0-9_.-]+)["']?\s*:/;
26735
26918
  var KEY_ON_LINE = /(?:["']([A-Za-z0-9_.-]+)["']|(?:^|[\s{,[-])([A-Za-z0-9_.-]+))\s*:(?=\s|["'[{|>]|$)/g;
26736
- var IMPERATIVE_BEFORE = /\b(?:run|execute|exec|paste|type|enter|invoke)\b\W{0,3}$/i;
26919
+ var IMPERATIVE_BEFORE = /(?<![.\w$])\b(?:run|execute|exec|paste|type|enter|invoke)\b[^\w(]{0,3}$/i;
26737
26920
  var normKey = (k) => k.toLowerCase().replace(/[-_]/g, "");
26738
26921
  function inExecContext(rel, text, at, match = "") {
26739
26922
  if (AGENT_ENV_PATH.test(rel)) return true;
@@ -26741,6 +26924,10 @@ function inExecContext(rel, text, at, match = "") {
26741
26924
  const lineStart = text.lastIndexOf("\n", at - 1) + 1;
26742
26925
  const before = text.slice(lineStart, at);
26743
26926
  if (IMPERATIVE_BEFORE.test(before.slice(-40))) return true;
26927
+ if (/\.json$/i.test(rel)) {
26928
+ const j = jsonKeyAt(text, at);
26929
+ if (j.inString && j.key !== null) return EXEC_KEYS.has(normKey(j.key));
26930
+ }
26744
26931
  const keys = [...before.matchAll(KEY_ON_LINE)];
26745
26932
  const own = keys[keys.length - 1];
26746
26933
  if (own) return EXEC_KEYS.has(normKey(own[1] ?? own[2] ?? ""));
@@ -26811,6 +26998,81 @@ function decodeBlob(s) {
26811
26998
  if (/[^A-Za-z0-9+/]/.test(b)) return null;
26812
26999
  return Buffer.from(b, "base64").toString("utf8");
26813
27000
  }
27001
+ var jsonCache = null;
27002
+ function jsonStrings(text) {
27003
+ if (jsonCache && jsonCache.text === text) return jsonCache.strings;
27004
+ const strings2 = [];
27005
+ const stack = [];
27006
+ let i = 0;
27007
+ while (i < text.length) {
27008
+ const c = text[i];
27009
+ if (c === '"') {
27010
+ let j = i + 1;
27011
+ while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
27012
+ let k = j + 1;
27013
+ while (k < text.length && /\s/.test(text[k] ?? "")) k++;
27014
+ const top = stack[stack.length - 1];
27015
+ if (top && top.kind === "{" && text[k] === ":") {
27016
+ try {
27017
+ top.key = JSON.parse(text.slice(i, j + 1));
27018
+ } catch {
27019
+ top.key = text.slice(i + 1, j);
27020
+ }
27021
+ } else {
27022
+ strings2.push({ start: i, end: j, key: top ? top.key : null });
27023
+ }
27024
+ i = j + 1;
27025
+ continue;
27026
+ }
27027
+ if (c === "{" || c === "[") {
27028
+ const top = stack[stack.length - 1];
27029
+ stack.push({ kind: c, key: c === "[" ? top ? top.key : null : null });
27030
+ } else if (c === "}" || c === "]") {
27031
+ stack.pop();
27032
+ } else if (c === ",") {
27033
+ const top = stack[stack.length - 1];
27034
+ if (top && top.kind === "{") top.key = null;
27035
+ }
27036
+ i++;
27037
+ }
27038
+ jsonCache = { text, strings: strings2 };
27039
+ return strings2;
27040
+ }
27041
+ function jsonKeyAt(text, at) {
27042
+ const strings2 = jsonStrings(text);
27043
+ let lo = 0;
27044
+ let hi = strings2.length - 1;
27045
+ while (lo <= hi) {
27046
+ const mid = lo + hi >> 1;
27047
+ const s = strings2[mid];
27048
+ if (!s) break;
27049
+ if (at < s.start) hi = mid - 1;
27050
+ else if (at > s.end) lo = mid + 1;
27051
+ else return { inString: true, key: s.key };
27052
+ }
27053
+ return { inString: false, key: null };
27054
+ }
27055
+ function isNegated(text, index, cues) {
27056
+ const prefix = text.slice(Math.max(0, index - 200), index);
27057
+ let cut = prefix.lastIndexOf("\n") + 1;
27058
+ for (const m of prefix.matchAll(/[.!?;](?=\s)/g)) cut = Math.max(cut, (m.index ?? 0) + 1);
27059
+ return cues.test(prefix.slice(cut));
27060
+ }
27061
+ var COMMAND_LIKE = /(https?:\/\/|\bcurl\b|\bwget\b|\|\s*(ba|z)?sh\b|powershell|\$\(|`)/i;
27062
+ var SQL_START = /^\s*(?:--[^\n]*\n\s*)*(?:select\s|insert\s+into\s|update\s+\S+\s+set\s|delete\s+from\s|create\s+(?:or\s+alter\s+)?(?:table|view|procedure|function|database|schema|index)\b|alter\s+table\b|with\s+\w+\s+as\s*\(|declare\s+@|merge\s+into\s)/i;
27063
+ var KQL_START = /^\s*(?:\/\/[^\n]*\n\s*)*(?:\.(?:create|alter|set|append|drop|show)\b|let\s+\w+\s*=|[A-Za-z_][\w.]*\s*\r?\n\s*\|\s*(?:where|project|summarize|extend|take|limit|join|order|sort|count|distinct|top|render|parse|mv-expand)\b)/i;
27064
+ var TMDL_START = /^\s*(?:table|model|namespace|culture|cultureInfo|relationship|expression|database)\b[^\n]*\r?\n\s+[A-Za-z]+\s*[:=]/;
27065
+ var MINISIGN = /^untrusted comment:/;
27066
+ var DECLARED_PAYLOAD = /"payloadType"\s*:\s*"InlineBase64"/i;
27067
+ function benignPayloadKind(decoded, around) {
27068
+ if (MINISIGN.test(decoded)) return "minisign key or signature";
27069
+ if (COMMAND_LIKE.test(decoded)) return null;
27070
+ if (SQL_START.test(decoded)) return "SQL script";
27071
+ if (KQL_START.test(decoded)) return "KQL script";
27072
+ if (TMDL_START.test(decoded)) return "semantic model definition";
27073
+ if (DECLARED_PAYLOAD.test(around)) return "declared InlineBase64 payload";
27074
+ return null;
27075
+ }
26814
27076
 
26815
27077
  // ../core/src/scanner/signature-engine.ts
26816
27078
  var MAX_SPAN = 120;
@@ -26864,13 +27126,42 @@ function locateJsonValue(original, value, occurrence = 0) {
26864
27126
  if (idx === -1) return { line: 1, col: 1 };
26865
27127
  return offsetToPosition(original, idx);
26866
27128
  }
27129
+ var OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set([
27130
+ "--python",
27131
+ "--python-preference",
27132
+ "--with",
27133
+ "--with-editable",
27134
+ "--with-requirements",
27135
+ "--index",
27136
+ "--index-url",
27137
+ "--extra-index-url",
27138
+ "--default-index",
27139
+ "--directory",
27140
+ "--env-file",
27141
+ "--constraints",
27142
+ "--overrides",
27143
+ "--registry",
27144
+ "--cache",
27145
+ "--cache-dir",
27146
+ "--userconfig"
27147
+ ]);
27148
+ var PYTHON_VERSION = /^(?:(?:cpython|pypy)[-@]?)?\d+(?:\.\d+){0,2}(?:t|-[a-z0-9_.-]+)?$/i;
26867
27149
  function packageArg(args) {
26868
27150
  for (let i = 0; i < args.length; i++) {
26869
27151
  const a = args[i];
26870
27152
  if (typeof a !== "string") return null;
26871
27153
  if (a === "--package" || a === "-p" || a === "--from") {
26872
27154
  const v = args[i + 1];
26873
- return typeof v === "string" ? v : null;
27155
+ if (typeof v !== "string") return null;
27156
+ if (a === "-p" && PYTHON_VERSION.test(v)) {
27157
+ i++;
27158
+ continue;
27159
+ }
27160
+ return v;
27161
+ }
27162
+ if (OPTIONS_WITH_VALUE.has(a)) {
27163
+ i++;
27164
+ continue;
26874
27165
  }
26875
27166
  const eq = /^--(?:package|from)=(.+)$/.exec(a);
26876
27167
  if (eq) return eq[1] ?? null;
@@ -26894,13 +27185,13 @@ function isHexText(s) {
26894
27185
  }
26895
27186
  function looksLikeText(bytes) {
26896
27187
  if (bytes.length < 24) return false;
26897
- let printable2 = 0;
26898
- for (const b of bytes) if (b >= 32 && b < 127 || b === 10 || b === 13 || b === 9) printable2++;
26899
- if (printable2 / bytes.length < 0.95) return false;
27188
+ let printable3 = 0;
27189
+ for (const b of bytes) if (b >= 32 && b < 127 || b === 10 || b === 13 || b === 9) printable3++;
27190
+ if (printable3 / bytes.length < 0.95) return false;
26900
27191
  const text = bytes.toString("latin1");
26901
27192
  if (/^\s*[{[]/.test(text)) return false;
26902
27193
  const words2 = text.split(/\s+/).filter((w) => /[A-Za-z]{2,}/.test(w)).length;
26903
- return words2 >= 4 || /(https?:\/\/|\bcurl\b|\bwget\b|\|\s*(ba|z)?sh\b|powershell|\$\(|`)/i.test(text);
27194
+ return words2 >= 4 || COMMAND_LIKE.test(text);
26904
27195
  }
26905
27196
  function rawMatches(re2, text) {
26906
27197
  const out = [];
@@ -26938,11 +27229,13 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
26938
27229
  const active = [];
26939
27230
  const jobs = [];
26940
27231
  const vis = norm.visible;
27232
+ const lowered = /* @__PURE__ */ new Set();
26941
27233
  const ctx2 = makeContext(file, norm, defs, limitMs);
26942
27234
  for (const def of defs) {
26943
27235
  if (def.enabled === false) continue;
26944
27236
  if (!def.applies_to.includes(file.role)) continue;
26945
27237
  if (def.skip_paths?.some((p) => getRegex(p, "i").test(file.rel))) continue;
27238
+ if (lowersSeverity(def, file.rel, file.role)) lowered.add(def.id);
26946
27239
  const { match } = def;
26947
27240
  if (match.analysis) continue;
26948
27241
  if (match.file_regex && file.role === "config" && !getRegex(match.file_regex, "i").test(norm.plain)) continue;
@@ -27025,10 +27318,18 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
27025
27318
  findings.push(...capPerFile(def, mineOut));
27026
27319
  }
27027
27320
  }
27321
+ if (match.hidden_text) {
27322
+ for (const h of findHiddenText(norm.plain)) {
27323
+ if (!ctx2.allows(def, h.text, h.index, norm.plain, h.index)) continue;
27324
+ const { line, col } = offsetToPosition(norm.original, norm.plainMap?.[h.index] ?? h.index);
27325
+ findings.push({ ...base, line, col, span: truncateSpan(h.text) });
27326
+ }
27327
+ }
27028
27328
  if (match.unicode_class && match.unicode_class.length > 0) {
27029
27329
  let run = [];
27030
27330
  const mineStart = findings.length;
27031
27331
  let minorRuns = 0;
27332
+ const guards = /* @__PURE__ */ new Set();
27032
27333
  let decodedRuns = 0;
27033
27334
  const flush = () => {
27034
27335
  const first = run[0];
@@ -27040,11 +27341,15 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
27040
27341
  const { line, col } = offsetToPosition(norm.original, first.offset);
27041
27342
  const minor = match.minor_run;
27042
27343
  const isMinor = Boolean(minor && run.length <= minor.max_length && run.every((h) => minor.classes.includes(h.class)));
27043
- if (isMinor) minorRuns++;
27044
- const severity = isMinor && minor ? minor.severity : base.severity;
27344
+ const guard = match.mention_guard;
27345
+ const isGuard = Boolean(guard && run.length === 1 && first.codePoint === 8203 && norm.original[first.offset - 1] === "@" && /[A-Za-z0-9_]/.test(norm.original[first.offset + 1] ?? ""));
27346
+ if (isMinor && !isGuard) minorRuns++;
27347
+ const severity = isGuard && guard ? guard.severity : isMinor && minor ? minor.severity : base.severity;
27045
27348
  const decoded = decodedRuns < MAX_HIDDEN_RUNS ? decodedForRun(run) : void 0;
27046
27349
  if (decoded !== void 0) decodedRuns += 1;
27047
- findings.push({ ...base, severity, line, col, span: joinEscapes(run), ...decoded !== void 0 ? { decoded } : {} });
27350
+ const out2 = { ...base, severity, line, col, span: joinEscapes(run), ...decoded !== void 0 ? { decoded } : {} };
27351
+ if (isGuard) guards.add(out2);
27352
+ findings.push(out2);
27048
27353
  run = [];
27049
27354
  };
27050
27355
  for (const hit of norm.hiddenUnicode) {
@@ -27060,7 +27365,7 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
27060
27365
  if (minorRuns >= MINOR_RUNS_ESCALATE) {
27061
27366
  for (let i = mineStart; i < findings.length; i++) {
27062
27367
  const f = findings[i];
27063
- if (f && f.ruleId === def.id) findings[i] = { ...f, severity: base.severity };
27368
+ if (f && f.ruleId === def.id && !guards.has(f)) findings[i] = { ...f, severity: base.severity };
27064
27369
  }
27065
27370
  }
27066
27371
  }
@@ -27103,7 +27408,8 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
27103
27408
  }
27104
27409
  }
27105
27410
  }
27106
- return sameLineGroups(findings, defs);
27411
+ const out = lowered.size === 0 ? findings : findings.map((f) => lowered.has(f.ruleId) ? { ...f, severity: "low" } : f);
27412
+ return sameLineGroups(out, defs);
27107
27413
  }
27108
27414
  var SEVERITY_RANK = { critical: 4, high: 3, medium: 2, low: 1 };
27109
27415
  function sameLineGroups(findings, defs) {
@@ -27155,7 +27461,11 @@ function makeContext(file, norm, defs, limitMs) {
27155
27461
  let fences = null;
27156
27462
  let rescan = null;
27157
27463
  const rescanRules = (self) => {
27158
- rescan ??= defs.filter((d) => d.enabled !== false && d.id !== self.id && d.match.regex && !d.match.merge_adjacent && (d.applies_to.includes("instruction") || d.applies_to.includes("hook"))).map((d) => ({ re: getRegex(d.match.regex, "gi"), cues: d.match.quoted_example_cues ? getRegex(d.match.quoted_example_cues, "i") : null }));
27464
+ rescan ??= defs.filter((d) => d.enabled !== false && d.id !== self.id && d.match.regex && !d.match.merge_adjacent && (d.applies_to.includes("instruction") || d.applies_to.includes("hook"))).map((d) => ({
27465
+ re: getRegex(d.match.regex, "gi"),
27466
+ cues: d.match.quoted_example_cues ? getRegex(d.match.quoted_example_cues, "i") : null,
27467
+ neg: d.match.negated_cues ? getRegex(d.match.negated_cues, "i") : null
27468
+ }));
27159
27469
  return rescan;
27160
27470
  };
27161
27471
  return {
@@ -27169,6 +27479,7 @@ function makeContext(file, norm, defs, limitMs) {
27169
27479
  if (inMarkdownCode(norm.plain, at, fences)) return false;
27170
27480
  }
27171
27481
  if (m.quoted_example_cues && isQuotedExample(src, index, text.length, getRegex(m.quoted_example_cues, "i"))) return false;
27482
+ if (m.negated_cues && isNegated(src, index, getRegex(m.negated_cues, "i"))) return false;
27172
27483
  return true;
27173
27484
  },
27174
27485
  /**
@@ -27186,7 +27497,9 @@ function makeContext(file, norm, defs, limitMs) {
27186
27497
  if (piece === void 0) return false;
27187
27498
  if (m.validate !== "base64-text" && m.validate !== "encoded-text") return true;
27188
27499
  const decoded = decodeBlob(merged) ?? decodeBlob(piece) ?? "";
27189
- if (embeddedDocumentKind(decoded) === null) return true;
27500
+ const first = group[0];
27501
+ const around = first ? norm.plain.slice(Math.max(0, first.at - 300), first.at + merged.length + 300) : "";
27502
+ if (embeddedDocumentKind(decoded) === null && benignPayloadKind(decoded, around) === null) return true;
27190
27503
  const sample = decoded.slice(0, 2e5);
27191
27504
  if (m.decoded_flag_regex && getRegex(m.decoded_flag_regex, "i").test(sample)) return true;
27192
27505
  const rules = rescanRules(def);
@@ -27194,12 +27507,512 @@ function makeContext(file, norm, defs, limitMs) {
27194
27507
  if (hits === null) return true;
27195
27508
  return hits.some((h, i) => h.some(([index, t]) => {
27196
27509
  const cues = rules[i]?.cues;
27197
- return !cues || !isQuotedExample(sample, index, t.length, cues);
27510
+ const neg = rules[i]?.neg;
27511
+ return (!cues || !isQuotedExample(sample, index, t.length, cues)) && (!neg || !isNegated(sample, index, neg));
27198
27512
  }));
27199
27513
  }
27200
27514
  };
27201
27515
  }
27202
27516
 
27517
+ // ../core/src/scanner/scan-text.ts
27518
+ function scanText(text, role, defs, label = "(text)", limitMs = REGEX_TIME_LIMIT_MS) {
27519
+ const file = { path: label, rel: label, role, sizeBytes: text.length };
27520
+ return runSignatures(file, normalize(text, role), defs, limitMs);
27521
+ }
27522
+
27523
+ // ../core/src/source-tools.ts
27524
+ var MAX_SITES = 100;
27525
+ var MAX_AHEAD = 2e4;
27526
+ var TS_EXT = [".ts", ".tsx", ".js", ".mjs", ".cjs", ".mts"];
27527
+ function languageOf(relPath) {
27528
+ const lower = String(relPath).toLowerCase();
27529
+ if (TS_EXT.some((e) => lower.endsWith(e))) return "ts";
27530
+ if (lower.endsWith(".py")) return "py";
27531
+ if (lower.endsWith(".go")) return "go";
27532
+ return null;
27533
+ }
27534
+ var isIdent = (c) => c !== void 0 && (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c >= "0" && c <= "9" || c === "_" || c === "$");
27535
+ var isHex = (s) => s.length > 0 && [...s].every((c) => c >= "0" && c <= "9" || c >= "a" && c <= "f" || c >= "A" && c <= "F");
27536
+ var isQuote = (c) => c === '"' || c === "'" || c === "`";
27537
+ function fromCode(code) {
27538
+ if (!Number.isInteger(code) || code < 0 || code > 1114111) return null;
27539
+ return String.fromCodePoint(code);
27540
+ }
27541
+ function readEscape(text, i, lang, limit) {
27542
+ const n = text[i + 1];
27543
+ if (n === void 0 || i + 1 >= limit) return null;
27544
+ if (n === "\n") return { out: "", len: 2 };
27545
+ if (n === "\r") return { out: "", len: text[i + 2] === "\n" ? 3 : 2 };
27546
+ const simple = { n: "\n", t: " ", r: "\r", b: "\b", f: "\f", v: "\v", a: "\x07" };
27547
+ if (n === "u" && text[i + 2] === "{" && lang === "ts") {
27548
+ const close = text.indexOf("}", i + 3);
27549
+ const hex = close === -1 || close - i > 12 ? "" : text.slice(i + 3, close);
27550
+ const ch = isHex(hex) ? fromCode(parseInt(hex, 16)) : null;
27551
+ return ch === null ? null : { out: ch, len: close - i + 1 };
27552
+ }
27553
+ const widths = { x: 2, u: 4 };
27554
+ const w = n === "U" && lang !== "ts" ? 8 : widths[n];
27555
+ if (w !== void 0) {
27556
+ const hex = text.slice(i + 2, i + 2 + w);
27557
+ const ch = hex.length === w && isHex(hex) ? fromCode(parseInt(hex, 16)) : null;
27558
+ return ch === null ? { out: lang === "py" ? `\\${n}` : n, len: 2 } : { out: ch, len: 2 + w };
27559
+ }
27560
+ if (lang === "go" && n >= "0" && n <= "7") {
27561
+ const oct = text.slice(i + 1, i + 4);
27562
+ if (oct.length === 3 && [...oct].every((c) => c >= "0" && c <= "7")) return { out: String.fromCharCode(parseInt(oct, 8)), len: 4 };
27563
+ }
27564
+ const s = simple[n];
27565
+ if (s !== void 0) return { out: s, len: 2 };
27566
+ if (n === "0" && lang !== "go") return { out: "\0", len: 2 };
27567
+ return { out: lang === "py" && n !== "\\" && n !== '"' && n !== "'" ? `\\${n}` : n, len: 2 };
27568
+ }
27569
+ function readLiteral(text, q, lang, limit, raw = false) {
27570
+ const quote = text[q];
27571
+ if (!isQuote(quote) || quote === void 0) return null;
27572
+ if (quote === "`" && lang === "py") return null;
27573
+ if (quote === "'" && lang === "go") return null;
27574
+ const triple = lang === "py" && text[q + 1] === quote && text[q + 2] === quote;
27575
+ const open3 = triple ? 3 : 1;
27576
+ const goRaw = lang === "go" && quote === "`";
27577
+ const start = q + open3;
27578
+ let value = "";
27579
+ const map2 = [];
27580
+ const push2 = (s, at) => {
27581
+ for (let k = 0; k < s.length; k++) {
27582
+ value += s[k];
27583
+ map2.push(at);
27584
+ }
27585
+ };
27586
+ let i = start;
27587
+ while (i < limit) {
27588
+ const c = text[i];
27589
+ if (c === void 0) return null;
27590
+ if (triple ? c === quote && text[i + 1] === quote && text[i + 2] === quote : c === quote) {
27591
+ map2.push(i);
27592
+ return { value, map: map2, start, contentEnd: i, next: i + open3 };
27593
+ }
27594
+ if (c === "\n" && !triple && !goRaw && quote !== "`") return null;
27595
+ if (lang === "ts" && quote === "`" && c === "$" && text[i + 1] === "{") return null;
27596
+ if (c === "\\" && !goRaw && !raw) {
27597
+ const e = readEscape(text, i, lang, limit);
27598
+ if (e === null) return null;
27599
+ push2(e.out, i);
27600
+ i += e.len;
27601
+ continue;
27602
+ }
27603
+ push2(c, i);
27604
+ i++;
27605
+ }
27606
+ return null;
27607
+ }
27608
+ function skipQuoted(text, q, lang, limit) {
27609
+ const quote = text[q];
27610
+ if (quote === void 0) return -1;
27611
+ const triple = lang === "py" && text[q + 1] === quote && text[q + 2] === quote;
27612
+ let i = q + (triple ? 3 : 1);
27613
+ while (i < limit) {
27614
+ const c = text[i];
27615
+ if (c === "\\" && !(lang === "go" && quote === "`")) {
27616
+ i += 2;
27617
+ continue;
27618
+ }
27619
+ if (triple ? c === quote && text[i + 1] === quote && text[i + 2] === quote : c === quote) return i + (triple ? 3 : 1);
27620
+ if (c === "\n" && !triple && quote !== "`") return -1;
27621
+ i++;
27622
+ }
27623
+ return -1;
27624
+ }
27625
+ function readPyString(text, p, limit) {
27626
+ let i = p;
27627
+ let raw = false;
27628
+ while (i < p + 2 && "rRuUbBfF".includes(text[i] ?? "#")) {
27629
+ if (text[i] === "r" || text[i] === "R") raw = true;
27630
+ i++;
27631
+ }
27632
+ return readLiteral(text, i, "py", limit, raw);
27633
+ }
27634
+ function skipTrivia(text, p, lang, limit) {
27635
+ let i = p;
27636
+ while (i < limit) {
27637
+ const c = text[i];
27638
+ if (c === " " || c === " " || c === "\n" || c === "\r") {
27639
+ i++;
27640
+ continue;
27641
+ }
27642
+ if (lang === "py" && c === "#") {
27643
+ i = lineEnd(text, i);
27644
+ continue;
27645
+ }
27646
+ if (lang !== "py" && c === "/" && text[i + 1] === "/") {
27647
+ i = lineEnd(text, i);
27648
+ continue;
27649
+ }
27650
+ if (lang !== "py" && c === "/" && text[i + 1] === "*") {
27651
+ const close = text.indexOf("*/", i + 2);
27652
+ if (close === -1 || close >= limit) return limit;
27653
+ i = close + 2;
27654
+ continue;
27655
+ }
27656
+ break;
27657
+ }
27658
+ return i;
27659
+ }
27660
+ function lineEnd(text, i) {
27661
+ const nl = text.indexOf("\n", i);
27662
+ return nl === -1 ? text.length : nl + 1;
27663
+ }
27664
+ function skipArgument(text, p, lang, limit) {
27665
+ let depth = 0;
27666
+ let i = p;
27667
+ while (i < limit) {
27668
+ const c = text[i];
27669
+ if (isQuote(c)) {
27670
+ const j = skipQuoted(text, i, lang, limit);
27671
+ if (j < 0) return -1;
27672
+ i = j;
27673
+ continue;
27674
+ }
27675
+ if (lang === "py" && c === "#" || lang !== "py" && c === "/" && (text[i + 1] === "/" || text[i + 1] === "*")) {
27676
+ const j = skipTrivia(text, i, lang, limit);
27677
+ i = j > i ? j : i + 1;
27678
+ continue;
27679
+ }
27680
+ if (c === "(" || c === "[" || c === "{") depth++;
27681
+ else if (c === ")" || c === "]" || c === "}") {
27682
+ if (depth === 0) return i;
27683
+ depth--;
27684
+ } else if (c === "," && depth === 0) return i;
27685
+ i++;
27686
+ }
27687
+ return -1;
27688
+ }
27689
+ function findKeyString(text, open3, lang, limit, sep2) {
27690
+ let depth = 0;
27691
+ let i = open3;
27692
+ let lit = null;
27693
+ const valueAt = (p) => {
27694
+ const v = skipTrivia(text, p, lang, limit);
27695
+ return lang === "py" ? readPyString(text, v, limit) : readLiteral(text, v, lang, limit);
27696
+ };
27697
+ const sepAt = (p) => {
27698
+ const j = skipTrivia(text, p, lang, limit);
27699
+ if (text[j] !== sep2 || sep2 === "=" && text[j + 1] === "=") return -1;
27700
+ return j + 1;
27701
+ };
27702
+ while (i < limit) {
27703
+ const c = text[i];
27704
+ if (c === void 0) break;
27705
+ if (isQuote(c)) {
27706
+ const l = lang === "ts" && depth === 1 ? readLiteral(text, i, lang, limit) : null;
27707
+ if (l && l.value === "description" && lit === null) {
27708
+ const s = sepAt(l.next);
27709
+ if (s >= 0) lit = valueAt(s);
27710
+ }
27711
+ const j = l ? l.next : skipQuoted(text, i, lang, limit);
27712
+ if (j < 0) return { lit, after: -1 };
27713
+ i = j;
27714
+ continue;
27715
+ }
27716
+ if (lang === "py" && c === "#" || lang !== "py" && c === "/" && (text[i + 1] === "/" || text[i + 1] === "*")) {
27717
+ const j = skipTrivia(text, i, lang, limit);
27718
+ i = j > i ? j : i + 1;
27719
+ continue;
27720
+ }
27721
+ if (c === "(" || c === "[" || c === "{") depth++;
27722
+ else if (c === ")" || c === "]" || c === "}") {
27723
+ depth--;
27724
+ if (depth <= 0) return { lit, after: i + 1 };
27725
+ } else if (depth === 1 && isIdent(c) && !isIdent(text[i - 1]) && text[i - 1] !== ".") {
27726
+ let j = i;
27727
+ while (j < limit && isIdent(text[j])) j++;
27728
+ if (j - i === "description".length && text.startsWith("description", i) && lit === null) {
27729
+ const s = sepAt(j);
27730
+ if (s >= 0) lit = valueAt(s);
27731
+ }
27732
+ i = j;
27733
+ continue;
27734
+ }
27735
+ i++;
27736
+ }
27737
+ return { lit, after: -1 };
27738
+ }
27739
+ var toFound = (l) => ({ text: l.value, offset: l.start, end: l.contentEnd, map: l.map });
27740
+ function indexesOf(text, needle, budget) {
27741
+ const out = [];
27742
+ let from = 0;
27743
+ while (budget.left > 0) {
27744
+ const i = text.indexOf(needle, from);
27745
+ if (i === -1) break;
27746
+ out.push(i);
27747
+ budget.left--;
27748
+ from = i + needle.length;
27749
+ }
27750
+ return out;
27751
+ }
27752
+ var lim = (text, from) => Math.min(text.length, from + MAX_AHEAD);
27753
+ function extractTs(text, budget, out) {
27754
+ for (const at of indexesOf(text, ".tool(", budget)) {
27755
+ const limit = lim(text, at);
27756
+ const first = skipTrivia(text, at + 6, "ts", limit);
27757
+ const e = skipArgument(text, first, "ts", limit);
27758
+ if (e < 0 || text[e] !== ",") continue;
27759
+ const p = skipTrivia(text, e + 1, "ts", limit);
27760
+ const l = isQuote(text[p]) ? readLiteral(text, p, "ts", limit) : null;
27761
+ if (l) out.push(toFound(l));
27762
+ }
27763
+ for (const needle of ["registerTool(", "registerTool<"]) {
27764
+ for (const at of indexesOf(text, needle, budget)) {
27765
+ const limit = lim(text, at);
27766
+ let paren = at + needle.length - 1;
27767
+ if (needle.endsWith("<")) {
27768
+ paren = text.indexOf("(", at + needle.length);
27769
+ if (paren === -1 || paren > at + 300) continue;
27770
+ }
27771
+ const first = skipTrivia(text, paren + 1, "ts", limit);
27772
+ const e = skipArgument(text, first, "ts", limit);
27773
+ if (e < 0 || text[e] !== ",") continue;
27774
+ const p = skipTrivia(text, e + 1, "ts", limit);
27775
+ if (text[p] !== "{") continue;
27776
+ const { lit } = findKeyString(text, p, "ts", limit, ":");
27777
+ if (lit) out.push(toFound(lit));
27778
+ }
27779
+ }
27780
+ }
27781
+ function docstringAfter(text, from, limit) {
27782
+ let i = from;
27783
+ let def = -1;
27784
+ while (i < limit) {
27785
+ const nl = text.indexOf("\n", i);
27786
+ if (nl === -1 || nl + 1 >= limit) return null;
27787
+ let p2 = nl + 1;
27788
+ while (text[p2] === " " || text[p2] === " ") p2++;
27789
+ if (text.startsWith("def ", p2) || text.startsWith("async def ", p2)) {
27790
+ def = p2;
27791
+ break;
27792
+ }
27793
+ if (text.startsWith("class ", p2)) return null;
27794
+ i = nl + 1;
27795
+ }
27796
+ if (def < 0) return null;
27797
+ let depth = 0;
27798
+ let j = def;
27799
+ let colon = -1;
27800
+ while (j < limit) {
27801
+ const c = text[j];
27802
+ if (isQuote(c)) {
27803
+ const k = skipQuoted(text, j, "py", limit);
27804
+ if (k < 0) return null;
27805
+ j = k;
27806
+ continue;
27807
+ }
27808
+ if (c === "#") {
27809
+ j = lineEnd(text, j);
27810
+ continue;
27811
+ }
27812
+ if (c === "(" || c === "[" || c === "{") depth++;
27813
+ else if (c === ")" || c === "]" || c === "}") depth--;
27814
+ else if (c === ":" && depth === 0) {
27815
+ colon = j;
27816
+ break;
27817
+ }
27818
+ j++;
27819
+ }
27820
+ if (colon < 0) return null;
27821
+ const p = skipTrivia(text, colon + 1, "py", limit);
27822
+ return readPyString(text, p, limit);
27823
+ }
27824
+ function extractPy(text, budget, out) {
27825
+ for (const name of ["@mcp.tool", "@server.tool", "@app.tool"]) {
27826
+ for (const at of indexesOf(text, name, budget)) {
27827
+ let b = at - 1;
27828
+ while (b >= 0 && (text[b] === " " || text[b] === " ")) b--;
27829
+ if (b >= 0 && text[b] !== "\n") continue;
27830
+ const nameEnd = at + name.length;
27831
+ if (isIdent(text[nameEnd]) || text[nameEnd] === ".") continue;
27832
+ const limit = lim(text, at);
27833
+ let after = nameEnd;
27834
+ let lit = null;
27835
+ if (text[nameEnd] === "(") {
27836
+ const r = findKeyString(text, nameEnd, "py", limit, "=");
27837
+ lit = r.lit;
27838
+ if (r.after > 0) after = r.after;
27839
+ }
27840
+ lit ??= docstringAfter(text, after, limit);
27841
+ if (lit) out.push(toFound(lit));
27842
+ }
27843
+ }
27844
+ }
27845
+ function extractGo(text, budget, out) {
27846
+ for (const at of indexesOf(text, "WithDescription(", budget)) {
27847
+ if (isIdent(text[at - 1])) continue;
27848
+ const limit = lim(text, at);
27849
+ const p = skipTrivia(text, at + "WithDescription(".length, "go", limit);
27850
+ const l = text[p] === '"' || text[p] === "`" ? readLiteral(text, p, "go", limit) : null;
27851
+ if (l) out.push(toFound(l));
27852
+ }
27853
+ }
27854
+ function extract(text, lang) {
27855
+ const out = [];
27856
+ const budget = { left: MAX_SITES };
27857
+ if (lang === "ts") extractTs(text, budget, out);
27858
+ else if (lang === "py") extractPy(text, budget, out);
27859
+ else extractGo(text, budget, out);
27860
+ const seen = /* @__PURE__ */ new Set();
27861
+ return out.filter((f) => !seen.has(f.offset) && seen.add(f.offset)).sort((a, b) => a.offset - b.offset);
27862
+ }
27863
+ function positionOf(text, offset) {
27864
+ let line = 1;
27865
+ let lastNl = -1;
27866
+ let i = text.indexOf("\n");
27867
+ while (i !== -1 && i < offset) {
27868
+ line++;
27869
+ lastNl = i;
27870
+ i = text.indexOf("\n", i + 1);
27871
+ }
27872
+ return { line, col: offset - lastNl };
27873
+ }
27874
+ function indexOfLineCol(s, line, col) {
27875
+ let start = 0;
27876
+ for (let l = 1; l < line; l++) {
27877
+ const nl = s.indexOf("\n", start);
27878
+ if (nl === -1) return 0;
27879
+ start = nl + 1;
27880
+ }
27881
+ return start + col - 1;
27882
+ }
27883
+ var ORDER_HINT = /^(?:before using this tool|(?:prior to|before) (?:invoking|calling|running|using) (?:this|any|the))\b/i;
27884
+ var SENSITIVE_TARGET = /~\/\.ssh|id_rsa|\.env\b|\bcredentials?\b|\bprivate key\b|\bapi[ _-]?key\b|\btoken\b|\bpassword\b/i;
27885
+ var CONCEALMENT = /\b(?:do not|don't|dont) (?:tell|inform|mention|notify)\b|\bwithout (?:telling|informing|notifying|asking)\b|\b(?:secret|hidden|silently)\b/i;
27886
+ var SEND_VERB = /\b(?:send|upload|forward|exfiltrate|post|include|attach)(?:s|es|ed|ing)?\b/i;
27887
+ var URL_OR_HOST = /https?:\/\/|\bwww\.|\b[a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:com|net|org|io|dev|xyz|invalid|test|example)\b/i;
27888
+ var SENTENCE_WINDOW = 500;
27889
+ function sentenceAround(whole, from, to) {
27890
+ const isEnd = (i) => {
27891
+ const c = whole.charAt(i);
27892
+ if (c === "\n") return true;
27893
+ return (c === "." || c === "!" || c === "?") && (i + 1 >= whole.length || /\s/.test(whole.charAt(i + 1)));
27894
+ };
27895
+ let start = Math.min(from, whole.length);
27896
+ const lo = Math.max(0, start - SENTENCE_WINDOW);
27897
+ while (start > lo && !isEnd(start - 1)) start--;
27898
+ let end = Math.max(Math.min(to, whole.length), start);
27899
+ const hi = Math.min(whole.length, end + SENTENCE_WINDOW);
27900
+ while (end < hi && !isEnd(end)) end++;
27901
+ return whole.slice(start, end);
27902
+ }
27903
+ function isSuspiciousSentence(sentence) {
27904
+ if (CONCEALMENT.test(sentence) || SENSITIVE_TARGET.test(sentence)) return true;
27905
+ return SEND_VERB.test(sentence) && URL_OR_HOST.test(sentence);
27906
+ }
27907
+ function isQuietHint(span, whole, at) {
27908
+ return ORDER_HINT.test(span.trim()) && !isSuspiciousSentence(sentenceAround(whole, at, at + span.length));
27909
+ }
27910
+ function scanSourceTools(file, text, defs) {
27911
+ try {
27912
+ const def = defs.find((d) => d.id === "EX-005");
27913
+ const lang = languageOf(file.rel);
27914
+ if (!def || lang === null || typeof text !== "string") return [];
27915
+ const out = [];
27916
+ for (const s of extract(text, lang)) {
27917
+ for (const hit of scanText(s.text, "mcp-config", [def], file.rel)) {
27918
+ const idx = Math.min(Math.max(indexOfLineCol(s.text, hit.line, hit.col), 0), s.text.length);
27919
+ if (isQuietHint(hit.span, s.text, idx)) continue;
27920
+ const at = s.map[idx] ?? s.offset;
27921
+ out.push({ ...hit, file: file.rel, ...positionOf(text, at) });
27922
+ }
27923
+ }
27924
+ return out;
27925
+ } catch {
27926
+ return [];
27927
+ }
27928
+ }
27929
+
27930
+ // ../core/src/path-names.ts
27931
+ var MAX_PATH_SPAN = 120;
27932
+ var CONTROL = /[\u0000-\u001F\u007F-\u009F]/;
27933
+ var AI_NAMES = /* @__PURE__ */ new Set(["assistant", "agent", "ai", "claude", "kiro", "copilot", "llm"]);
27934
+ var FILLER = /* @__PURE__ */ new Set(["please", "now", "first", "then", "also", "always", "you", "must", "should", "to"]);
27935
+ var ACTION_VERBS = /* @__PURE__ */ new Set([
27936
+ "read",
27937
+ "send",
27938
+ "upload",
27939
+ "post",
27940
+ "email",
27941
+ "leak",
27942
+ "exfiltrate",
27943
+ "forward",
27944
+ "paste",
27945
+ "copy",
27946
+ "print",
27947
+ "cat",
27948
+ "run",
27949
+ "execute",
27950
+ "fetch",
27951
+ "curl",
27952
+ "download",
27953
+ "write",
27954
+ "edit",
27955
+ "delete",
27956
+ "reveal",
27957
+ "dump",
27958
+ "ignore",
27959
+ "disregard",
27960
+ "forget"
27961
+ ]);
27962
+ var SENSITIVE = /* @__PURE__ */ new Set([
27963
+ "env",
27964
+ "dotenv",
27965
+ "secret",
27966
+ "secrets",
27967
+ "credential",
27968
+ "credentials",
27969
+ "token",
27970
+ "tokens",
27971
+ "key",
27972
+ "keys",
27973
+ "ssh",
27974
+ "passwd",
27975
+ "password",
27976
+ "passwords",
27977
+ "apikey"
27978
+ ]);
27979
+ var OVERRIDE2 = /^(?:(?:please|now|first|you must|always) )?(?:ignore|disregard|forget|override) (?:all |any |the |your |every )?(?:previous|prior|above|earlier|preceding|system) (?:instructions?|rules|prompts?|context|guidelines|directives)\b/;
27980
+ function nameWords(name) {
27981
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[\s._+\-]+/).map((w) => w.toLowerCase()).filter((w) => w.length > 0);
27982
+ }
27983
+ function escapePathSpan(name) {
27984
+ let out = "";
27985
+ let count = 0;
27986
+ for (const ch of name) {
27987
+ const cp = ch.codePointAt(0) ?? 0;
27988
+ const shown = isHiddenCodePoint(cp) || CONTROL.test(ch) || cp === 8232 || cp === 8233 ? `[U+${cp.toString(16).toUpperCase().padStart(4, "0")}]` : ch;
27989
+ if (count >= MAX_PATH_SPAN) return `${out}\u2026`;
27990
+ out += shown;
27991
+ count++;
27992
+ }
27993
+ return out;
27994
+ }
27995
+ function readsAsInstruction(words2) {
27996
+ if (words2.length < 3) return false;
27997
+ if (OVERRIDE2.test(words2.join(" "))) return true;
27998
+ if (words2.length < 4) return false;
27999
+ const verbs = words2.filter((w) => ACTION_VERBS.has(w));
28000
+ const hasSensitive = words2.some((w) => SENSITIVE.has(w));
28001
+ const aiNamed = words2.some((w) => AI_NAMES.has(w));
28002
+ if (aiNamed && verbs.length >= 1 && hasSensitive) return true;
28003
+ const lead = words2.filter((w, i) => !(FILLER.has(w) && words2.slice(0, i).every((p) => FILLER.has(p))));
28004
+ const first = lead[0];
28005
+ return first !== void 0 && ACTION_VERBS.has(first) && verbs.length >= 2 && hasSensitive;
28006
+ }
28007
+ function checkPathSegment(name) {
28008
+ if (name.length === 0) return null;
28009
+ if (CONTROL.test(name) || findHiddenUnicode(name).length > 0) {
28010
+ return { kind: "hidden-chars", span: escapePathSpan(name) };
28011
+ }
28012
+ if (readsAsInstruction(nameWords(name))) return { kind: "instruction", span: escapePathSpan(name) };
28013
+ return null;
28014
+ }
28015
+
27203
28016
  // ../core/src/scanner/orchestrator.ts
27204
28017
  init_heuristic_engine();
27205
28018
 
@@ -27561,6 +28374,8 @@ init_zod();
27561
28374
  import { constants } from "node:fs";
27562
28375
  import { lstat, open as open2 } from "node:fs/promises";
27563
28376
  import { join as join6 } from "node:path";
28377
+ init_severity_paths();
28378
+ init_walker();
27564
28379
  var TRIFECTA_RULE_ID = "EX-023";
27565
28380
  var MAX_PINS_BYTES = 4e6;
27566
28381
  function stripJsonc(text) {
@@ -27761,6 +28576,8 @@ function trifectaFinding(config2, map2, defs) {
27761
28576
  if (!map2.trifecta || map2.severity === null) return null;
27762
28577
  const def = defs.find((d) => d.id === TRIFECTA_RULE_ID && d.enabled !== false && d.match.analysis === "trifecta");
27763
28578
  if (!def) return null;
28579
+ if (def.skip_paths?.some((p) => new RegExp(p, "i").test(config2.file))) return null;
28580
+ const lowered = lowersSeverity(def, config2.file, classifyFile(config2.file));
27764
28581
  const legs = CAPABILITIES.map((c) => `${LEG_WORDS[c]} ${map2.legs[c].join(", ")}`).join("; ");
27765
28582
  const auto = map2.ghosts.filter((g) => g.autoApproved && g.capabilities.length > 0).map((g) => g.name);
27766
28583
  const autoText = auto.length > 0 ? ` Tools on ${auto.join(", ")} are auto-approved, so nothing asks you first.` : "";
@@ -27768,7 +28585,7 @@ function trifectaFinding(config2, map2, defs) {
27768
28585
  source: "signature",
27769
28586
  ruleId: def.id,
27770
28587
  title: def.title,
27771
- severity: map2.severity,
28588
+ severity: lowered ? "low" : map2.severity,
27772
28589
  file: config2.file,
27773
28590
  line: config2.anchor.line,
27774
28591
  col: config2.anchor.col,
@@ -27827,6 +28644,34 @@ async function trifectaReport(root, configs, rules, defs) {
27827
28644
  });
27828
28645
  return { map: { configs: maps }, findings, notes: note ? [note] : [] };
27829
28646
  }
28647
+ async function* pathNameFindings(root, def) {
28648
+ const seen = /* @__PURE__ */ new Set();
28649
+ try {
28650
+ for await (const p of walkPaths(root)) {
28651
+ const segments = p.rel.split("/");
28652
+ for (let i = 0; i < segments.length; i++) {
28653
+ const prefix = segments.slice(0, i + 1).join("/");
28654
+ if (seen.has(prefix)) continue;
28655
+ seen.add(prefix);
28656
+ const hit = checkPathSegment(segments[i] ?? "");
28657
+ if (!hit) continue;
28658
+ yield {
28659
+ source: "signature",
28660
+ ruleId: def.id,
28661
+ title: def.title,
28662
+ severity: def.severity,
28663
+ file: prefix,
28664
+ line: 1,
28665
+ col: 1,
28666
+ span: hit.span,
28667
+ owasp: def.owasp,
28668
+ fix: def.fix
28669
+ };
28670
+ }
28671
+ }
28672
+ } catch {
28673
+ }
28674
+ }
27830
28675
  async function* scanRepo(root, options) {
27831
28676
  const defs = await loadDefinitions(options.definitionsDir);
27832
28677
  const canaries = loadCanariesFile(canariesPath(root));
@@ -27877,7 +28722,8 @@ async function* scanRepo(root, options) {
27877
28722
  const sigs = runSignatures(file, norm, defs);
27878
28723
  const heurs = options.bedrockClient ? await runHeuristics(file, norm, sigs, options.bedrockClient) : [];
27879
28724
  const traps = canaryFindings(text, file.rel, records, ex022);
27880
- let deduped = deduplicate([...sigs, ...heurs, ...traps]);
28725
+ const sourceTools = (file.role === "code" || file.role === "unknown") && languageOf(file.rel) !== null ? scanSourceTools(file, text, defs) : [];
28726
+ let deduped = deduplicate([...sigs, ...heurs, ...traps, ...sourceTools]);
27881
28727
  if (checkVault && deduped.length > 0 && file.rel.includes(".exorcist/vault/")) {
27882
28728
  const backup = checkVault(file.rel, await readFile3(file.path));
27883
28729
  if (backup) deduped = deduped.map((f) => asBackupFinding(f, backup));
@@ -27905,6 +28751,13 @@ async function* scanRepo(root, options) {
27905
28751
  yield { type: "error", file: "capabilities.yaml", message: capabilities.error };
27906
28752
  }
27907
28753
  }
28754
+ const ex029 = defs.find((d) => d.id === "EX-029" && d.enabled !== false && d.match.analysis === "path-names");
28755
+ if (ex029) {
28756
+ for await (const finding of pathNameFindings(root, ex029)) {
28757
+ findingsTotal++;
28758
+ yield { type: "finding", finding };
28759
+ }
28760
+ }
27908
28761
  yield {
27909
28762
  type: "done",
27910
28763
  stats: {
@@ -27916,14 +28769,58 @@ async function* scanRepo(root, options) {
27916
28769
  };
27917
28770
  }
27918
28771
 
27919
- // ../core/src/scanner/scan-text.ts
27920
- function scanText(text, role, defs, label = "(text)", limitMs = REGEX_TIME_LIMIT_MS) {
27921
- const file = { path: label, rel: label, role, sizeBytes: text.length };
27922
- return runSignatures(file, normalize(text, role), defs, limitMs);
28772
+ // ../core/src/reporters/json-reporter.ts
28773
+ init_zod();
28774
+
28775
+ // ../core/src/redact-secrets.ts
28776
+ var MIN_LENGTH_FOR_PREFIX = 16;
28777
+ var PREFIX_CHARS = 4;
28778
+ var TOKEN_KINDS = [
28779
+ { type: "github-token", re: /^(?:gh[pousr]_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{60,})$/ },
28780
+ { type: "anthropic-key", re: /^sk-ant-api\d\d-[A-Za-z0-9_-]{40,}$/ },
28781
+ { type: "openai-key", re: /^sk-(?:proj-)?[A-Za-z0-9_-]{40,}$/ },
28782
+ { type: "aws-access-key", re: /^AKIA[0-9A-Z]{16}$/ },
28783
+ { type: "slack-token", re: /^xox[baprs]-[0-9A-Za-z-]{20,}$/ },
28784
+ { type: "google-api-key", re: /^AIza[0-9A-Za-z_-]{35}$/ },
28785
+ { type: "stripe-key", re: /^sk_live_[0-9A-Za-z]{24,}$/ },
28786
+ { type: "npm-token", re: /^npm_[A-Za-z0-9]{36}$/ }
28787
+ ];
28788
+ var BARE_TOKEN = /\b(?:gh[pousr]_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{60,}|sk-(?:proj-|ant-api\d\d-)?[A-Za-z0-9_-]{40,}|AKIA[0-9A-Z]{16}|xox[baprs]-[0-9A-Za-z-]{20,}|AIza[0-9A-Za-z_-]{35}|sk_live_[0-9A-Za-z]{24,}|npm_[A-Za-z0-9]{36})\b/g;
28789
+ var PEM = ["PRIVATE", "KEY"].join(" ");
28790
+ var PRIVATE_KEY = new RegExp(
28791
+ `-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?${PEM}(?: BLOCK)?-----(?:[\\s\\S]*?-----END [A-Z ]*${PEM}(?: BLOCK)?-----|[\\s\\S]*$)`,
28792
+ "g"
28793
+ );
28794
+ var DATABASE_URL = /\b(DATABASE_URL=)([a-z+]+:\/\/[^\s:@/]+:[^\s@/]+@[^\s]+)/g;
28795
+ var SECRET_VARIABLE = /\b((?:AWS_SECRET_ACCESS_KEY|GITHUB_TOKEN|GH_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|SLACK_BOT_TOKEN|STRIPE_SECRET_KEY|GOOGLE_API_KEY|NPM_TOKEN)=)(?!EXAMPLE_|\[redacted )([^\s]+)/g;
28796
+ var PLACEHOLDER_VALUE = /^["']?(?:\[?redacted\]?|x{3,}|\*{3,}|<|\$\{?[A-Za-z_]+\}?|your[_-]|changeme|placeholder|dummy|fake)/i;
28797
+ function typeOfToken(value) {
28798
+ return TOKEN_KINDS.find((k) => k.re.test(value))?.type ?? "secret-variable";
28799
+ }
28800
+ function redactionMarker(type2, secret) {
28801
+ const head = secret.length >= MIN_LENGTH_FOR_PREFIX ? `${secret.slice(0, PREFIX_CHARS)}\u2026, ` : "";
28802
+ return `[redacted ${type2}: ${head}${secret.length} chars]`;
28803
+ }
28804
+ function redactSecretText(text) {
28805
+ if (text.length === 0) return text;
28806
+ let out = text.replace(PRIVATE_KEY, (m) => `[redacted private-key: ${m.length} chars]`);
28807
+ out = out.replace(DATABASE_URL, (_m, name, value) => `${name}${redactionMarker("database-url", value)}`);
28808
+ out = out.replace(SECRET_VARIABLE, (m, name, value) => PLACEHOLDER_VALUE.test(value) ? m : `${name}${redactionMarker(typeOfToken(value.replace(/^["']|["',;]+$/g, "")), value)}`);
28809
+ out = out.replace(BARE_TOKEN, (m) => redactionMarker(typeOfToken(m), m));
28810
+ return out;
28811
+ }
28812
+ function redactFinding(f) {
28813
+ let span = redactSecretText(f.span);
28814
+ if (f.ruleId === "EX-011" && span === f.span && f.span.length > 0 && !f.span.includes("[redacted ")) {
28815
+ span = `[redacted secret: ${f.span.length} chars]`;
28816
+ }
28817
+ const out = { ...f, span };
28818
+ if (out.source === "heuristic") out.rationale = redactSecretText(out.rationale);
28819
+ if (out.source === "signature" && out.decoded !== void 0) out.decoded = redactSecretText(out.decoded);
28820
+ return out;
27923
28821
  }
27924
28822
 
27925
28823
  // ../core/src/reporters/json-reporter.ts
27926
- init_zod();
27927
28824
  var ScanStatsSchema = external_exports.object({
27928
28825
  filesScanned: external_exports.number().int().nonnegative(),
27929
28826
  filesSkipped: external_exports.number().int().nonnegative(),
@@ -27942,6 +28839,11 @@ var FindingSchema = external_exports.object({
27942
28839
  owasp: external_exports.array(external_exports.string()),
27943
28840
  fix: external_exports.string()
27944
28841
  }).passthrough();
28842
+ var SuppressedSchema = external_exports.object({
28843
+ baseline: external_exports.number().int().nonnegative(),
28844
+ inline: external_exports.array(external_exports.object({ ruleId: external_exports.string(), file: external_exports.string(), line: external_exports.number(), reason: external_exports.string() })),
28845
+ rejected: external_exports.array(external_exports.object({ ruleId: external_exports.string(), file: external_exports.string(), line: external_exports.number(), cause: external_exports.string() }))
28846
+ });
27945
28847
  var ScanReportSchema = external_exports.object({
27946
28848
  version: external_exports.literal("1"),
27947
28849
  createdAt: external_exports.string().datetime(),
@@ -27950,7 +28852,9 @@ var ScanReportSchema = external_exports.object({
27950
28852
  scanner: external_exports.object({ name: external_exports.string(), version: external_exports.string() }).optional(),
27951
28853
  target: external_exports.string().optional(),
27952
28854
  stats: ScanStatsSchema,
27953
- findings: external_exports.array(FindingSchema)
28855
+ findings: external_exports.array(FindingSchema),
28856
+ // Findings hidden by the baseline or inline directives. Optional (m9).
28857
+ suppressed: SuppressedSchema.optional()
27954
28858
  });
27955
28859
 
27956
28860
  // ../core/src/plain.ts
@@ -28047,6 +28951,14 @@ var ENTRIES = {
28047
28951
  headline: "Together, these tool servers can leak your secrets",
28048
28952
  attack: 'Each tool server looks harmless alone. But one agent session that can read private data, read text anyone can write (a web page, an issue, an email) and send data somewhere can be told by that text to copy your secrets out. This is the "lethal trifecta".'
28049
28953
  },
28954
+ "EX-028": {
28955
+ headline: "Text you cannot see is giving your AI orders",
28956
+ attack: "A page or file contains text that is styled to be invisible (white, tiny, off-screen or hidden) but a model still reads it. Here it talks to the AI or tells it to write, run, fetch or send something. This is how a web page can try to steer an agent that was only asked to summarise it."
28957
+ },
28958
+ "EX-029": {
28959
+ headline: "A file or folder name is giving your AI orders",
28960
+ attack: 'The name of a file or folder reads like an instruction ("ignore previous instructions...") or hides invisible characters. An agent that lists the project reads every name, so a name alone can steer it.'
28961
+ },
28050
28962
  "EX-027": {
28051
28963
  headline: "Your AI read untrusted text and private data, and now wants to send something out",
28052
28964
  attack: "Earlier in this session your AI read text anyone can write (a web page, an issue, a message) and then private data (a secrets file, a key). Each step looked harmless. Sending data out now is exactly how a prompt injection steals it, so the Shield holds the call until you say yes."
@@ -28071,6 +28983,23 @@ function plainFor(ruleId, fallbackTitle) {
28071
28983
  };
28072
28984
  }
28073
28985
 
28986
+ // ../core/src/plural.ts
28987
+ function plural(n, one, many = `${one}s`) {
28988
+ return `${n} ${n === 1 ? one : many}`;
28989
+ }
28990
+
28991
+ // ../core/src/exorcise.ts
28992
+ init_walker();
28993
+ var RULE_CLASSES = {
28994
+ "EX-001": ["zero-width", "bidi-override", "tag-block"],
28995
+ "EX-021": ["variation-selector"]
28996
+ };
28997
+ var ALL_CLASSES = /* @__PURE__ */ new Set([...RULE_CLASSES["EX-001"], ...RULE_CLASSES["EX-021"]]);
28998
+
28999
+ // ../core/src/redact-patch.ts
29000
+ var PEM2 = ["PRIVATE", "KEY"].join(" ");
29001
+ var MARKER_LINE = new RegExp(`^-----(?:BEGIN|END) [A-Z ]*${PEM2}(?: BLOCK)?-----\\s*$`);
29002
+
28074
29003
  // ../core/src/index.ts
28075
29004
  init_secrets_check();
28076
29005
  init_canary();
@@ -28158,7 +29087,11 @@ var AllowedReadsSchema = external_exports.object({ version: external_exports.lit
28158
29087
  init_walker();
28159
29088
  var MAX_SCAN_BYTES = 10 * 1048576;
28160
29089
 
29090
+ // ../core/src/gate.ts
29091
+ init_walker();
29092
+
28161
29093
  // ../core/src/index.ts
29094
+ init_walker();
28162
29095
  init_heuristic_engine();
28163
29096
  init_walker();
28164
29097
 
@@ -28171,7 +29104,7 @@ var DEFAULT_ZIP_LIMITS = {
28171
29104
  };
28172
29105
 
28173
29106
  // ../core/src/definitions/version.ts
28174
- var BUNDLED_DEFINITIONS_VERSION = "20261123.0";
29107
+ var BUNDLED_DEFINITIONS_VERSION = "20261124.0";
28175
29108
 
28176
29109
  // ../core/src/liveupdate.ts
28177
29110
  init_zod();
@@ -28315,19 +29248,25 @@ function findActiveInstalledSet(o = {}) {
28315
29248
  return null;
28316
29249
  }
28317
29250
 
28318
- // ../core/src/exorcise.ts
28319
- init_walker();
28320
- var RULE_CLASSES = {
28321
- "EX-001": ["zero-width", "bidi-override", "tag-block"],
28322
- "EX-021": ["variation-selector"]
28323
- };
28324
- var ALL_CLASSES = /* @__PURE__ */ new Set([...RULE_CLASSES["EX-001"], ...RULE_CLASSES["EX-021"]]);
28325
-
28326
29251
  // ../core/src/exorcise-registry.ts
28327
29252
  init_zod();
28328
29253
  var NpmLatest = external_exports.object({ version: external_exports.string().max(100) });
28329
29254
  var PypiProject = external_exports.object({ info: external_exports.object({ version: external_exports.string().max(100) }) });
28330
29255
 
29256
+ // ../core/src/baseline.ts
29257
+ init_zod();
29258
+ var BASELINE_VERSION = 1;
29259
+ var BaselineEntrySchema = external_exports.object({
29260
+ ruleId: external_exports.string().min(1),
29261
+ file: external_exports.string().min(1),
29262
+ fingerprint: external_exports.string().regex(/^[0-9a-f]{32}$/),
29263
+ line: external_exports.number().int().min(0)
29264
+ }).strict();
29265
+ var BaselineSchema = external_exports.object({
29266
+ version: external_exports.literal(BASELINE_VERSION),
29267
+ entries: external_exports.array(BaselineEntrySchema)
29268
+ }).strict();
29269
+
28331
29270
  // ../shield/src/paraphrase.ts
28332
29271
  var W = String.raw`[\s\W_]{0,3}`;
28333
29272
  var words = (...ws) => ws.join(`${W}`);
@@ -28360,7 +29299,7 @@ var SET_ASIDE = any(
28360
29299
  "(?:do\\W{0,3}not|don'?t|stop|no\\W{0,3}longer)\\W{0,3}(?:follow(?:ing)?|obey(?:ing)?|listen(?:ing)?\\W{0,3}to|heed(?:ing)?|honou?r(?:ing)?)"
28361
29300
  );
28362
29301
  var PREVIOUS = any("previous", "prior", "earlier", "above", "preceding", "foregoing", "original", "initial", "system", "developer", "your", "all");
28363
- var FILLER = any("the", "any", "every", "of", "old", "existing", "current", "default", "these", "those", "such", "other");
29302
+ var FILLER2 = any("the", "any", "every", "of", "old", "existing", "current", "default", "these", "those", "such", "other");
28364
29303
  var ORDERS = any(
28365
29304
  "instructions?",
28366
29305
  "directions?",
@@ -28389,8 +29328,8 @@ var BEFORE = any(
28389
29328
  "the\\W{0,3}(?:conversation|chat)\\W{0,3}so\\W{0,3}far",
28390
29329
  "your\\W{0,3}(?:task|job|instructions)"
28391
29330
  );
28392
- var OVERRIDE = [
28393
- new RegExp(`\\b${SET_ASIDE}${W}(?:${FILLER}${W}){0,2}${PREVIOUS}${W}(?:${any(FILLER, PREVIOUS)}${W}){0,2}${ORDERS}\\b`, "i"),
29331
+ var OVERRIDE3 = [
29332
+ new RegExp(`\\b${SET_ASIDE}${W}(?:${FILLER2}${W}){0,2}${PREVIOUS}${W}(?:${any(FILLER2, PREVIOUS)}${W}){0,2}${ORDERS}\\b`, "i"),
28394
29333
  new RegExp(`\\b${SET_ASIDE}${W}${BEFORE}`, "i"),
28395
29334
  new RegExp(`\\b${any("new", "updated", "revised", "real", "actual", "true", "secret", "hidden", "important", "priority", "urgent", "override")}${W}${any("instructions?", "task", "objective", "directives?", "mission", "orders?", "goal")}${W}(?:is|are|:|for\\W{0,3}(?:you|the\\W{0,3}(?:assistant|ai|agent|model)))`, "i"),
28396
29335
  new RegExp(`\\b${words("your", any("real", "actual", "true", "new", "only"), any("task", "job", "goal", "purpose", "instructions?", "mission"))}${W}(?:is|are|now)\\b`, "i"),
@@ -28404,7 +29343,7 @@ var CONCEAL = [
28404
29343
  new RegExp(`\\b${any("silently", "quietly", "covertly", "secretly", "discreetly", "invisibly", "in\\W{0,3}the\\W{0,3}background", "behind\\W{0,3}the\\W{0,3}scenes")}${W}${any("send", "upload", "post", "run", "execute", "call", "forward", "copy", "include", "attach", "email", "transmit")}`, "i"),
28405
29344
  new RegExp(`\\b${any("the\\W{0,3}user\\W{0,3}(?:must|should)\\W{0,3}not\\W{0,3}(?:know|see|find\\W{0,3}out)", "hide\\W{0,3}(?:this|it)\\W{0,3}from")}`, "i")
28406
29345
  ];
28407
- var SENSITIVE = any(
29346
+ var SENSITIVE2 = any(
28408
29347
  "\\.env\\b",
28409
29348
  "env(?:ironment)?\\W{0,3}(?:file|variables?|vars)",
28410
29349
  "credentials?",
@@ -28436,8 +29375,8 @@ var SENSITIVE = any(
28436
29375
  "system\\W{0,3}prompt"
28437
29376
  );
28438
29377
  var SEND = any("send", "post", "upload", "transmit", "forward", "e-?mail", "share", "exfiltrate", "leak", "submit", "paste", "copy", "include", "attach", "append", "embed", "encode", "write", "dump", "print", "reveal", "output", "return", "read");
28439
- var ACTION = [
28440
- new RegExp(`\\b${SEND}${W}(?:(?:the|all|any|every|your|my|their|of|full|entire|contents?|values?)${W}){0,4}${SENSITIVE}`, "i"),
29378
+ var ACTION2 = [
29379
+ new RegExp(`\\b${SEND}${W}(?:(?:the|all|any|every|your|my|their|of|full|entire|contents?|values?)${W}){0,4}${SENSITIVE2}`, "i"),
28441
29380
  new RegExp(`\\b${any("run", "execute", "exec", "eval", "invoke", "type", "enter", "paste")}${W}(?:this|the\\W{0,3}following|these)?${W}?(?:command|script|code|line)?s?${W}?[:\`'"]?${W}?${any("curl", "wget", "bash", "sh\\W{0,3}-c", "zsh", "powershell", "iex", "invoke-expression", "rm\\W{0,3}-rf", "chmod", "base64\\W{0,3}-d", "nc\\W", "ncat", "python\\W{0,3}-c", "node\\W{0,3}-e", "eval")}`, "i"),
28442
29381
  new RegExp(`\\b${any("curl", "wget")}\\b[^\\n]{0,120}\\|\\s*(?:ba|z)?sh\\b`, "i"),
28443
29382
  new RegExp(`\\b${any("call", "use", "invoke", "trigger")}${W}(?:the${W})?[\\w.-]{2,40}${W}tool${W}${any("with", "to\\W{0,3}send", "to\\W{0,3}upload", "to\\W{0,3}delete", "to\\W{0,3}write")}`, "i"),
@@ -28516,6 +29455,40 @@ var SessionRecordSchema = external_exports.object({
28516
29455
  grants: external_exports.array(GrantSchema).max(MAX_GRANTS)
28517
29456
  }).strict();
28518
29457
 
29458
+ // ../shield/src/os-auth.ts
29459
+ var AVAILABLE_SCRIPT = [
29460
+ "ObjC.import('LocalAuthentication');",
29461
+ "ObjC.import('Foundation');",
29462
+ "function out(s) { $.NSFileHandle.fileHandleWithStandardOutput.writeData($(s + '\\n').dataUsingEncoding($.NSUTF8StringEncoding)); }",
29463
+ "const ctx = $.LAContext.alloc.init;",
29464
+ "const err = Ref();",
29465
+ "out(ctx.canEvaluatePolicyError(2, err) ? 'yes' : 'no');"
29466
+ ].join("\n");
29467
+ var VERIFY_SCRIPT = [
29468
+ "ObjC.import('LocalAuthentication');",
29469
+ "ObjC.import('Foundation');",
29470
+ "function out(s) { $.NSFileHandle.fileHandleWithStandardOutput.writeData($(s + '\\n').dataUsingEncoding($.NSUTF8StringEncoding)); }",
29471
+ "const raw = $.NSProcessInfo.processInfo.environment.objectForKey('EXORCIST_REASON');",
29472
+ "const reason = ObjC.unwrap(raw) || 'Release one held call';",
29473
+ "let result = null;",
29474
+ "const ctx = $.LAContext.alloc.init;",
29475
+ "const err = Ref();",
29476
+ "if (!ctx.canEvaluatePolicyError(2, err)) {",
29477
+ " out('error');",
29478
+ "} else {",
29479
+ " ctx.evaluatePolicyLocalizedReasonReply(2, $(reason), function (success, error) {",
29480
+ " if (success) { result = 'ok'; return; }",
29481
+ " let code = 0;",
29482
+ " try { code = error.code; } catch (e) { code = 0; }",
29483
+ " result = [-1, -2, -4, -9].indexOf(code) >= 0 ? 'denied' : 'error';",
29484
+ " });",
29485
+ " while (result === null) {",
29486
+ " $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.1));",
29487
+ " }",
29488
+ " out(result);",
29489
+ "}"
29490
+ ].join("\n");
29491
+
28519
29492
  // ../shield/src/lockfile.ts
28520
29493
  init_zod();
28521
29494
  var Sha2562 = external_exports.string().regex(/^[0-9a-f]{64}$/);
@@ -28648,11 +29621,71 @@ function quarantineServer(o) {
28648
29621
  return { ok: true, value: e };
28649
29622
  }
28650
29623
 
29624
+ // ../shield/src/events.ts
29625
+ init_zod();
29626
+ var MAX_EVENT_BYTES = 1024 * 1024;
29627
+ var MAX_LINE_BYTES = 8 * 1024;
29628
+ var MAX_READ_BYTES = 8 * 1024 * 1024;
29629
+ var NAME_CHARS2 = 80;
29630
+ var WHY_CHARS = 400;
29631
+ var MESSAGE_CHARS = 600;
29632
+ var RULE_RE2 = /^[A-Z][A-Z0-9-]{1,15}$/;
29633
+ var KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
29634
+ var Time2 = external_exports.string().max(40).refine((t) => !Number.isNaN(Date.parse(t)), "not a time");
29635
+ var Name2 = external_exports.string().max(NAME_CHARS2);
29636
+ var Rule = external_exports.string().regex(RULE_RE2);
29637
+ var Base = {
29638
+ v: external_exports.literal(1),
29639
+ time: Time2,
29640
+ pid: external_exports.number().int().positive(),
29641
+ server: Name2,
29642
+ session: external_exports.string().regex(KEY_RE).optional()
29643
+ };
29644
+ var StartEvent = external_exports.object({
29645
+ ...Base,
29646
+ kind: external_exports.literal("start"),
29647
+ mode: external_exports.enum(["enforce", "monitor"]),
29648
+ guard: external_exports.enum(["hold", "block", "monitor", "off"]),
29649
+ remote: external_exports.boolean(),
29650
+ /** How a held Session Guard call is released: in the system prompt (`os`) or with `exorcist approve session` (`terminal`). Absent in older logs. */
29651
+ release: external_exports.enum(["os", "terminal"]).optional()
29652
+ }).strict();
29653
+ var CallEvent = external_exports.object({
29654
+ ...Base,
29655
+ kind: external_exports.literal("call"),
29656
+ tool: Name2,
29657
+ decision: external_exports.enum(["allowed", "held", "blocked"]),
29658
+ ruleId: Rule.optional(),
29659
+ why: external_exports.string().max(WHY_CHARS).optional(),
29660
+ monitor: external_exports.literal(true).optional(),
29661
+ prompt: external_exports.number().int().positive().optional(),
29662
+ by: external_exports.literal("user").optional(),
29663
+ /** The hold is answered in the system prompt (Touch ID or login password), not in the agent's approval prompt. `prompt` then numbers the system prompt. */
29664
+ via: external_exports.literal("os").optional()
29665
+ }).strict();
29666
+ var ResultEvent = external_exports.object({
29667
+ ...Base,
29668
+ kind: external_exports.literal("result"),
29669
+ tool: Name2,
29670
+ decision: external_exports.enum(["withheld", "flagged"]),
29671
+ ruleId: Rule,
29672
+ why: external_exports.string().max(WHY_CHARS).optional()
29673
+ }).strict();
29674
+ var AlertEvent = external_exports.object({
29675
+ ...Base,
29676
+ kind: external_exports.literal("alert"),
29677
+ severity: external_exports.enum(["critical", "high", "medium"]),
29678
+ ruleId: Rule,
29679
+ tool: Name2.optional(),
29680
+ message: external_exports.string().max(MESSAGE_CHARS)
29681
+ }).strict();
29682
+ var ShieldEventSchema = external_exports.discriminatedUnion("kind", [StartEvent, CallEvent, ResultEvent, AlertEvent]);
29683
+
28651
29684
  // ../shield/src/launch.ts
28652
29685
  var MAX_HASHED_BYTES = 64 * 1024 * 1024;
28653
29686
 
28654
29687
  // ../shield/src/remote.ts
28655
- var MAX_EVENT_BYTES = 16 * 1024 * 1024;
29688
+ var MAX_EVENT_BYTES2 = 16 * 1024 * 1024;
28656
29689
 
28657
29690
  // ../shield/src/locate.ts
28658
29691
  import { existsSync as existsSync2, readdirSync as readdirSync3, statSync as statSync3 } from "node:fs";
@@ -28707,7 +29740,8 @@ function isWrapped(entry) {
28707
29740
  }
28708
29741
 
28709
29742
  // src/tools.ts
28710
- import { basename as basename5, dirname as dirname3, isAbsolute as isAbsolute4, join as join10, relative as relative3, resolve as resolve5 } from "node:path";
29743
+ import { homedir as homedir2 } from "node:os";
29744
+ import { basename as basename5, dirname as dirname3, isAbsolute as isAbsolute4, join as join10, relative as relative3, resolve as resolve5, sep } from "node:path";
28711
29745
  var quotesWanted = (ctx2, asked) => asked === true && ctx2.noQuotes !== true;
28712
29746
  var RANK = { critical: 0, high: 1, medium: 2, low: 3 };
28713
29747
  var HIDDEN2 = /[\u200B-\u200D\uFEFF\u202A-\u202E\u2066-\u2069\u{E0000}-\u{E007F}]/gu;
@@ -28718,21 +29752,110 @@ function reveal(s) {
28718
29752
  function findDefinitionsDir2(cwd) {
28719
29753
  return findDefinitionsDir({ callerUrl: import.meta.url, cwd });
28720
29754
  }
28721
- function resolveInside(cwd, p, roots = []) {
28722
- const bases = [realpathSync(cwd), ...roots.filter((r) => existsSync3(r)).map((r) => realpathSync(r))];
29755
+ function resolveInside(cwd, p, roots = [], primary) {
29756
+ const real = (d) => realpathSync(d);
29757
+ const extra = roots.filter((r) => existsSync3(r)).map(real);
29758
+ const first = primary !== void 0 && extra.includes(real(primary)) ? [real(primary)] : [];
29759
+ const bases = [.../* @__PURE__ */ new Set([...first, real(cwd), ...extra])];
28723
29760
  const tries = isAbsolute4(p) ? [p] : bases.map((b) => resolve5(b, p));
28724
29761
  const found = tries.find((t) => existsSync3(t));
28725
29762
  if (!found) return { ok: false, error: `Path not found: ${p}` };
28726
- const real = realpathSync(found);
29763
+ const target = realpathSync(found);
28727
29764
  const base = bases.find((b) => {
28728
- const rel = relative3(b, real);
29765
+ const rel = relative3(b, target);
28729
29766
  return !rel.startsWith("..") && !isAbsolute4(rel);
28730
29767
  });
28731
29768
  if (!base) {
28732
29769
  const where = bases.length > 1 ? `the project folder (${bases[0]}) or the folders your client shared` : `the project folder (${bases[0]})`;
28733
- return { ok: false, error: `"${p}" is outside ${where}. Only paths inside ${bases.length > 1 ? "them" : "it"} can be used.` };
29770
+ return { ok: false, outside: true, error: `"${p}" is outside ${where}. Only paths inside ${bases.length > 1 ? "them" : "it"} can be used.` };
29771
+ }
29772
+ return { ok: true, path: target, base };
29773
+ }
29774
+ var PROJECT_MARKERS = [
29775
+ ".git",
29776
+ ".kiro",
29777
+ ".claude",
29778
+ ".cursor",
29779
+ ".vscode",
29780
+ ".mcp.json",
29781
+ "mcp.json",
29782
+ "package.json",
29783
+ "pyproject.toml",
29784
+ "requirements.txt",
29785
+ "Cargo.toml",
29786
+ "go.mod",
29787
+ "pom.xml",
29788
+ "build.gradle",
29789
+ "Gemfile",
29790
+ "composer.json",
29791
+ "AGENTS.md",
29792
+ "CLAUDE.md",
29793
+ "README.md",
29794
+ "README"
29795
+ ];
29796
+ function looksLikeProject(dir) {
29797
+ const has = (n) => existsSync3(join10(dir, n));
29798
+ if (has("plugin.json") || has("POWER.md")) return false;
29799
+ return PROJECT_MARKERS.some(has);
29800
+ }
29801
+ var SENSITIVE_IN_HOME = [".ssh", ".aws", ".gnupg", ".kube", ".docker", ".azure", ".config", ".password-store", join10("Library", "Keychains")];
29802
+ var SENSITIVE_ABSOLUTE = ["/etc", "/private/etc", "/System", "/var/root", "/root"];
29803
+ var isWithin = (base, p) => {
29804
+ const rel = relative3(base, p);
29805
+ return rel === "" || !rel.startsWith("..") && !isAbsolute4(rel);
29806
+ };
29807
+ function sensitiveReason(real, home = homedir2()) {
29808
+ const realHome = existsSync3(home) ? realpathSync(home) : home;
29809
+ if (dirname3(real) === real) return "it is the filesystem root";
29810
+ if (isWithin(real, realHome)) return real === realHome ? "it is the home folder" : "it contains the home folder";
29811
+ for (const n of SENSITIVE_IN_HOME) {
29812
+ const s = join10(realHome, n);
29813
+ if (isWithin(s, real) || isWithin(real, s)) return `it holds credentials or settings (${n.split(sep)[0]})`;
29814
+ }
29815
+ for (const s of SENSITIVE_ABSOLUTE) if (isWithin(s, real)) return "it is a system folder";
29816
+ return null;
29817
+ }
29818
+ var printable2 = (s) => s.replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u2028\u2029\u202A-\u202E\u2066-\u2069\uFEFF\u{E0000}-\u{E007F}]/gu, (c) => `[U+${(c.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0")}]`);
29819
+ function approvalMessage(folder) {
29820
+ const shown = printable2(folder);
29821
+ const where = shown.length > 300 ? `${shown.slice(0, 300)}...` : shown;
29822
+ return `Allow Exorcist 98 to read the folder ${where} for this session? It can scan the files in it, and disable MCP servers in its config files only if you ask. The permission ends when the server stops.`;
29823
+ }
29824
+ var FIXES = "Either set EXORCIST_ROOTS to the absolute path of the project folder in the env of the exorcist MCP server, or add the exorcist server to the workspace .kiro/settings/mcp.json, where Kiro starts it in the project folder.";
29825
+ function noProjectError(ctx2, p, inside2) {
29826
+ if (inside2.outside || isAbsolute4(p) || (ctx2.roots?.length ?? 0) > 0 || looksLikeProject(ctx2.cwd)) return null;
29827
+ const how = ctx2.ask ? "Call the tool again with the absolute path of the project folder; the person will be asked to allow it for this session. Other fixes: set EXORCIST_ROOTS to that folder in the env of the exorcist MCP server, or add the exorcist server to the workspace .kiro/settings/mcp.json, where Kiro starts it in the project folder." : FIXES;
29828
+ return `No project folder is known, so "${p}" was not scanned. This server was started in ${ctx2.cwd}, which is not a project, and the client did not share a workspace folder (MCP roots). Nothing was checked. ${how} Do not report this as a clean scan.`;
29829
+ }
29830
+ async function resolveAllowed(ctx2, p) {
29831
+ const first = resolveInside(ctx2.cwd, p, ctx2.roots, ctx2.base);
29832
+ if (first.ok || !first.outside || !isAbsolute4(p)) return first;
29833
+ const noRoots = (ctx2.roots?.length ?? 0) === 0;
29834
+ if (!ctx2.ask) {
29835
+ return noRoots && !looksLikeProject(ctx2.cwd) ? { ...first, error: `${first.error} No project folder is known. ${FIXES}` } : first;
29836
+ }
29837
+ let folder;
29838
+ try {
29839
+ const real = realpathSync(p);
29840
+ folder = statSync4(real).isDirectory() ? real : dirname3(real);
29841
+ } catch {
29842
+ return first;
29843
+ }
29844
+ const refused = sensitiveReason(folder, ctx2.home);
29845
+ if (refused) return { ok: false, outside: true, error: `${printable2(folder)} cannot be allowed: ${refused}.` };
29846
+ let yes = false;
29847
+ try {
29848
+ yes = await ctx2.ask(folder) === true;
29849
+ } catch {
29850
+ yes = false;
28734
29851
  }
28735
- return { ok: true, path: real, base };
29852
+ if (!yes) {
29853
+ return { ok: false, outside: true, error: `The person did not allow Exorcist 98 to read ${printable2(folder)}, so nothing was read. Do not ask again unless the user requests it.` };
29854
+ }
29855
+ ctx2.approved = [...ctx2.approved ?? [], folder];
29856
+ ctx2.roots = [...ctx2.roots ?? [], folder];
29857
+ ctx2.base ??= folder;
29858
+ return resolveInside(ctx2.cwd, p, ctx2.roots, ctx2.base);
28736
29859
  }
28737
29860
  function usableRoots(entries, home) {
28738
29861
  const out = [];
@@ -28778,19 +29901,22 @@ function describe(findings, limit, quotes) {
28778
29901
  sorted.slice(0, limit).forEach((f, i) => {
28779
29902
  lines.push(`${i + 1}. [${f.severity.toUpperCase()}] ${plainFor(f.ruleId, f.title).headline}`);
28780
29903
  lines.push(` where: ${f.file}:${f.line}:${f.col} rule: ${f.ruleId}`);
28781
- if (quotes) lines.push(` quoted: ${JSON.stringify(reveal(f.span).slice(0, 80))}`);
29904
+ if (quotes) lines.push(` quoted: ${JSON.stringify(reveal(redactFinding(f).span).slice(0, 80))}`);
28782
29905
  lines.push(` fix: ${f.fix.replace(/\s+/g, " ").trim()}`);
28783
29906
  });
28784
29907
  if (sorted.length > limit) lines.push(`...and ${sorted.length - limit} more. Use a smaller folder or raise maxFindings.`);
28785
29908
  return lines.join("\n");
28786
29909
  }
28787
29910
  function summary(findings, files) {
28788
- if (findings.length === 0) return `No threats found in ${files} files.`;
29911
+ if (findings.length === 0) return `No threats found. Scanned ${plural(files, "file")}.`;
28789
29912
  const counts = ["critical", "high", "medium", "low"].map((s) => ({ s, n: findings.filter((f) => f.severity === s).length })).filter((c) => c.n > 0).map((c) => `${c.n} ${c.s}`).join(", ");
28790
- return `${findings.length} threat${findings.length === 1 ? "" : "s"} in ${files} files (${counts}).`;
29913
+ const withFindings = new Set(findings.map((f) => f.file)).size;
29914
+ return `${plural(findings.length, "threat")} in ${plural(withFindings, "file")} (${counts}). Scanned ${plural(files, "file")}.`;
28791
29915
  }
28792
29916
  async function scanRepoTool(ctx2, a) {
28793
- const inside2 = resolveInside(ctx2.cwd, a.path, ctx2.roots);
29917
+ const inside2 = await resolveAllowed(ctx2, a.path);
29918
+ const none = noProjectError(ctx2, a.path, inside2);
29919
+ if (none) return err(none);
28794
29920
  if (!inside2.ok) return err(inside2.error);
28795
29921
  const defs = await loadDefs(ctx2);
28796
29922
  if (!defs.ok) return err(defs.error);
@@ -28808,7 +29934,9 @@ async function scanRepoTool(ctx2, a) {
28808
29934
  return { text: [summary(findings, files), quotes ? UNTRUSTED : "", describe(findings, limit, quotes)].filter(Boolean).join("\n") };
28809
29935
  }
28810
29936
  async function scanMcpConfigTool(ctx2, a) {
28811
- const inside2 = resolveInside(ctx2.cwd, a.path, ctx2.roots);
29937
+ const inside2 = await resolveAllowed(ctx2, a.path);
29938
+ const none = noProjectError(ctx2, a.path, inside2);
29939
+ if (none) return err(none);
28812
29940
  if (!inside2.ok) return err(inside2.error);
28813
29941
  if (!statSync4(inside2.path).isFile()) return err(`${a.path} is a folder. Give the path of an MCP config file.`);
28814
29942
  const defs = await loadDefs(ctx2);
@@ -28851,13 +29979,15 @@ async function explainFindingTool(ctx2, a) {
28851
29979
  return { text: lines.join("\n") };
28852
29980
  }
28853
29981
  async function quarantineTool(ctx2, a) {
28854
- const inside2 = resolveInside(ctx2.cwd, a.config, ctx2.roots);
29982
+ const inside2 = await resolveAllowed(ctx2, a.config);
29983
+ const none = noProjectError(ctx2, a.config, inside2);
29984
+ if (none) return err(none);
28855
29985
  if (!inside2.ok) return err(inside2.error);
28856
29986
  const r = quarantineServer({
28857
29987
  configPath: inside2.path,
28858
29988
  serverName: a.server,
28859
29989
  reason: a.reason?.slice(0, 200) ?? "quarantined from an AI agent request",
28860
- vaultDir: join10(realpathSync(ctx2.cwd), ".exorcist", "vault")
29990
+ vaultDir: join10(inside2.base, ".exorcist", "vault")
28861
29991
  });
28862
29992
  if (!r.ok) return err(r.error);
28863
29993
  return {
@@ -28867,17 +29997,42 @@ Tell the user. They can undo this with: exorcist vault restore ${r.value.id}`
28867
29997
  }
28868
29998
 
28869
29999
  // src/index.ts
28870
- var VERSION = "0.1.1";
30000
+ var VERSION = "0.2.0";
28871
30001
  var ctx = {
28872
30002
  cwd: process.cwd(),
30003
+ approved: [],
28873
30004
  definitionsDir: findDefinitionsDir2(process.cwd()) ?? "",
28874
30005
  noQuotes: process.env["EXORCIST_MCP_NO_QUOTES"] === "1"
28875
30006
  };
28876
30007
  var reply = (r) => ({ content: [{ type: "text", text: r.text }], ...r.isError ? { isError: true } : {} });
28877
30008
  var server = new McpServer({ name: "exorcist", version: VERSION });
30009
+ var canAsk = () => {
30010
+ const e = server.server.getClientCapabilities()?.elicitation;
30011
+ return e !== void 0 && (e.form !== void 0 || e.url === void 0);
30012
+ };
30013
+ async function askPerson(folder) {
30014
+ try {
30015
+ const r = await server.server.elicitInput(
30016
+ {
30017
+ mode: "form",
30018
+ message: approvalMessage(folder),
30019
+ requestedSchema: {
30020
+ type: "object",
30021
+ properties: { allow: { type: "boolean", title: "Allow for this session", description: "Yes lets Exorcist 98 read this folder until the server stops. No reads nothing.", default: false } },
30022
+ required: ["allow"]
30023
+ }
30024
+ },
30025
+ { timeout: 12e4 }
30026
+ );
30027
+ return r.action === "accept" && r.content?.["allow"] === true;
30028
+ } catch {
30029
+ return false;
30030
+ }
30031
+ }
28878
30032
  var clientRoots = null;
28879
30033
  async function refreshRoots() {
28880
30034
  const fromEnv = (process.env["EXORCIST_ROOTS"] ?? "").split(delimiter);
30035
+ const home = homedir3();
28881
30036
  let fromClient = [];
28882
30037
  if (server.server.getClientCapabilities()?.roots) {
28883
30038
  if (clientRoots === null) {
@@ -28889,13 +30044,17 @@ async function refreshRoots() {
28889
30044
  }
28890
30045
  fromClient = clientRoots;
28891
30046
  }
28892
- ctx.roots = usableRoots([...fromEnv, ...fromClient], homedir2());
30047
+ const approved = ctx.approved ?? [];
30048
+ ctx.base = usableRoots(fromClient, home)[0] ?? usableRoots(fromEnv, home)[0] ?? approved[0];
30049
+ ctx.roots = usableRoots([...fromEnv, ...fromClient, ...approved], home);
28893
30050
  }
28894
30051
  server.server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
28895
30052
  clientRoots = null;
28896
30053
  });
28897
30054
  var withRoots = (fn) => async (a) => {
28898
30055
  await refreshRoots();
30056
+ if (canAsk()) ctx.ask = askPerson;
30057
+ else delete ctx.ask;
28899
30058
  return fn(ctx, a);
28900
30059
  };
28901
30060
  server.registerTool(
@@ -28904,7 +30063,7 @@ server.registerTool(
28904
30063
  title: "Scan a folder for attacks on AI agents",
28905
30064
  description: "Scan a folder or file inside the project for hidden instructions, poisoned tool descriptions, dangerous hooks and leaked secrets. Returns plain-language findings with file and line. Quoted text is left out unless includeQuotes is true.",
28906
30065
  inputSchema: {
28907
- path: external_exports.string().min(1).describe("Folder or file to scan, relative to the project folder"),
30066
+ path: external_exports.string().min(1).describe('Folder or file to scan, relative to the project folder (use "." for the whole project)'),
28908
30067
  maxFindings: external_exports.number().int().min(1).max(100).optional().describe("How many findings to list (default 25)"),
28909
30068
  includeQuotes: external_exports.boolean().optional().describe("Include the matched text, revealed and marked untrusted")
28910
30069
  },