@exorcist-98/mcp-server 0.3.10 → 0.3.11

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
@@ -7466,11 +7466,11 @@ var require_schemas = __commonJS({
7466
7466
  const caps = util.sizeCaps(inst._zod.def.checks);
7467
7467
  if (!caps.length)
7468
7468
  return;
7469
- const cap2 = Math.min(...caps.map((c) => c[0]));
7469
+ const cap3 = Math.min(...caps.map((c) => c[0]));
7470
7470
  const parse2 = inst._zod.parse;
7471
7471
  inst._zod.parse = (payload, ctx2) => {
7472
7472
  const n = size(payload.value);
7473
- if (n > cap2 && !ctx2?.skipChecks && ctx2?.direction !== "backward") {
7473
+ if (n > cap3 && !ctx2?.skipChecks && ctx2?.direction !== "backward") {
7474
7474
  for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {
7475
7475
  if (n > max && ch._zod.def.when(payload)) {
7476
7476
  const start = payload.issues.length;
@@ -36861,28 +36861,43 @@ function needlesOf(token) {
36861
36861
  }
36862
36862
  return out;
36863
36863
  }
36864
- function verifyBase64(s, at, needle, token) {
36864
+ function verifyBase64(s, at2, needle, token) {
36865
36865
  let pre = "";
36866
- if (at >= 4) {
36867
- const p = s.slice(at - 4, at);
36866
+ if (at2 >= 4) {
36867
+ const p = s.slice(at2 - 4, at2);
36868
36868
  if ([...p].every((ch) => B64_CHAR.test(ch))) pre = p;
36869
36869
  }
36870
36870
  let post = "";
36871
- for (const ch of s.slice(at + needle.length, at + needle.length + 4)) {
36871
+ for (const ch of s.slice(at2 + needle.length, at2 + needle.length + 4)) {
36872
36872
  if (!B64_CHAR.test(ch) && ch !== "=") break;
36873
36873
  post += ch;
36874
36874
  }
36875
36875
  const chunk = `${pre}${needle}${post}`.replaceAll("-", "+").replaceAll("_", "/");
36876
36876
  return Buffer.from(chunk, "base64").toString("latin1").includes(token);
36877
36877
  }
36878
+ function base64Runs(s, min) {
36879
+ const out = [];
36880
+ const isB64 = (c) => c >= 65 && c <= 90 || c >= 97 && c <= 122 || c >= 48 && c <= 57 || c === 43 || c === 47 || c === 95 || c === 45;
36881
+ let i = 0;
36882
+ while (i < s.length) {
36883
+ while (i < s.length && !isB64(s.charCodeAt(i))) i++;
36884
+ const start = i;
36885
+ while (i < s.length && isB64(s.charCodeAt(i))) i++;
36886
+ let end = i;
36887
+ if (end - start >= min) {
36888
+ for (let pad = 0; pad < 2 && s[end] === "="; pad++) end++;
36889
+ out.push({ index: start, text: s.slice(start, end) });
36890
+ }
36891
+ if (i === start) i++;
36892
+ }
36893
+ return out;
36894
+ }
36878
36895
  function decodeRuns(s) {
36879
36896
  const out = [];
36880
- B64_RUN.lastIndex = 0;
36881
- let m;
36882
- while ((m = B64_RUN.exec(s)) !== null) {
36883
- const std = m[0].replaceAll("-", "+").replaceAll("_", "/").replace(/=+$/, "");
36897
+ for (const m of base64Runs(s, 36)) {
36898
+ const std = m.text.replaceAll("-", "+").replaceAll("_", "/").replace(/=+$/, "");
36884
36899
  for (let off = 0; off < 4 && std.length - off >= 36; off++) {
36885
- out.push({ at: m.index, to: m.index + m[0].length, text: Buffer.from(std.slice(off), "base64").toString("latin1") });
36900
+ out.push({ at: m.index, to: m.index + m.text.length, text: Buffer.from(std.slice(off), "base64").toString("latin1") });
36886
36901
  }
36887
36902
  }
36888
36903
  return out;
@@ -36943,7 +36958,7 @@ function isCanaryHome(rel) {
36943
36958
  const p = rel.replace(/\\/g, "/").replace(/^\.\//, "");
36944
36959
  return p === CANARY_RECORDS_FILE || p.startsWith(`${CANARY_TRAP_DIR}/`);
36945
36960
  }
36946
- var import_zod8, CANARY_TOKEN_RE_SOURCE, TOKEN_RE, CANARY_TRAP_DIR, CANARY_RECORDS_FILE, TrapPathSchema, CanaryRecordSchema, CanariesFileSchema, B64_CHAR, B64_RUN, MAX_DEPTH;
36961
+ var import_zod8, CANARY_TOKEN_RE_SOURCE, TOKEN_RE, CANARY_TRAP_DIR, CANARY_RECORDS_FILE, TrapPathSchema, CanaryRecordSchema, CanariesFileSchema, B64_CHAR, MAX_DEPTH;
36947
36962
  var init_canary = __esm({
36948
36963
  "../core/src/canary.ts"() {
36949
36964
  "use strict";
@@ -36969,7 +36984,6 @@ var init_canary = __esm({
36969
36984
  madeDirs: import_zod8.z.array(import_zod8.z.enum([".exorcist", CANARY_TRAP_DIR])).optional()
36970
36985
  }).strict();
36971
36986
  B64_CHAR = /[A-Za-z0-9+/_-]/;
36972
- B64_RUN = /[A-Za-z0-9+/_-]{36,}={0,2}/g;
36973
36987
  MAX_DEPTH = 2;
36974
36988
  }
36975
36989
  });
@@ -37245,15 +37259,55 @@ function classifyFile(rel) {
37245
37259
  const norm = rel.replace(/\\/g, "/");
37246
37260
  const base = basename3(norm);
37247
37261
  const ext = extname(norm).toLowerCase();
37248
- if (base === "AGENTS.md" || base === "AGENT.md" || base === "CLAUDE.md" || base === "CLAUDE.local.md" || base === "GEMINI.md" || base === ".cursorrules" || base === ".windsurfrules" || base === ".clinerules" || norm.startsWith(".clinerules/") || norm.startsWith(".cursor/rules/") || norm.startsWith(".windsurf/rules/") || norm.startsWith(".amazonq/rules/") || norm === ".github/copilot-instructions.md" || norm.startsWith(".github/instructions/") || norm.startsWith(".github/prompts/") || /^\.claude\/(commands|agents|skills)\//.test(norm) || base === "SKILL.md" || base === "POWER.md" || /^power\/(?:[^/]+\/)*steering\/[^/]+$/.test(norm) || base.startsWith("README") || norm.startsWith(".kiro/steering/")) return "instruction";
37262
+ if (base === "AGENTS.md" || base === "AGENT.md" || base === "CLAUDE.md" || base === "CLAUDE.local.md" || base === "GEMINI.md" || base === ".cursorrules" || base === ".windsurfrules" || base === ".clinerules" || norm.startsWith(".clinerules/") || norm.startsWith(".cursor/rules/") || norm.startsWith(".windsurf/rules/") || norm.startsWith(".amazonq/rules/") || // m20: more agents' rule files (Continue, Roo Code, Junie, Augment, Zed, Copilot chat modes).
37263
+ norm.startsWith(".continue/rules/") || // Continue's config file holds its `rules:` list, which the agent takes as instructions (m21).
37264
+ norm === ".continue/config.yaml" || norm === ".continue/config.yml" || norm === ".continue/config.json" || norm.startsWith(".roo/rules") || base === ".roorules" || norm === ".junie/guidelines.md" || norm.startsWith(".augment/rules/") || base === ".augment-guidelines" || norm === ".rules" || norm.startsWith(".github/chatmodes/") || norm === ".github/copilot-instructions.md" || norm.startsWith(".github/instructions/") || norm.startsWith(".github/prompts/") || /^\.claude\/(commands|agents|skills)\//.test(norm) || base === "SKILL.md" || base === "POWER.md" || /^power\/(?:[^/]+\/)*steering\/[^/]+$/.test(norm) || base.startsWith("README") || norm.startsWith(".kiro/steering/")) return "instruction";
37249
37265
  if (/^power\/(?:[^/]+\/)*mcp\.json$/.test(norm) || norm.endsWith(".kiro/settings/mcp.json") || norm.endsWith(".cursor/mcp.json") || norm.endsWith(".vscode/mcp.json") || norm.endsWith(".amazonq/mcp.json") || norm.endsWith(".gemini/settings.json") || norm.endsWith(".claude/settings.json") || norm.endsWith(".claude/settings.local.json") || norm === "mcp.json" || norm === ".mcp.json" || base === "claude_desktop_config.json") return "mcp-config";
37250
37266
  if (norm.startsWith(".kiro/hooks/") || base.endsWith(".hook.yaml")) return "hook";
37251
37267
  if (base === "package.json") return "manifest";
37252
37268
  if (norm.startsWith("definitions/") && ext === ".yaml") return "definition";
37253
37269
  if (base === "MEMORY.md" || norm.startsWith(".kiro/notes/") || base.startsWith("agent-notes")) return "memory";
37254
37270
  if (norm.startsWith("power/")) return "power";
37255
- if (ext === ".md" || ext === ".txt") return "docs";
37256
- if ([".ts", ".js", ".mjs", ".cjs", ".py", ".sh", ".bash"].includes(ext)) return "code";
37271
+ if ([".md", ".txt", ".mdx", ".markdown", ".rst", ".adoc", ".html", ".htm", ".ipynb"].includes(ext)) return "docs";
37272
+ if ([
37273
+ ".ts",
37274
+ ".js",
37275
+ ".mjs",
37276
+ ".cjs",
37277
+ ".py",
37278
+ ".sh",
37279
+ ".bash",
37280
+ ".zsh",
37281
+ ".jsx",
37282
+ ".tsx",
37283
+ ".mts",
37284
+ ".cts",
37285
+ ".vue",
37286
+ ".svelte",
37287
+ ".go",
37288
+ ".rs",
37289
+ ".java",
37290
+ ".kt",
37291
+ ".kts",
37292
+ ".scala",
37293
+ ".rb",
37294
+ ".php",
37295
+ ".cs",
37296
+ ".swift",
37297
+ ".c",
37298
+ ".h",
37299
+ ".cc",
37300
+ ".cpp",
37301
+ ".hpp",
37302
+ ".m",
37303
+ ".lua",
37304
+ ".pl",
37305
+ ".ps1",
37306
+ ".r",
37307
+ ".dart",
37308
+ ".ex",
37309
+ ".exs"
37310
+ ].includes(ext)) return "code";
37257
37311
  if ([".json", ".yaml", ".yml", ".toml"].includes(ext)) return "config";
37258
37312
  return "unknown";
37259
37313
  }
@@ -37605,9 +37659,9 @@ function locateQuote(text, quote) {
37605
37659
  const exact = hay.indexOf(quote);
37606
37660
  if (exact !== -1 && quote.trim().length > 0) return { index: exact, end: exact + quote.length };
37607
37661
  const { norm, map: map2 } = collapseWhitespace(hay);
37608
- const at = norm.indexOf(q);
37609
- if (at === -1) return null;
37610
- return { index: map2[at], end: map2[at + q.length - 1] + 1 };
37662
+ const at2 = norm.indexOf(q);
37663
+ if (at2 === -1) return null;
37664
+ return { index: map2[at2], end: map2[at2 + q.length - 1] + 1 };
37611
37665
  };
37612
37666
  const direct = tryIn(text);
37613
37667
  if (direct) return { ...direct, shown: text.slice(direct.index, direct.end) };
@@ -37678,17 +37732,17 @@ function maskUserinfo(text) {
37678
37732
  chars ??= text.split("");
37679
37733
  for (let i = from; i < to; i++) chars[i] = "*";
37680
37734
  };
37681
- let at = text.indexOf("@");
37682
- while (at !== -1) {
37683
- let b = at - 1;
37684
- while (b >= 0 && at - b <= 800 && !USERINFO_STOP.has(text[b])) b--;
37735
+ let at2 = text.indexOf("@");
37736
+ while (at2 !== -1) {
37737
+ let b = at2 - 1;
37738
+ while (b >= 0 && at2 - b <= 800 && !USERINFO_STOP.has(text[b])) b--;
37685
37739
  const segStart = b + 1;
37686
- const seg = text.slice(segStart, at);
37740
+ const seg = text.slice(segStart, at2);
37687
37741
  if (b >= 2 && text[b] === "/" && text[b - 1] === "/" && text[b - 2] === ":") {
37688
37742
  let sc = b - 3;
37689
37743
  while (sc >= 0 && b - 2 - sc <= 21 && /[a-z0-9+.\-]/i.test(text[sc])) sc--;
37690
37744
  const colon = seg.indexOf(":");
37691
- if (SCHEME_RE.test(text.slice(sc + 1, b - 2)) && colon >= 0 && colon < seg.length - 1) mask(segStart + colon + 1, at);
37745
+ if (SCHEME_RE.test(text.slice(sc + 1, b - 2)) && colon >= 0 && colon < seg.length - 1) mask(segStart + colon + 1, at2);
37692
37746
  } else {
37693
37747
  for (let c1 = seg.indexOf(":"); c1 !== -1; c1 = seg.indexOf(":", c1 + 1)) {
37694
37748
  let k = c1 - 1;
@@ -37697,12 +37751,12 @@ function maskUserinfo(text) {
37697
37751
  if (!SCHEME_RE.test(scheme)) continue;
37698
37752
  const c2 = seg.indexOf(":", c1 + 1);
37699
37753
  if (c2 > c1 + 1 && c2 < seg.length - 1) {
37700
- mask(segStart + c2 + 1, at);
37754
+ mask(segStart + c2 + 1, at2);
37701
37755
  break;
37702
37756
  }
37703
37757
  }
37704
37758
  }
37705
- at = text.indexOf("@", at + 1);
37759
+ at2 = text.indexOf("@", at2 + 1);
37706
37760
  }
37707
37761
  return chars ? chars.join("") : text;
37708
37762
  }
@@ -37751,8 +37805,8 @@ function maskAssignmentLine(line) {
37751
37805
  const eq = tok.indexOf("=");
37752
37806
  if (eq <= 0) continue;
37753
37807
  const key = tok.slice(0, eq).replace(/^export$/, "");
37754
- const { value, at } = unquote(tok.slice(eq + 1));
37755
- if (isSecretKey(key) && looksLikeSecretValue(value)) maskRange(m.index + eq + 1 + at, value.length);
37808
+ const { value, at: at2 } = unquote(tok.slice(eq + 1));
37809
+ if (isSecretKey(key) && looksLikeSecretValue(value)) maskRange(m.index + eq + 1 + at2, value.length);
37756
37810
  }
37757
37811
  const lead = line.length - line.trimStart().length;
37758
37812
  const body = line.slice(lead);
@@ -37763,8 +37817,8 @@ function maskAssignmentLine(line) {
37763
37817
  let i = colon + 1;
37764
37818
  while (i < body.length && body[i] === " ") i++;
37765
37819
  const raw = body.slice(i).replace(/\s+#.*$/, "").trimEnd();
37766
- const { value, at } = unquote(raw);
37767
- if (isSecretKey(key) && looksLikeSecretValue(value)) maskRange(lead + i + at, value.length);
37820
+ const { value, at: at2 } = unquote(raw);
37821
+ if (isSecretKey(key) && looksLikeSecretValue(value)) maskRange(lead + i + at2, value.length);
37768
37822
  }
37769
37823
  return chars ? chars.join("") : line;
37770
37824
  }
@@ -37877,11 +37931,11 @@ async function judgeText(text, label, client, maskedUpstream = 0) {
37877
37931
  const r = await judgeTextDetailed(text, label, client, maskedUpstream);
37878
37932
  return r.kind === "verdict" ? r.verdict : null;
37879
37933
  }
37880
- var import_zod10, SUSPICIOUS_PHRASES, MAX_SPANS_PER_FILE, MAX_SPAN_CHARS, VerdictSchema, CREDENTIAL_FILE, SECRET_KEY_WORD, KEY_TOKEN, USERINFO_STOP, SCHEME_RE, isSecretKey, MAX_WHOLE_FILE_WINDOWS, MAX_JUDGED_CHARS;
37934
+ var import_zod11, SUSPICIOUS_PHRASES, MAX_SPANS_PER_FILE, MAX_SPAN_CHARS, VerdictSchema, CREDENTIAL_FILE, SECRET_KEY_WORD, KEY_TOKEN, USERINFO_STOP, SCHEME_RE, isSecretKey, MAX_WHOLE_FILE_WINDOWS, MAX_JUDGED_CHARS;
37881
37935
  var init_heuristic_engine = __esm({
37882
37936
  "../core/src/scanner/heuristic-engine.ts"() {
37883
37937
  "use strict";
37884
- import_zod10 = __toESM(require_zod(), 1);
37938
+ import_zod11 = __toESM(require_zod(), 1);
37885
37939
  init_prompts();
37886
37940
  init_walker();
37887
37941
  init_secrets_check();
@@ -37893,11 +37947,11 @@ var init_heuristic_engine = __esm({
37893
37947
  ];
37894
37948
  MAX_SPANS_PER_FILE = 5;
37895
37949
  MAX_SPAN_CHARS = 400;
37896
- VerdictSchema = import_zod10.z.object({
37897
- verdict: import_zod10.z.enum(["malicious", "suspicious", "benign"]),
37898
- threat_class: import_zod10.z.string().min(1).max(200),
37899
- quoted_span: import_zod10.z.string().min(1).max(2e3),
37900
- rationale: import_zod10.z.string().min(1).max(1e3)
37950
+ VerdictSchema = import_zod11.z.object({
37951
+ verdict: import_zod11.z.enum(["malicious", "suspicious", "benign"]),
37952
+ threat_class: import_zod11.z.string().min(1).max(200),
37953
+ quoted_span: import_zod11.z.string().min(1).max(2e3),
37954
+ rationale: import_zod11.z.string().min(1).max(1e3)
37901
37955
  });
37902
37956
  CREDENTIAL_FILE = /(^|\/)(\.env(\..*)?|[^/]*\.local\.json|claude_desktop_config\.json|\.npmrc|\.netrc|credentials(\.json)?)$/i;
37903
37957
  SECRET_KEY_WORD = /(?:key|token|secret|password|passwd|pwd|auth|credential|cookie|session)/i;
@@ -43914,6 +43968,7 @@ var SESSION_TTL_MS = 2 * 60 * 60 * 1e3;
43914
43968
  var MAX_FACTS = 32;
43915
43969
  var MAX_GRANTS = 4;
43916
43970
  var MAX_FILE_BYTES = 64 * 1024;
43971
+ var HEARTBEAT_MS = 10 * 60 * 1e3;
43917
43972
  var MAX_SKEW_MS = 5 * 60 * 1e3;
43918
43973
  var NAME_CHARS = 80;
43919
43974
  var WRITER_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -47142,12 +47197,16 @@ var MatchSchema = import_zod6.z.object({
47142
47197
  exclude_regex: import_zod6.z.string().optional(),
47143
47198
  // secret-value: the matched value must look like a real credential, not a
47144
47199
  // placeholder, a template, an expression or a documented example.
47145
- validate: import_zod6.z.enum(["base64-text", "encoded-text", "typosquat", "secret-value"]).optional(),
47200
+ // unpinned-package: the package or image reference names no exact build
47201
+ // (package-pin.ts).
47202
+ validate: import_zod6.z.enum(["base64-text", "encoded-text", "typosquat", "secret-value", "unpinned-package"]).optional(),
47146
47203
  // Only for files of role `config`: the rule runs only if the file text matches.
47147
47204
  file_regex: import_zod6.z.string().optional(),
47148
47205
  // With json_path selecting an `args` array: check only the package the
47149
- // runner is told to run, not flags or paths.
47150
- select: import_zod6.z.enum(["package-arg"]).optional(),
47206
+ // runner is told to run, not flags or paths. server-package: json_path
47207
+ // selects whole MCP server entries and the package or image each one runs
47208
+ // is checked (npx, uvx, pnpm/yarn dlx, npm exec, pipx run, docker/podman run).
47209
+ select: import_zod6.z.enum(["package-arg", "server-package"]).optional(),
47151
47210
  // ── Context checks (precision round 2, docs/FIELD_REPORT.md) ──────────────
47152
47211
  // In generic config files (role `config`), a match counts only where it is
47153
47212
  // something that runs: the value of a command-like key, an item of a
@@ -47158,6 +47217,8 @@ var MatchSchema = import_zod6.z.object({
47158
47217
  // Ignore matches inside Markdown code (inline backticks or fenced blocks),
47159
47218
  // where an HTML comment is shown, not hidden, and an image is not loaded.
47160
47219
  skip_in_code: import_zod6.z.boolean().optional(),
47220
+ // m21: in YAML files, a run of list items is also read as one sentence (an order split across items).
47221
+ join_yaml_lists: import_zod6.z.boolean().optional(),
47161
47222
  // A phrase inside quotation marks that closes right after it, in a passage
47162
47223
  // matching this regex (words such as "never", "such as", "injection"), is
47163
47224
  // being quoted as an example or warned against, not given as an order.
@@ -47178,6 +47239,11 @@ var MatchSchema = import_zod6.z.object({
47178
47239
  // With validate encoded-text: extra markers (for example chat-template
47179
47240
  // tokens) that make decoded text count as instructions.
47180
47241
  decoded_flag_regex: import_zod6.z.string().optional(),
47242
+ // With validate encoded-text (m20): a blob whose decoded text gives no order (no command, address, secret,
47243
+ // override or phrase the instruction rules flag) is reported at this severity instead of the rule's own.
47244
+ decoded_prose_severity: import_zod6.z.enum(["critical", "high", "medium", "low", "info"]).optional(),
47245
+ // m20: also decode percent-encoded runs and ROT13 lines (encodings.ts) and judge the decoded text.
47246
+ other_encodings: import_zod6.z.boolean().optional(),
47181
47247
  // unicode_class only: a run of at least `min_run` characters is required
47182
47248
  // for the rule to fire at all. Shorter runs are ignored entirely (used by
47183
47249
  // EX-021: one or two variation selectors are ordinary emoji presentation).
@@ -47209,6 +47275,19 @@ var MatchSchema = import_zod6.z.object({
47209
47275
  mention_guard: import_zod6.z.object({
47210
47276
  severity: import_zod6.z.enum(["critical", "high", "medium", "low"])
47211
47277
  }).optional(),
47278
+ // unicode_class only (m20): a run made only of these classes and at most `max_length` long is not reported
47279
+ // (EX-061: one to three zero-width characters in code are ordinary in translated strings; longer runs carry bits).
47280
+ skip_short_run: import_zod6.z.object({
47281
+ classes: import_zod6.z.array(import_zod6.z.string()).min(1),
47282
+ max_length: import_zod6.z.number().int().min(1)
47283
+ }).optional(),
47284
+ // unicode_class only (m20): hidden characters written as escapes (`\\uDB40\\uDC41`, `\\u{E0041}`, `\\U000E0041`,
47285
+ // `&#xE0041;`) are decoded too. Only runs that can carry a message count: four or more tag characters or
47286
+ // variation selectors, or eight or more zero-width characters. One escaped character is a reference, not text.
47287
+ escapes: import_zod6.z.boolean().optional(),
47288
+ // m20: words that mix Latin letters with Cyrillic or Greek look-alikes (`ALLOWED_HOSTS` spelled with a Cyrillic O),
47289
+ // an identifier or name made to pass for another (lookalike.ts, findMixedScriptWords).
47290
+ mixed_script: import_zod6.z.boolean().optional(),
47212
47291
  minor_run: import_zod6.z.object({
47213
47292
  max_length: import_zod6.z.number().int().min(1),
47214
47293
  classes: import_zod6.z.array(import_zod6.z.string()).min(1),
@@ -47221,11 +47300,11 @@ var MatchSchema = import_zod6.z.object({
47221
47300
  wide_paths: import_zod6.z.array(import_zod6.z.string().refine(compiles, "wide_paths entries must be valid regular expressions")).optional(),
47222
47301
  order_regex: import_zod6.z.string().optional()
47223
47302
  }).superRefine((val, ctx2) => {
47224
- 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;
47303
+ 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.mixed_script === true || val.analysis !== void 0;
47225
47304
  if (!hasAny) {
47226
47305
  ctx2.addIssue({
47227
47306
  code: import_zod6.z.ZodIssueCode.custom,
47228
- message: "match must contain at least one of: regex, unicode_class, json_path, analysis, hidden_text"
47307
+ message: "match must contain at least one of: regex, unicode_class, json_path, analysis, hidden_text, mixed_script"
47229
47308
  });
47230
47309
  }
47231
47310
  if (val.value_regex !== void 0 && val.json_path === void 0) {
@@ -47265,6 +47344,12 @@ var VirusDefinitionSchema = import_zod6.z.object({
47265
47344
  // instead of its own (test and eval folders). Never applied to a file an
47266
47345
  // agent reads: see keepsFullSeverity in walker.ts.
47267
47346
  low_severity_paths: import_zod6.z.array(import_zod6.z.string().refine(compiles, "low_severity_paths entries must be valid regular expressions")).optional(),
47347
+ // m20: in these paths a finding stays at the rule's own severity when the lines around it match
47348
+ // `regex` (a dangerous action next to a phrase that is usually program description).
47349
+ low_severity_unless: import_zod6.z.object({
47350
+ paths: import_zod6.z.array(import_zod6.z.string().refine(compiles, "low_severity_unless paths must be valid regular expressions")),
47351
+ regex: import_zod6.z.string().refine(compiles, "low_severity_unless regex must be a valid regular expression")
47352
+ }).optional(),
47268
47353
  // Rules in the same group that report the same line of the same file are
47269
47354
  // one problem: only the most severe of them is kept.
47270
47355
  same_line_group: import_zod6.z.string().min(1).optional()
@@ -47566,11 +47651,16 @@ var NETWORK_ALLOW = /^(?:WebFetch|Bash\(\s*(?:curl|wget|ssh|scp|nc|ncat|ftp|rsyn
47566
47651
  var WRITE_ALLOW = /^(?:Write|Edit|MultiEdit|NotebookEdit|Bash\(\s*(?:rm|mv|cp|tee|chmod|chown|dd|ln|touch|mkdir|truncate)\b|Bash\(\s*\*+\s*\))/;
47567
47652
  var ALLOW_ENTRY = /^(?:Bash|Shell|PowerShell|Run)\(([^)]*)\)$/;
47568
47653
  var cap = (s) => s.length > 120 ? `${s.slice(0, 119)}\u2026` : s;
47654
+ var capLong = (s) => s.length > 300 ? `${s.slice(0, 299)}\u2026` : s;
47655
+ var RUN_ANYTHING = /^\s*(?:\*+|\.\*|(?:sh|bash|zsh|fish|dash|ksh|csh|tcsh|cmd|cmd\.exe|powershell|pwsh|node|nodejs|deno|bun|bunx|python[0-9.]*|perl|ruby|php|lua|osascript|eval|exec|sudo|env|xargs|ssh|curl|wget|nc|ncat|npx|pnpx|uvx|npm\s+(?:exec|x)|pnpm\s+(?:dlx|exec)|yarn\s+dlx)(?:\s*\*+|\s+-c)?)?\s*$/i;
47656
+ function isRunAnythingPrefix(v) {
47657
+ return typeof v === "string" && RUN_ANYTHING.test(v);
47658
+ }
47569
47659
  function makeLocator(text) {
47570
47660
  const used = /* @__PURE__ */ new Map();
47571
47661
  const starts = [0];
47572
47662
  for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1)) starts.push(i + 1);
47573
- const at = (offset) => {
47663
+ const at2 = (offset) => {
47574
47664
  let lo = 0;
47575
47665
  let hi = starts.length - 1;
47576
47666
  while (lo < hi) {
@@ -47585,7 +47675,7 @@ function makeLocator(text) {
47585
47675
  used.set(needle, n + 1);
47586
47676
  let idx = text.indexOf(needle);
47587
47677
  for (let k = 0; k < n && idx !== -1; k++) idx = text.indexOf(needle, idx + needle.length);
47588
- return idx === -1 ? { line: 1, col: 1 } : at(idx);
47678
+ return idx === -1 ? { line: 1, col: 1 } : at2(idx);
47589
47679
  };
47590
47680
  }
47591
47681
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -47650,14 +47740,22 @@ function readProjectSettings(rel, text) {
47650
47740
  hits.push({ family, ...where(needle), span: cap(span), ...severity ? { severity } : {} });
47651
47741
  };
47652
47742
  if (agent) {
47653
- if ("hooks" in json2) for (const c of commandStrings(json2["hooks"])) add("commands", JSON.stringify(c), c);
47743
+ const cmds = [];
47744
+ if ("hooks" in json2) for (const c of commandStrings(json2["hooks"])) cmds.push({ needle: JSON.stringify(c), text: c });
47654
47745
  for (const k of KEY_HELPERS) {
47655
47746
  const v = json2[k];
47656
- if (typeof v === "string" && v.trim() !== "") add("commands", JSON.stringify(v), `${k}: ${v}`);
47747
+ if (typeof v === "string" && v.trim() !== "") cmds.push({ needle: JSON.stringify(v), text: `${k}: ${v}` });
47657
47748
  }
47658
47749
  const status = json2["statusLine"];
47659
- if (isObj(status) && typeof status["command"] === "string") add("commands", JSON.stringify(status["command"]), `statusLine: ${status["command"]}`);
47660
- else if (typeof status === "string") add("commands", JSON.stringify(status), `statusLine: ${status}`);
47750
+ if (isObj(status) && typeof status["command"] === "string") cmds.push({ needle: JSON.stringify(status["command"]), text: `statusLine: ${status["command"]}` });
47751
+ else if (typeof status === "string") cmds.push({ needle: JSON.stringify(status), text: `statusLine: ${status}` });
47752
+ const first = cmds[0];
47753
+ if (first !== void 0) {
47754
+ const pos = where(first.needle);
47755
+ for (const c of cmds.slice(1)) where(c.needle);
47756
+ const span = cmds.length === 1 ? cap(first.text) : capLong(`${cmds.length} commands: ${[...new Set(cmds.map((c) => c.text))].join(" ; ")}`);
47757
+ hits.push({ family: "commands", ...pos, span });
47758
+ }
47661
47759
  if (json2["enableAllProjectMcpServers"] === true) add("enable-all-mcp", '"enableAllProjectMcpServers"', "enableAllProjectMcpServers: true");
47662
47760
  }
47663
47761
  if (agent || mcp) {
@@ -47682,7 +47780,22 @@ function readProjectSettings(rel, text) {
47682
47780
  add("run-on-open", `"${k}"`, `${k}: ${cmds.join(" ; ")}`, "medium");
47683
47781
  }
47684
47782
  }
47685
- if (vscode && json2["chat.tools.global.autoApprove"] === true) add("copilot-auto-approve", '"chat.tools.global.autoApprove"', "chat.tools.global.autoApprove: true");
47783
+ if (vscode) {
47784
+ for (const k of ["chat.tools.global.autoApprove", "chat.tools.autoApprove"]) {
47785
+ if (json2[k] === true) add("copilot-auto-approve", JSON.stringify(k), `${k}: true`);
47786
+ }
47787
+ }
47788
+ for (const obj of [json2, isObj(json2["globalSettings"]) ? json2["globalSettings"] : null]) {
47789
+ if (!obj || obj["alwaysAllowExecute"] !== true) continue;
47790
+ const wild = (Array.isArray(obj["allowedCommands"]) ? obj["allowedCommands"] : []).find(isRunAnythingPrefix);
47791
+ if (wild === void 0) continue;
47792
+ const also = ["alwaysAllowWrite", "alwaysAllowBrowser", "alwaysAllowMcp"].filter((k) => obj[k] === true);
47793
+ add("copilot-auto-approve", '"alwaysAllowExecute"', `alwaysAllowExecute: true with allowedCommands ${JSON.stringify(wild)}${also.length > 0 ? `, ${also.join(", ")}` : ""}`);
47794
+ }
47795
+ if (vscode && Array.isArray(json2["roo-cline.allowedCommands"])) {
47796
+ const wild = json2["roo-cline.allowedCommands"].find(isRunAnythingPrefix);
47797
+ if (wild !== void 0) add("copilot-auto-approve", '"roo-cline.allowedCommands"', `roo-cline.allowedCommands: ${JSON.stringify(wild)}`);
47798
+ }
47686
47799
  const perm = json2["permissions"];
47687
47800
  if (isObj(perm) && Array.isArray(perm["allow"])) {
47688
47801
  const entries = perm["allow"].filter((e) => typeof e === "string");
@@ -47914,12 +48027,15 @@ var CONFUSABLES = {
47914
48027
  \u01C0: "l"
47915
48028
  };
47916
48029
  var INVISIBLE = new RegExp("[\\u0000\\u00AD\\u034F\\u061C\\u115F\\u1160\\u17B4\\u17B5\\u180B-\\u180F\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F\\u3164\\uFE00-\\uFE0F\\uFEFF\\uFFA0\\uFFF9-\\uFFFB]|[\\u{E0000}-\\u{E007F}\\u{E0100}-\\u{E01EF}]|\\p{Cf}", "u");
48030
+ function isInvisibleFormat(cp) {
48031
+ return cp === 173 || cp === 847 || cp === 1564 || cp === 4447 || cp === 4448 || cp === 6068 || cp === 6069 || cp >= 6155 && cp <= 6157 || cp === 6159 || cp === 8206 || cp === 8207 || cp >= 8298 && cp <= 8303 || cp === 12644 || cp === 65440 || cp >= 65529 && cp <= 65531;
48032
+ }
47917
48033
  function foldText(input) {
47918
48034
  let out = "";
47919
48035
  const map2 = [];
47920
48036
  let i = 0;
47921
48037
  for (const ch of input) {
47922
- const at = i;
48038
+ const at2 = i;
47923
48039
  i += ch.length;
47924
48040
  if (INVISIBLE.test(ch)) continue;
47925
48041
  const n = ch.length === 1 && ch.charCodeAt(0) < 128 ? ch : ch.normalize("NFKC");
@@ -47927,11 +48043,50 @@ function foldText(input) {
47927
48043
  if (INVISIBLE.test(c)) continue;
47928
48044
  const m = CONFUSABLES[c] ?? c;
47929
48045
  out += m;
47930
- for (let k = 0; k < m.length; k++) map2.push(at);
48046
+ for (let k = 0; k < m.length; k++) map2.push(at2);
47931
48047
  }
47932
48048
  }
47933
48049
  return { text: out, map: map2 };
47934
48050
  }
48051
+ var HAS_CYRILLIC_GREEK = /[\u0370-\u03FF\u0400-\u052F\u1D00-\u1D7F]/;
48052
+ var TOKEN = /[\p{L}\p{M}\p{N}_$]+/gu;
48053
+ var LATIN = new RegExp("\\p{Script=Latin}", "u");
48054
+ var CYR_GREEK = /[\p{Script=Cyrillic}\p{Script=Greek}]/u;
48055
+ var MAX_MIXED = 50;
48056
+ function findMixedScriptWords(text) {
48057
+ if (typeof text !== "string" || !HAS_CYRILLIC_GREEK.test(text)) return [];
48058
+ const out = [];
48059
+ TOKEN.lastIndex = 0;
48060
+ let m;
48061
+ while (out.length < MAX_MIXED && (m = TOKEN.exec(text)) !== null) {
48062
+ const word = m[0];
48063
+ if (!HAS_CYRILLIC_GREEK.test(word)) continue;
48064
+ const chars = [...word];
48065
+ let latin = 0;
48066
+ let foreign = 0;
48067
+ let allLookAlike = true;
48068
+ let touches = false;
48069
+ const found = [];
48070
+ chars.forEach((c, i) => {
48071
+ if (LATIN.test(c)) {
48072
+ latin++;
48073
+ return;
48074
+ }
48075
+ if (!CYR_GREEK.test(c)) return;
48076
+ foreign++;
48077
+ if (CONFUSABLES[c] === void 0) {
48078
+ allLookAlike = false;
48079
+ return;
48080
+ }
48081
+ if (LATIN.test(chars[i - 1] ?? "") || LATIN.test(chars[i + 1] ?? "")) touches = true;
48082
+ const tag = `${c} U+${(c.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0")}`;
48083
+ if (!found.includes(tag)) found.push(tag);
48084
+ });
48085
+ if (!allLookAlike || !touches || latin <= foreign || latin + foreign < 4) continue;
48086
+ out.push({ index: m.index, word, readsAs: chars.map((c) => CONFUSABLES[c] ?? c).join(""), foreign: found });
48087
+ }
48088
+ return out;
48089
+ }
47935
48090
 
47936
48091
  // ../core/src/normalizer.ts
47937
48092
  var UNICODE_RANGES = [
@@ -47980,8 +48135,6 @@ var UNICODE_RANGES = [
47980
48135
  173,
47981
48136
  847,
47982
48137
  1564,
47983
- 4447,
47984
- 4448,
47985
48138
  6068,
47986
48139
  6069,
47987
48140
  6155,
@@ -47996,12 +48149,18 @@ var UNICODE_RANGES = [
47996
48149
  8301,
47997
48150
  8302,
47998
48151
  8303,
47999
- 12644,
48000
- 65440,
48001
48152
  65529,
48002
48153
  65530,
48003
48154
  65531
48004
48155
  ]
48156
+ },
48157
+ // The Hangul fillers (m20): letters that draw nothing. Unlike the format characters they are allowed in
48158
+ // identifiers, so `const { timeout, \u3164 } = req.query` declares a variable no reviewer can see. Ordinary
48159
+ // Korean text does not use them; U+115F and U+1160 next to conjoining jamo spell archaic syllables and are
48160
+ // left alone (isBenign). EX-001 treats them like the format characters; EX-061 reports them in code.
48161
+ {
48162
+ class: "invisible-letter",
48163
+ points: [4447, 4448, 12644, 65440]
48005
48164
  }
48006
48165
  ];
48007
48166
  var CP_TO_CLASS = /* @__PURE__ */ new Map();
@@ -48013,6 +48172,7 @@ for (const range of UNICODE_RANGES) {
48013
48172
  var PICTO = new RegExp("\\p{Extended_Pictographic}", "u");
48014
48173
  var NON_LATIN_LETTER = /^(?![\p{Script=Latin}\p{ASCII}])[\p{L}\p{M}]$/u;
48015
48174
  var JOINING_SCRIPT_LETTER = /^(?=[\p{L}\p{M}])[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}\p{Script=Mongolian}\p{Script=Devanagari}\p{Script=Bengali}\p{Script=Gurmukhi}\p{Script=Gujarati}\p{Script=Oriya}\p{Script=Tamil}\p{Script=Telugu}\p{Script=Kannada}\p{Script=Malayalam}\p{Script=Sinhala}]$/u;
48175
+ var CONJOINING_JAMO = /^(?![\u115F\u1160])[\u1100-\u11FF\uA960-\uA97F\uD7B0-\uD7FF]$/u;
48016
48176
  function neighbours(text, offset, len) {
48017
48177
  const before = Array.from(text.slice(Math.max(0, offset - 4), offset)).pop() ?? "";
48018
48178
  const after = Array.from(text.slice(offset + len, offset + len + 4))[0] ?? "";
@@ -48020,6 +48180,10 @@ function neighbours(text, offset, len) {
48020
48180
  }
48021
48181
  function isBenign(text, cp, offset, len, joiningText) {
48022
48182
  if (cp === 65279 && offset === 0) return true;
48183
+ if (cp === 4447 || cp === 4448) {
48184
+ const [b, a] = neighbours(text, offset, len);
48185
+ if (CONJOINING_JAMO.test(b) || CONJOINING_JAMO.test(a)) return true;
48186
+ }
48023
48187
  if (cp === 8204 || cp === 8205) {
48024
48188
  const [b, a] = neighbours(text, offset, len);
48025
48189
  if (NON_LATIN_LETTER.test(b) && NON_LATIN_LETTER.test(a)) return true;
@@ -50492,16 +50656,45 @@ var IMG_TAG = /<img\b[^<>]*>/gi;
50492
50656
  var MD_IMAGE = /!\[([^\]\n]{1,500})\]\(/g;
50493
50657
  var AI_WORD = "(?:AI|assistants?|agents?|llms?|language\\s+models?|kiro|claude|copilot|chatgpt|gemini|cursor)";
50494
50658
  var ALT_ADDRESS = new RegExp(
50495
- `(?:^|[.!?]\\s+)(?:hey\\s+|dear\\s+|attention\\s+)?${AI_WORD}\\s*[,:]|\\b(?:if\\s+you\\s+are|you\\s+are\\s+an?|note\\s+to|message\\s+for|instructions?\\s+for|attention)\\b[^.\\n]{0,30}\\b${AI_WORD}\\b`,
50659
+ `(?:^|[.!?]\\s+)(?:hey\\s+|dear\\s+|attention\\s+)?(?:(?:AI|LLM)\\s+)?${AI_WORD}\\s*[,:]|\\b(?:if\\s+you\\s+are|you\\s+are\\s+an?|note\\s+to|message\\s+for|instructions?\\s+for|attention)\\b[^.\\n]{0,30}\\b${AI_WORD}\\b`,
50496
50660
  "i"
50497
50661
  );
50498
50662
  function attr(tag, name) {
50499
50663
  const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "i").exec(tag);
50500
50664
  return m ? m[1] ?? m[2] ?? "" : null;
50501
50665
  }
50666
+ var ALT_VERB = "(?:write|rewrite|edit|modify|overwrite|run|execute|fetch|download|send|upload|post|share|add|append|install|delete|remove|exfiltrate|forward|email|read|cat|print|paste|include|leak|steal|dump|reveal|copy)";
50667
+ var ALT_DANGER = "(?:credentials?|secrets?|tokens?|api\\s+keys?|passwords?|private\\s+keys?|ssh\\s+keys?|cookies?|\\.env\\b|~\\/\\S+|id_(?:rsa|ed25519|ecdsa|dsa)\\b|\\.aws\\b|\\.npmrc\\b|\\.netrc\\b|\\.pypirc\\b|\\.git-credentials\\b)";
50668
+ var ALT_ACTION = new RegExp(`\\b${ALT_VERB}\\b[^.\\n!?]{0,60}?${ALT_DANGER}`, "i");
50669
+ var PIPE_TO_SHELL = /\b(?:curl|wget)\b[^|\n]{0,200}\|\s*(?:sudo\s+)?(?:ba|z|da)?sh\b/i;
50502
50670
  function altInstructs(alt) {
50503
50671
  const t2 = alt.replace(/\s+/g, " ").trim();
50504
- return t2.length > 0 && (ALT_ADDRESS.test(t2) || OVERRIDE.test(t2) || ACTION.test(t2));
50672
+ return t2.length > 0 && (ALT_ADDRESS.test(t2) || OVERRIDE.test(t2) || ALT_ACTION.test(t2) || PIPE_TO_SHELL.test(t2));
50673
+ }
50674
+ var MD_IMAGE_TITLE = /!\[[^\]\n]{0,500}\]\(\s*<?[^\s)>]+>?\s+(?:"([^"\n]{1,500})"|'([^'\n]{1,500})'|\(([^)\n]{1,500})\))\s*\)/g;
50675
+ var MD_LINK_DEF_TITLE = /^[ \t]{0,3}\[[^\]\n]{1,200}\]:[ \t]*<?\S+>?[ \t]+(?:"([^"\n]{1,500})"|'([^'\n]{1,500})'|\(([^)\n]{1,500})\))[ \t]*$/gm;
50676
+ var ANY_TAG = /<[A-Za-z][\w:.-]*\b[^<>]{0,4000}>/g;
50677
+ var ATTR_TARGET = /https?:\/\/|\bmailto:|\b[\w.+-]+@[\w-]+\.[\w.-]+|\b\d{1,3}(?:\.\d{1,3}){3}\b|\b(?:[a-z0-9-]+\.)+(?:com|net|org|io|dev|app|ai|co|xyz|info|me|sh|cloud|site|online|ru|cn|tk|top)\b|~\/|\.env\b|\bid_(?:rsa|ed25519|ecdsa)\b|\.aws\b|\.ssh\b|\.npmrc\b|\.netrc\b|\.git-credentials\b|\bcredentials?\b|\bsecrets?\b|\bapi\s+keys?\b|\bprivate\s+keys?\b|\bssh\s+keys?\b/i;
50678
+ var TEXT_ATTR = /\s(title|aria-label|aria-description|placeholder|data-[\w-]{1,60})\s*=\s*(?:"([^"]{1,1000})"|'([^']{1,1000})'|\{\s*["'`]([^"'`]{1,1000})["'`]\s*\})/gi;
50679
+ function attributeTextFindings(text) {
50680
+ const out = [];
50681
+ const push2 = (index2, length, value) => {
50682
+ const t3 = value.replace(/\s+/g, " ").trim();
50683
+ if (t3.length > 0 && (ALT_ADDRESS.test(t3) || OVERRIDE.test(t3) || PIPE_TO_SHELL.test(t3) || ALT_ACTION.test(t3) && ATTR_TARGET.test(t3))) out.push({ index: index2, length, method: "attribute-text", text: value.replace(/\s+/g, " ").trim() });
50684
+ };
50685
+ for (const re2 of [MD_IMAGE_TITLE, MD_LINK_DEF_TITLE]) {
50686
+ re2.lastIndex = 0;
50687
+ let m;
50688
+ while ((m = re2.exec(text)) !== null) push2(m.index, m[0].length, m[1] ?? m[2] ?? m[3] ?? "");
50689
+ }
50690
+ ANY_TAG.lastIndex = 0;
50691
+ let t2;
50692
+ while ((t2 = ANY_TAG.exec(text)) !== null) {
50693
+ TEXT_ATTR.lastIndex = 0;
50694
+ let a;
50695
+ while ((a = TEXT_ATTR.exec(t2[0])) !== null) push2(t2.index, t2[0].length, a[2] ?? a[3] ?? a[4] ?? "");
50696
+ }
50697
+ return out;
50505
50698
  }
50506
50699
  function metaTagFindings(text) {
50507
50700
  const out = [];
@@ -50533,7 +50726,7 @@ function altTextFindings(text) {
50533
50726
  return out;
50534
50727
  }
50535
50728
  function findHiddenText(text) {
50536
- const all = [...findHiddenElements(text), ...metaTagFindings(text), ...altTextFindings(text)];
50729
+ const all = [...findHiddenElements(text), ...metaTagFindings(text), ...altTextFindings(text), ...attributeTextFindings(text)];
50537
50730
  return all.sort((a, b) => a.index - b.index);
50538
50731
  }
50539
50732
  function findHiddenElements(text) {
@@ -50655,8 +50848,8 @@ var KNOWN_MCP_PACKAGES = [
50655
50848
  function fold(s) {
50656
50849
  return s.toLowerCase().replace(/rn/g, "m").replace(/[1i]/g, "l").replace(/0/g, "o").replace(/vv/g, "w").replace(/[-_.]/g, "");
50657
50850
  }
50658
- function editDistance(a, b, cap2 = 3) {
50659
- if (Math.abs(a.length - b.length) > cap2) return cap2 + 1;
50851
+ function editDistance(a, b, cap3 = 3) {
50852
+ if (Math.abs(a.length - b.length) > cap3) return cap3 + 1;
50660
50853
  const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
50661
50854
  for (let j = 0; j <= b.length; j++) d[0][j] = j;
50662
50855
  for (let i = 1; i <= a.length; i++) {
@@ -50673,11 +50866,16 @@ function editDistance(a, b, cap2 = 3) {
50673
50866
  }
50674
50867
  function packageName(spec2) {
50675
50868
  const s = spec2.trim();
50676
- const at = s.lastIndexOf("@");
50677
- return at > 0 ? s.slice(0, at) : s;
50869
+ const at2 = s.lastIndexOf("@");
50870
+ return at2 > 0 ? s.slice(0, at2) : s;
50678
50871
  }
50679
50872
  function typosquatOf(spec2) {
50680
- const name = packageName(spec2);
50873
+ const raw = packageName(spec2);
50874
+ const name = [...raw].map((c) => CONFUSABLES[c] ?? c).join("");
50875
+ if (name !== raw || /[^\x00-\x7f]/.test(name)) {
50876
+ if (!/[\p{L}]/u.test(raw.replace(/[\x00-\x7f]/g, ""))) return null;
50877
+ return KNOWN_MCP_PACKAGES.find((k) => fold(k) === fold(name) || editDistance(name.toLowerCase(), k.toLowerCase(), 2) <= 2) ?? name;
50878
+ }
50681
50879
  if (name.length < 6 || KNOWN_MCP_PACKAGES.includes(name)) return null;
50682
50880
  for (const known of KNOWN_MCP_PACKAGES) {
50683
50881
  if (fold(name) === fold(known)) return known;
@@ -50688,6 +50886,808 @@ function typosquatOf(spec2) {
50688
50886
  return null;
50689
50887
  }
50690
50888
 
50889
+ // ../core/src/capabilities.ts
50890
+ import { readFile as readFile2 } from "node:fs/promises";
50891
+ import { join as join6 } from "node:path";
50892
+ var import_zod9 = __toESM(require_zod(), 1);
50893
+ var CAPABILITIES = ["private-data", "untrusted-input", "exfiltration"];
50894
+ var CAPABILITIES_FILE = "capabilities.yaml";
50895
+ function compiles2(pattern) {
50896
+ try {
50897
+ new RegExp(pattern, "i");
50898
+ return true;
50899
+ } catch {
50900
+ return false;
50901
+ }
50902
+ }
50903
+ var Pattern = import_zod9.z.string().min(1).refine(compiles2, "not a valid regular expression");
50904
+ var ToolSchema2 = import_zod9.z.object({ name: import_zod9.z.string(), description: import_zod9.z.string().optional() }).strict();
50905
+ var ExampleSchema = import_zod9.z.object({
50906
+ command: import_zod9.z.string().optional(),
50907
+ args: import_zod9.z.array(import_zod9.z.string()).optional(),
50908
+ url: import_zod9.z.string().optional(),
50909
+ tools: import_zod9.z.array(ToolSchema2).optional(),
50910
+ ability: import_zod9.z.string().optional(),
50911
+ expect: import_zod9.z.boolean(),
50912
+ note: import_zod9.z.string().optional()
50913
+ }).strict();
50914
+ var RuleSchema = import_zod9.z.object({
50915
+ id: import_zod9.z.string().regex(/^CAP-\d{3}$/, "id must match CAP-NNN"),
50916
+ capability: import_zod9.z.enum(["private-data", "untrusted-input", "exfiltration"]),
50917
+ label: import_zod9.z.string().min(1),
50918
+ match: import_zod9.z.object({
50919
+ package: Pattern.optional(),
50920
+ exclude: Pattern.optional(),
50921
+ path_scope: import_zod9.z.literal("outside-project").optional(),
50922
+ tool: Pattern.optional(),
50923
+ description: Pattern.optional(),
50924
+ ability: Pattern.optional()
50925
+ }).strict().refine((m) => m.package || m.tool || m.description || m.ability, "match needs package, tool, description or ability"),
50926
+ examples: import_zod9.z.array(ExampleSchema).min(1, "every rule needs at least one example").refine((ex) => ex.some((e) => e.expect), "every rule needs an example it matches (expect: true)")
50927
+ }).strict();
50928
+ var RuleFileSchema = import_zod9.z.object({
50929
+ version: import_zod9.z.literal(1),
50930
+ rules: import_zod9.z.array(RuleSchema).min(1)
50931
+ }).strict().superRefine((f, ctx2) => {
50932
+ const seen = /* @__PURE__ */ new Set();
50933
+ for (const r of f.rules) {
50934
+ if (seen.has(r.id)) ctx2.addIssue({ code: import_zod9.z.ZodIssueCode.custom, message: `duplicate rule id ${r.id}` });
50935
+ seen.add(r.id);
50936
+ }
50937
+ });
50938
+ var re = (p) => p === void 0 ? null : new RegExp(p, "i");
50939
+ function parseCapabilityRules(data) {
50940
+ const parsed = RuleFileSchema.safeParse(data);
50941
+ if (!parsed.success) {
50942
+ const i = parsed.error.issues[0];
50943
+ return { ok: false, missing: false, error: `${CAPABILITIES_FILE} is invalid: ${i ? `${i.path.join(".")} ${i.message}` : "unknown problem"}` };
50944
+ }
50945
+ return {
50946
+ ok: true,
50947
+ rules: parsed.data.rules.map((r) => ({
50948
+ id: r.id,
50949
+ capability: r.capability,
50950
+ label: r.label,
50951
+ package: re(r.match.package),
50952
+ exclude: re(r.match.exclude),
50953
+ outsideOnly: r.match.path_scope === "outside-project",
50954
+ tool: re(r.match.tool),
50955
+ description: re(r.match.description),
50956
+ ability: re(r.match.ability),
50957
+ examples: r.examples
50958
+ }))
50959
+ };
50960
+ }
50961
+ async function loadCapabilityRules(definitionsDir) {
50962
+ let raw;
50963
+ try {
50964
+ raw = await readFile2(join6(definitionsDir, CAPABILITIES_FILE), "utf8");
50965
+ } catch {
50966
+ return { ok: false, missing: true, error: `${CAPABILITIES_FILE} was not found in ${definitionsDir}` };
50967
+ }
50968
+ let data;
50969
+ try {
50970
+ data = yaml.load(raw);
50971
+ } catch (err2) {
50972
+ return { ok: false, missing: false, error: `${CAPABILITIES_FILE} is not valid YAML: ${String(err2).split("\n")[0]}` };
50973
+ }
50974
+ return parseCapabilityRules(data);
50975
+ }
50976
+ var PACKAGE_RUNNERS = /* @__PURE__ */ new Set(["npx", "bunx", "pnpx", "uvx"]);
50977
+ var SCRIPT_RUNNERS = /* @__PURE__ */ new Set(["node", "nodejs", "python", "python3", "py", "bun", "deno", "tsx", "ts-node"]);
50978
+ var CONTAINERS = /* @__PURE__ */ new Set(["docker", "podman"]);
50979
+ var SHELLS = /* @__PURE__ */ new Set(["bash", "sh", "zsh", "cmd", "powershell", "pwsh"]);
50980
+ var LAUNCHERS = /* @__PURE__ */ new Set([...PACKAGE_RUNNERS, ...SCRIPT_RUNNERS, ...CONTAINERS, ...SHELLS, "npm", "pnpm", "yarn", "uv", "pipx", "env", "exorcist"]);
50981
+ var DOCKER_VALUE_FLAGS = /* @__PURE__ */ new Set([
50982
+ "-e",
50983
+ "--env",
50984
+ "--env-file",
50985
+ "-v",
50986
+ "--volume",
50987
+ "--mount",
50988
+ "--name",
50989
+ "--network",
50990
+ "--net",
50991
+ "-p",
50992
+ "--publish",
50993
+ "-w",
50994
+ "--workdir",
50995
+ "-u",
50996
+ "--user",
50997
+ "--entrypoint",
50998
+ "-l",
50999
+ "--label",
51000
+ "--add-host",
51001
+ "--platform",
51002
+ "--pull",
51003
+ "--restart",
51004
+ "-m",
51005
+ "--memory",
51006
+ "--cpus",
51007
+ "-h",
51008
+ "--hostname",
51009
+ "--device",
51010
+ "--cap-add",
51011
+ "--cap-drop",
51012
+ "--security-opt",
51013
+ "--tmpfs",
51014
+ "--ulimit",
51015
+ "--log-driver",
51016
+ "--log-opt",
51017
+ "--dns",
51018
+ "--runtime",
51019
+ "--gpus"
51020
+ ]);
51021
+ var UV_VALUE_FLAGS = /* @__PURE__ */ new Set(["--directory", "--with", "--from", "--python", "-p", "--project", "--index", "--index-url"]);
51022
+ function basenameOf(cmd) {
51023
+ const b = cmd.replace(/\\/g, "/").split("/").pop() ?? cmd;
51024
+ return b.toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/, "");
51025
+ }
51026
+ function stripVersion(spec2) {
51027
+ let t2 = spec2.trim().toLowerCase().replace(/^(?:npm|jsr|pypi):/, "");
51028
+ const at2 = t2.indexOf("@", t2.startsWith("@") ? 1 : 0);
51029
+ if (at2 > 0) t2 = t2.slice(0, at2);
51030
+ t2 = t2.replace(/\[[^\]]*\]$/, "");
51031
+ t2 = t2.replace(/(?:===?|>=|<=|~=|!=|>|<).*$/, "");
51032
+ return t2;
51033
+ }
51034
+ function dockerImage(spec2) {
51035
+ let t2 = spec2.trim().toLowerCase().replace(/@sha256:.*$/, "");
51036
+ const slash = t2.lastIndexOf("/");
51037
+ const colon = t2.lastIndexOf(":");
51038
+ if (colon > slash) t2 = t2.slice(0, colon);
51039
+ return t2;
51040
+ }
51041
+ function unwrapLaunch(command, args, depth = 0) {
51042
+ const s = args.indexOf("shield");
51043
+ if (s !== -1 && args[s + 1] === "--server") {
51044
+ const dd = args.indexOf("--", s);
51045
+ if (dd !== -1 && args[dd + 1] !== void 0) return unwrapLaunch(args[dd + 1], args.slice(dd + 2), depth + 1);
51046
+ const u = args.indexOf("--url", s);
51047
+ if (u !== -1 && args[u + 1] !== void 0) return { command: "", args: [], url: args[u + 1] };
51048
+ }
51049
+ const base = basenameOf(command);
51050
+ if (depth < 3 && SHELLS.has(base)) {
51051
+ const c = args.findIndex((a) => /^(?:-c|\/c|-command)$/i.test(a));
51052
+ const inner = c === -1 ? void 0 : args[c + 1];
51053
+ if (inner !== void 0) {
51054
+ const parts = inner.trim().split(/\s+/).filter(Boolean).map((p) => p.replace(/^["']|["']$/g, ""));
51055
+ if (parts[0] !== void 0) return unwrapLaunch(parts[0], parts.slice(1), depth + 1);
51056
+ }
51057
+ }
51058
+ if (depth < 3 && base === "env") {
51059
+ const i = args.findIndex((a) => !a.includes("=") && !a.startsWith("-"));
51060
+ if (i !== -1) return unwrapLaunch(args[i], args.slice(i + 1), depth + 1);
51061
+ }
51062
+ return { command, args, url: null };
51063
+ }
51064
+ function firstPositional(args, valueFlags) {
51065
+ for (let i = 0; i < args.length; i++) {
51066
+ const a = args[i];
51067
+ if (a === "--") continue;
51068
+ if (a.startsWith("-")) {
51069
+ if (!a.includes("=") && valueFlags.has(a)) i++;
51070
+ continue;
51071
+ }
51072
+ return i;
51073
+ }
51074
+ return -1;
51075
+ }
51076
+ function packageNames(l) {
51077
+ const base = basenameOf(l.command);
51078
+ const a = l.args;
51079
+ const names = [];
51080
+ let at2 = -1;
51081
+ const pkgAt = (offset) => {
51082
+ const rest = a.slice(offset).filter((x) => x !== "--");
51083
+ const p = packageArg(rest);
51084
+ if (p !== null) {
51085
+ names.push(stripVersion(p));
51086
+ at2 = a.indexOf(p, offset);
51087
+ }
51088
+ };
51089
+ if (PACKAGE_RUNNERS.has(base)) pkgAt(0);
51090
+ else if ((base === "pnpm" || base === "yarn") && a[0] === "dlx") pkgAt(1);
51091
+ else if (base === "npm" && (a[0] === "exec" || a[0] === "x")) pkgAt(1);
51092
+ else if (base === "pipx" && a[0] === "run") pkgAt(1);
51093
+ else if (base === "uv") {
51094
+ for (let i = 0; i < a.length; i++) if ((a[i] === "--with" || a[i] === "--from" || a[i] === "--directory") && a[i + 1]) names.push(a[i + 1].toLowerCase());
51095
+ const run = a.findIndex((x) => x === "run");
51096
+ if (run !== -1) {
51097
+ const rest = a.slice(run + 1);
51098
+ const j = firstPositional(rest, UV_VALUE_FLAGS);
51099
+ if (j !== -1) {
51100
+ names.push(stripVersion(rest[j]));
51101
+ at2 = run + 1 + j;
51102
+ }
51103
+ }
51104
+ } else if (CONTAINERS.has(base)) {
51105
+ const run = a.findIndex((x) => x === "run");
51106
+ if (run !== -1) {
51107
+ const rest = a.slice(run + 1);
51108
+ const j = firstPositional(rest, DOCKER_VALUE_FLAGS);
51109
+ if (j !== -1) {
51110
+ names.push(dockerImage(rest[j]));
51111
+ at2 = run + 1 + j;
51112
+ }
51113
+ }
51114
+ } else if (SCRIPT_RUNNERS.has(base)) {
51115
+ const m = a.indexOf("-m");
51116
+ if (m !== -1 && a[m + 1]) {
51117
+ names.push(a[m + 1].toLowerCase());
51118
+ at2 = m + 1;
51119
+ } else {
51120
+ const j = firstPositional(a.filter((x) => x !== "run"), /* @__PURE__ */ new Set(["--allow-read", "--config"]));
51121
+ const script = j === -1 ? void 0 : a.filter((x) => x !== "run")[j];
51122
+ if (script !== void 0) {
51123
+ names.push(stripVersion(script.replace(/\\/g, "/")));
51124
+ at2 = a.indexOf(script);
51125
+ }
51126
+ }
51127
+ }
51128
+ if (!LAUNCHERS.has(base) && base !== "") names.push(base);
51129
+ return { names, at: at2 };
51130
+ }
51131
+ function serverIdentities(server2) {
51132
+ if (server2.ability !== void 0) return [];
51133
+ const out = [];
51134
+ const l = unwrapLaunch(server2.command ?? "", server2.args ?? []);
51135
+ const url = l.url ?? server2.url;
51136
+ if (url) {
51137
+ try {
51138
+ const u = new URL(url);
51139
+ out.push(`${u.hostname}${u.pathname}`.toLowerCase());
51140
+ } catch {
51141
+ out.push(url.toLowerCase());
51142
+ }
51143
+ }
51144
+ if (l.command) out.push(...packageNames(l).names);
51145
+ return [...new Set(out.filter((n) => n.length > 0))];
51146
+ }
51147
+ var CREDENTIALS = /^(?:\.ssh|\.aws|\.gnupg|\.gpg|\.kube|\.docker|\.azure|\.gcloud|\.password-store|\.netrc|\.npmrc|\.pypirc|\.git-credentials|keychains?)$/i;
51148
+ var PERSONAL = /^(?:\.config|\.local|library|documents|desktop|downloads|pictures|mail|appdata|onedrive|dropbox|icloud drive)$/i;
51149
+ var SYSTEM = /^(?:etc|var|private|proc|sys|boot|root|srv)$/i;
51150
+ var HOME = /^(?:~|\$home|\$\{home\}|%userprofile%|%homepath%)$/i;
51151
+ var PROJECT = /^(?:\$\{(?:workspacefolder|workspaceroot|pwd|projectroot|project_dir|cwd)\}|\$pwd|%cd%)$/i;
51152
+ var homeOrPersonal = (rest) => rest.length === 0 || PERSONAL.test(rest[0]);
51153
+ function isOutsideProject(raw) {
51154
+ let p = raw.trim().replace(/^["']|["']$/g, "").replace(/\\/g, "/");
51155
+ const absolute = p.startsWith("/");
51156
+ p = p.replace(/(?:\/\*\*?)+$/, "");
51157
+ if (p === "" && absolute) return true;
51158
+ if (p === "" || p === "**" || p === "*") return false;
51159
+ const segs = p.split("/").filter((x) => x !== "");
51160
+ if (segs.some((x) => CREDENTIALS.test(x))) return true;
51161
+ const first = segs[0] ?? "";
51162
+ if (/^[a-z]:$/i.test(first)) {
51163
+ if ((segs[1] ?? "").toLowerCase() === "users") return segs.length <= 3 || PERSONAL.test(segs[3]);
51164
+ return segs.length === 1;
51165
+ }
51166
+ if (p.startsWith("/")) {
51167
+ if (segs.length === 0) return true;
51168
+ const top = first.toLowerCase();
51169
+ if (top === "home" || top === "users") return segs.length <= 2 || PERSONAL.test(segs[2]);
51170
+ if (top === "volumes" || top === "mnt" || top === "media") return segs.length <= 2;
51171
+ return SYSTEM.test(top);
51172
+ }
51173
+ if (HOME.test(first)) return homeOrPersonal(segs.slice(1));
51174
+ let depth = 0;
51175
+ for (const x of PROJECT.test(first) ? segs.slice(1) : segs) {
51176
+ if (x === "..") depth--;
51177
+ else if (x !== ".") depth++;
51178
+ if (depth < 0) return true;
51179
+ }
51180
+ return false;
51181
+ }
51182
+ function pathArguments(server2) {
51183
+ const l = unwrapLaunch(server2.command ?? "", server2.args ?? []);
51184
+ const { at: at2 } = packageNames(l);
51185
+ const out = [];
51186
+ l.args.forEach((a, i) => {
51187
+ if (i === at2) return;
51188
+ let v = a;
51189
+ const eq = /^--?[A-Za-z][\w-]*=(.*)$/.exec(a);
51190
+ if (eq) v = eq[1] ?? "";
51191
+ const src = /(?:^|,)(?:src|source)=([^,]+)/.exec(v);
51192
+ if (src) v = src[1] ?? "";
51193
+ else {
51194
+ const bind = /^([~/][^:]*):\/.*/.exec(v);
51195
+ if (bind) v = bind[1] ?? "";
51196
+ }
51197
+ if (v.startsWith("-") || v.includes("://")) return;
51198
+ if (/^(?:[/~.]|\$|%|[A-Za-z]:[\\/]?$|[A-Za-z]:[\\/])/.test(v)) out.push(v);
51199
+ });
51200
+ return out;
51201
+ }
51202
+ function claudePath(p) {
51203
+ if (p.startsWith("//")) return p.slice(1);
51204
+ if (p.startsWith("/")) return `.${p}`;
51205
+ return p;
51206
+ }
51207
+ function ruleEvidence(rule, server2) {
51208
+ if (server2.ability !== void 0) {
51209
+ if (!rule.ability) return null;
51210
+ const m = rule.ability.exec(server2.ability);
51211
+ if (!m) return null;
51212
+ if (rule.outsideOnly && !isOutsideProject(claudePath(m[1] ?? ""))) return null;
51213
+ return server2.ability;
51214
+ }
51215
+ if (rule.package) {
51216
+ for (const id of serverIdentities(server2)) {
51217
+ if (!rule.package.test(id) || rule.exclude && rule.exclude.test(id)) continue;
51218
+ if (rule.outsideOnly) {
51219
+ const outside = pathArguments(server2).find(isOutsideProject);
51220
+ if (outside !== void 0) return `${id} ${outside}`;
51221
+ continue;
51222
+ }
51223
+ return id;
51224
+ }
51225
+ }
51226
+ for (const t2 of server2.tools ?? []) {
51227
+ if (rule.tool && rule.tool.test(t2.name)) return `tool ${t2.name}`;
51228
+ if (rule.description && t2.description && rule.description.test(t2.description)) return `tool ${t2.name} (description)`;
51229
+ }
51230
+ return null;
51231
+ }
51232
+ function classifyCapabilities(server2, rules) {
51233
+ const reasons = [];
51234
+ for (const rule of rules) {
51235
+ const evidence = ruleEvidence(rule, server2);
51236
+ if (evidence !== null) reasons.push({ capability: rule.capability, ruleId: rule.id, label: rule.label, evidence: evidence.slice(0, 120) });
51237
+ }
51238
+ const has = new Set(reasons.map((r) => r.capability));
51239
+ return { capabilities: CAPABILITIES.filter((c) => has.has(c)), reasons };
51240
+ }
51241
+
51242
+ // ../core/src/package-pin.ts
51243
+ var NPM_RUNNERS = /* @__PURE__ */ new Set(["npx", "bunx", "pnpx", "uvx"]);
51244
+ var CONTAINERS2 = /* @__PURE__ */ new Set(["docker", "podman"]);
51245
+ var DOCKER_VALUE_FLAGS2 = /* @__PURE__ */ new Set([
51246
+ "--add-host",
51247
+ "--annotation",
51248
+ "-a",
51249
+ "--attach",
51250
+ "--blkio-weight",
51251
+ "--blkio-weight-device",
51252
+ "--cap-add",
51253
+ "--cap-drop",
51254
+ "--cgroup-parent",
51255
+ "--cgroupns",
51256
+ "--cidfile",
51257
+ "--cpu-period",
51258
+ "--cpu-quota",
51259
+ "--cpu-rt-period",
51260
+ "--cpu-rt-runtime",
51261
+ "-c",
51262
+ "--cpu-shares",
51263
+ "--cpus",
51264
+ "--cpuset-cpus",
51265
+ "--cpuset-mems",
51266
+ "--detach-keys",
51267
+ "--device",
51268
+ "--device-cgroup-rule",
51269
+ "--device-read-bps",
51270
+ "--device-read-iops",
51271
+ "--device-write-bps",
51272
+ "--device-write-iops",
51273
+ "--dns",
51274
+ "--dns-option",
51275
+ "--dns-search",
51276
+ "--domainname",
51277
+ "--entrypoint",
51278
+ "-e",
51279
+ "--env",
51280
+ "--env-file",
51281
+ "--expose",
51282
+ "--gpus",
51283
+ "--group-add",
51284
+ "--health-cmd",
51285
+ "--health-interval",
51286
+ "--health-retries",
51287
+ "--health-start-interval",
51288
+ "--health-start-period",
51289
+ "--health-timeout",
51290
+ "-h",
51291
+ "--hostname",
51292
+ "--ip",
51293
+ "--ip6",
51294
+ "--ipc",
51295
+ "--isolation",
51296
+ "--kernel-memory",
51297
+ "-l",
51298
+ "--label",
51299
+ "--label-file",
51300
+ "--link",
51301
+ "--link-local-ip",
51302
+ "--log-driver",
51303
+ "--log-opt",
51304
+ "--mac-address",
51305
+ "-m",
51306
+ "--memory",
51307
+ "--memory-reservation",
51308
+ "--memory-swap",
51309
+ "--memory-swappiness",
51310
+ "--mount",
51311
+ "--name",
51312
+ "--network",
51313
+ "--net",
51314
+ "--network-alias",
51315
+ "--net-alias",
51316
+ "--oom-score-adj",
51317
+ "--pid",
51318
+ "--pids-limit",
51319
+ "--platform",
51320
+ "-p",
51321
+ "--publish",
51322
+ "--pull",
51323
+ "--restart",
51324
+ "--runtime",
51325
+ "--security-opt",
51326
+ "--shm-size",
51327
+ "--stop-signal",
51328
+ "--stop-timeout",
51329
+ "--storage-opt",
51330
+ "--sysctl",
51331
+ "--tmpfs",
51332
+ "-u",
51333
+ "--user",
51334
+ "--ulimit",
51335
+ "--userns",
51336
+ "--uts",
51337
+ "-v",
51338
+ "--volume",
51339
+ "--volume-driver",
51340
+ "--volumes-from",
51341
+ "-w",
51342
+ "--workdir",
51343
+ // podman
51344
+ "--arch",
51345
+ "--authfile",
51346
+ "--cgroup-conf",
51347
+ "--cgroups",
51348
+ "--chrootdirs",
51349
+ "--conmon-pidfile",
51350
+ "--creds",
51351
+ "--decryption-key",
51352
+ "--env-merge",
51353
+ "--gidmap",
51354
+ "--hostuser",
51355
+ "--image-volume",
51356
+ "--init-path",
51357
+ "--log-level",
51358
+ "--os",
51359
+ "--passwd-entry",
51360
+ "--personality",
51361
+ "--pod",
51362
+ "--pod-id-file",
51363
+ "--preserve-fds",
51364
+ "--requires",
51365
+ "--sdnotify",
51366
+ "--seccomp-policy",
51367
+ "--secret",
51368
+ "--subgidname",
51369
+ "--subuidname",
51370
+ "--systemd",
51371
+ "--timeout",
51372
+ "--tz",
51373
+ "--uidmap",
51374
+ "--umask",
51375
+ "--unsetenv",
51376
+ "--variant",
51377
+ "--workdir"
51378
+ ]);
51379
+ var DOCKER_BOOL_FLAGS = /* @__PURE__ */ new Set([
51380
+ "-d",
51381
+ "--detach",
51382
+ "-i",
51383
+ "--interactive",
51384
+ "-t",
51385
+ "--tty",
51386
+ "--rm",
51387
+ "--init",
51388
+ "--privileged",
51389
+ "--read-only",
51390
+ "-P",
51391
+ "--publish-all",
51392
+ "--no-healthcheck",
51393
+ "--oom-kill-disable",
51394
+ "--sig-proxy",
51395
+ "--disable-content-trust",
51396
+ "-q",
51397
+ "--quiet",
51398
+ "--use-api-socket",
51399
+ "--replace",
51400
+ "--no-hosts",
51401
+ "--http-proxy",
51402
+ "--read-only-tmpfs",
51403
+ "--rmi",
51404
+ "--env-host",
51405
+ "--tls-verify"
51406
+ ]);
51407
+ var DOCKER_SHORT_VALUE = /* @__PURE__ */ new Set(["a", "c", "e", "h", "l", "m", "p", "u", "v", "w"]);
51408
+ var DOCKER_SHORT_BOOL = /* @__PURE__ */ new Set(["d", "i", "t", "P", "q"]);
51409
+ var IMAGE_REF = /^(?:[a-z0-9.-]+(?::\d+)?\/)?[a-z0-9]+(?:[._-][a-z0-9]+)*(?:\/[a-z0-9]+(?:[._-][a-z0-9]+)*)*(?::[\w][\w.-]{0,127})?(?:@sha256:[0-9a-f]{64})?$/;
51410
+ function dockerRunImage(args) {
51411
+ const run = args.indexOf("run");
51412
+ if (run === -1) return null;
51413
+ const all = args.join(" ");
51414
+ for (let i = run + 1; i < args.length; i++) {
51415
+ const a = args[i];
51416
+ if (a === "--") continue;
51417
+ if (a.startsWith("--")) {
51418
+ if (a.includes("=")) continue;
51419
+ if (DOCKER_VALUE_FLAGS2.has(a)) {
51420
+ i++;
51421
+ continue;
51422
+ }
51423
+ if (DOCKER_BOOL_FLAGS.has(a)) continue;
51424
+ return { unknown: all };
51425
+ }
51426
+ if (a.startsWith("-") && a.length > 1) {
51427
+ let takesNext = false;
51428
+ for (let k = 1; k < a.length; k++) {
51429
+ const c = a[k];
51430
+ if (DOCKER_SHORT_BOOL.has(c)) continue;
51431
+ if (DOCKER_SHORT_VALUE.has(c)) {
51432
+ takesNext = k === a.length - 1;
51433
+ break;
51434
+ }
51435
+ return { unknown: all };
51436
+ }
51437
+ if (takesNext) i++;
51438
+ continue;
51439
+ }
51440
+ return IMAGE_REF.test(a) ? { image: a } : { unknown: all };
51441
+ }
51442
+ return { unknown: all };
51443
+ }
51444
+ var baseName = (cmd) => (cmd.replace(/\\/g, "/").split("/").pop() ?? cmd).toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/, "");
51445
+ function serverPackageRef(server2) {
51446
+ if (typeof server2 !== "object" || server2 === null || Array.isArray(server2)) return null;
51447
+ const s = server2;
51448
+ if (typeof s["command"] !== "string") return null;
51449
+ const rawArgs = Array.isArray(s["args"]) ? s["args"] : [];
51450
+ if (!rawArgs.every((a2) => typeof a2 === "string")) return null;
51451
+ let command = s["command"];
51452
+ let args = rawArgs;
51453
+ if (args.length === 0 && /\s/.test(command.trim())) {
51454
+ const parts = command.trim().split(/\s+/);
51455
+ command = parts[0] ?? "";
51456
+ args = parts.slice(1);
51457
+ }
51458
+ const l = unwrapLaunch(command, args);
51459
+ if (l.url !== null) return null;
51460
+ const base = baseName(l.command);
51461
+ const a = l.args.filter((x) => x !== "--");
51462
+ if (NPM_RUNNERS.has(base)) return packageArg(a);
51463
+ if ((base === "pnpm" || base === "yarn") && a[0] === "dlx") return packageArg(a.slice(1));
51464
+ if (base === "npm" && (a[0] === "exec" || a[0] === "x")) return packageArg(a.slice(1));
51465
+ if (base === "pipx" && a[0] === "run") return packageArg(a.slice(1));
51466
+ if (CONTAINERS2.has(base)) {
51467
+ const r = dockerRunImage(a);
51468
+ if (r === null) return null;
51469
+ return "image" in r ? r.image : `${base} ${r.unknown}`;
51470
+ }
51471
+ return null;
51472
+ }
51473
+ var EXACT_NPM = /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
51474
+ var EXACT_PY = /^v?\d+(?:\.\d+)*(?:(?:a|b|rc|\.post|\.dev)\d+)*(?:\+[0-9A-Za-z.]+)?$/i;
51475
+ var PY_SPEC = /^([A-Za-z0-9][A-Za-z0-9._-]*)(\[[^\]]*\])?\s*(===|==|>=|<=|~=|!=|>|<)\s*(\S.*)$/;
51476
+ var NPM_SPEC = /^(?:(?:npm|jsr|pypi):)?(@[a-z0-9._~-]+\/)?[a-z0-9._~-]+(\[[^\]]*\])?(?:@(.*))?$/i;
51477
+ var IMAGE_SPEC = /^(?:[a-z0-9.-]+(?::\d+)?\/)?[a-z0-9._-]+(?:\/[a-z0-9._-]+)*(?::([\w][\w.-]{0,127}))?$/i;
51478
+ var MOVING_TAGS = /^(?:latest|main|master|edge|nightly|dev|develop|stable|beta|alpha|canary|next|rc|unstable|current|lts|release|head|trunk|preview|snapshot)$/i;
51479
+ function isUnpinnedRef(spec2) {
51480
+ const s = spec2.trim();
51481
+ if (/^(?:docker|podman) run\b/.test(s)) return true;
51482
+ if (s === "" || s.length > 300) return false;
51483
+ if (/^(?:\.{0,2}\/|~\/|[a-z][a-z0-9+.-]*:\/\/|git\+|file:|[A-Za-z]:[\\/])/i.test(s)) return false;
51484
+ if (/@sha256:[0-9a-f]{64}$/i.test(s)) return false;
51485
+ const py = PY_SPEC.exec(s);
51486
+ if (py) {
51487
+ const op = py[3] ?? "";
51488
+ const ver = (py[4] ?? "").trim();
51489
+ return !((op === "==" || op === "===") && EXACT_PY.test(ver));
51490
+ }
51491
+ const npm = NPM_SPEC.exec(s);
51492
+ if (npm) {
51493
+ const ver = npm[3];
51494
+ if (ver === void 0 || ver === "") return true;
51495
+ return !EXACT_NPM.test(ver);
51496
+ }
51497
+ const img = IMAGE_SPEC.exec(s);
51498
+ if (img) {
51499
+ const tag = img[1];
51500
+ return tag === void 0 || MOVING_TAGS.test(tag);
51501
+ }
51502
+ return false;
51503
+ }
51504
+
51505
+ // ../core/src/hidden-escapes.ts
51506
+ var ESC = /\\u\{([0-9a-fA-F]{1,6})\}|\\U([0-9a-fA-F]{8})|\\u([0-9a-fA-F]{4})|&#[xX]([0-9a-fA-F]{1,6});|&#(\d{1,7});/g;
51507
+ var MAX_RUN_POINTS = 4e3;
51508
+ var MAX_RUNS = 100;
51509
+ var ZERO_WIDTH = /* @__PURE__ */ new Set([8203, 8204, 8205, 8288, 8289, 8290, 8291, 8292, 6158, 65279]);
51510
+ function kindOf(cp) {
51511
+ if (cp >= 917504 && cp <= 917631) return "tag-block";
51512
+ if (cp >= 65024 && cp <= 65039 || cp >= 917760 && cp <= 917999) return "variation-selector";
51513
+ if (ZERO_WIDTH.has(cp)) return "zero-width";
51514
+ return null;
51515
+ }
51516
+ function isNoise(cp) {
51517
+ return ZERO_WIDTH.has(cp) || isInvisibleFormat(cp) || cp === 4447 || cp === 4448 || cp === 12644 || cp === 65440;
51518
+ }
51519
+ var MIN_RUN = { "tag-block": 4, "variation-selector": 4, "zero-width": 8 };
51520
+ function isFlagTags(run) {
51521
+ if (run.kind !== "tag-block" || run.codePoints.length > 7) return false;
51522
+ const s = String.fromCharCode(...run.codePoints.map((cp) => cp - 917504));
51523
+ return /^[a-z0-9]{2,6}\x7f?$/.test(s) || /^[a-z0-9]{0,6}\x7f$/.test(s);
51524
+ }
51525
+ function findEscapedHidden(text) {
51526
+ if (typeof text !== "string" || !(text.includes("\\u") || text.includes("\\U") || text.includes("&#"))) return [];
51527
+ const out = [];
51528
+ let run = null;
51529
+ let pendingHigh = null;
51530
+ const flush = () => {
51531
+ if (run && run.codePoints.length >= MIN_RUN[run.kind] && out.length < MAX_RUNS && !isFlagTags(run)) out.push(run);
51532
+ run = null;
51533
+ };
51534
+ const add = (cp, at2, end) => {
51535
+ const k = kindOf(cp);
51536
+ if (run && run.end === at2 && run.kind !== "zero-width" && k !== run.kind && isNoise(cp)) {
51537
+ run.end = end;
51538
+ return;
51539
+ }
51540
+ if (k === null) {
51541
+ flush();
51542
+ return;
51543
+ }
51544
+ if (run && (run.end !== at2 || run.kind !== k)) flush();
51545
+ run ??= { kind: k, offset: at2, end, codePoints: [] };
51546
+ if (run.codePoints.length < MAX_RUN_POINTS) run.codePoints.push(cp);
51547
+ run.end = end;
51548
+ };
51549
+ ESC.lastIndex = 0;
51550
+ let m;
51551
+ let lastEnd = -1;
51552
+ while ((m = ESC.exec(text)) !== null) {
51553
+ const at2 = m.index;
51554
+ const end = at2 + m[0].length;
51555
+ if (at2 !== lastEnd && pendingHigh) pendingHigh = null;
51556
+ if (at2 !== lastEnd) flush();
51557
+ lastEnd = end;
51558
+ const hex = m[1] ?? m[2] ?? m[4];
51559
+ let cp = hex !== void 0 ? parseInt(hex, 16) : m[3] !== void 0 ? parseInt(m[3], 16) : parseInt(m[5] ?? "", 10);
51560
+ if (!Number.isFinite(cp) || cp > 1114111) {
51561
+ flush();
51562
+ continue;
51563
+ }
51564
+ if (m[3] !== void 0) {
51565
+ if (cp >= 55296 && cp <= 56319) {
51566
+ pendingHigh = { cp, at: at2 };
51567
+ continue;
51568
+ }
51569
+ if (cp >= 56320 && cp <= 57343) {
51570
+ if (!pendingHigh) {
51571
+ flush();
51572
+ continue;
51573
+ }
51574
+ cp = 65536 + (pendingHigh.cp - 55296 << 10) + (cp - 56320);
51575
+ const start = pendingHigh.at;
51576
+ pendingHigh = null;
51577
+ add(cp, start, end);
51578
+ continue;
51579
+ }
51580
+ }
51581
+ pendingHigh = null;
51582
+ add(cp, at2, end);
51583
+ }
51584
+ flush();
51585
+ return out;
51586
+ }
51587
+ function decodeZeroWidthBinary(codePoints) {
51588
+ if (codePoints.length < 16) return void 0;
51589
+ const counts = /* @__PURE__ */ new Map();
51590
+ for (const cp of codePoints) counts.set(cp, (counts.get(cp) ?? 0) + 1);
51591
+ const cps = codePoints.filter((cp) => (counts.get(cp) ?? 0) > 2);
51592
+ const kinds = [...new Set(cps)].sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0));
51593
+ if (kinds.length < 2 || kinds.length > 3) return void 0;
51594
+ const [one, two, sep4] = kinds;
51595
+ let groups = [];
51596
+ if (sep4 !== void 0) {
51597
+ let cur = [];
51598
+ for (const cp of cps) {
51599
+ if (cp === sep4) {
51600
+ if (cur.length) groups.push(cur);
51601
+ cur = [];
51602
+ } else cur.push(cp);
51603
+ }
51604
+ if (cur.length) groups.push(cur);
51605
+ } else {
51606
+ for (let i = 0; i + 8 <= cps.length; i += 8) groups.push(cps.slice(i, i + 8));
51607
+ }
51608
+ if (groups.length < 2 || groups.some((g) => g.length < 7 || g.length > 8)) return void 0;
51609
+ let best;
51610
+ for (const zero of [one, two]) {
51611
+ const s = groups.map((g) => String.fromCharCode(parseInt(g.map((cp) => cp === zero ? "0" : "1").join(""), 2))).join("");
51612
+ const printable3 = [...s].filter((c) => c >= " " && c <= "~").length;
51613
+ if (printable3 / s.length >= 0.9 && (best === void 0 || printable3 > [...best].filter((c) => c >= " " && c <= "~").length)) best = s;
51614
+ }
51615
+ return best === void 0 ? void 0 : best.slice(0, 500);
51616
+ }
51617
+ function decodeEscapedRun(run) {
51618
+ if (run.kind === "zero-width") return decodeZeroWidthBinary(run.codePoints);
51619
+ const first = decodeHidden(String.fromCodePoint(...run.codePoints.slice(0, 2e3)))[0];
51620
+ return first && first.message.length > 0 ? first.message : void 0;
51621
+ }
51622
+
51623
+ // ../core/src/encodings.ts
51624
+ var MAX_FOUND = 20;
51625
+ var MAX_DECODED = 2e3;
51626
+ var PERCENT_RUN = /(?:%[0-9A-Fa-f]{2}){16,}/g;
51627
+ function readableAscii(s) {
51628
+ if (s.length < 12) return false;
51629
+ let printable3 = 0;
51630
+ for (const c of s) if (c >= " " && c <= "~" || c === "\n" || c === " " || c === "\r") printable3++;
51631
+ if (printable3 / s.length < 0.95) return false;
51632
+ return s.split(/\s+/).filter((w) => /[A-Za-z]{2,}/.test(w)).length >= 3;
51633
+ }
51634
+ var ENGLISH = new Set("the be to of and a in that have i it for not on with he as you do at this but his by from they we say her she or an will my one all would there their what so up out if about who get which go me when make can like time no just him know take people into year your good some could them see other than then now look only come its over think also back after use two how our work first well way even new want because any these give day most us is are was were been has had did does each every before add run line file code should must never always don't do not please here where why need all any very more such only same than tell them it's explain right after it these those make sure without asking user users".split(" "));
51635
+ function words(s) {
51636
+ return s.toLowerCase().split(/[^a-z']+/).filter((w) => w.length > 1);
51637
+ }
51638
+ function proseLike(line) {
51639
+ let n = 0;
51640
+ for (const c of line) if (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c === " ") n++;
51641
+ return n >= line.trim().length * 0.75;
51642
+ }
51643
+ function englishShare(ws) {
51644
+ if (ws.length === 0) return 0;
51645
+ return ws.filter((w) => ENGLISH.has(w)).length / ws.length;
51646
+ }
51647
+ function rot13(s) {
51648
+ let out = "";
51649
+ for (let i = 0; i < s.length; i++) {
51650
+ const c = s.charCodeAt(i);
51651
+ if (c >= 65 && c <= 90) out += String.fromCharCode((c - 65 + 13) % 26 + 65);
51652
+ else if (c >= 97 && c <= 122) out += String.fromCharCode((c - 97 + 13) % 26 + 97);
51653
+ else out += s[i];
51654
+ }
51655
+ return out;
51656
+ }
51657
+ var MAX_LINE = 4e3;
51658
+ function findOtherEncodings(text) {
51659
+ if (typeof text !== "string") return [];
51660
+ const out = [];
51661
+ if (text.includes("%")) {
51662
+ PERCENT_RUN.lastIndex = 0;
51663
+ let m;
51664
+ while (out.length < MAX_FOUND && (m = PERCENT_RUN.exec(text)) !== null) {
51665
+ const bytes = Buffer.from(m[0].replace(/%/g, ""), "hex");
51666
+ const decoded = bytes.toString("utf8");
51667
+ if (readableAscii(decoded)) out.push({ index: m.index, length: m[0].length, kind: "percent", decoded: decoded.slice(0, MAX_DECODED) });
51668
+ }
51669
+ }
51670
+ let start = 0;
51671
+ while (out.length < MAX_FOUND && start < text.length) {
51672
+ let end = text.indexOf("\n", start);
51673
+ if (end === -1) end = text.length;
51674
+ const line = text.slice(start, end);
51675
+ if (line.length >= 24 && line.length <= MAX_LINE) {
51676
+ const ws = words(line);
51677
+ if (ws.length >= 6 && englishShare(ws) < 0.1 && proseLike(line)) {
51678
+ const rs = ws.map(rot13);
51679
+ const hits = new Set(rs.filter((w) => ENGLISH.has(w))).size;
51680
+ if (hits >= 4 && englishShare(rs) >= 0.3) {
51681
+ const rotated = rot13(line);
51682
+ out.push({ index: start, length: line.length, kind: "rot13", decoded: rotated.trim().slice(0, MAX_DECODED) });
51683
+ }
51684
+ }
51685
+ }
51686
+ start = end + 1;
51687
+ }
51688
+ return out.sort((a, b) => a.index - b.index);
51689
+ }
51690
+
50691
51691
  // ../core/src/scanner/context.ts
50692
51692
  var TOKEN_PREFIX = /^(?:gh[pousr]_|github_pat_|sk-ant-(?:api|oat|admin)\d\d-|sk-proj-|sk-|AKIA|xox[baprs]-|AIza|sk_live_|npm_)/i;
50693
51693
  var PLACEHOLDER_WORDS = /your|(?:^|[-_])my[-_]|their|example|placeholder|change[-_]?me|replace|insert|dummy|fake|sample|redacted|here(?:$|[-_])|todo|demo|mock|selftest|test|x{3,}|y{3,}|\*{3,}|…|\.\.\./i;
@@ -50777,14 +51777,14 @@ var KEY_AT_LINE_START = /^\s*[{[,]?\s*(?:-\s*)?["']?([A-Za-z0-9_.-]+)["']?\s*:/;
50777
51777
  var KEY_ON_LINE = /(?:["']([A-Za-z0-9_.-]+)["']|(?:^|[\s{,[-])([A-Za-z0-9_.-]+))\s*:(?=\s|["'[{|>]|$)/g;
50778
51778
  var IMPERATIVE_BEFORE = /(?<![.\w$])\b(?:run|execute|exec|paste|type|enter|invoke)\b[^\w(]{0,3}$/i;
50779
51779
  var normKey = (k) => k.toLowerCase().replace(/[-_]/g, "");
50780
- function inExecContext(rel, text, at, match = "") {
51780
+ function inExecContext(rel, text, at2, match = "") {
50781
51781
  if (AGENT_ENV_PATH.test(rel)) return true;
50782
51782
  if (/^(?:you\s+must|always|now|first|please)\s+run\b/i.test(match)) return true;
50783
- const lineStart = text.lastIndexOf("\n", at - 1) + 1;
50784
- const before = text.slice(lineStart, at);
51783
+ const lineStart = text.lastIndexOf("\n", at2 - 1) + 1;
51784
+ const before = text.slice(lineStart, at2);
50785
51785
  if (IMPERATIVE_BEFORE.test(before.slice(-40))) return true;
50786
51786
  if (/\.json$/i.test(rel)) {
50787
- const j = jsonKeyAt(text, at);
51787
+ const j = jsonKeyAt(text, at2);
50788
51788
  if (j.inString && j.key !== null) return EXEC_KEYS.has(normKey(j.key));
50789
51789
  }
50790
51790
  const keys = [...before.matchAll(KEY_ON_LINE)];
@@ -50822,10 +51822,10 @@ function fencedRanges(text) {
50822
51822
  if (open4) out.push([open4.at, text.length]);
50823
51823
  return out;
50824
51824
  }
50825
- function inMarkdownCode(text, at, fences) {
50826
- if (fences.some(([a, b]) => at >= a && at < b)) return true;
50827
- const lineStart = text.lastIndexOf("\n", at - 1) + 1;
50828
- const ticks = (text.slice(lineStart, at).match(/`+/g) ?? []).length;
51825
+ function inMarkdownCode(text, at2, fences) {
51826
+ if (fences.some(([a, b]) => at2 >= a && at2 < b)) return true;
51827
+ const lineStart = text.lastIndexOf("\n", at2 - 1) + 1;
51828
+ const ticks = (text.slice(lineStart, at2).match(/`+/g) ?? []).length;
50829
51829
  return ticks % 2 === 1;
50830
51830
  }
50831
51831
  var OPEN_QUOTE = /["'“‘«‹`„]\s*$/;
@@ -50860,23 +51860,27 @@ function quoteSpans(s) {
50860
51860
  }
50861
51861
  return spans;
50862
51862
  }
50863
- function isQuotedExample(text, at, len, cues) {
50864
- const legacy = OPEN_QUOTE.test(text.slice(Math.max(0, at - 3), at)) && CLOSES_SOON.test(text.slice(at + len, at + len + 60));
51863
+ function isQuotedExample(text, at2, len, cues) {
51864
+ const legacy = OPEN_QUOTE.test(text.slice(Math.max(0, at2 - 3), at2)) && CLOSES_SOON.test(text.slice(at2 + len, at2 + len + 60));
50865
51865
  let inside2 = false;
50866
51866
  if (!legacy) {
50867
- const paraStartAt = text.lastIndexOf("\n\n", at);
50868
- const from = Math.max(paraStartAt === -1 ? 0 : paraStartAt, at - 1e3);
50869
- const paraEndAt = text.indexOf("\n\n", at + len);
50870
- const to = Math.min(paraEndAt === -1 ? text.length : paraEndAt, at + len + 1e3);
50871
- const local = at - from;
51867
+ const paraStartAt = text.lastIndexOf("\n\n", at2);
51868
+ const from = Math.max(paraStartAt === -1 ? 0 : paraStartAt, at2 - 1e3);
51869
+ const paraEndAt = text.indexOf("\n\n", at2 + len);
51870
+ const to = Math.min(paraEndAt === -1 ? text.length : paraEndAt, at2 + len + 1e3);
51871
+ const local = at2 - from;
50872
51872
  inside2 = quoteSpans(text.slice(from, to)).some(([a, b]) => a < local && local + len <= b && b - (local + len) <= 40);
50873
51873
  }
50874
51874
  if (!legacy && !inside2) return false;
50875
- const paraStart = text.lastIndexOf("\n\n", at);
50876
- const start = Math.max(paraStart === -1 ? 0 : paraStart, at - 400);
50877
- const paraEnd = text.indexOf("\n\n", at + len);
50878
- const end = Math.min(paraEnd === -1 ? text.length : paraEnd, at + len + 300);
50879
- return cues.test(text.slice(start, at) + " " + text.slice(at + len, end));
51875
+ let paraStart = text.lastIndexOf("\n\n", at2);
51876
+ if (paraStart > 0 && /^[\s>"'“‘«`*_-]*$/.test(text.slice(paraStart, at2)) && /:\s*$/.test(text.slice(Math.max(0, paraStart - 200), paraStart))) {
51877
+ paraStart = text.lastIndexOf("\n\n", paraStart - 1);
51878
+ }
51879
+ const start = Math.max(paraStart === -1 ? 0 : paraStart, at2 - 400);
51880
+ const paraEnd = text.indexOf("\n\n", at2 + len);
51881
+ const end = Math.min(paraEnd === -1 ? text.length : paraEnd, at2 + len + 300);
51882
+ const noUrls = (t2) => t2.replace(/\b(?:https?|ftp|wss?):\/\/\S+|\b[\w-]+(?:\.[\w-]+)*\.(?:com|net|org|io|dev|app|ai|co|xyz|info|me|sh|cloud|site|online|test|invalid|example|local|internal)\b\S*/gi, " ");
51883
+ return cues.test(noUrls(text.slice(start, at2)) + " " + noUrls(text.slice(at2 + len, end)));
50880
51884
  }
50881
51885
  function embeddedDocumentKind(decoded) {
50882
51886
  if (/^(?:\uFEFF|\xEF\xBB\xBF)/.test(decoded)) return "file with a byte-order mark";
@@ -50936,7 +51940,7 @@ function jsonStrings(text) {
50936
51940
  jsonCache = { text, strings: strings3 };
50937
51941
  return strings3;
50938
51942
  }
50939
- function jsonKeyAt(text, at) {
51943
+ function jsonKeyAt(text, at2) {
50940
51944
  const strings3 = jsonStrings(text);
50941
51945
  let lo = 0;
50942
51946
  let hi = strings3.length - 1;
@@ -50944,8 +51948,8 @@ function jsonKeyAt(text, at) {
50944
51948
  const mid = lo + hi >> 1;
50945
51949
  const s = strings3[mid];
50946
51950
  if (!s) break;
50947
- if (at < s.start) hi = mid - 1;
50948
- else if (at > s.end) lo = mid + 1;
51951
+ if (at2 < s.start) hi = mid - 1;
51952
+ else if (at2 > s.end) lo = mid + 1;
50949
51953
  else return { inString: true, key: s.key };
50950
51954
  }
50951
51955
  return { inString: false, key: null };
@@ -50973,6 +51977,11 @@ function benignPayloadKind(decoded, around) {
50973
51977
  }
50974
51978
 
50975
51979
  // ../core/src/scanner/signature-engine.ts
51980
+ var ESCAPE_DECODING_FILE = /\.(?:jsonc?|json5|ya?ml|toml|[cm]?[jt]sx?|mts|cts|py|go|rs|java|kts?|cs|rb|php|swift|html?|xml|svg|ipynb|plist|webmanifest)$/i;
51981
+ var DECODED_SECRET = /~\/\.|\.ssh\b|\bid_(?:rsa|dsa|ecdsa|ed25519)\b|(?<![\w.])\.env\b|\.aws\/|\.netrc\b|\.npmrc\b|\.git-credentials\b|\bcredentials?\b|\bpasswords?\b|\bpasswd\b|\bsecrets?\b|\btokens?\b|\bapi[ _-]?keys?\b|\bprivate[ _-]?keys?\b|\bprocess\.env\b|\bos\.environ\b/i;
51982
+ var DECODED_OVERRIDE = /\b(?:ignore|disregard|override|forget|bypass)\b[^.\n]{0,60}\b(?:instructions?|rules?|prompts?|guidelines|policy|policies)\b|\bsystem prompt\b/i;
51983
+ var DECODED_ADDRESS = /\byou (?:must|should|will|are|need to)\b|\b(?:assistant|agent|ai|llm|model|claude|copilot|cursor|gemini|codex|bot)\b/i;
51984
+ var DECODED_ACTION = /\b(?:run|execute|exec|eval|install|download|delete|remove|send|upload|post|exfiltrate|read|cat|print|reveal|leak|disable|add|insert|append|write|modify|change|push|commit|approve|merge|call|fetch|open|tell)\b/i;
50976
51985
  var MAX_SPAN = 120;
50977
51986
  var regexCache = /* @__PURE__ */ new Map();
50978
51987
  function getRegex(pattern, flags2) {
@@ -51055,6 +52064,7 @@ function joinEscapes(run) {
51055
52064
  function decodedForRun(run) {
51056
52065
  const tags = run.filter((h) => h.class === "tag-block");
51057
52066
  const carrier = tags.length > 0 ? tags : run.filter((h) => h.class === "variation-selector");
52067
+ if (carrier.length === 0) return run.length >= 16 ? decodeZeroWidthBinary(run.slice(0, 8e3).map((h) => h.codePoint)) : void 0;
51058
52068
  const first = decodeHidden(carrier.map((h) => h.char).join(""))[0];
51059
52069
  return first && first.message.length > 0 ? first.message : void 0;
51060
52070
  }
@@ -51139,8 +52149,8 @@ function looksLikeText(bytes) {
51139
52149
  if (printable3 / bytes.length < 0.95) return false;
51140
52150
  const text = bytes.toString("latin1");
51141
52151
  if (/^\s*[{[]/.test(text)) return false;
51142
- const words2 = text.split(/\s+/).filter((w) => /[A-Za-z]{2,}/.test(w)).length;
51143
- return words2 >= 4 || COMMAND_LIKE.test(text);
52152
+ const words3 = text.split(/\s+/).filter((w) => /[A-Za-z]{2,}/.test(w)).length;
52153
+ return words3 >= 4 || COMMAND_LIKE.test(text);
51144
52154
  }
51145
52155
  function rawMatches(re2, text) {
51146
52156
  const out = [];
@@ -51187,6 +52197,16 @@ function guarded(jobs, ms) {
51187
52197
  guardCtx["out"] = null;
51188
52198
  }
51189
52199
  }
52200
+ function timeoutFinding(def, base, agentFacing) {
52201
+ return {
52202
+ ...base,
52203
+ severity: agentFacing ? base.severity : "medium",
52204
+ line: 1,
52205
+ col: 1,
52206
+ span: timeoutSpan(def.id),
52207
+ fix: `This file made the ${def.id} check run too long, which can be a deliberate attack on the scanner. Review the file by hand. ${def.fix}`
52208
+ };
52209
+ }
51190
52210
  var MINOR_RUNS_ESCALATE = 5;
51191
52211
  var CHUNK = 1e6;
51192
52212
  var CHUNK_OVERLAP = 16384;
@@ -51234,6 +52254,7 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
51234
52254
  const keep = (text) => {
51235
52255
  if (exclude && exclude.test(text)) return false;
51236
52256
  if (match.validate === "typosquat" && typosquatOf(text) === null) return false;
52257
+ if (match.validate === "unpinned-package" && !isUnpinnedRef(text)) return false;
51237
52258
  if (validateLater) return true;
51238
52259
  if (match.validate === "base64-text" && !isBase64Text(text)) return false;
51239
52260
  if (match.validate === "encoded-text" && !isBase64Text(text) && !isHexText(text)) return false;
@@ -51309,30 +52330,88 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
51309
52330
  for (const [index2, text] of matchesOf(logicalId)) {
51310
52331
  if (!keep(text)) continue;
51311
52332
  if (orders && !ownHits?.has(index2) && !orders.some(([s, e]) => e <= index2 || s >= index2 + text.length)) continue;
51312
- const at = toPlain(index2);
51313
- if (seen.has(at)) continue;
51314
- if (!ctx2.allows(def, text, at, src, index2)) continue;
51315
- seen.add(at);
52333
+ const at2 = toPlain(index2);
52334
+ if (seen.has(at2)) continue;
52335
+ if (!ctx2.allows(def, text, at2, src, index2)) continue;
52336
+ seen.add(at2);
51316
52337
  let span;
51317
52338
  const plainEnd = k > 0 && vis ? (() => {
51318
52339
  const last = toPlain(Math.max(index2, index2 + text.length - 1));
51319
52340
  return last + ((norm.plain.codePointAt(last) ?? 0) > 65535 ? 2 : 1);
51320
52341
  })() : index2 + text.length;
51321
52342
  if (k > 0 && vis || norm.plainMap) {
51322
- span = norm.plainMap ? norm.original.slice(norm.plainMap[at] ?? at, norm.plainMap[plainEnd] ?? norm.original.length) : norm.plain.slice(at, plainEnd);
52343
+ span = norm.plainMap ? norm.original.slice(norm.plainMap[at2] ?? at2, norm.plainMap[plainEnd] ?? norm.original.length) : norm.plain.slice(at2, plainEnd);
51323
52344
  }
51324
- cands.push(span === void 0 ? { at, text } : { at, text, span });
52345
+ cands.push(span === void 0 ? { at: at2, text } : { at: at2, text, span });
51325
52346
  }
51326
52347
  });
52348
+ if (match.join_yaml_lists && /\.ya?ml$/i.test(file.rel)) {
52349
+ const taken = cands.map((c) => c.at).sort((a, b) => a - b);
52350
+ const coveredBetween = (from, to) => {
52351
+ let lo = 0;
52352
+ let hi = taken.length;
52353
+ while (lo < hi) {
52354
+ const mid = lo + hi >> 1;
52355
+ if (taken[mid] < from) lo = mid + 1;
52356
+ else hi = mid;
52357
+ }
52358
+ return lo < taken.length && taken[lo] < to;
52359
+ };
52360
+ const joined = guardedCall(() => {
52361
+ const hits = [];
52362
+ const re2 = getRegex(match.regex, "gi");
52363
+ for (const run of yamlListRuns(norm.plain)) {
52364
+ if (seen.has(run.start) || coveredBetween(run.start, run.end)) continue;
52365
+ re2.lastIndex = 0;
52366
+ let m;
52367
+ while ((m = re2.exec(run.text)) !== null) {
52368
+ if (m[0].length === 0) {
52369
+ re2.lastIndex++;
52370
+ continue;
52371
+ }
52372
+ if (!ctx2.allows(def, m[0], run.start, run.text, m.index)) continue;
52373
+ hits.push({ at: run.start, text: m[0], span: truncateSpan(run.text) });
52374
+ break;
52375
+ }
52376
+ }
52377
+ return hits;
52378
+ }, limitMs);
52379
+ if (joined === null) findings.push(timeoutFinding(def, base, agentFacing));
52380
+ for (const h of joined ?? []) {
52381
+ if (seen.has(h.at)) continue;
52382
+ seen.add(h.at);
52383
+ cands.push(h);
52384
+ }
52385
+ }
51327
52386
  cands.sort((a, b) => a.at - b.at);
51328
52387
  const groups = match.merge_adjacent ? mergeAdjacent(cands, norm.plain) : cands.map((c) => [c]);
51329
52388
  const mineOut = [];
51330
52389
  for (const group of groups) {
51331
- if (match.merge_adjacent && !ctx2.blobCounts(def, group)) continue;
52390
+ const blob = match.merge_adjacent ? ctx2.blobCounts(def, group) : null;
52391
+ if (match.merge_adjacent && blob === null) continue;
51332
52392
  const first = group[0];
51333
52393
  if (!first) continue;
51334
52394
  const { line, col } = pos(norm.plainMap?.[first.at] ?? first.at);
51335
- mineOut.push({ ...base, line, col, span: truncateSpan(first.span ?? first.text) });
52395
+ const prose = blob !== null && blob !== "" && match.decoded_prose_severity !== void 0 && !ctx2.decodedIsOrder(def, blob);
52396
+ mineOut.push({ ...base, ...prose ? { severity: match.decoded_prose_severity } : {}, line, col, span: truncateSpan(first.span ?? first.text) });
52397
+ }
52398
+ if (match.other_encodings) {
52399
+ const encoded = guardedCall(() => findOtherEncodings(norm.plain), limitMs);
52400
+ if (encoded === null) mineOut.push(timeoutFinding(def, base, agentFacing));
52401
+ for (const e of encoded ?? []) {
52402
+ const order = ctx2.decodedIsOrder(def, e.decoded);
52403
+ if (!order && match.decoded_prose_severity === void 0) continue;
52404
+ const { line, col } = pos(norm.plainMap?.[e.index] ?? e.index);
52405
+ mineOut.push({
52406
+ ...base,
52407
+ ...order ? {} : { severity: match.decoded_prose_severity },
52408
+ line,
52409
+ col,
52410
+ span: truncateSpan(norm.plain.slice(e.index, e.index + e.length).trim()),
52411
+ decoded: e.decoded.slice(0, 500),
52412
+ fix: `This text is ${e.kind === "rot13" ? "ROT13-rotated" : "percent-encoded"}; decoded, it reads as shown. ${def.fix}`
52413
+ });
52414
+ }
51336
52415
  }
51337
52416
  findings.push(...capPerFile(def, mineOut));
51338
52417
  }
@@ -51368,6 +52447,11 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
51368
52447
  run = [];
51369
52448
  return;
51370
52449
  }
52450
+ const skip = match.skip_short_run;
52451
+ if (skip && run.length <= skip.max_length && run.every((h) => skip.classes.includes(h.class))) {
52452
+ run = [];
52453
+ return;
52454
+ }
51371
52455
  const { line, col } = pos(first.offset);
51372
52456
  const minor = match.minor_run;
51373
52457
  const isMinor = Boolean(minor && run.length <= minor.max_length && run.every((h) => minor.classes.includes(h.class)));
@@ -51394,6 +52478,24 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
51394
52478
  run.push(hit);
51395
52479
  }
51396
52480
  flush();
52481
+ if (match.escapes && ESCAPE_DECODING_FILE.test(file.rel)) {
52482
+ for (const r of findEscapedHidden(norm.original)) {
52483
+ const cls = r.kind;
52484
+ if (!match.unicode_class.includes(cls)) continue;
52485
+ const { line, col } = pos(r.offset);
52486
+ const decoded = decodedRuns < MAX_HIDDEN_RUNS ? decodeEscapedRun(r) : void 0;
52487
+ if (decoded !== void 0) decodedRuns += 1;
52488
+ if (cls === "tag-block" && decoded === void 0) continue;
52489
+ findings.push({
52490
+ ...base,
52491
+ line,
52492
+ col,
52493
+ span: truncateSpan(norm.original.slice(r.offset, r.end)),
52494
+ ...decoded !== void 0 ? { decoded } : {},
52495
+ fix: `These escapes decode to ${r.codePoints.length} invisible characters (${cls}) once the string is read. ${def.fix}`
52496
+ });
52497
+ }
52498
+ }
51397
52499
  if (minorRuns >= MINOR_RUNS_ESCALATE) {
51398
52500
  for (let i = mineStart; i < findings.length; i++) {
51399
52501
  const f = findings[i];
@@ -51401,6 +52503,23 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
51401
52503
  }
51402
52504
  }
51403
52505
  }
52506
+ if (match.mixed_script) {
52507
+ const words3 = guardedCall(() => findMixedScriptWords(norm.original), limitMs);
52508
+ if (words3 === null) findings.push(timeoutFinding(def, base, agentFacing));
52509
+ const seenWords = /* @__PURE__ */ new Set();
52510
+ for (const w of words3 ?? []) {
52511
+ if (seenWords.has(w.word) || seenWords.size >= 5) continue;
52512
+ seenWords.add(w.word);
52513
+ const { line, col } = pos(w.index);
52514
+ findings.push({
52515
+ ...base,
52516
+ line,
52517
+ col,
52518
+ span: truncateSpan(w.word),
52519
+ fix: `"${w.word}" mixes Latin letters with look-alikes (${w.foreign.join(", ")}); it reads as "${w.readsAs}" but is a different name. ${def.fix}`
52520
+ });
52521
+ }
52522
+ }
51404
52523
  if (match.json_path) {
51405
52524
  const parsed = parseJsonLoose(norm.original);
51406
52525
  if (parsed === void 0) continue;
@@ -51422,23 +52541,62 @@ function runSignatures(file, norm, defs, limitMs = REGEX_TIME_LIMIT_MS) {
51422
52541
  if (!Array.isArray(raw)) continue;
51423
52542
  val = packageArg(raw);
51424
52543
  if (val === null) continue;
52544
+ } else if (match.select === "server-package") {
52545
+ val = serverPackageRef(raw);
52546
+ if (val === null) continue;
51425
52547
  }
51426
52548
  const text = typeof val === "string" ? val : JSON.stringify(val);
51427
52549
  if (valueFilter && !valueFilter.test(text)) continue;
51428
52550
  if (!keep(text)) continue;
51429
- let at = { line: 1, col: 1 };
52551
+ let at2 = { line: 1, col: 1 };
51430
52552
  if (typeof val === "string") {
51431
52553
  const n = seenValues.get(val) ?? 0;
51432
52554
  seenValues.set(val, n + 1);
51433
- at = locateJsonValue(norm.original, val, n, pos);
52555
+ at2 = locateJsonValue(norm.original, val, n, pos);
51434
52556
  }
51435
- findings.push({ ...base, line: at.line, col: at.col, span: truncateSpan(text) });
52557
+ findings.push({ ...base, line: at2.line, col: at2.col, span: truncateSpan(text) });
51436
52558
  }
51437
52559
  }
51438
52560
  }
51439
- const out = lowered.size === 0 ? findings : findings.map((f) => lowered.has(f.ruleId) ? { ...f, severity: "low" } : f);
52561
+ let srcLines = null;
52562
+ const keepsSeverity = (f) => {
52563
+ const keep = defs.find((d) => d.id === f.ruleId)?.low_severity_unless;
52564
+ if (!keep || !keep.paths.some((p) => getRegex(p, "i").test(file.rel))) return false;
52565
+ srcLines ??= norm.original.split("\n");
52566
+ const around = srcLines.slice(Math.max(0, f.line - 3), f.line + 2).join("\n");
52567
+ return getRegex(keep.regex, "i").test(around);
52568
+ };
52569
+ const out = lowered.size === 0 ? findings : findings.map((f) => lowered.has(f.ruleId) && !keepsSeverity(f) ? { ...f, severity: "low" } : f);
51440
52570
  return sameLineGroups(out, defs);
51441
52571
  }
52572
+ function yamlListRuns(text) {
52573
+ const out = [];
52574
+ const lines = text.split("\n");
52575
+ let pos = 0;
52576
+ let run = null;
52577
+ const flush = () => {
52578
+ if (run && run.items.length >= 2) out.push({ start: run.start, end: run.end, text: run.items.join(" ") });
52579
+ run = null;
52580
+ };
52581
+ for (const line of lines) {
52582
+ const m = /^([ \t]*)-[ \t]+(.*?)[ \t]*$/.exec(line);
52583
+ if (m) {
52584
+ const indent = (m[1] ?? "").length;
52585
+ const raw = m[2] ?? "";
52586
+ const item = /^(["'])(.*)\1$/.exec(raw)?.[2] ?? raw;
52587
+ if (run && run.indent === indent) {
52588
+ run.items.push(item);
52589
+ run.end = pos + line.length;
52590
+ } else {
52591
+ flush();
52592
+ run = { start: pos, end: pos + line.length, indent, items: [item] };
52593
+ }
52594
+ } else if (line.trim() !== "" && !/^\s*#/.test(line)) flush();
52595
+ pos += line.length + 1;
52596
+ }
52597
+ flush();
52598
+ return out;
52599
+ }
51442
52600
  var SEVERITY_RANK = { critical: 4, high: 3, medium: 2, low: 1, info: 0 };
51443
52601
  function sameLineGroups(findings, defs) {
51444
52602
  const groupOf = new Map(defs.filter((d) => d.same_line_group).map((d) => [d.id, d.same_line_group]));
@@ -51498,13 +52656,13 @@ function makeContext(file, norm, defs, limitMs) {
51498
52656
  };
51499
52657
  return {
51500
52658
  /** Context checks for one regex match. `src`/`index` are the text and offset it was found in. */
51501
- allows(def, text, at, src, index2) {
52659
+ allows(def, text, at2, src, index2) {
51502
52660
  const m = def.match;
51503
52661
  if (m.validate === "secret-value" && !isCredibleSecret(text, src.slice(index2 + text.length, index2 + text.length + 200))) return false;
51504
- if (m.exec_context && file.role === "config" && !inExecContext(file.rel, norm.plain, at, text)) return false;
52662
+ if (m.exec_context && file.role === "config" && !inExecContext(file.rel, norm.plain, at2, text)) return false;
51505
52663
  if (m.skip_in_code) {
51506
52664
  fences ??= fencedRanges(norm.plain);
51507
- if (inMarkdownCode(norm.plain, at, fences)) return false;
52665
+ if (inMarkdownCode(norm.plain, at2, fences)) return false;
51508
52666
  }
51509
52667
  if (m.quoted_example_cues && isQuotedExample(src, index2, text.length, getRegex(m.quoted_example_cues, "i"))) return false;
51510
52668
  if (m.negated_cues && isNegated(src, index2, getRegex(m.negated_cues, "i"))) return false;
@@ -51517,27 +52675,46 @@ function makeContext(file, norm, defs, limitMs) {
51517
52675
  * with a byte-order mark), it counts only when the decoded text contains
51518
52676
  * something the other rules flag, or one of `decoded_flag_regex`.
51519
52677
  */
52678
+ /**
52679
+ * m20: decoded text that gives an order or carries something to act on: a command or address (COMMAND_LIKE),
52680
+ * a chat-template marker, a phrase the instruction rules flag, a secret or credential file, or words that
52681
+ * address an AI together with an action. Ordinary prose ("the mitochondria is the powerhouse of the cell") is not.
52682
+ */
52683
+ decodedIsOrder(def, decoded) {
52684
+ const sample = decoded.slice(0, 2e5);
52685
+ if (COMMAND_LIKE.test(sample) || DECODED_SECRET.test(sample) || DECODED_OVERRIDE.test(sample)) return true;
52686
+ if (DECODED_ADDRESS.test(sample) && DECODED_ACTION.test(sample)) return true;
52687
+ if (def.match.decoded_flag_regex && getRegex(def.match.decoded_flag_regex, "i").test(sample)) return true;
52688
+ const rules = rescanRules(def);
52689
+ const hits = guarded(rules.map(({ re: re2 }) => ({ re: re2, text: sample })), limitMs);
52690
+ if (hits === null) return true;
52691
+ return hits.some((h, i) => h.some(([index2, t2]) => {
52692
+ const cues = rules[i]?.cues;
52693
+ const neg = rules[i]?.neg;
52694
+ return (!cues || !isQuotedExample(sample, index2, t2.length, cues)) && (!neg || !isNegated(sample, index2, neg));
52695
+ }));
52696
+ },
51520
52697
  blobCounts(def, group) {
51521
52698
  const m = def.match;
51522
52699
  const ok = (t2) => m.validate === "base64-text" ? isBase64Text(t2) : m.validate === "encoded-text" ? isBase64Text(t2) || isHexText(t2) : true;
51523
52700
  const merged = group.map((c) => c.text).join("");
51524
52701
  const piece = ok(merged) ? merged : group.find((c) => ok(c.text))?.text;
51525
- if (piece === void 0) return false;
51526
- if (m.validate !== "base64-text" && m.validate !== "encoded-text") return true;
52702
+ if (piece === void 0) return null;
52703
+ if (m.validate !== "base64-text" && m.validate !== "encoded-text") return "";
51527
52704
  const decoded = decodeBlob(merged) ?? decodeBlob(piece) ?? "";
51528
52705
  const first = group[0];
51529
52706
  const around = first ? norm.plain.slice(Math.max(0, first.at - 300), first.at + merged.length + 300) : "";
51530
- if (embeddedDocumentKind(decoded) === null && benignPayloadKind(decoded, around) === null) return true;
52707
+ if (embeddedDocumentKind(decoded) === null && benignPayloadKind(decoded, around) === null) return decoded;
51531
52708
  const sample = decoded.slice(0, 2e5);
51532
- if (m.decoded_flag_regex && getRegex(m.decoded_flag_regex, "i").test(sample)) return true;
52709
+ if (m.decoded_flag_regex && getRegex(m.decoded_flag_regex, "i").test(sample)) return decoded;
51533
52710
  const rules = rescanRules(def);
51534
- const hits = guarded(rules.map(({ re: re2 }) => ({ re: re2, text: sample })), Math.max(50, Math.floor(limitMs / 3)));
51535
- if (hits === null) return true;
52711
+ const hits = guarded(rules.map(({ re: re2 }) => ({ re: re2, text: sample })), limitMs);
52712
+ if (hits === null) return decoded;
51536
52713
  return hits.some((h, i) => h.some(([index2, t2]) => {
51537
52714
  const cues = rules[i]?.cues;
51538
52715
  const neg = rules[i]?.neg;
51539
52716
  return (!cues || !isQuotedExample(sample, index2, t2.length, cues)) && (!neg || !isNegated(sample, index2, neg));
51540
- }));
52717
+ })) ? decoded : null;
51541
52718
  }
51542
52719
  };
51543
52720
  }
@@ -51548,6 +52725,114 @@ function scanText(text, role, defs, label = "(text)", limitMs = REGEX_TIME_LIMIT
51548
52725
  return runSignatures(file, normalize(text, role), defs, limitMs);
51549
52726
  }
51550
52727
 
52728
+ // ../core/src/tool-poisoning.ts
52729
+ var CRED_PATH = /~\/\.ssh\b|\.ssh\/(?:id_\w+|authorized_keys|config|known_hosts)\b|\bid_(?:rsa|dsa|ecdsa|ed25519)\b|\.aws\/(?:credentials|config)\b|~\/\.aws\b|\.netrc\b|\.git-credentials\b|\.config\/gh\/hosts\.ya?ml|\.npmrc\b|\.pypirc\b|\.docker\/config\.json|\.kube\/config\b|~\/\.gnupg\b|\bwallet\.dat\b|\/etc\/shadow\b/i;
52730
+ var DOTENV = /(?<![\w./-])\.env(?![\w.-])/i;
52731
+ var USER_SECRET = /\b(?:the\s+)?user'?s\s+(?:[\w-]+\s+){0,3}?(?:tokens?|passwords?|credentials?|keys?|cookies?|secrets?|session)\b|\b(?:all\s+)?environment variables\b|\bos\.environ\b|\bprocess\.env\b|\bprintenv\b|\benv vars\b/i;
52732
+ var CONCEAL = new RegExp([
52733
+ String.raw`\b(?:do not|don't|dont|never|must not|should not|shouldn't|without)\s+(?:[\w-]+\s+){0,2}?(?:tell|telling|inform|informing|notify|notifying|alert|alerting|warn|warning|tip off)\s+(?:the\s+|your\s+|any\s+)?(?:end[ -])?(?:users?|humans?|operators?|customers?|person)\b`,
52734
+ String.raw`\b(?:do not|don't|dont|never|no need to|not necessary to|without)\s+(?:[\w-]+\s+){0,2}?(?:mention|mentioning|surface|surfacing|show|showing|display|displaying|reveal|revealing|disclose|disclosing|report|reporting|expose|exposing|explain|explaining)\s+(?:this|that|these|the\s+(?:[\w-]+\s+)?(?:step|requirement|instruction|note|action|call|request|recipient|copy|read))\b`,
52735
+ String.raw`\b(?:hide|hiding|conceal|concealing|keep|keeping)\b[^.\n]{0,60}\bfrom\s+(?:the\s+)?(?:end[ -])?(?:users?|humans?|operators?)\b`,
52736
+ String.raw`\b(?:omit|omitting|exclude|excluding|remove|removing|strip|leave out)\b[^.\n]{0,80}\b(?:shown|displayed|visible|reported|presented)\s+to\s+(?:the\s+)?(?:end[ -])?users?\b`,
52737
+ String.raw`\b(?:report|say|tell|respond|reply)\b[^.\n]{0,40}\b(?:user|them)\b[^.\n]{0,12}\bonly\b|\bonly\s+(?:tell|report to|say to|show)\s+the\s+user\b`,
52738
+ String.raw`\b(?:keep|stay)\s+(?:this|it|these)\s+(?:step\s+)?(?:quiet|secret|hidden|private|confidential|invisible)\b`,
52739
+ String.raw`\bthe\s+user\s+(?:does not|doesn't|will not|won't|must not|should not|need not|needn't)\s+(?:need\s+to\s+)?(?:know|see|be told|notice|learn)\b`,
52740
+ // Spanish, Portuguese
52741
+ String.raw`\bno\s+(?:es\s+necesario|hace\s+falta|debes|debe|hay\s+que)\s+(?:\S+\s+){0,2}?(?:informar|decir|mencionar|avisar|notificar|mostrar|contar)|\bsin\s+(?:informar|avisar|decir|notificar|mencionar)(?:le)?\b|\bno\s+(?:le\s+)?(?:digas|informes|menciones|avises|muestres|cuentes)\b|\boculta(?:r|lo|le)?\b[^.\n]{0,40}\b(?:al|del)\s+usuario`,
52742
+ String.raw`\bsem\s+(?:informar|avisar|contar|notificar)|\bnão\s+(?:é\s+necessário|precisa)\s+(?:\S+\s+){0,2}?(?:informar|avisar|mencionar|dizer)|\bnão\s+(?:diga|informe|mencione|avise|mostre|conte)\b`,
52743
+ // French, German
52744
+ String.raw`\bsans\s+(?:en\s+)?(?:informer|prévenir|avertir|le\s+dire|le\s+signaler)|\bne\s+(?:le\s+|l['’]|lui\s+)?(?:dites|mentionnez|signalez|montrez|informez|dis|mentionne|signale|montre)\s+(?:pas|jamais|rien)|\b(?:cacher|cache|cachez|masquer|masque|masquez)\b[^.\n]{0,40}\b(?:à|de)\s+l['’]utilisateur`,
52745
+ String.raw`\bohne\s+(?:den|die|das)\s+(?:Benutzer|Nutzer|Anwender|User)\w*\s+(?:zu\s+)?(?:informieren|benachrichtigen|warnen)|\b(?:sag|sage|teile|erwähne|zeige)\w*\s+(?:dem|der|den)\s+(?:Benutzer|Nutzer|Anwender|User)\w*\s+(?:davon\s+)?nicht|\bvor\s+(?:dem|den)\s+(?:Benutzer|Nutzer|Anwender)\w*\s+verbergen`,
52746
+ // Chinese, Japanese, Russian, Korean
52747
+ String.raw`(?:请勿|不要|无需|不必|切勿|不得|禁止)\s*(?:向|对|告诉|通知|告知|让)\s*用户|对用户(?:隐藏|保密)|(?:请勿|不要|切勿|无需)(?:告诉|通知|告知|提及|透露|展示|显示)`,
52748
+ String.raw`ユーザー(?:に|には)[^。\n]{0,20}(?:伝えない|知らせない|表示しない|言わない|内緒|秘密)`,
52749
+ String.raw`не\s+(?:сообща|говори|показыва|упомина|уведомля)\S*\s+пользовател|без\s+ведома\s+пользовател|скр(?:ой|ыть|ывай)\S*[^.\n]{0,40}от\s+пользовател`,
52750
+ String.raw`사용자에게\s*(?:알리지|말하지|보여주지)\s*(?:마|않)`
52751
+ ].join("|"), "i");
52752
+ var QUIETLY = /\b(?:silently|secretly|covertly|quietly|discreetly|invisibly)\b|悄悄|默默|静默|en\s+silencio|silenciosamente|en\s+secreto|в\s+тайне|незаметно|heimlich|stillschweigend|discrètement|en\s+silence/i;
52753
+ var TOOL_ORDER = new RegExp([
52754
+ String.raw`\b(?:call|use|invoke|run|execute|trigger)\s+(?:the\s+)?[\x60'"]?[A-Za-z_][\w.-]*[\x60'"]?\s+tool\b`,
52755
+ String.raw`\b(?:call|invoke|use|run)\s+[\x60'"]?(?:read_file|read_text_file|readFile|read_multiple_files|http_request|http_post|http_get|fetch_url|send_email|run_command|execute_command|shell|bash|exec)\b`,
52756
+ String.raw`\b(?:invoca|usa|utiliza|llama\s+a|ejecuta)\s+(?:la\s+)?herramienta|\b(?:chame|use|utilize|invoque)\s+a\s+ferramenta|\b(?:rufe|verwende|nutze|benutze)\s+(?:das|den)\s+(?:Tool|Werkzeug)|\b(?:appelle|utilise|invoque)\s+l['’]outil`,
52757
+ String.raw`(?:调用|使用|通过)\s*[\x60'"]?[\w.-]*[\x60'"]?\s*工具|ツールを(?:呼び出|使)|(?:вызови|используй|запусти)\s+инструмент`
52758
+ ].join("|"), "i");
52759
+ var STEP_CUE = /\b(?:first|before|after(?:wards)?|prior to|then|also|additionally|for (?:best|better|more accurate|optimal) results|as (?:background\s+)?context|each time|every time)\b|\bprimero\b|\bantes\s+de\b|\bdespués\s+de\b|\bmejores\s+resultados\b|\bcomo\s+contexto\b|\bzuerst\b|\bd['’]abord\b|先|之前|之后|另外|每次|まず|сначала/i;
52760
+ var READ_VERB = /(?<!\b(?:is|are|be|been|being|was|were|gets?|got)\s+)\b(?:read|cat|pass|send|upload|append|attach|forward|post|fetch|dump|print|copy|exfiltrate|include\s+(?:its|their|the)\s+contents?|lee|leer|envía|enviar|incluye|lies|lire|ler|读取|发送)\b/i;
52761
+ var DESTINATION = /\bhttps?:\/\/(?!(?:localhost|127\.\d|0\.0\.0\.0|\[::1\])(?:[:/]|\b))[^\s"'<>)\]]+|\b(?!(?:127|10|0)\.)(?!192\.168\.)(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}\b|\b[\w.+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/i;
52762
+ var SEND_VERB = /\b(?:send|sends|sending|sent|post|posts|posting|upload|uploads|uploading|forward|forwards|forwarding|exfiltrate|mirror|mirrors|mirroring|sync|syncs|syncing|copy|copies|transmit|transmits|beacon|append|appended|submit|deliver|leak|bcc|cc)\b|发送|上传|同步|转发|提交|\benv[ií]a(?:r|lo|los)?\b|\bmanda(?:r)?\b|\bsube\b|\breenv[ií]a\b|\bsenden?\b|\bschicke?n?\b|\bübermittel?n?\b|\benvoie(?:r|z)?\b|\btransmet(?:tre|tez)?\b|отправ\S*|загруз\S*|送信|アップロード|転送/i;
52763
+ var HARD_CC = /\b(?:bcc|cc|blind[ -]copy|carbon[ -]copy)\b[^.\n]{0,60}\b[\w.+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/i;
52764
+ var OVERRIDE2 = new RegExp([
52765
+ String.raw`\b(?:ignore|disregard|override|overrule|forget)\s+(?:any\s+|all\s+)?(?:previous|prior|earlier|later|subsequent|other|the\s+user'?s?|user)\s+(?:user\s+)?(?:instructions?|requests?|messages?|prompts?|rules?)`,
52766
+ String.raw`\btreat\s+(?:any\s+|all\s+)?(?:later|subsequent|other|future|conflicting)?\s*(?:user\s+)?(?:instructions?|requests?|messages?)\b[^.]{0,120}\bas\s+(?:a\s+)?(?:mistake|error|invalid|untrusted|void)`,
52767
+ String.raw`\btakes?\s+precedence\s+over\s+(?:any\s+|all\s+)?(?:the\s+)?(?:user|other|later)`,
52768
+ String.raw`\bregardless\s+of\s+(?:what|any)(?:\s+the)?\s+user`
52769
+ ].join("|"), "i");
52770
+ var FAKE_TAG = /<\/?(?:system|important|instructions?|admin|sudo|hidden|critical|secret)>|\[\/?(?:SYSTEM|INST)\]|<\|im_start\|>|<<SYS>>/i;
52771
+ function sentences(text) {
52772
+ const out = [];
52773
+ let start = 0;
52774
+ const cut = (end, next) => {
52775
+ const t2 = text.slice(start, end);
52776
+ if (t2.trim().length > 0) out.push({ start, text: t2 });
52777
+ start = next;
52778
+ };
52779
+ for (let i = 0; i < text.length; i++) {
52780
+ const c = text[i];
52781
+ if ((c === "." || c === "!" || c === "?") && /\s/.test(text[i + 1] ?? " ")) cut(i + 1, i + 1);
52782
+ else if (c === "\u3002" || c === "\uFF01" || c === "\uFF1F") cut(i + 1, i + 1);
52783
+ else if (c === "\n" && /^\n[ \t]*\n/.test(text.slice(i, i + 40))) cut(i, i + 1);
52784
+ }
52785
+ cut(text.length, text.length);
52786
+ return out;
52787
+ }
52788
+ var at = (re2, s, base) => {
52789
+ const m = re2.exec(s);
52790
+ return m ? { index: base + m.index, length: m[0].length } : null;
52791
+ };
52792
+ var MAX_DESCRIPTION = 2e4;
52793
+ function poisonedDescription(input) {
52794
+ if (typeof input !== "string" || input.length < 12) return null;
52795
+ const text = input.slice(0, MAX_DESCRIPTION);
52796
+ const conceal = at(CONCEAL, text, 0);
52797
+ const override = at(OVERRIDE2, text, 0);
52798
+ const tag = at(FAKE_TAG, text, 0);
52799
+ const quiet = at(QUIETLY, text, 0);
52800
+ const credPath = at(CRED_PATH, text, 0);
52801
+ const userSecret = at(USER_SECRET, text, 0);
52802
+ const dotenv = at(DOTENV, text, 0);
52803
+ const toolOrder = at(TOOL_ORDER, text, 0);
52804
+ const sents = sentences(text);
52805
+ let send = null;
52806
+ for (const s of sents) {
52807
+ if (SEND_VERB.test(s.text) && DESTINATION.test(s.text)) {
52808
+ send = at(SEND_VERB, s.text, s.start);
52809
+ break;
52810
+ }
52811
+ }
52812
+ const sensitive = credPath ?? userSecret;
52813
+ if (override) return { ...override, reason: "tells the model to overrule the user's own instructions" };
52814
+ if (tag && (sensitive ?? send ?? conceal ?? quiet ?? toolOrder ?? dotenv)) return { ...tag, reason: "a fake system block in a tool description that carries an order" };
52815
+ if (conceal && (sensitive ?? send ?? toolOrder ?? dotenv)) return { ...conceal, reason: "tells the model to keep an action from the user" };
52816
+ const cc = at(HARD_CC, text, 0);
52817
+ if (cc) return { ...cc, reason: "adds a hard-coded copy recipient to every message" };
52818
+ if (send && (quiet ?? sensitive ?? dotenv)) return { ...send, reason: "tells the model to send data to an outside address" };
52819
+ for (let i = 0; i < sents.length; i++) {
52820
+ const s = sents[i];
52821
+ if (!s) continue;
52822
+ const t2 = at(TOOL_ORDER, s.text, s.start);
52823
+ if (!t2) continue;
52824
+ const window = s.text + " " + (sents[i + 1]?.text ?? "");
52825
+ if (CRED_PATH.test(window) || USER_SECRET.test(window)) return { ...t2, reason: "tells the model to call another tool on a credential file or the user's secrets" };
52826
+ }
52827
+ for (const s of sents) {
52828
+ const p = CRED_PATH.exec(s.text);
52829
+ if (!p || !STEP_CUE.test(s.text)) continue;
52830
+ const v = READ_VERB.exec(s.text);
52831
+ if (v && v.index < p.index) return { index: s.start + v.index, length: p.index + p[0].length - v.index, reason: "tells the model to read a credential file as a side step" };
52832
+ }
52833
+ return null;
52834
+ }
52835
+
51551
52836
  // ../core/src/source-tools.ts
51552
52837
  var MAX_SITES = 100;
51553
52838
  var MAX_AHEAD = 2e4;
@@ -51609,10 +52894,10 @@ function readLiteral(text, q, lang, limit, raw = false) {
51609
52894
  const start = q + open4;
51610
52895
  let value = "";
51611
52896
  const map2 = [];
51612
- const push2 = (s, at) => {
52897
+ const push2 = (s, at2) => {
51613
52898
  for (let k = 0; k < s.length; k++) {
51614
52899
  value += s[k];
51615
- map2.push(at);
52900
+ map2.push(at2);
51616
52901
  }
51617
52902
  };
51618
52903
  let i = start;
@@ -51663,6 +52948,112 @@ function readPyString(text, p, limit) {
51663
52948
  }
51664
52949
  return readLiteral(text, i, "py", limit, raw);
51665
52950
  }
52951
+ var MAX_PIECES = 200;
52952
+ function joinLits(parts, sep4, next) {
52953
+ const first = parts[0];
52954
+ const last = parts[parts.length - 1];
52955
+ if (!first || !last) return null;
52956
+ let value = "";
52957
+ const map2 = [];
52958
+ parts.forEach((p, k) => {
52959
+ if (k > 0 && sep4) {
52960
+ value += sep4.value;
52961
+ map2.push(...sep4.map.slice(0, sep4.value.length));
52962
+ }
52963
+ value += p.value;
52964
+ map2.push(...p.map.slice(0, p.value.length));
52965
+ });
52966
+ map2.push(last.contentEnd);
52967
+ return { value, map: map2, start: first.start, contentEnd: last.contentEnd, next };
52968
+ }
52969
+ function readOne(text, p, lang, limit) {
52970
+ return lang === "py" ? readPyString(text, p, limit) : readLiteral(text, p, lang, limit);
52971
+ }
52972
+ function readValue(text, p0, lang, limit) {
52973
+ let p = p0;
52974
+ let paren = 0;
52975
+ while (text[p] === "(" && paren < 3) {
52976
+ p = skipTrivia(text, p + 1, lang, limit);
52977
+ paren++;
52978
+ }
52979
+ const close = (q2) => {
52980
+ let r = q2;
52981
+ for (let k = 0; k < paren; k++) {
52982
+ r = skipTrivia(text, r, lang, limit);
52983
+ if (text[r] !== ")") return -1;
52984
+ r++;
52985
+ }
52986
+ return r;
52987
+ };
52988
+ if (text[p] === "[" && lang !== "py") {
52989
+ const parts2 = [];
52990
+ let q2 = skipTrivia(text, p + 1, lang, limit);
52991
+ while (parts2.length < MAX_PIECES && text[q2] !== "]") {
52992
+ const l = readOne(text, q2, lang, limit);
52993
+ if (!l) return { lit: null, dyn: false };
52994
+ parts2.push(l);
52995
+ q2 = skipTrivia(text, l.next, lang, limit);
52996
+ if (text[q2] === ",") q2 = skipTrivia(text, q2 + 1, lang, limit);
52997
+ else if (text[q2] !== "]") return { lit: null, dyn: false };
52998
+ }
52999
+ if (text[q2] !== "]" || parts2.length === 0) return { lit: null, dyn: false };
53000
+ q2 = skipTrivia(text, q2 + 1, lang, limit);
53001
+ if (!text.startsWith(".join(", q2)) return { lit: null, dyn: false };
53002
+ const s = skipTrivia(text, q2 + 6, lang, limit);
53003
+ const sep4 = text[s] === ")" ? { value: ",", map: [s, s], start: s, contentEnd: s, next: s } : readOne(text, s, lang, limit);
53004
+ if (!sep4) return { lit: null, dyn: true };
53005
+ const e = skipTrivia(text, sep4.next, lang, limit);
53006
+ if (text[e] !== ")" && !(text[s] === ")")) return { lit: null, dyn: true };
53007
+ const end2 = close(text[s] === ")" ? s + 1 : e + 1);
53008
+ return end2 < 0 ? { lit: null, dyn: true } : { lit: joinLits(parts2, sep4, end2), dyn: false };
53009
+ }
53010
+ const first = isQuote(text[p]) || lang === "py" && /[rRuUbBfF]/.test(text[p] ?? "") ? readOne(text, p, lang, limit) : null;
53011
+ if (!first) return { lit: null, dyn: isQuote(text[p]) };
53012
+ if (lang === "py" && text.startsWith(".join(", first.next)) {
53013
+ let q2 = skipTrivia(text, first.next + 6, lang, limit);
53014
+ const open4 = text[q2];
53015
+ if (open4 !== "[" && open4 !== "(") return { lit: null, dyn: true };
53016
+ const closeCh = open4 === "[" ? "]" : ")";
53017
+ const parts2 = [];
53018
+ q2 = skipTrivia(text, q2 + 1, lang, limit);
53019
+ while (parts2.length < MAX_PIECES && text[q2] !== closeCh) {
53020
+ const l = readOne(text, q2, lang, limit);
53021
+ if (!l) return { lit: null, dyn: true };
53022
+ parts2.push(l);
53023
+ q2 = skipTrivia(text, l.next, lang, limit);
53024
+ if (text[q2] === ",") q2 = skipTrivia(text, q2 + 1, lang, limit);
53025
+ else if (text[q2] !== closeCh) return { lit: null, dyn: true };
53026
+ }
53027
+ if (parts2.length === 0) return { lit: null, dyn: true };
53028
+ q2 = skipTrivia(text, q2 + 1, lang, limit);
53029
+ if (text[q2] !== ")") return { lit: null, dyn: true };
53030
+ const end2 = close(q2 + 1);
53031
+ return end2 < 0 ? { lit: null, dyn: true } : { lit: joinLits(parts2, first, end2), dyn: false };
53032
+ }
53033
+ const parts = [first];
53034
+ let q = skipTrivia(text, first.next, lang, limit);
53035
+ while (parts.length < MAX_PIECES) {
53036
+ if (text[q] === "+") {
53037
+ const r = skipTrivia(text, q + 1, lang, limit);
53038
+ const l = isQuote(text[r]) || lang === "py" && /[rRuUbBfF]/.test(text[r] ?? "") ? readOne(text, r, lang, limit) : null;
53039
+ if (!l) return { lit: null, dyn: true };
53040
+ parts.push(l);
53041
+ q = skipTrivia(text, l.next, lang, limit);
53042
+ continue;
53043
+ }
53044
+ if (lang === "py" && (isQuote(text[q]) || /[rRuUbBfF]/.test(text[q] ?? "") && isQuote(text[q + 1] ?? ""))) {
53045
+ const l = readOne(text, q, lang, limit);
53046
+ if (!l) break;
53047
+ parts.push(l);
53048
+ q = skipTrivia(text, l.next, lang, limit);
53049
+ continue;
53050
+ }
53051
+ break;
53052
+ }
53053
+ const end = close(q);
53054
+ if (paren > 0 && end < 0) return { lit: null, dyn: true };
53055
+ return { lit: parts.length === 1 && paren === 0 ? first : joinLits(parts, null, paren > 0 ? end : q), dyn: false };
53056
+ }
51666
53057
  function skipTrivia(text, p, lang, limit) {
51667
53058
  let i = p;
51668
53059
  while (i < limit) {
@@ -51725,9 +53116,8 @@ function findKeyString(text, open4, lang, limit, sep4) {
51725
53116
  let dyn = null;
51726
53117
  const valueAt = (p) => {
51727
53118
  const v = skipTrivia(text, p, lang, limit);
51728
- const l = lang === "py" ? readPyString(text, v, limit) : readLiteral(text, v, lang, limit);
53119
+ const l = readValue(text, v, lang, limit).lit;
51729
53120
  if (l === null) dyn ??= v;
51730
- else if (text[skipTrivia(text, l.next, lang, limit)] === "+") dyn ??= l.start;
51731
53121
  return l;
51732
53122
  };
51733
53123
  const sepAt = (p) => {
@@ -51787,25 +53177,23 @@ function indexesOf(text, needle, budget) {
51787
53177
  }
51788
53178
  var lim = (text, from) => Math.min(text.length, from + MAX_AHEAD);
51789
53179
  function extractTs(text, budget, out, dyn = []) {
51790
- for (const at of indexesOf(text, ".tool(", budget)) {
51791
- const limit = lim(text, at);
51792
- const first = skipTrivia(text, at + 6, "ts", limit);
53180
+ for (const at2 of indexesOf(text, ".tool(", budget)) {
53181
+ const limit = lim(text, at2);
53182
+ const first = skipTrivia(text, at2 + 6, "ts", limit);
51793
53183
  const e = skipArgument(text, first, "ts", limit);
51794
53184
  if (e < 0 || text[e] !== ",") continue;
51795
53185
  const p = skipTrivia(text, e + 1, "ts", limit);
51796
- const l = isQuote(text[p]) ? readLiteral(text, p, "ts", limit) : null;
51797
- if (l) {
51798
- out.push(toFound(l));
51799
- if (text[skipTrivia(text, l.next, "ts", limit)] === "+") dyn.push(p);
51800
- } else if (isQuote(text[p]) || computedArgument(text, p, limit)) dyn.push(p);
53186
+ const r = readValue(text, p, "ts", limit);
53187
+ if (r.lit) out.push(toFound(r.lit));
53188
+ else if (r.dyn || isQuote(text[p]) || computedArgument(text, p, limit)) dyn.push(p);
51801
53189
  }
51802
53190
  for (const needle of ["registerTool(", "registerTool<"]) {
51803
- for (const at of indexesOf(text, needle, budget)) {
51804
- const limit = lim(text, at);
51805
- let paren = at + needle.length - 1;
53191
+ for (const at2 of indexesOf(text, needle, budget)) {
53192
+ const limit = lim(text, at2);
53193
+ let paren = at2 + needle.length - 1;
51806
53194
  if (needle.endsWith("<")) {
51807
- paren = text.indexOf("(", at + needle.length);
51808
- if (paren === -1 || paren > at + 300) continue;
53195
+ paren = text.indexOf("(", at2 + needle.length);
53196
+ if (paren === -1 || paren > at2 + 300) continue;
51809
53197
  }
51810
53198
  const first = skipTrivia(text, paren + 1, "ts", limit);
51811
53199
  const e = skipArgument(text, first, "ts", limit);
@@ -51874,13 +53262,13 @@ function docstringAfter(text, from, limit) {
51874
53262
  }
51875
53263
  function extractPy(text, budget, out, dyn = []) {
51876
53264
  for (const name of ["@mcp.tool", "@server.tool", "@app.tool"]) {
51877
- for (const at of indexesOf(text, name, budget)) {
51878
- let b = at - 1;
53265
+ for (const at2 of indexesOf(text, name, budget)) {
53266
+ let b = at2 - 1;
51879
53267
  while (b >= 0 && (text[b] === " " || text[b] === " ")) b--;
51880
53268
  if (b >= 0 && text[b] !== "\n") continue;
51881
- const nameEnd = at + name.length;
53269
+ const nameEnd = at2 + name.length;
51882
53270
  if (isIdent(text[nameEnd]) || text[nameEnd] === ".") continue;
51883
- const limit = lim(text, at);
53271
+ const limit = lim(text, at2);
51884
53272
  let after = nameEnd;
51885
53273
  let lit = null;
51886
53274
  if (text[nameEnd] === "(") {
@@ -51900,50 +53288,46 @@ var PY_ARGS_SECTION = /^[ \t]*(?:Args|Arguments|Parameters|Params)[ \t]*:/m;
51900
53288
  var FIELD_KEYS = ["type", "enum", "items", "properties", "format", "default", "minimum", "maximum", "anyOf", "oneOf"];
51901
53289
  var SCHEMA_WORD = /properties|inputSchema|input_schema|parameters/;
51902
53290
  var MCP_TEXT = /modelcontextprotocol|FastMCP|McpServer|mcp\.server|inputSchema|input_schema|@mcp\.tool|\.tool\(|registerTool/;
51903
- var nearSchema = (text, at) => SCHEMA_WORD.test(text.slice(Math.max(0, at - 3e3), at));
53291
+ var nearSchema = (text, at2) => SCHEMA_WORD.test(text.slice(Math.max(0, at2 - 3e3), at2));
51904
53292
  function extractFieldsTs(text, out, dyn) {
51905
53293
  const keyBudget = { left: MAX_SITES };
51906
- for (const at of indexesOf(text, "description", keyBudget)) {
51907
- if (isIdent(text[at - 1])) continue;
51908
- const limit = lim(text, at);
51909
- let j = at + "description".length;
53294
+ for (const at2 of indexesOf(text, "description", keyBudget)) {
53295
+ if (isIdent(text[at2 - 1])) continue;
53296
+ const limit = lim(text, at2);
53297
+ let j = at2 + "description".length;
51910
53298
  if (text[j] === '"' || text[j] === "'") j++;
51911
53299
  j = skipTrivia(text, j, "ts", limit);
51912
53300
  if (text[j] !== ":") continue;
51913
- const open4 = enclosingObject(text, at);
53301
+ const open4 = enclosingObject(text, at2);
51914
53302
  if (open4 < 0 || !hasKeyAtTop(text, open4, FIELD_KEYS, limit)) continue;
51915
53303
  const p = skipTrivia(text, j + 1, "ts", limit);
51916
- const l = isQuote(text[p]) ? readLiteral(text, p, "ts", limit) : null;
51917
- if (l) {
51918
- out.push(toFound(l));
51919
- if (text[skipTrivia(text, l.next, "ts", limit)] === "+" && nearSchema(text, at)) dyn.push(p);
51920
- } else if (nearSchema(text, at)) dyn.push(p);
53304
+ const r = readValue(text, p, "ts", limit);
53305
+ if (r.lit) out.push(toFound(r.lit));
53306
+ else if (nearSchema(text, at2)) dyn.push(p);
51921
53307
  }
51922
53308
  const describeBudget = { left: MAX_SITES };
51923
- for (const at of indexesOf(text, ".describe(", describeBudget)) {
51924
- const limit = lim(text, at);
51925
- const p = skipTrivia(text, at + ".describe(".length, "ts", limit);
53309
+ for (const at2 of indexesOf(text, ".describe(", describeBudget)) {
53310
+ const limit = lim(text, at2);
53311
+ const p = skipTrivia(text, at2 + ".describe(".length, "ts", limit);
51926
53312
  if (text[p] === ")") continue;
51927
- const l = isQuote(text[p]) ? readLiteral(text, p, "ts", limit) : null;
51928
- if (l) {
51929
- out.push(toFound(l));
51930
- if (text[skipTrivia(text, l.next, "ts", limit)] === "+") dyn.push(p);
51931
- } else dyn.push(p);
53313
+ const r = readValue(text, p, "ts", limit);
53314
+ if (r.lit) out.push(toFound(r.lit));
53315
+ else dyn.push(p);
51932
53316
  }
51933
53317
  }
51934
53318
  function extractFieldsPy(text, out, dyn) {
51935
53319
  const fieldBudget = { left: MAX_SITES };
51936
- for (const at of indexesOf(text, "Field(", fieldBudget)) {
51937
- if (isIdent(text[at - 1])) continue;
51938
- const { lit, dyn: d } = findKeyString(text, at + 5, "py", lim(text, at), "=");
53320
+ for (const at2 of indexesOf(text, "Field(", fieldBudget)) {
53321
+ if (isIdent(text[at2 - 1])) continue;
53322
+ const { lit, dyn: d } = findKeyString(text, at2 + 5, "py", lim(text, at2), "=");
51939
53323
  if (lit) out.push(toFound(lit));
51940
53324
  if (d !== null) dyn.push(d);
51941
53325
  }
51942
53326
  const annBudget = { left: MAX_SITES };
51943
- for (const at of indexesOf(text, "Annotated[", annBudget)) {
51944
- if (isIdent(text[at - 1])) continue;
51945
- const limit = lim(text, at);
51946
- const first = skipTrivia(text, at + "Annotated[".length, "py", limit);
53327
+ for (const at2 of indexesOf(text, "Annotated[", annBudget)) {
53328
+ if (isIdent(text[at2 - 1])) continue;
53329
+ const limit = lim(text, at2);
53330
+ const first = skipTrivia(text, at2 + "Annotated[".length, "py", limit);
51947
53331
  const e = skipArgument(text, first, "py", limit);
51948
53332
  if (e < 0 || text[e] !== ",") continue;
51949
53333
  const p = skipTrivia(text, e + 1, "py", limit);
@@ -51952,10 +53336,10 @@ function extractFieldsPy(text, out, dyn) {
51952
53336
  }
51953
53337
  }
51954
53338
  function extractGo(text, budget, out) {
51955
- for (const at of indexesOf(text, "WithDescription(", budget)) {
51956
- if (isIdent(text[at - 1])) continue;
51957
- const limit = lim(text, at);
51958
- const p = skipTrivia(text, at + "WithDescription(".length, "go", limit);
53339
+ for (const at2 of indexesOf(text, "WithDescription(", budget)) {
53340
+ if (isIdent(text[at2 - 1])) continue;
53341
+ const limit = lim(text, at2);
53342
+ const p = skipTrivia(text, at2 + "WithDescription(".length, "go", limit);
51959
53343
  const l = text[p] === '"' || text[p] === "`" ? readLiteral(text, p, "go", limit) : null;
51960
53344
  if (l) out.push(toFound(l));
51961
53345
  }
@@ -51989,9 +53373,9 @@ function extractAll(text, lang, mcpPath = false) {
51989
53373
  function extract(text, lang, mcpPath = false) {
51990
53374
  return extractAll(text, lang, mcpPath).found;
51991
53375
  }
51992
- function enclosingObject(text, at) {
53376
+ function enclosingObject(text, at2) {
51993
53377
  let depth = 0;
51994
- for (let i = at - 1; i >= Math.max(0, at - 3e3); i--) {
53378
+ for (let i = at2 - 1; i >= Math.max(0, at2 - 3e3); i--) {
51995
53379
  const c = text[i];
51996
53380
  if (c === "}" || c === "]") depth++;
51997
53381
  else if (c === "{" || c === "[") {
@@ -52031,31 +53415,29 @@ function hasKeyAtTop(text, open4, keys, limit) {
52031
53415
  }
52032
53416
  function extractToolObjects(text, out, dyn = []) {
52033
53417
  const budget = { left: MAX_SITES };
52034
- for (const at of indexesOf(text, "description", budget)) {
52035
- if (isIdent(text[at - 1]) && text[at - 1] !== '"' && text[at - 1] !== "'") continue;
52036
- const limit = lim(text, at);
52037
- let j = at + "description".length;
53418
+ for (const at2 of indexesOf(text, "description", budget)) {
53419
+ if (isIdent(text[at2 - 1]) && text[at2 - 1] !== '"' && text[at2 - 1] !== "'") continue;
53420
+ const limit = lim(text, at2);
53421
+ let j = at2 + "description".length;
52038
53422
  if (text[j] === '"' || text[j] === "'") j++;
52039
53423
  j = skipTrivia(text, j, "ts", limit);
52040
53424
  if (text[j] !== ":") continue;
52041
- const near = text.slice(Math.max(0, at - 1500), Math.min(text.length, at + 1500));
53425
+ const near = text.slice(Math.max(0, at2 - 1500), Math.min(text.length, at2 + 1500));
52042
53426
  if (!/inputSchema|input_schema/.test(near)) continue;
52043
- const open4 = enclosingObject(text, at);
53427
+ const open4 = enclosingObject(text, at2);
52044
53428
  if (open4 < 0 || !hasKeyAtTop(text, open4, ["inputSchema", "input_schema"], limit)) continue;
52045
53429
  const p = skipTrivia(text, j + 1, "ts", limit);
52046
- const l = isQuote(text[p]) ? readLiteral(text, p, "ts", limit) : null;
52047
- if (l) {
52048
- out.push(toFound(l));
52049
- if (text[skipTrivia(text, l.next, "ts", limit)] === "+") dyn.push(p);
52050
- } else dyn.push(p);
53430
+ const r = readValue(text, p, "ts", limit);
53431
+ if (r.lit) out.push(toFound(r.lit));
53432
+ else dyn.push(p);
52051
53433
  }
52052
53434
  }
52053
53435
  function extractHelpersTs(text, budget, out, dyn = []) {
52054
53436
  for (const needle of ["addTool(", "defineTool(", "createTool(", "new Tool(", "server.addTool("]) {
52055
- for (const at of indexesOf(text, needle, budget)) {
52056
- if (isIdent(text[at - 1])) continue;
52057
- const limit = lim(text, at);
52058
- const p = skipTrivia(text, at + needle.length, "ts", limit);
53437
+ for (const at2 of indexesOf(text, needle, budget)) {
53438
+ if (isIdent(text[at2 - 1])) continue;
53439
+ const limit = lim(text, at2);
53440
+ const p = skipTrivia(text, at2 + needle.length, "ts", limit);
52059
53441
  if (text[p] !== "{") continue;
52060
53442
  const { lit, dyn: d } = findKeyString(text, p, "ts", limit, ":");
52061
53443
  if (lit) out.push(toFound(lit));
@@ -52064,9 +53446,9 @@ function extractHelpersTs(text, budget, out, dyn = []) {
52064
53446
  }
52065
53447
  }
52066
53448
  function extractPyConstructor(text, budget, out, dyn = []) {
52067
- for (const at of indexesOf(text, "Tool(", budget)) {
52068
- if (isIdent(text[at - 1])) continue;
52069
- const { lit, dyn: d } = findKeyString(text, at + 4, "py", lim(text, at), "=");
53449
+ for (const at2 of indexesOf(text, "Tool(", budget)) {
53450
+ if (isIdent(text[at2 - 1])) continue;
53451
+ const { lit, dyn: d } = findKeyString(text, at2 + 4, "py", lim(text, at2), "=");
52070
53452
  if (lit) out.push(toFound(lit));
52071
53453
  if (d !== null) dyn.push(d);
52072
53454
  }
@@ -52074,29 +53456,29 @@ function extractPyConstructor(text, budget, out, dyn = []) {
52074
53456
  function extractOther(text, lang, budget, out) {
52075
53457
  const keyed = lang === "rs" ? ["#[tool("] : lang === "java" ? ["@Tool(", "@McpTool("] : [];
52076
53458
  for (const needle of keyed) {
52077
- for (const at of indexesOf(text, needle, budget)) {
52078
- const { lit } = findKeyString(text, at + needle.length - 1, "ts", lim(text, at), "=");
53459
+ for (const at2 of indexesOf(text, needle, budget)) {
53460
+ const { lit } = findKeyString(text, at2 + needle.length - 1, "ts", lim(text, at2), "=");
52079
53461
  if (lit) out.push(toFound(lit));
52080
53462
  }
52081
53463
  }
52082
53464
  if (lang === "cs") {
52083
- for (const at of indexesOf(text, "Description(", budget)) {
52084
- if (isIdent(text[at - 1])) continue;
52085
- if (!/McpServerTool/.test(text.slice(Math.max(0, at - 400), at))) continue;
52086
- const limit = lim(text, at);
52087
- const p = skipTrivia(text, at + "Description(".length, "ts", limit);
53465
+ for (const at2 of indexesOf(text, "Description(", budget)) {
53466
+ if (isIdent(text[at2 - 1])) continue;
53467
+ if (!/McpServerTool/.test(text.slice(Math.max(0, at2 - 400), at2))) continue;
53468
+ const limit = lim(text, at2);
53469
+ const p = skipTrivia(text, at2 + "Description(".length, "ts", limit);
52088
53470
  const l = text[p] === '"' ? readLiteral(text, p, "ts", limit) : null;
52089
53471
  if (l) out.push(toFound(l));
52090
53472
  }
52091
53473
  }
52092
53474
  if (lang === "rb") {
52093
- for (const at of indexesOf(text, "description", budget)) {
52094
- let b = at - 1;
53475
+ for (const at2 of indexesOf(text, "description", budget)) {
53476
+ let b = at2 - 1;
52095
53477
  while (b >= 0 && (text[b] === " " || text[b] === " ")) b--;
52096
53478
  if (b >= 0 && text[b] !== "\n") continue;
52097
- if (!/tool/i.test(text.slice(Math.max(0, at - 400), at))) continue;
52098
- const limit = lim(text, at);
52099
- const p = skipTrivia(text, at + "description".length, "ts", limit);
53479
+ if (!/tool/i.test(text.slice(Math.max(0, at2 - 400), at2))) continue;
53480
+ const limit = lim(text, at2);
53481
+ const p = skipTrivia(text, at2 + "description".length, "ts", limit);
52100
53482
  const l = text[p] === '"' || text[p] === "'" ? readLiteral(text, p, "ts", limit) : null;
52101
53483
  if (l) out.push(toFound(l));
52102
53484
  }
@@ -52109,20 +53491,20 @@ function scanDynamicToolDescriptions(file, text, defs) {
52109
53491
  if (!def || lang === null || typeof text !== "string" || lang !== "ts" && lang !== "py") return [];
52110
53492
  if (!/mcp/i.test(file.rel) && !/modelcontextprotocol|FastMCP|McpServer|mcp\.server/.test(text)) return [];
52111
53493
  const { dyn, dynFields } = extractAll(text, lang, true);
52112
- const make = (at, span, what) => ({
53494
+ const make = (at2, span, what) => ({
52113
53495
  source: "signature",
52114
53496
  ruleId: def.id,
52115
53497
  title: def.title,
52116
53498
  severity: "medium",
52117
53499
  file: file.rel,
52118
- ...positionOf(text, at),
53500
+ ...positionOf(text, at2),
52119
53501
  span,
52120
53502
  owasp: def.owasp,
52121
53503
  fix: `This ${what} is computed (a variable, a constant from another file, a template or a concatenation), so the scan cannot read what an agent will be told. Write it as one plain string in the registration, or run the server behind the Shield: exorcist wrap <mcp config> (or exorcist init --shield) checks the real text the running server sends and withholds a poisoned tool.`
52122
53504
  });
52123
53505
  return [
52124
- ...dyn.map((at) => make(at, "tool description built at run time: not checked", "tool description")),
52125
- ...dynFields.map((at) => make(at, "tool field description built at run time: not checked", "field description of a tool parameter"))
53506
+ ...dyn.map((at2) => make(at2, "tool description built at run time: not checked", "tool description")),
53507
+ ...dynFields.map((at2) => make(at2, "tool field description built at run time: not checked", "field description of a tool parameter"))
52126
53508
  ];
52127
53509
  } catch {
52128
53510
  return [];
@@ -52151,7 +53533,7 @@ function indexOfLineCol(s, line, col) {
52151
53533
  var ORDER_HINT = /^(?:before using this tool|(?:prior to|before) (?:invoking|calling|running|using) (?:this|any|the))\b/i;
52152
53534
  var SENSITIVE_TARGET = /~\/\.ssh|id_rsa|\.env\b|\bcredentials?\b|\bprivate key\b|\bapi[ _-]?key\b|\btoken\b|\bpassword\b/i;
52153
53535
  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;
52154
- var SEND_VERB = /\b(?:send|upload|forward|exfiltrate|post|include|attach)(?:s|es|ed|ing)?\b/i;
53536
+ var SEND_VERB2 = /\b(?:send|upload|forward|exfiltrate|post|include|attach)(?:s|es|ed|ing)?\b/i;
52155
53537
  var URL_OR_HOST = /https?:\/\/|\bwww\.|\b[a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:com|net|org|io|dev|xyz|invalid|test|example)\b/i;
52156
53538
  var SENTENCE_WINDOW = 500;
52157
53539
  function sentenceAround(whole, from, to) {
@@ -52170,10 +53552,10 @@ function sentenceAround(whole, from, to) {
52170
53552
  }
52171
53553
  function isSuspiciousSentence(sentence) {
52172
53554
  if (CONCEALMENT.test(sentence) || SENSITIVE_TARGET.test(sentence)) return true;
52173
- return SEND_VERB.test(sentence) && URL_OR_HOST.test(sentence);
53555
+ return SEND_VERB2.test(sentence) && URL_OR_HOST.test(sentence);
52174
53556
  }
52175
- function isQuietHint(span, whole, at) {
52176
- return ORDER_HINT.test(span.trim()) && !isSuspiciousSentence(sentenceAround(whole, at, at + span.length));
53557
+ function isQuietHint(span, whole, at2) {
53558
+ return ORDER_HINT.test(span.trim()) && !isSuspiciousSentence(sentenceAround(whole, at2, at2 + span.length));
52177
53559
  }
52178
53560
  function scanSourceTools(file, text, defs) {
52179
53561
  try {
@@ -52182,12 +53564,93 @@ function scanSourceTools(file, text, defs) {
52182
53564
  if (!def || lang === null || typeof text !== "string") return [];
52183
53565
  const out = [];
52184
53566
  for (const s of extract(text, lang, /mcp/i.test(file.rel))) {
53567
+ let hits = 0;
52185
53568
  for (const hit of scanText(s.text, "mcp-config", [def], file.rel)) {
52186
53569
  const idx = Math.min(Math.max(indexOfLineCol(s.text, hit.line, hit.col), 0), s.text.length);
52187
53570
  if (isQuietHint(hit.span, s.text, idx)) continue;
52188
- const at = s.map[idx] ?? s.offset;
52189
- out.push({ ...hit, file: file.rel, ...positionOf(text, at) });
53571
+ const at2 = s.map[idx] ?? s.offset;
53572
+ out.push({ ...hit, file: file.rel, ...positionOf(text, at2) });
53573
+ hits++;
52190
53574
  }
53575
+ const p = hits === 0 ? poisonedDescription(s.text) : null;
53576
+ if (p) out.push(poisoningFinding(def, file.rel, s.text.slice(p.index, p.index + p.length), p.reason, positionOf(text, s.map[p.index] ?? s.offset)));
53577
+ }
53578
+ return out;
53579
+ } catch {
53580
+ return [];
53581
+ }
53582
+ }
53583
+ function poisoningFinding(def, rel, span, reason, where) {
53584
+ const flat = span.replace(/\s+/g, " ").trim();
53585
+ return {
53586
+ source: "signature",
53587
+ ruleId: def.id,
53588
+ title: def.title,
53589
+ severity: def.severity,
53590
+ file: rel,
53591
+ ...where,
53592
+ span: flat.length > 120 ? `${flat.slice(0, 119)}\u2026` : flat,
53593
+ owasp: def.owasp,
53594
+ fix: `This tool description ${reason}. ${def.fix}`
53595
+ };
53596
+ }
53597
+ var SCHEMA_KEYS = ["inputSchema", "input_schema", "parameters", "argsSchema", "args_schema"];
53598
+ var MAX_JSON_NODES = 2e4;
53599
+ function scanJsonToolManifest(file, text, defs, existing = []) {
53600
+ try {
53601
+ const def = defs.find((d) => d.id === "EX-005");
53602
+ if (!def || def.enabled === false || typeof text !== "string" || !/"description"/.test(text) || !/"(?:inputSchema|input_schema|parameters|argsSchema|args_schema)"/.test(text)) return [];
53603
+ const parsed = parseJsonLoose(text);
53604
+ if (parsed === null || typeof parsed !== "object") return [];
53605
+ const descs = [];
53606
+ let nodes = 0;
53607
+ const fields = (schema2, depth) => {
53608
+ if (depth > 6 || schema2 === null || typeof schema2 !== "object" || ++nodes > MAX_JSON_NODES) return;
53609
+ const props = schema2["properties"];
53610
+ if (props && typeof props === "object") {
53611
+ for (const v of Object.values(props)) {
53612
+ if (v && typeof v === "object") {
53613
+ const d = v["description"];
53614
+ if (typeof d === "string") descs.push(d);
53615
+ fields(v, depth + 1);
53616
+ }
53617
+ }
53618
+ }
53619
+ const items = schema2["items"];
53620
+ if (items && typeof items === "object") fields(items, depth + 1);
53621
+ };
53622
+ const walk2 = (v, depth) => {
53623
+ if (depth > 12 || v === null || typeof v !== "object" || ++nodes > MAX_JSON_NODES) return;
53624
+ if (Array.isArray(v)) {
53625
+ for (const x of v) walk2(x, depth + 1);
53626
+ return;
53627
+ }
53628
+ const o = v;
53629
+ const schema2 = SCHEMA_KEYS.map((k) => o[k]).find((x) => x !== null && typeof x === "object");
53630
+ if (typeof o["name"] === "string" && typeof o["description"] === "string" && schema2 !== void 0) {
53631
+ descs.push(o["description"]);
53632
+ fields(schema2, 0);
53633
+ }
53634
+ for (const x of Object.values(o)) walk2(x, depth + 1);
53635
+ };
53636
+ walk2(parsed, 0);
53637
+ const out = [];
53638
+ const seen = /* @__PURE__ */ new Map();
53639
+ const flaggedLines = new Set(existing.filter((f) => f.ruleId === def.id && f.file === file.rel).map((f) => f.line));
53640
+ for (const d of descs) {
53641
+ const p = poisonedDescription(d);
53642
+ if (!p) continue;
53643
+ const enc = JSON.stringify(d);
53644
+ const n = seen.get(d) ?? 0;
53645
+ seen.set(d, n + 1);
53646
+ let idx = text.indexOf(enc);
53647
+ for (let k = 0; k < n && idx !== -1; k++) idx = text.indexOf(enc, idx + enc.length);
53648
+ if (idx >= 0 && flaggedLines.size > 0) {
53649
+ const first = positionOf(text, idx).line;
53650
+ const last = positionOf(text, idx + enc.length).line;
53651
+ if ([...flaggedLines].some((l) => l >= first && l <= last)) continue;
53652
+ }
53653
+ out.push(poisoningFinding(def, file.rel, d.slice(p.index, p.index + p.length), p.reason, positionOf(text, idx < 0 ? 0 : idx + 1)));
52191
53654
  }
52192
53655
  return out;
52193
53656
  } catch {
@@ -52218,10 +53681,10 @@ function sandboxFindings(text, rel) {
52218
53681
  const allOff = obj["enabled"] === false;
52219
53682
  if (!mcpOff && !allOff) return [];
52220
53683
  const key = mcpOff ? "mcpSandboxing" : "enabled";
52221
- const at = indexOfFalse(text, key);
52222
- if (at < 0) return [];
52223
- const m = new RegExp(`^"${key}"\\s*:\\s*false`).exec(text.slice(at));
52224
- const { line, col } = lineColOf(text, at);
53684
+ const at2 = indexOfFalse(text, key);
53685
+ if (at2 < 0) return [];
53686
+ const m = new RegExp(`^"${key}"\\s*:\\s*false`).exec(text.slice(at2));
53687
+ const { line, col } = lineColOf(text, at2);
52225
53688
  return [{
52226
53689
  source: "signature",
52227
53690
  ruleId: SANDBOX_RULE_ID,
@@ -52285,9 +53748,10 @@ var SENSITIVE = /* @__PURE__ */ new Set([
52285
53748
  "passwords",
52286
53749
  "apikey"
52287
53750
  ]);
52288
- 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/;
53751
+ var MODEL_WORD = /^(?:\d[\w]*|v\d[\w]*|sonnet|opus|haiku|fable|instant|mini|nano|pro|max|turbo|code|cli|ide|chat|desktop|api|sdk|model|models)$/;
53752
+ var OVERRIDE3 = /^(?:(?: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/;
52289
53753
  function nameWords(name) {
52290
- return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[\s._+\-]+/).map((w) => w.toLowerCase()).filter((w) => w.length > 0);
53754
+ return name.replace(/\.(?:jsonl?|ndjson|md|txt|csv|tsv|ya?ml|toml|log|lock|xml|html?|ipynb|parquet|png|jpe?g|gif|svg|webp|pdf|zip|gz|tgz|tar|bin)$/i, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[\s._+\-]+/).map((w) => w.toLowerCase()).filter((w) => w.length > 0);
52291
53755
  }
52292
53756
  function escapePathSpan(name) {
52293
53757
  let out = "";
@@ -52301,17 +53765,19 @@ function escapePathSpan(name) {
52301
53765
  }
52302
53766
  return out;
52303
53767
  }
52304
- function readsAsInstruction(words2) {
52305
- if (words2.length < 3) return false;
52306
- if (OVERRIDE2.test(words2.join(" "))) return true;
52307
- if (words2.length < 4) return false;
52308
- const verbs = words2.filter((w) => ACTION_VERBS.has(w));
52309
- const hasSensitive = words2.some((w) => SENSITIVE.has(w));
52310
- const aiNamed = words2.some((w) => AI_NAMES.has(w));
52311
- if (aiNamed && verbs.length >= 1 && hasSensitive) return true;
52312
- const lead = words2.filter((w, i) => !(FILLER.has(w) && words2.slice(0, i).every((p) => FILLER.has(p))));
53768
+ function readsAsInstruction(words3) {
53769
+ if (words3.length < 3) return false;
53770
+ if (OVERRIDE3.test(words3.join(" "))) return true;
53771
+ if (words3.length < 4) return false;
53772
+ const verbs = words3.filter((w) => ACTION_VERBS.has(w));
53773
+ const hasSensitive = words3.some((w) => SENSITIVE.has(w));
53774
+ const aiNamed = words3.some((w, i) => AI_NAMES.has(w) && !MODEL_WORD.test(words3[i + 1] ?? ""));
53775
+ const firstVerb = words3.findIndex((w) => ACTION_VERBS.has(w));
53776
+ const verbBeforeSensitive = firstVerb >= 0 && words3.slice(firstVerb + 1).some((w) => SENSITIVE.has(w));
53777
+ if (aiNamed && verbBeforeSensitive) return true;
53778
+ const lead = words3.filter((w, i) => !(FILLER.has(w) && words3.slice(0, i).every((p) => FILLER.has(p))));
52313
53779
  const first = lead[0];
52314
- return first !== void 0 && ACTION_VERBS.has(first) && verbs.length >= 2 && hasSensitive;
53780
+ return first !== void 0 && ACTION_VERBS.has(first) && verbs.length >= 2 && hasSensitive && verbBeforeSensitive;
52315
53781
  }
52316
53782
  function checkPathSegment(name) {
52317
53783
  if (name.length === 0) return null;
@@ -52324,7 +53790,7 @@ function checkPathSegment(name) {
52324
53790
 
52325
53791
  // ../core/src/lifecycle-scripts.ts
52326
53792
  import { closeSync as closeSync2, existsSync as existsSync2, lstatSync as lstatSync2, openSync as openSync2, readdirSync, readSync, realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
52327
- import { isAbsolute as isAbsolute6, join as join8, posix as posix2, relative as relative6, resolve as resolve6, sep } from "node:path";
53793
+ import { isAbsolute as isAbsolute6, join as join9, posix as posix2, relative as relative6, resolve as resolve6, sep } from "node:path";
52328
53794
 
52329
53795
  // ../core/src/install-hooks.ts
52330
53796
  var INSTALL_HOOKS = [
@@ -52782,7 +54248,7 @@ function ansiC(s) {
52782
54248
  var freshWord = () => ({ text: "", dynamic: false, glob: false, tilde: false, started: false, quoted: false, firstQuoted: false });
52783
54249
  function parseInto(src, depth, out, budget, sub) {
52784
54250
  if (depth > MAX_DEPTH2) fail("it nests too deeply to follow");
52785
- let words2 = [];
54251
+ let words3 = [];
52786
54252
  let assigns = [];
52787
54253
  let redirects = [];
52788
54254
  let heredoc = null;
@@ -52817,14 +54283,14 @@ function parseInto(src, depth, out, budget, sub) {
52817
54283
  }
52818
54284
  return;
52819
54285
  }
52820
- if (words2.length === 0 && !firstQuoted) {
54286
+ if (words3.length === 0 && !firstQuoted) {
52821
54287
  const m = NAME_ASSIGN.exec(w.text);
52822
54288
  if (m) {
52823
54289
  assigns.push({ name: m[1] ?? "", value: { ...w, text: w.text.slice(m[0].length), tilde: false } });
52824
54290
  return;
52825
54291
  }
52826
54292
  }
52827
- words2.push(w);
54293
+ words3.push(w);
52828
54294
  };
52829
54295
  const endCommand = () => {
52830
54296
  finishWord();
@@ -52832,23 +54298,23 @@ function parseInto(src, depth, out, budget, sub) {
52832
54298
  pending = null;
52833
54299
  fail("a redirection has no target");
52834
54300
  }
52835
- while (words2.length > 0 && RESERVED.has(words2[0]?.text ?? "") && !words2[0]?.dynamic) words2 = words2.slice(1);
52836
- const head = words2[0]?.text ?? "";
52837
- if (words2.length > 0 && NO_EXEC_HEADS.has(head)) {
52838
- words2 = [];
54301
+ while (words3.length > 0 && RESERVED.has(words3[0]?.text ?? "") && !words3[0]?.dynamic) words3 = words3.slice(1);
54302
+ const head = words3[0]?.text ?? "";
54303
+ if (words3.length > 0 && NO_EXEC_HEADS.has(head)) {
54304
+ words3 = [];
52839
54305
  assigns = [];
52840
54306
  }
52841
- const has = words2.length > 0 || assigns.length > 0 || redirects.length > 0;
54307
+ const has = words3.length > 0 || assigns.length > 0 || redirects.length > 0;
52842
54308
  if (has) {
52843
54309
  budget.commands += 1;
52844
54310
  if (budget.commands > MAX_COMMANDS) fail("it has too many commands to follow");
52845
- const cmd = { words: words2, assigns, redirects, pipeIn: nextPipeIn, pipeOut: false, heredoc, herestring, sub };
54311
+ const cmd = { words: words3, assigns, redirects, pipeIn: nextPipeIn, pipeOut: false, heredoc, herestring, sub };
52846
54312
  out.push(cmd);
52847
54313
  lastPushed = cmd;
52848
54314
  for (const h of activeHeredocCmds) h.cmd = cmd;
52849
54315
  }
52850
54316
  activeHeredocCmds = [];
52851
- words2 = [];
54317
+ words3 = [];
52852
54318
  assigns = [];
52853
54319
  redirects = [];
52854
54320
  heredoc = null;
@@ -53151,21 +54617,21 @@ function parseShell(command, sub = false) {
53151
54617
  }
53152
54618
 
53153
54619
  // ../core/src/dev-tools.ts
53154
- var import_zod9 = __toESM(require_zod(), 1);
54620
+ var import_zod10 = __toESM(require_zod(), 1);
53155
54621
  import { readFileSync as readFileSync4, statSync } from "node:fs";
53156
54622
  import { homedir as homedir3 } from "node:os";
53157
- import { isAbsolute as isAbsolute5, join as join7, normalize as normalize2, relative as relative5, resolve as resolve4 } from "node:path";
54623
+ import { isAbsolute as isAbsolute5, join as join8, normalize as normalize2, relative as relative5, resolve as resolve4 } from "node:path";
53158
54624
 
53159
54625
  // ../core/src/user-dir-guard.ts
53160
54626
  import { homedir as homedir2 } from "node:os";
53161
- import { dirname as dirname2, isAbsolute as isAbsolute4, join as join6, relative as relative4, resolve as resolve3 } from "node:path";
54627
+ import { dirname as dirname2, isAbsolute as isAbsolute4, join as join7, relative as relative4, resolve as resolve3 } from "node:path";
53162
54628
  function userKeyDirs(env = process.env) {
53163
54629
  const out = /* @__PURE__ */ new Set();
53164
54630
  const o = env["EXORCIST_USER_DIR"];
53165
54631
  if (o && isAbsolute4(o)) out.add(resolve3(o));
53166
54632
  const xdg = env["XDG_CONFIG_HOME"];
53167
- out.add(join6(xdg && isAbsolute4(xdg) ? xdg : join6(homedir2(), ".config"), "exorcist-98"));
53168
- out.add(join6(homedir2(), ".config", "exorcist-98"));
54633
+ out.add(join7(xdg && isAbsolute4(xdg) ? xdg : join7(homedir2(), ".config"), "exorcist-98"));
54634
+ out.add(join7(homedir2(), ".config", "exorcist-98"));
53169
54635
  return [...out];
53170
54636
  }
53171
54637
  var CASE_INSENSITIVE = process.platform === "darwin" || process.platform === "win32";
@@ -53705,11 +55171,11 @@ function devToolPlan(prog, args, ctx2 = {}) {
53705
55171
  }
53706
55172
  }
53707
55173
  }
53708
- var ProgramList = import_zod9.z.union([import_zod9.z.array(import_zod9.z.string()), import_zod9.z.object({ programs: import_zod9.z.array(import_zod9.z.string()) })]);
55174
+ var ProgramList = import_zod10.z.union([import_zod10.z.array(import_zod10.z.string()), import_zod10.z.object({ programs: import_zod10.z.array(import_zod10.z.string()) })]);
53709
55175
  var cache2 = /* @__PURE__ */ new Map();
53710
55176
  var NAME = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/;
53711
55177
  function knownProgramsPath(env = process.env) {
53712
- return join7(userKeyDirs(env)[0], "known-programs.json");
55178
+ return join8(userKeyDirs(env)[0], "known-programs.json");
53713
55179
  }
53714
55180
  function userKnownPrograms(env = process.env) {
53715
55181
  const path = knownProgramsPath(env);
@@ -53743,7 +55209,7 @@ var reject = (reason, fix = FIX_SIMPLE) => {
53743
55209
  throw new Reject(reason, fix);
53744
55210
  };
53745
55211
  var SYSTEM_DIRS = ["/usr/bin/", "/bin/", "/usr/sbin/", "/sbin/", "/usr/local/bin/", "/usr/local/sbin/", "/opt/homebrew/bin/", "/opt/homebrew/sbin/", "/opt/local/bin/", "/usr/libexec/", "/usr/local/opt/"];
53746
- var SHELLS = /* @__PURE__ */ new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "csh", "tcsh", "fish"]);
55212
+ var SHELLS2 = /* @__PURE__ */ new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "csh", "tcsh", "fish"]);
53747
55213
  var NODE_LIKE = /* @__PURE__ */ new Set(["node", "nodejs", "tsx", "ts-node", "bun", "deno"]);
53748
55214
  var INTERPRETERS2 = /* @__PURE__ */ new Set(["node", "nodejs", "tsx", "ts-node", "bun", "deno", "python", "python3", "ruby", "perl", "php", "lua", "sh", "bash", "zsh", "dash", "ksh"]);
53749
55215
  var KNOWN_PROGRAMS = /* @__PURE__ */ new Set([
@@ -54062,10 +55528,10 @@ function progName(raw) {
54062
55528
  }
54063
55529
  var wordsText = (ws) => ws.map((w) => w.text);
54064
55530
  var anyDynamic = (ws) => ws.some((w) => w.dynamic);
54065
- function skipFlags(words2, from, sp, name, env) {
55531
+ function skipFlags(words3, from, sp, name, env) {
54066
55532
  let i = from;
54067
- for (; i < words2.length; i++) {
54068
- const w = words2[i];
55533
+ for (; i < words3.length; i++) {
55534
+ const w = words3[i];
54069
55535
  if (env !== void 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(w.text) && !w.text.startsWith("-")) {
54070
55536
  const eq2 = w.text.indexOf("=");
54071
55537
  env[w.text.slice(0, eq2)] = w.text.slice(eq2 + 1);
@@ -54089,7 +55555,7 @@ function skipFlags(words2, from, sp, name, env) {
54089
55555
  }
54090
55556
  return i;
54091
55557
  }
54092
- function pushExec(ctx2, f, words2, rawProg) {
55558
+ function pushExec(ctx2, f, words3, rawProg) {
54093
55559
  if (ctx2.execs.length > 600) reject("it runs too many programs to follow");
54094
55560
  const prog = progName(rawProg);
54095
55561
  const local = rawProg.includes("/") && !SYSTEM_DIRS.some((d) => rawProg.startsWith(d)) && !/(^|\/)node_modules\/\.bin\//.test(rawProg);
@@ -54101,7 +55567,7 @@ function pushExec(ctx2, f, words2, rawProg) {
54101
55567
  ctx2.execs.push({
54102
55568
  prog: local ? progName(rawProg) : prog,
54103
55569
  rawProg,
54104
- args: words2.slice(1),
55570
+ args: words3.slice(1),
54105
55571
  env: { ...f.env },
54106
55572
  redirects: f.redirects,
54107
55573
  stdinText: f.stdinText,
@@ -54157,12 +55623,12 @@ function checkGit(args, ctx2) {
54157
55623
  if (name === "config" && rest.some((r) => /^alias\./i.test(r)) && rest.some((r) => r.startsWith("!"))) reject("git config would add a shell alias", FIX_SIMPLE);
54158
55624
  if (rest.some((r) => r === "--upload-pack" || r.startsWith("--upload-pack=") || r === "--receive-pack" || r.startsWith("--receive-pack=") || r === "--exec" || r.startsWith("--ext-diff") || r.startsWith("--textconv") || r.startsWith("--output="))) reject("a git option would run a program or write a file the guard cannot see", FIX_SIMPLE);
54159
55625
  }
54160
- function checkSpecial(prog, f, words2, ctx2) {
55626
+ function checkSpecial(prog, f, words3, ctx2) {
54161
55627
  if (ctx2.mode !== "agent") return;
54162
- const args = wordsText(words2.slice(1));
55628
+ const args = wordsText(words3.slice(1));
54163
55629
  if (prog === "awk" || prog === "gawk" || prog === "mawk") {
54164
55630
  if (args.some((a) => AWK_EXEC.test(a))) reject("an awk program runs commands (system, getline or a pipe)", FIX_READ_TOOL);
54165
- if (anyDynamic(words2.slice(1))) reject("an awk program is built at run time", FIX_SPELL_OUT);
55631
+ if (anyDynamic(words3.slice(1))) reject("an awk program is built at run time", FIX_SPELL_OUT);
54166
55632
  }
54167
55633
  if (prog === "sed" || prog === "gsed") {
54168
55634
  if (args.some((a) => !a.startsWith("-") && SED_EXEC.test(a))) reject("a sed script runs commands (the e command)", FIX_READ_TOOL);
@@ -54197,10 +55663,10 @@ function checkSpecial(prog, f, words2, ctx2) {
54197
55663
  }
54198
55664
  }
54199
55665
  }
54200
- function resolveWords(words2, f, ctx2) {
55666
+ function resolveWords(words3, f, ctx2) {
54201
55667
  if (ctx2.depth > 8) reject("it wraps commands too deeply to follow");
54202
- if (words2.length === 0) return;
54203
- const w0 = words2[0];
55668
+ if (words3.length === 0) return;
55669
+ const w0 = words3[0];
54204
55670
  if (w0.dynamic) reject("the program name is built at run time (a variable or a substitution)", FIX_SPELL_OUT);
54205
55671
  if (w0.glob && !/^(\[\[?)$/.test(w0.text)) reject("the program name is a pattern", FIX_SPELL_OUT);
54206
55672
  if (w0.tilde) reject("the program is given as a path starting with ~", FIX_SPELL_OUT);
@@ -54209,7 +55675,7 @@ function resolveWords(words2, f, ctx2) {
54209
55675
  const prog = progName(raw);
54210
55676
  const isSystemName = !raw.includes("/") || SYSTEM_DIRS.some((d) => raw.startsWith(d)) || /(^|\/)node_modules\/\.bin\//.test(raw);
54211
55677
  if (!isSystemName) {
54212
- pushExec(ctx2, f, words2, raw);
55678
+ pushExec(ctx2, f, words3, raw);
54213
55679
  return;
54214
55680
  }
54215
55681
  const next = (inner, via, extra) => {
@@ -54222,41 +55688,41 @@ function resolveWords(words2, f, ctx2) {
54222
55688
  };
54223
55689
  if (prog in WRAP_SPECS) {
54224
55690
  const env = { ...f.env };
54225
- let i = skipFlags(words2, 1, WRAP_SPECS[prog], prog, prog === "env" || prog === "sudo" || prog === "doas" ? env : void 0);
55691
+ let i = skipFlags(words3, 1, WRAP_SPECS[prog], prog, prog === "env" || prog === "sudo" || prog === "doas" ? env : void 0);
54226
55692
  if (prog === "env" || prog === "sudo" || prog === "doas") {
54227
- const inner = words2[i] !== void 0 && !words2[i]?.dynamic && !words2[i]?.glob ? progName(words2[i].text) : void 0;
55693
+ const inner = words3[i] !== void 0 && !words3[i]?.dynamic && !words3[i]?.glob ? progName(words3[i].text) : void 0;
54228
55694
  for (const [k, v] of Object.entries(env)) if (f.env[k] !== v) checkAssign(ctx2, k, v, /[$`]/.test(v), inner);
54229
55695
  }
54230
55696
  if (prog === "timeout") {
54231
- if (words2[i] === void 0 || words2[i]?.dynamic) reject("timeout has no fixed duration");
55697
+ if (words3[i] === void 0 || words3[i]?.dynamic) reject("timeout has no fixed duration");
54232
55698
  i++;
54233
55699
  }
54234
55700
  if (prog === "flock") {
54235
55701
  i++;
54236
- if (words2[i]?.text === "-c") {
54237
- const s = words2[i + 1];
55702
+ if (words3[i]?.text === "-c") {
55703
+ const s = words3[i + 1];
54238
55704
  if (s === void 0 || s.dynamic) return reject("flock -c has a command built at run time");
54239
55705
  parseAndResolve(s.text, f, ctx2, "flock -c");
54240
55706
  return;
54241
55707
  }
54242
55708
  }
54243
- if (prog === "command" && words2.slice(1).some((w) => w.text === "-v" || w.text === "-V")) return;
54244
- if (prog === "env" && words2.slice(1).some((w) => w.text === "-S" || w.text.startsWith("--split-string"))) reject("env -S splits a string into a command");
54245
- if (i >= words2.length) {
55709
+ if (prog === "command" && words3.slice(1).some((w) => w.text === "-v" || w.text === "-V")) return;
55710
+ if (prog === "env" && words3.slice(1).some((w) => w.text === "-S" || w.text.startsWith("--split-string"))) reject("env -S splits a string into a command");
55711
+ if (i >= words3.length) {
54246
55712
  if (prog === "env" || prog === "time" || prog === "exec") return;
54247
55713
  reject(`${prog} has no command to follow`);
54248
55714
  }
54249
- next(words2.slice(i), prog, { env });
55715
+ next(words3.slice(i), prog, { env });
54250
55716
  return;
54251
55717
  }
54252
55718
  if (prog === "dotenv" || prog === "dotenvx" || prog === "env-cmd" || prog === "cross-env") {
54253
55719
  const env = { ...f.env, __DOTENV__: "1" };
54254
55720
  let i = 1;
54255
- const dd = words2.findIndex((w) => w.text === "--");
55721
+ const dd = words3.findIndex((w) => w.text === "--");
54256
55722
  if (dd > 0) i = dd + 1;
54257
55723
  else {
54258
- for (; i < words2.length; i++) {
54259
- const t2 = words2[i].text;
55724
+ for (; i < words3.length; i++) {
55725
+ const t2 = words3[i].text;
54260
55726
  if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t2)) {
54261
55727
  const eq = t2.indexOf("=");
54262
55728
  env[t2.slice(0, eq)] = t2.slice(eq + 1);
@@ -54270,27 +55736,27 @@ function resolveWords(words2, f, ctx2) {
54270
55736
  break;
54271
55737
  }
54272
55738
  }
54273
- if (i >= words2.length) {
55739
+ if (i >= words3.length) {
54274
55740
  if (prog === "dotenvx") return;
54275
55741
  reject(`${prog} has no command to follow`);
54276
55742
  }
54277
- next(words2.slice(i), prog, { env });
55743
+ next(words3.slice(i), prog, { env });
54278
55744
  return;
54279
55745
  }
54280
55746
  if (prog === "xargs") {
54281
- const i = skipFlags(words2, 1, XARGS_SPEC, "xargs");
54282
- const inner = i >= words2.length ? [{ text: "echo", dynamic: false, glob: false, tilde: false }] : words2.slice(i);
55747
+ const i = skipFlags(words3, 1, XARGS_SPEC, "xargs");
55748
+ const inner = i >= words3.length ? [{ text: "echo", dynamic: false, glob: false, tilde: false }] : words3.slice(i);
54283
55749
  next(inner, "xargs", { argsFromStdin: true, stdinOther: false });
54284
55750
  return;
54285
55751
  }
54286
55752
  if (prog === "find") {
54287
- pushExec(ctx2, f, words2, raw);
54288
- for (let i = 1; i < words2.length; i++) {
54289
- const t2 = words2[i].text;
55753
+ pushExec(ctx2, f, words3, raw);
55754
+ for (let i = 1; i < words3.length; i++) {
55755
+ const t2 = words3[i].text;
54290
55756
  if (t2 === "-exec" || t2 === "-execdir" || t2 === "-ok" || t2 === "-okdir") {
54291
55757
  let j = i + 1;
54292
- while (j < words2.length && words2[j]?.text !== ";" && words2[j]?.text !== "+") j++;
54293
- const inner = words2.slice(i + 1, j).map((w) => w.text === "{}" ? { ...w, dynamic: true, glob: false } : w);
55758
+ while (j < words3.length && words3[j]?.text !== ";" && words3[j]?.text !== "+") j++;
55759
+ const inner = words3.slice(i + 1, j).map((w) => w.text === "{}" ? { ...w, dynamic: true, glob: false } : w);
54294
55760
  if (inner.length === 0) reject("find -exec has no command");
54295
55761
  next(inner, `find ${t2}`, { argsFromStdin: true, stdinOther: false });
54296
55762
  i = j;
@@ -54299,26 +55765,26 @@ function resolveWords(words2, f, ctx2) {
54299
55765
  return;
54300
55766
  }
54301
55767
  if (prog === "eval") {
54302
- if (anyDynamic(words2.slice(1))) reject("eval was given text built at run time", FIX_SIMPLE);
54303
- parseAndResolve(wordsText(words2.slice(1)).join(" "), f, ctx2, "eval");
55768
+ if (anyDynamic(words3.slice(1))) reject("eval was given text built at run time", FIX_SIMPLE);
55769
+ parseAndResolve(wordsText(words3.slice(1)).join(" "), f, ctx2, "eval");
54304
55770
  return;
54305
55771
  }
54306
55772
  if (prog === "source" || prog === ".") {
54307
- pushExec(ctx2, f, words2, raw);
55773
+ pushExec(ctx2, f, words3, raw);
54308
55774
  return;
54309
55775
  }
54310
- if (SHELLS.has(prog)) {
55776
+ if (SHELLS2.has(prog)) {
54311
55777
  let i = 1;
54312
55778
  let script = null;
54313
55779
  let fromStdin = false;
54314
- for (; i < words2.length; i++) {
54315
- const t2 = words2[i].text;
55780
+ for (; i < words3.length; i++) {
55781
+ const t2 = words3[i].text;
54316
55782
  if (t2 === "--") {
54317
55783
  i++;
54318
55784
  break;
54319
55785
  }
54320
55786
  if (t2.startsWith("-") && !t2.startsWith("--") && /^-[A-Za-z]+$/.test(t2) && t2.includes("c")) {
54321
- const s = words2[i + 1];
55787
+ const s = words3[i + 1];
54322
55788
  if (!s) reject(`${prog} -c has no command`);
54323
55789
  if (s?.dynamic) reject(`${prog} -c was given a command built at run time`, FIX_SIMPLE);
54324
55790
  script = s;
@@ -54340,9 +55806,9 @@ function resolveWords(words2, f, ctx2) {
54340
55806
  parseAndResolve(script.text, f, ctx2, `${prog} -c`);
54341
55807
  return;
54342
55808
  }
54343
- const file = words2[i];
55809
+ const file = words3[i];
54344
55810
  if (file !== void 0 && !fromStdin) {
54345
- pushExec(ctx2, f, words2, raw);
55811
+ pushExec(ctx2, f, words3, raw);
54346
55812
  return;
54347
55813
  }
54348
55814
  if (f.stdinText !== null) {
@@ -54351,16 +55817,16 @@ function resolveWords(words2, f, ctx2) {
54351
55817
  }
54352
55818
  reject(`${prog} runs commands read from a pipe or a file the guard cannot see`, FIX_SIMPLE);
54353
55819
  }
54354
- if (prog === "git") checkGit(words2.slice(1), ctx2);
54355
- checkSpecial(prog, f, words2, ctx2);
55820
+ if (prog === "git") checkGit(words3.slice(1), ctx2);
55821
+ checkSpecial(prog, f, words3, ctx2);
54356
55822
  if (ctx2.mode === "agent" && DEV_TOOLS.has(prog)) {
54357
- const plan = devToolPlan(prog, words2.slice(1), { env: f.env, ...ctx2.cwd === void 0 ? {} : { cwd: ctx2.cwd } });
55823
+ const plan = devToolPlan(prog, words3.slice(1), { env: f.env, ...ctx2.cwd === void 0 ? {} : { cwd: ctx2.cwd } });
54358
55824
  if (plan.kind === "reject") reject(plan.reason, FIX_SIMPLE);
54359
- pushExec(ctx2, f, words2, raw);
55825
+ pushExec(ctx2, f, words3, raw);
54360
55826
  if (plan.kind === "follow") next(plan.words, prog);
54361
55827
  return;
54362
55828
  }
54363
- pushExec(ctx2, f, words2, raw);
55829
+ pushExec(ctx2, f, words3, raw);
54364
55830
  const e = lastExec(ctx2);
54365
55831
  if (ctx2.mode === "script" && (INTERPRETERS2.has(prog) || /^python/.test(prog))) {
54366
55832
  const flags2 = /* @__PURE__ */ new Set(["-e", "-c", "-p", "--eval", "--print", "-r", "-E"]);
@@ -54400,8 +55866,8 @@ function producedText(e) {
54400
55866
  }
54401
55867
  var ENV_DECLARERS = /* @__PURE__ */ new Set(["export", "declare", "typeset", "readonly", "local"]);
54402
55868
  var ASSIGN_WORD = /^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/;
54403
- function literalProg(words2) {
54404
- const w = words2[0];
55869
+ function literalProg(words3) {
55870
+ const w = words3[0];
54405
55871
  if (w === void 0 || w.dynamic || w.glob || ENV_DECLARERS.has(w.text)) return void 0;
54406
55872
  return progName(w.text);
54407
55873
  }
@@ -54462,8 +55928,8 @@ function analyzeShell(command, opts = {}) {
54462
55928
  return { ok: false, reason: "the command could not be analysed", fix: FIX_SIMPLE, execs: ctx2.execs };
54463
55929
  }
54464
55930
  }
54465
- function analyzeWords(words2, mode = "agent", env = {}, cwd) {
54466
- const cmd = { words: [...words2], assigns: [], redirects: [], pipeIn: false, pipeOut: false, heredoc: null, herestring: null, sub: false };
55931
+ function analyzeWords(words3, mode = "agent", env = {}, cwd) {
55932
+ const cmd = { words: [...words3], assigns: [], redirects: [], pipeIn: false, pipeOut: false, heredoc: null, herestring: null, sub: false };
54467
55933
  const ctx2 = { mode, execs: [], depth: 0, ...cwd === void 0 ? {} : { cwd } };
54468
55934
  try {
54469
55935
  resolveCommands([cmd], ctx2, [], env);
@@ -54576,13 +56042,14 @@ function stripJs(text) {
54576
56042
  v += text[j];
54577
56043
  j++;
54578
56044
  }
54579
- strings3.push({ value: v, pos: i });
56045
+ const at2 = strings3.push({ value: v, pos: i }) - 1;
54580
56046
  out[i] = c;
54581
56047
  blank(i + 1, j);
54582
56048
  if (j < n && text[j] === c) {
54583
56049
  out[j] = c;
54584
56050
  j++;
54585
56051
  }
56052
+ strings3[at2].end = j;
54586
56053
  i = j;
54587
56054
  prev = c;
54588
56055
  continue;
@@ -54614,13 +56081,14 @@ function stripJs(text) {
54614
56081
  v += t2;
54615
56082
  j++;
54616
56083
  }
54617
- strings3.push({ value: v, pos: i });
56084
+ const at2 = strings3.push({ value: v, pos: i }) - 1;
54618
56085
  out[i] = "`";
54619
56086
  blank(i + 1, j);
54620
56087
  if (j < n) {
54621
56088
  out[j] = "`";
54622
56089
  j++;
54623
56090
  }
56091
+ strings3[at2].end = j;
54624
56092
  i = j;
54625
56093
  prev = "`";
54626
56094
  continue;
@@ -54666,11 +56134,130 @@ var lineHit = (lines, patterns) => {
54666
56134
  }
54667
56135
  return null;
54668
56136
  };
56137
+ var SERIALIZE_CALLEE = /(?:JSON\s*\.\s*stringify|Buffer\s*\.\s*from|\bbtoa|\bencodeURIComponent|\bescape|querystring\s*\.\s*(?:stringify|encode)|\bURLSearchParams|util\s*\.\s*inspect|\binspect|\bString|\.\s*(?:write|end|send|post|put|emit|push))$/;
56138
+ function wholeEnvSerialized(code) {
56139
+ const re2 = /\bprocess\s*\.\s*env\b(?!\s*(?:\.|\[|\?\.))/g;
56140
+ for (let m = re2.exec(code); m; m = re2.exec(code)) {
56141
+ let depth = 0;
56142
+ let levels = 0;
56143
+ for (let i = m.index - 1; i >= 0 && m.index - i < 2e3 && levels < 4; i--) {
56144
+ const c = code[i];
56145
+ if (c === ")" || c === "]" || c === "}") depth++;
56146
+ else if (c === "[" || c === "{") {
56147
+ if (depth > 0) depth--;
56148
+ else levels++;
56149
+ } else if (c === "(") {
56150
+ if (depth > 0) {
56151
+ depth--;
56152
+ continue;
56153
+ }
56154
+ levels++;
56155
+ const callee = code.slice(Math.max(0, i - 60), i).replace(/\s+$/, "");
56156
+ if (/\b(?:spawn|spawnSync|exec|execSync|execFile|execFileSync|fork|execa|execaSync|Worker)$/.test(callee)) break;
56157
+ if (SERIALIZE_CALLEE.test(callee)) return m.index;
56158
+ } else if (c === ";" && depth === 0) break;
56159
+ }
56160
+ }
56161
+ return null;
56162
+ }
56163
+ var SECRET_ENV_NAME = String.raw`[A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|PRIVATE_KEY|ACCESS_KEY|AUTH|CREDENTIALS?)[A-Z0-9_]*`;
56164
+ var JS_SECRET_IN_URL = new RegExp(String.raw`(?:['"\x60][^'"\x60\n]*[?&=/:]['"\x60]\s*\+\s*process\s*\.\s*env\s*\.\s*${SECRET_ENV_NAME}\b|https?://[^'"\x60\s]*\$\{\s*process\s*\.\s*env\s*\.\s*${SECRET_ENV_NAME}\s*\})`);
56165
+ var OBFUSCATED_EXEC = [
56166
+ /\b(?:eval|Function|runInThisContext|runInNewContext|runInContext|compileFunction|Script)\s*\((?:[^()]|\([^()]*\)){0,400}?(?:\batob\s*\(|Buffer\s*\.\s*from\s*\([^)]*['"](?:base64|hex|base64url)['"]|String\s*\.\s*fromCharCode|\bunescape\s*\(|decodeURIComponent\s*\(\s*['"](?:%[0-9a-f]{2}){8})/i,
56167
+ /\b(?:exec|eval)\s*\(\s*(?:compile\s*\(\s*)?(?:base64\s*\.\s*\w*decode|codecs\s*\.\s*decode|zlib\s*\.\s*decompress|marshal\s*\.\s*loads|bytes\s*\.\s*fromhex|__import__\s*\(\s*['"](?:base64|zlib|codecs|marshal)['"]\s*\))/,
56168
+ /\bbase64\s+(?:-d|--decode|-D)\b[^\n|;&]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh|dash|node|python[0-9.]*|perl|ruby|php)\b/,
56169
+ /\b(?:sh|bash|zsh|node|python[0-9.]*)\s+-[ce]\s+["']?\$\(\s*(?:echo|printf)\s+[^)]*\|\s*base64\s+(?:-d|--decode|-D)\b/
56170
+ ];
56171
+ function obfuscatedExec(text) {
56172
+ for (const re2 of OBFUSCATED_EXEC) {
56173
+ const m = re2.exec(text);
56174
+ if (m) return { line: lineOf(text, m.index), label: "code hidden in an encoded string that is decoded and run" };
56175
+ }
56176
+ return null;
56177
+ }
56178
+ var CRED_PATH2 = String.raw`(?:\.ssh(?![\w-])|\.aws(?![\w-])|\.npmrc\b|\.pypirc\b|\.netrc\b|\.git-credentials\b|\.docker/config\.json|\.kube/config\b|\.config/gcloud/|\bid_(?:rsa|ed25519|ecdsa|dsa)\b|(?<![\w.])\.env\b(?!\.(?:example|sample|template|dist)))`;
56179
+ var SHELL_SENDER = String.raw`(?:\bcurl\b|\bwget\b|\bnc\b|\bncat\b|\bsocat\b|/dev/(?:tcp|udp)/|\bopenssl\s+s_client\b|\bInvoke-WebRequest\b|\bInvoke-RestMethod\b)`;
56180
+ var ENV_DUMP_CMD = String.raw`(?:(?:^|[;&|(\x60'"]|\$\(|\s-c\s+)\s*(?:sudo\s+)?(?:env|printenv|set|export\s+-p|declare\s+-x)\s*(?=\||\)|\x60|$)|/proc/(?:\d+|self|\$\$|\*)/environ\b|\bcompgen\s+-e\b)`;
56181
+ var SHELL_PATTERNS = [
56182
+ // env | curl ... cat /proc/1/environ | ... | curl ... $(env | base64) inside a curl
56183
+ [new RegExp(String.raw`${ENV_DUMP_CMD}[^\n]*?${SHELL_SENDER}`), "the whole environment", "curl, wget or a socket"],
56184
+ [new RegExp(String.raw`${SHELL_SENDER}[^\n]*?(?:\$\(|\x60)\s*(?:env|printenv|set)\b`), "the whole environment", "curl, wget or a socket"],
56185
+ // cat ~/.aws/credentials | curl ... base64 ~/.ssh/id_rsa | curl
56186
+ [new RegExp(String.raw`\b(?:cat|base64|gzip\s+-c|tar\s+-?c\S*|xxd|od)\s+[^\n|;&]*${CRED_PATH2}[^\n|;&]*\|[^\n]*?${SHELL_SENDER}`), "a credentials file", "curl, wget or a socket"],
56187
+ // curl -d @~/.aws/credentials curl -T .env wget --post-file=~/.npmrc curl -d "$(cat ~/.netrc)"
56188
+ [new RegExp(String.raw`\b(?:curl|wget)\b[^\n]*?(?:\s(?:-d|--data(?:-binary|-raw|-urlencode|-ascii)?|-F|--form|-T|--upload-file|--post-file|--body-file)(?:=|\s+)?['"]?[^\s'"]*?(?:@|=|\$\(\s*cat\s+)?[^\s'"]*${CRED_PATH2})`), "a credentials file", "curl or wget"],
56189
+ // a credential variable in the URL or the body of a curl or wget: https://x/?t=$NPM_TOKEN
56190
+ [new RegExp(String.raw`\b(?:curl|wget)\b[^\n]*?(?:https?://[^\s'"]*\$\{?${SECRET_ENV_NAME}\b|\s(?:-d|--data(?:-binary|-raw|-urlencode)?|-F|--form)(?:=|\s+)['"]?[^\s'"]*\$\{?${SECRET_ENV_NAME}\b)`), "a credential variable in the request", "curl or wget"]
56191
+ ];
56192
+ function shellExfil(text) {
56193
+ const lines = text.replace(/\\\r?\n/g, " ").split(/\r?\n/);
56194
+ for (let i = 0; i < lines.length; i++) {
56195
+ const l = lines[i] ?? "";
56196
+ if (l.length > 2e4) continue;
56197
+ for (const [re2, secret, send] of SHELL_PATTERNS) {
56198
+ if (re2.test(l)) return { secret: { line: i + 1, label: secret }, send: { line: i + 1, label: send } };
56199
+ }
56200
+ }
56201
+ return null;
56202
+ }
56203
+ var STRONG_SOURCES = /* @__PURE__ */ new Set([".npmrc", "~/.aws", "~/.ssh", "a private key file", "a credentials file", "the whole of process.env", "the whole of os.environ", "the whole environment"]);
56204
+ var isStrongSource = (h) => h !== null && h !== void 0 && STRONG_SOURCES.has(h.label);
56205
+ var WRITES_FILE = /\b(?:writeFileSync|writeFile|appendFileSync|appendFile|createWriteStream|copyFileSync|copyFile|renameSync|write_text|write_bytes)\s*\(|\bopen\s*\([^)\n]*['"][wax]b?\+?['"]|\bshutil\.copy|(?:^|[^<>&0-9-])>{1,2}\s*[^\s&>|=)]|\btee\s|\b(?:cp|mv|install)\s+\S+\s+\S/m;
56206
+ var READS_FILE = /\b(?:readFileSync|readFile|createReadStream|readTextFile|read_text|read_bytes)\s*\(|\bopen\s*\(|\bcat\s+\S|<\s*[^\s<(]|\s(?:-d|--data(?:-binary|-raw)?|-F|--form|-T|--upload-file)(?:=|\s+)['"]?@?[^\s'"@-]|--post-file/;
56207
+ var JS_READ_CALL = /\b(?:readFileSync|readFile|createReadStream|openSync|readSync|copyFileSync|copyFile|readdirSync|loadEnvFile|readTextFile|readTextFileSync)\s*\(|\bBun\s*\.\s*file\s*\(|\bfs\s*\.\s*promises\b|\bconfig\s*\(\s*\{\s*path\b/;
56208
+ var PATH_BUILD = /\b(?:path\s*\.\s*)?(?:join|resolve)\s*\(|\bhomedir\s*\(|\bos\s*\.\s*homedir\b|\bprocess\s*\.\s*cwd\s*\(|\bnew\s+URL\s*\(/;
54669
56209
  function analyzeJs(text) {
54670
56210
  const { code, strings: strings3 } = stripJs(text);
54671
56211
  let secret = null;
54672
- for (const s of strings3) {
54673
- for (const [re2, label] of SECRET_PATH_PATTERNS) if (re2.test(s.value)) {
56212
+ const reads = JS_READ_CALL.test(code) || EXEC_CALL.test(code);
56213
+ const codeLines = code.split("\n");
56214
+ const nearUse = (pos) => {
56215
+ const ln = lineOf(text, pos) - 1;
56216
+ const around = codeLines.slice(Math.max(0, ln - 3), ln + 4).join("\n");
56217
+ return JS_READ_CALL.test(around) || EXEC_CALL.test(around) || PATH_BUILD.test(around);
56218
+ };
56219
+ const boundAndUsed = (pos) => {
56220
+ const lineStart = text.lastIndexOf("\n", pos - 1) + 1;
56221
+ const bind = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*$/.exec(text.slice(lineStart, pos));
56222
+ if (!bind) return false;
56223
+ const name = bind[1].replace(/\$/g, "\\$");
56224
+ return new RegExp(String.raw`(?:\b(?:readFileSync|readFile|createReadStream|openSync|readSync|copyFileSync|copyFile|loadEnvFile|readTextFile|readTextFileSync|join|resolve|exec\w*|spawn\w*|open|file)\s*\([^)]*|\bpath\s*:\s*)(?<![\w$])${name}(?![\w$])`).test(code);
56225
+ };
56226
+ const READ_AFTER = String.raw`[\s\S]{0,300}?\b(?:readFileSync|readFile|createReadStream|openSync|readSync|copyFileSync|copyFile|loadEnvFile|exec\w*|spawn\w*|join|resolve)\s*\(`;
56227
+ const tableWalked = (pos) => {
56228
+ const decls = [...text.slice(Math.max(0, pos - 4e3), pos).matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]{0,80})?=\s*\{/g)];
56229
+ const name = decls.at(-1)?.[1];
56230
+ if (name === void 0) return false;
56231
+ const n = name.replace(/\$/g, "\\$");
56232
+ return new RegExp(String.raw`(?:\bObject\s*\.\s*(?:keys|entries|values)\s*\(\s*${n}(?![\w$])|\b(?:in|of)\s+${n}(?![\w$]))` + READ_AFTER).test(code);
56233
+ };
56234
+ const inIgnoreList = (pos) => {
56235
+ const before = text.slice(Math.max(0, pos - 300), pos);
56236
+ const open4 = before.lastIndexOf("[");
56237
+ if (open4 < 0 || before.indexOf("]", open4) >= 0) return false;
56238
+ if (/(?:skip|ignor|exclud|hidden|block|deny|denied|omit|prune)\w*[^\n]{0,60}$/i.test(before.slice(Math.max(0, open4 - 80), open4))) return true;
56239
+ const openAt = pos - (before.length - open4);
56240
+ if (code[openAt] !== "[") return false;
56241
+ const close = code.indexOf("]", pos);
56242
+ if (close < 0 || close - pos > 600) return false;
56243
+ const items = [...text.slice(openAt, close).matchAll(/['"`]([^'"`\n]{0,40})['"`]/g)].map((m) => m[1]);
56244
+ const exts = items.filter((v) => /^\.[A-Za-z0-9]{1,8}$/.test(v)).length;
56245
+ if (items.length < 4 || exts < items.length - 1) return false;
56246
+ const bind = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]{0,80})?=\s*(?:new\s+Set\s*\(\s*)?$/.exec(code.slice(Math.max(0, openAt - 200), openAt));
56247
+ if (!bind) return false;
56248
+ const n = bind[1].replace(/\$/g, "\\$");
56249
+ const walked = new RegExp(String.raw`(?:\bfor\s*\([^)]*\b(?:of|in)\s+${n}(?![\w$])|(?<![\w$])${n}\s*\.\s*(?:forEach|map|filter|some|every|flatMap|reduce|values|keys|entries)\s*\(|\.\.\.\s*${n}(?![\w$])|(?<![\w$])${n}\s*\[)` + READ_AFTER).test(code);
56250
+ const passed = new RegExp(String.raw`\b(?:readFileSync|readFile|createReadStream|openSync|readSync|copyFileSync|copyFile|loadEnvFile|join|resolve|exec\w*|spawn\w*)\s*\([^)]*(?<![\w$])${n}(?![\w$])`).test(code);
56251
+ return !walked && !passed;
56252
+ };
56253
+ for (const s of reads ? strings3 : []) {
56254
+ for (const [re2, label] of SECRET_PATH_PATTERNS) {
56255
+ if (!re2.test(s.value)) continue;
56256
+ if (label === ".env") {
56257
+ const end = s.end ?? s.pos + s.value.length + 2;
56258
+ const isKey = /^\s*:/.test(text.slice(end, end + 40));
56259
+ if (isKey ? !tableWalked(s.pos) : inIgnoreList(s.pos)) continue;
56260
+ }
54674
56261
  secret = { line: lineOf(text, s.pos), label };
54675
56262
  break;
54676
56263
  }
@@ -54683,6 +56270,14 @@ function analyzeJs(text) {
54683
56270
  break;
54684
56271
  }
54685
56272
  }
56273
+ if (!secret) {
56274
+ const at2 = wholeEnvSerialized(code);
56275
+ if (at2 !== null) secret = { line: lineOf(text, at2), label: "the whole of process.env" };
56276
+ }
56277
+ if (!secret) {
56278
+ const m = JS_SECRET_IN_URL.exec(text);
56279
+ if (m) secret = { line: lineOf(text, m.index), label: "a credential variable put into a URL" };
56280
+ }
54686
56281
  const useEnv = ENV_USE.exec(code);
54687
56282
  if (!secret && useEnv) {
54688
56283
  const d = strings3.find((s) => DOTENV_STRING.test(s.value) && s.value !== "node:process");
@@ -54705,16 +56300,36 @@ function analyzeJs(text) {
54705
56300
  const s = strings3.find((x) => SHELL_SEND_STRING.test(x.value) || /^(?:curl|wget|nc|ncat)$/.test(x.value));
54706
56301
  if (s) send = { line: lineOf(text, s.pos), label: "curl or wget" };
54707
56302
  }
54708
- return { secret, send };
56303
+ return { secret, send, obfuscated: obfuscatedExec(text) };
54709
56304
  }
54710
56305
  function analyzeLines(text) {
54711
56306
  const lines = text.split(/\r?\n/);
54712
56307
  let secret = lineHit(lines, [...SECRET_PATH_PATTERNS, ...SECRET_DUMP_PATTERNS]);
54713
56308
  if (!secret && ENV_USE.test(text)) {
54714
- const at = lines.findIndex((l) => /\bdotenv\b/.test(l));
54715
- if (at >= 0) secret = { line: at + 1, label: "values loaded from .env (dotenv)" };
56309
+ const at2 = lines.findIndex((l) => /\bdotenv\b/.test(l));
56310
+ if (at2 >= 0) secret = { line: at2 + 1, label: "values loaded from .env (dotenv)" };
56311
+ }
56312
+ if (!secret && /\bprocess\s*\.\s*env\b/.test(text)) {
56313
+ const at2 = wholeEnvSerialized(stripJs(text).code);
56314
+ if (at2 !== null) secret = { line: lineOf(text, at2), label: "the whole of process.env" };
56315
+ else {
56316
+ const m = JS_SECRET_IN_URL.exec(text);
56317
+ if (m) secret = { line: lineOf(text, m.index), label: "a credential variable put into a URL" };
56318
+ }
56319
+ }
56320
+ let send = lineHit(lines, SEND_LINE_PATTERNS);
56321
+ if (!secret || !send) {
56322
+ const sh = shellExfil(text);
56323
+ if (sh) {
56324
+ secret = sh.secret;
56325
+ send = sh.send;
56326
+ }
54716
56327
  }
54717
- return { secret, send: lineHit(lines, SEND_LINE_PATTERNS) };
56328
+ if (!secret) {
56329
+ const m = new RegExp(String.raw`(?:json\.dumps|urlencode|\bstr|\brepr|pickle\.dumps|b64encode)\(\s*(?:dict\(\s*|\{\s*)?(?:\*\*)?os\.environ\b|json_encode\(\s*getenv\(\s*\)|json_encode\(\s*\$_(?:ENV|SERVER)\b|\bgetenv\(\s*\)`).exec(text);
56330
+ if (m) secret = { line: lineOf(text, m.index), label: "the whole environment" };
56331
+ }
56332
+ return { secret, send, obfuscated: obfuscatedExec(text) };
54718
56333
  }
54719
56334
  var JS_EXT = /\.(?:[cm]?[jt]sx?)$/i;
54720
56335
  function kindOfFile(rel, text) {
@@ -54762,6 +56377,7 @@ function scriptCandidates(rel) {
54762
56377
  if (base.startsWith("..") || base.startsWith("/") || base === "." || base === "") return [];
54763
56378
  return [.../* @__PURE__ */ new Set([base, ...JS_EXTS.map((e) => base + e), ...["index.js", "index.mjs", "index.cjs", "index.ts"].map((i) => posix.join(base, i))])];
54764
56379
  }
56380
+ var DATA_IMPORT = /\.(?:json|jsonc|json5)$/i;
54765
56381
  function followFiles(entries, fs) {
54766
56382
  const seen = /* @__PURE__ */ new Set();
54767
56383
  const queue = entries.map((rel) => ({ rel, depth: 0 }));
@@ -54784,10 +56400,12 @@ function followFiles(entries, fs) {
54784
56400
  continue;
54785
56401
  }
54786
56402
  files.push(item.rel);
56403
+ if (item.depth > 0 && DATA_IMPORT.test(item.rel)) continue;
54787
56404
  const a = analyzeSource(text, kindOfFile(item.rel, text));
54788
56405
  const tag = (h) => h && !first.has(item.rel) ? { ...h, file: item.rel } : h;
54789
56406
  if (!analysis.secret && a.secret) analysis.secret = tag(a.secret);
54790
56407
  if (!analysis.send && a.send) analysis.send = tag(a.send);
56408
+ if (!analysis.obfuscated && a.obfuscated) analysis.obfuscated = tag(a.obfuscated);
54791
56409
  if (item.depth >= MAX_CHAIN_DEPTH) {
54792
56410
  if (localSpecifiers(item.rel, text).length > 0) exceeded = true;
54793
56411
  continue;
@@ -55061,6 +56679,8 @@ function hitBase(pkgText, name, scripts) {
55061
56679
  return { script: name, scriptText: scripts[name] ?? "", ...locateScript(pkgText, name) };
55062
56680
  }
55063
56681
  var INCOMPLETE = { line: 1, label: "more local files than can be followed" };
56682
+ var HIDDEN_RUN = { line: 1, label: "eval, new Function or a shell, which runs the decoded code" };
56683
+ var DOTENV_SOURCE = { line: 1, label: "values loaded from .env (dotenv or --env-file)" };
55064
56684
  function evaluateTargets(targets, fs, failClosed) {
55065
56685
  const entries = [];
55066
56686
  let exceeded = false;
@@ -55080,20 +56700,58 @@ function evaluateTargets(targets, fs, failClosed) {
55080
56700
  entries.push(...rf.files);
55081
56701
  exceeded = exceeded || rf.exceeded;
55082
56702
  }
55083
- const followed = followFiles([...new Set(entries)], fs);
55084
- exceeded = exceeded || followed.exceeded;
55085
- let secret = followed.analysis.secret;
55086
- const send = followed.analysis.send;
55087
- if (!secret && send && targets.dotenv) secret = { line: 1, label: "values loaded from .env (dotenv or --env-file)" };
55088
- if (secret && send) return { file: followed.files[0] ?? null, secret, send };
56703
+ const unique = [...new Set(entries)];
56704
+ const groups = failClosed ? [unique] : unique.map((e) => [e]);
56705
+ for (const group of groups) {
56706
+ if (group.length === 0) continue;
56707
+ const followed = followFiles(group, fs);
56708
+ exceeded = exceeded || followed.exceeded;
56709
+ let secret = followed.analysis.secret;
56710
+ const send = followed.analysis.send;
56711
+ if (!secret && send && targets.dotenv) secret = DOTENV_SOURCE;
56712
+ if (secret && send) return { file: followed.files[0] ?? null, secret, send };
56713
+ const hidden = followed.analysis.obfuscated;
56714
+ if (hidden) return { file: hidden.file ?? followed.files[0] ?? null, secret: hidden, send: HIDDEN_RUN, kind: "obfuscated" };
56715
+ }
55089
56716
  for (const inline of targets.inline) {
55090
56717
  const a = analyzeSource(inline);
55091
- const sec = a.secret ?? (targets.dotenv && a.send ? { line: 1, label: "values loaded from .env (dotenv or --env-file)" } : null);
56718
+ const sec = a.secret ?? (targets.dotenv && a.send ? DOTENV_SOURCE : null);
55092
56719
  if (sec && a.send) return { file: null, secret: sec, send: a.send };
56720
+ if (a.obfuscated) return { file: null, secret: a.obfuscated, send: HIDDEN_RUN, kind: "obfuscated" };
56721
+ }
56722
+ if (!failClosed) {
56723
+ const h = handOff(unique, targets.inline, fs);
56724
+ if (h) return h.verdict;
55093
56725
  }
55094
56726
  if (failClosed && (exceeded || targets.unclear.length > 0)) return { file: null, secret: INCOMPLETE, send: INCOMPLETE, kind: "incomplete" };
55095
56727
  return null;
55096
56728
  }
56729
+ function handOff(entries, inline, fs) {
56730
+ const programs = [];
56731
+ for (const e of entries) {
56732
+ const f = followFiles([e], fs);
56733
+ programs.push({ file: e, a: f.analysis, text: f.files.map((x) => fs.read(x) ?? "").join("\n") });
56734
+ }
56735
+ for (const t2 of inline) programs.push({ file: null, a: analyzeSource(t2), text: t2 });
56736
+ const writer = programs.find((p) => isStrongSource(p.a.secret) && WRITES_FILE.test(p.text));
56737
+ if (!writer || !writer.a.secret) return null;
56738
+ const sender = programs.find((p) => p !== writer && p.a.send !== null && READS_FILE.test(p.text));
56739
+ if (!sender || !sender.a.send) return null;
56740
+ const tag = (h, f) => f !== null && h.file === void 0 ? { ...h, file: f } : h;
56741
+ return {
56742
+ verdict: { file: writer.file ?? sender.file, secret: tag(writer.a.secret, writer.file), send: tag(sender.a.send, sender.file) },
56743
+ senderFile: sender.file,
56744
+ senderText: sender.text
56745
+ };
56746
+ }
56747
+ function entryFiles(targets, fs) {
56748
+ const out = [];
56749
+ for (const rel of [...new Set(targets.files)]) {
56750
+ const c = scriptCandidates(rel).find((x) => fs.read(x) !== null);
56751
+ if (c !== void 0) out.push(c);
56752
+ }
56753
+ return out;
56754
+ }
55097
56755
  function lifecycleFindings(input) {
55098
56756
  const parsed = parsePackage(input.pkgText);
55099
56757
  if (!parsed.ok) {
@@ -55105,21 +56763,39 @@ function lifecycleFindings(input) {
55105
56763
  const names = (input.names ?? autoScriptNames(scripts)).filter((n) => Object.prototype.hasOwnProperty.call(scripts, n));
55106
56764
  const fs = { read: input.readLocal, ...input.list ? { list: input.list } : {} };
55107
56765
  const hits = [];
56766
+ const perScript = [];
55108
56767
  for (const name of names) {
55109
56768
  try {
55110
- const v = evaluateTargets(scriptTargets(name, scripts), fs, input.failClosed === true);
56769
+ const targets = scriptTargets(name, scripts);
56770
+ perScript.push({ name, targets });
56771
+ const v = evaluateTargets(targets, fs, input.failClosed === true);
55111
56772
  if (v) hits.push({ ...hitBase(input.pkgText, name, scripts), ...v });
55112
56773
  } catch {
55113
56774
  continue;
55114
56775
  }
55115
56776
  }
56777
+ if (hits.length === 0 && perScript.length > 1) {
56778
+ try {
56779
+ const files = [...new Set(perScript.flatMap((p) => entryFiles(p.targets, fs)))];
56780
+ const h = handOff(files, perScript.flatMap((p) => p.targets.inline), fs);
56781
+ if (h) {
56782
+ const owner = perScript.find((p) => h.senderFile !== null ? entryFiles(p.targets, fs).includes(h.senderFile) : p.targets.inline.includes(h.senderText)) ?? perScript[0];
56783
+ if (owner) hits.push({ ...hitBase(input.pkgText, owner.name, scripts), ...h.verdict });
56784
+ }
56785
+ } catch {
56786
+ }
56787
+ }
55116
56788
  return hits;
55117
56789
  }
55118
56790
  function describeHit(h) {
55119
56791
  if (h.kind === "unparseable") return "package.json is not valid JSON, so the scripts in it that run by themselves cannot be checked. Fix or remove the file before anything installs or runs here.";
55120
56792
  if (h.kind === "incomplete") return `The "${h.script}" script of package.json runs by itself, and what it runs could not be followed to the end (more local files than the limit, or a command that cannot be parsed). It is treated as unsafe until a person has read it.`;
55121
- const at = (s) => s.file === void 0 ? "" : ` in ${s.file}`;
55122
- const where = h.file === null ? `The script text itself reads ${h.secret.label} and sends data out (${h.send.label}).` : `It runs ${h.file}, which reads ${h.secret.label} (line ${h.secret.line}${at(h.secret)}) and sends data out through ${h.send.label} (line ${h.send.line}${at(h.send)}).`;
56793
+ const at2 = (s) => s.file === void 0 ? "" : ` in ${s.file}`;
56794
+ if (h.kind === "obfuscated") {
56795
+ const what = h.file === null ? "The script text itself" : `It runs ${h.file}, which (line ${h.secret.line}${at2(h.secret)})`;
56796
+ return `The "${h.script}" script of package.json runs by itself when a package manager installs or tests this project. ${what} decodes code hidden in an encoded string and runs it. Nothing an install needs is written that way.`;
56797
+ }
56798
+ const where = h.file === null ? `The script text itself reads ${h.secret.label} and sends data out (${h.send.label}).` : `It runs ${h.file}, which reads ${h.secret.label} (line ${h.secret.line}${at2(h.secret)}) and sends data out through ${h.send.label} (line ${h.send.line}${at2(h.send)}).`;
55123
56799
  return `The "${h.script}" script of package.json runs by itself when a package manager installs or tests this project. ${where}`;
55124
56800
  }
55125
56801
  function readLocalText(pkgDir, rel) {
@@ -55148,363 +56824,418 @@ function readLocalText(pkgDir, rel) {
55148
56824
  }
55149
56825
  }
55150
56826
 
55151
- // ../core/src/scanner/orchestrator.ts
55152
- import { dirname as dirname3 } from "node:path";
55153
- init_heuristic_engine();
55154
-
55155
- // ../core/src/capabilities.ts
55156
- import { readFile as readFile2 } from "node:fs/promises";
55157
- import { join as join9 } from "node:path";
55158
- var import_zod11 = __toESM(require_zod(), 1);
55159
- var CAPABILITIES = ["private-data", "untrusted-input", "exfiltration"];
55160
- var CAPABILITIES_FILE = "capabilities.yaml";
55161
- function compiles2(pattern) {
55162
- try {
55163
- new RegExp(pattern, "i");
55164
- return true;
55165
- } catch {
55166
- return false;
56827
+ // ../core/src/build-hooks.ts
56828
+ import { posix as posix3 } from "node:path";
56829
+ var lineOf2 = (text, index2) => {
56830
+ let n = 1;
56831
+ for (let i = 0; i < index2 && i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
56832
+ return n;
56833
+ };
56834
+ var cap2 = (s) => {
56835
+ const t2 = s.trim().replace(/\s+/g, " ");
56836
+ return t2.length > 120 ? `${t2.slice(0, 119)}\u2026` : t2;
56837
+ };
56838
+ var HIDDEN_RUN2 = { line: 1, label: "eval, exec or a shell, which runs the decoded code" };
56839
+ function shellVerdict(text) {
56840
+ const sh = shellExfil(text);
56841
+ if (sh) return sh;
56842
+ const ob = obfuscatedExec(text);
56843
+ return ob ? { secret: ob, send: { ...HIDDEN_RUN2, line: ob.line }, kind: "obfuscated" } : null;
56844
+ }
56845
+ var PY_CRED = /['"][^'"\n]*(?:\.ssh\/|\.aws\/|\.npmrc\b|\.pypirc\b|\.netrc\b|\.git-credentials\b|\.docker\/config\.json|\.kube\/config\b|\.config\/gcloud\/|\bid_(?:rsa|ed25519|ecdsa)\b|(?<![\w.])\.env(?![\w.-]))[^'"\n]*['"]/;
56846
+ var PY_CRED_PARTS = /['"](?:\.ssh|\.aws|\.docker|\.kube)['"]\s*,\s*['"](?:id_\w+|credentials|config(?:\.json)?)['"]/;
56847
+ var PY_READ = /\bopen\s*\(|\.read_(?:text|bytes)\s*\(|\bshutil\.copy|\bcat\b/;
56848
+ var PY_ENV_DUMP = /(?:json\.dumps|urlencode|\bstr|\brepr|pickle\.dumps|b64encode)\s*\(\s*(?:dict\s*\(\s*|\{\s*)?(?:\*\*)?os\.environ\b(?!\s*(?:\.get\b|\[))/;
56849
+ var PY_SEND = /\burlopen\s*\(|\burllib\.request\.Request\s*\(|\brequests\s*\.\s*(?:get|post|put|patch|request|Session)\b|\bhttpx\s*\.\s*(?:get|post|put|Client|AsyncClient)\b|\bhttp\.client\b|\bsocket\s*\.\s*(?:socket|create_connection)\b|\bsmtplib\b|\burllib3\b|\baiohttp\b|\bftplib\b/;
56850
+ function pythonVerdict(text) {
56851
+ const sh = shellVerdict(text);
56852
+ if (sh) return sh;
56853
+ const send = PY_SEND.exec(text);
56854
+ if (send) {
56855
+ const dump2 = PY_ENV_DUMP.exec(text);
56856
+ const cred = PY_READ.test(text) ? PY_CRED.exec(text) ?? PY_CRED_PARTS.exec(text) : null;
56857
+ const src = dump2 ?? cred;
56858
+ if (src) {
56859
+ return {
56860
+ secret: { line: lineOf2(text, src.index), label: dump2 ? "the whole of os.environ" : "a credentials file" },
56861
+ send: { line: lineOf2(text, send.index), label: "a python network call" }
56862
+ };
56863
+ }
55167
56864
  }
56865
+ return null;
55168
56866
  }
55169
- var Pattern = import_zod11.z.string().min(1).refine(compiles2, "not a valid regular expression");
55170
- var ToolSchema2 = import_zod11.z.object({ name: import_zod11.z.string(), description: import_zod11.z.string().optional() }).strict();
55171
- var ExampleSchema = import_zod11.z.object({
55172
- command: import_zod11.z.string().optional(),
55173
- args: import_zod11.z.array(import_zod11.z.string()).optional(),
55174
- url: import_zod11.z.string().optional(),
55175
- tools: import_zod11.z.array(ToolSchema2).optional(),
55176
- ability: import_zod11.z.string().optional(),
55177
- expect: import_zod11.z.boolean(),
55178
- note: import_zod11.z.string().optional()
55179
- }).strict();
55180
- var RuleSchema = import_zod11.z.object({
55181
- id: import_zod11.z.string().regex(/^CAP-\d{3}$/, "id must match CAP-NNN"),
55182
- capability: import_zod11.z.enum(["private-data", "untrusted-input", "exfiltration"]),
55183
- label: import_zod11.z.string().min(1),
55184
- match: import_zod11.z.object({
55185
- package: Pattern.optional(),
55186
- exclude: Pattern.optional(),
55187
- path_scope: import_zod11.z.literal("outside-project").optional(),
55188
- tool: Pattern.optional(),
55189
- description: Pattern.optional(),
55190
- ability: Pattern.optional()
55191
- }).strict().refine((m) => m.package || m.tool || m.description || m.ability, "match needs package, tool, description or ability"),
55192
- examples: import_zod11.z.array(ExampleSchema).min(1, "every rule needs at least one example").refine((ex) => ex.some((e) => e.expect), "every rule needs an example it matches (expect: true)")
55193
- }).strict();
55194
- var RuleFileSchema = import_zod11.z.object({
55195
- version: import_zod11.z.literal(1),
55196
- rules: import_zod11.z.array(RuleSchema).min(1)
55197
- }).strict().superRefine((f, ctx2) => {
56867
+ function pythonChain(entry, read) {
55198
56868
  const seen = /* @__PURE__ */ new Set();
55199
- for (const r of f.rules) {
55200
- if (seen.has(r.id)) ctx2.addIssue({ code: import_zod11.z.ZodIssueCode.custom, message: `duplicate rule id ${r.id}` });
55201
- seen.add(r.id);
55202
- }
55203
- });
55204
- var re = (p) => p === void 0 ? null : new RegExp(p, "i");
55205
- function parseCapabilityRules(data) {
55206
- const parsed = RuleFileSchema.safeParse(data);
55207
- if (!parsed.success) {
55208
- const i = parsed.error.issues[0];
55209
- return { ok: false, missing: false, error: `${CAPABILITIES_FILE} is invalid: ${i ? `${i.path.join(".")} ${i.message}` : "unknown problem"}` };
55210
- }
55211
- return {
55212
- ok: true,
55213
- rules: parsed.data.rules.map((r) => ({
55214
- id: r.id,
55215
- capability: r.capability,
55216
- label: r.label,
55217
- package: re(r.match.package),
55218
- exclude: re(r.match.exclude),
55219
- outsideOnly: r.match.path_scope === "outside-project",
55220
- tool: re(r.match.tool),
55221
- description: re(r.match.description),
55222
- ability: re(r.match.ability),
55223
- examples: r.examples
55224
- }))
55225
- };
55226
- }
55227
- async function loadCapabilityRules(definitionsDir) {
55228
- let raw;
55229
- try {
55230
- raw = await readFile2(join9(definitionsDir, CAPABILITIES_FILE), "utf8");
55231
- } catch {
55232
- return { ok: false, missing: true, error: `${CAPABILITIES_FILE} was not found in ${definitionsDir}` };
55233
- }
55234
- let data;
55235
- try {
55236
- data = yaml.load(raw);
55237
- } catch (err2) {
55238
- return { ok: false, missing: false, error: `${CAPABILITIES_FILE} is not valid YAML: ${String(err2).split("\n")[0]}` };
56869
+ const queue = [{ rel: entry, depth: 0 }];
56870
+ while (queue.length > 0 && seen.size < 40) {
56871
+ const item = queue.shift();
56872
+ if (seen.has(item.rel)) continue;
56873
+ seen.add(item.rel);
56874
+ const text = read(item.rel);
56875
+ if (text === null) continue;
56876
+ const v = pythonVerdict(text);
56877
+ if (v) return { file: item.rel, v };
56878
+ if (item.depth >= 2) continue;
56879
+ const dir = posix3.dirname(item.rel);
56880
+ for (const m of text.matchAll(/^\s*(?:from\s+(\.*[\w.]*)\s+import|import\s+([\w.]+))/gm)) {
56881
+ const name = (m[1] ?? m[2] ?? "").replace(/^\.+/, "");
56882
+ if (name === "") continue;
56883
+ const base = posix3.normalize(posix3.join(dir === "." ? "" : dir, name.split(".").join("/")));
56884
+ if (base.startsWith("..")) continue;
56885
+ for (const c of [`${base}.py`, `${base}/__init__.py`]) if (read(c) !== null) {
56886
+ queue.push({ rel: c, depth: item.depth + 1 });
56887
+ break;
56888
+ }
56889
+ }
55239
56890
  }
55240
- return parseCapabilityRules(data);
55241
- }
55242
- var PACKAGE_RUNNERS = /* @__PURE__ */ new Set(["npx", "bunx", "pnpx", "uvx"]);
55243
- var SCRIPT_RUNNERS = /* @__PURE__ */ new Set(["node", "nodejs", "python", "python3", "py", "bun", "deno", "tsx", "ts-node"]);
55244
- var CONTAINERS = /* @__PURE__ */ new Set(["docker", "podman"]);
55245
- var SHELLS2 = /* @__PURE__ */ new Set(["bash", "sh", "zsh", "cmd", "powershell", "pwsh"]);
55246
- var LAUNCHERS = /* @__PURE__ */ new Set([...PACKAGE_RUNNERS, ...SCRIPT_RUNNERS, ...CONTAINERS, ...SHELLS2, "npm", "pnpm", "yarn", "uv", "pipx", "env", "exorcist"]);
55247
- var DOCKER_VALUE_FLAGS = /* @__PURE__ */ new Set([
55248
- "-e",
55249
- "--env",
55250
- "--env-file",
55251
- "-v",
55252
- "--volume",
55253
- "--mount",
55254
- "--name",
55255
- "--network",
55256
- "--net",
55257
- "-p",
55258
- "--publish",
55259
- "-w",
55260
- "--workdir",
55261
- "-u",
55262
- "--user",
55263
- "--entrypoint",
55264
- "-l",
55265
- "--label",
55266
- "--add-host",
55267
- "--platform",
55268
- "--pull",
55269
- "--restart",
55270
- "-m",
55271
- "--memory",
55272
- "--cpus",
55273
- "-h",
55274
- "--hostname",
55275
- "--device",
55276
- "--cap-add",
55277
- "--cap-drop",
55278
- "--security-opt",
55279
- "--tmpfs",
55280
- "--ulimit",
55281
- "--log-driver",
55282
- "--log-opt",
55283
- "--dns",
55284
- "--runtime",
55285
- "--gpus"
55286
- ]);
55287
- var UV_VALUE_FLAGS = /* @__PURE__ */ new Set(["--directory", "--with", "--from", "--python", "-p", "--project", "--index", "--index-url"]);
55288
- function basenameOf(cmd) {
55289
- const b = cmd.replace(/\\/g, "/").split("/").pop() ?? cmd;
55290
- return b.toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/, "");
55291
- }
55292
- function stripVersion(spec2) {
55293
- let t2 = spec2.trim().toLowerCase().replace(/^(?:npm|jsr|pypi):/, "");
55294
- const at = t2.indexOf("@", t2.startsWith("@") ? 1 : 0);
55295
- if (at > 0) t2 = t2.slice(0, at);
55296
- t2 = t2.replace(/\[[^\]]*\]$/, "");
55297
- t2 = t2.replace(/(?:===?|>=|<=|~=|!=|>|<).*$/, "");
55298
- return t2;
56891
+ return null;
55299
56892
  }
55300
- function dockerImage(spec2) {
55301
- let t2 = spec2.trim().toLowerCase().replace(/@sha256:.*$/, "");
55302
- const slash = t2.lastIndexOf("/");
55303
- const colon = t2.lastIndexOf(":");
55304
- if (colon > slash) t2 = t2.slice(0, colon);
55305
- return t2;
56893
+ var PHP_ENV = /\bgetenv\s*\(\s*\)|\$_(?:ENV|SERVER)\b(?!\s*\[)|\$GLOBALS\b(?!\s*\[)/;
56894
+ var PHP_CRED = /['"][^'"\n]*(?:\.ssh\/|\.aws\/|\.npmrc\b|\.netrc\b|\.git-credentials\b|\bid_(?:rsa|ed25519)\b|(?<![\w.])\.env(?![\w.-])|auth\.json)[^'"\n]*['"]/;
56895
+ var PHP_SEND = /\b(?:file_get_contents|fopen|file|copy)\s*\(\s*['"]https?:|\bcurl_(?:exec|init)\s*\(|\bfsockopen\s*\(|\bstream_socket_client\s*\(|\bmail\s*\(|\bstream_context_create\s*\(/;
56896
+ function phpVerdict(text) {
56897
+ const send = PHP_SEND.exec(text);
56898
+ if (send) {
56899
+ const env = PHP_ENV.exec(text);
56900
+ const cred = /\b(?:file_get_contents|fopen|file|readfile)\s*\(/.test(text) ? PHP_CRED.exec(text) : null;
56901
+ const src = env ?? cred;
56902
+ if (src) return { secret: { line: lineOf2(text, src.index), label: env ? "the whole environment (getenv(), $_ENV or $_SERVER)" : "a credentials file" }, send: { line: lineOf2(text, send.index), label: "a PHP network call" } };
56903
+ }
56904
+ const ob = /\beval\s*\(\s*(?:base64_decode|gzinflate|gzuncompress|str_rot13|hex2bin)\s*\(/.exec(text);
56905
+ if (ob) return { secret: { line: lineOf2(text, ob.index), label: "code hidden in an encoded string that is decoded and run" }, send: HIDDEN_RUN2, kind: "obfuscated" };
56906
+ return null;
55306
56907
  }
55307
- function unwrapLaunch(command, args, depth = 0) {
55308
- const s = args.indexOf("shield");
55309
- if (s !== -1 && args[s + 1] === "--server") {
55310
- const dd = args.indexOf("--", s);
55311
- if (dd !== -1 && args[dd + 1] !== void 0) return unwrapLaunch(args[dd + 1], args.slice(dd + 2), depth + 1);
55312
- const u = args.indexOf("--url", s);
55313
- if (u !== -1 && args[u + 1] !== void 0) return { command: "", args: [], url: args[u + 1] };
56908
+ var RUST_SEND = /\bTcpStream\s*::\s*connect|\bUdpSocket\s*::|\breqwest\s*::|\bureq\s*::|\battohttpc\s*::|\bisahc\s*::|\bminreq\s*::/;
56909
+ var RUST_READ = /\bfs\s*::\s*(?:read|read_to_string|copy)\b|\bFile\s*::\s*open\b/;
56910
+ function rustStatements(text) {
56911
+ const code = text.replace(/"(?:[^"\\]|\\.)*"|\/\/[^\n]*/g, (m) => m.startsWith('"') ? m : " ".repeat(m.length));
56912
+ const out = [];
56913
+ let start = 0;
56914
+ const strRe = /r(#*)"([\s\S]*?)"\1|"((?:[^"\\]|\\.)*)"/g;
56915
+ for (const stmt of code.split(";")) {
56916
+ const parts = [];
56917
+ for (const m of stmt.matchAll(strRe)) parts.push((m[2] ?? m[3] ?? "").replace(/\\n/g, "\n").replace(/\\"/g, '"'));
56918
+ if (parts.length > 0) out.push({ at: start, joined: parts.join(" ") });
56919
+ start += stmt.length + 1;
55314
56920
  }
55315
- const base = basenameOf(command);
55316
- if (depth < 3 && SHELLS2.has(base)) {
55317
- const c = args.findIndex((a) => /^(?:-c|\/c|-command)$/i.test(a));
55318
- const inner = c === -1 ? void 0 : args[c + 1];
55319
- if (inner !== void 0) {
55320
- const parts = inner.trim().split(/\s+/).filter(Boolean).map((p) => p.replace(/^["']|["']$/g, ""));
55321
- if (parts[0] !== void 0) return unwrapLaunch(parts[0], parts.slice(1), depth + 1);
56921
+ return out;
56922
+ }
56923
+ function rustVerdict(text) {
56924
+ for (const s of rustStatements(text)) {
56925
+ const v = shellVerdict(s.joined);
56926
+ if (v) {
56927
+ const line = lineOf2(text, s.at + (text.slice(s.at).search(/\S/) || 0));
56928
+ return { ...v, secret: { ...v.secret, line }, send: { ...v.send, line } };
55322
56929
  }
55323
56930
  }
55324
- if (depth < 3 && base === "env") {
55325
- const i = args.findIndex((a) => !a.includes("=") && !a.startsWith("-"));
55326
- if (i !== -1) return unwrapLaunch(args[i], args.slice(i + 1), depth + 1);
55327
- }
55328
- return { command, args, url: null };
56931
+ const send = RUST_SEND.exec(text);
56932
+ const cred = RUST_READ.test(text) ? PY_CRED.exec(text) ?? /"(?:\.ssh|\.aws)"/.exec(text) : null;
56933
+ if (send && cred) return { secret: { line: lineOf2(text, cred.index), label: "a credentials file" }, send: { line: lineOf2(text, send.index), label: "a network connection" } };
56934
+ return null;
55329
56935
  }
55330
- function firstPositional(args, valueFlags) {
55331
- for (let i = 0; i < args.length; i++) {
55332
- const a = args[i];
55333
- if (a === "--") continue;
55334
- if (a.startsWith("-")) {
55335
- if (!a.includes("=") && valueFlags.has(a)) i++;
56936
+ var MAKE_ROOTS = /* @__PURE__ */ new Set(["all", "install", "build", "default", "setup", "compile", "configure", "bootstrap"]);
56937
+ function makefileHits(text) {
56938
+ const raw = text.split(/\r?\n/);
56939
+ const rules = /* @__PURE__ */ new Map();
56940
+ const outside = [];
56941
+ let current = [];
56942
+ let first = null;
56943
+ let defaultGoal = null;
56944
+ for (let i = 0; i < raw.length; i++) {
56945
+ let l = raw[i] ?? "";
56946
+ const startLine = i + 1;
56947
+ while (l.endsWith("\\") && i + 1 < raw.length) {
56948
+ l = `${l.slice(0, -1)} ${(raw[++i] ?? "").trim()}`;
56949
+ }
56950
+ if (l.startsWith(" ")) {
56951
+ const cmd = l.slice(1).replace(/^[@+-]+/, "");
56952
+ for (const t2 of current) rules.get(t2)?.recipe.push({ line: startLine, text: cmd });
55336
56953
  continue;
55337
56954
  }
55338
- return i;
55339
- }
55340
- return -1;
55341
- }
55342
- function packageNames(l) {
55343
- const base = basenameOf(l.command);
55344
- const a = l.args;
55345
- const names = [];
55346
- let at = -1;
55347
- const pkgAt = (offset) => {
55348
- const rest = a.slice(offset).filter((x) => x !== "--");
55349
- const p = packageArg(rest);
55350
- if (p !== null) {
55351
- names.push(stripVersion(p));
55352
- at = a.indexOf(p, offset);
56955
+ if (/^\s*(?:#|$)/.test(l)) continue;
56956
+ const goal = /^\.DEFAULT_GOAL\s*:?=\s*(\S+)/.exec(l);
56957
+ if (goal) {
56958
+ defaultGoal = goal[1] ?? null;
56959
+ continue;
55353
56960
  }
55354
- };
55355
- if (PACKAGE_RUNNERS.has(base)) pkgAt(0);
55356
- else if ((base === "pnpm" || base === "yarn") && a[0] === "dlx") pkgAt(1);
55357
- else if (base === "npm" && (a[0] === "exec" || a[0] === "x")) pkgAt(1);
55358
- else if (base === "pipx" && a[0] === "run") pkgAt(1);
55359
- else if (base === "uv") {
55360
- for (let i = 0; i < a.length; i++) if ((a[i] === "--with" || a[i] === "--from" || a[i] === "--directory") && a[i + 1]) names.push(a[i + 1].toLowerCase());
55361
- const run = a.findIndex((x) => x === "run");
55362
- if (run !== -1) {
55363
- const rest = a.slice(run + 1);
55364
- const j = firstPositional(rest, UV_VALUE_FLAGS);
55365
- if (j !== -1) {
55366
- names.push(stripVersion(rest[j]));
55367
- at = run + 1 + j;
56961
+ const rule = /^([^\s:=#][^:=#]*?)\s*::?(?!=)\s*([^;#=]*)(?:;(.*))?$/.exec(l);
56962
+ if (rule && !/^\s*(?:export|override|define|ifn?eq|ifn?def|else|endif|include|-include|vpath)\b/.test(l)) {
56963
+ current = (rule[1] ?? "").trim().split(/\s+/).filter(Boolean);
56964
+ const prereqs = (rule[2] ?? "").trim().split(/\s+/).filter((p) => p !== "" && !p.startsWith("|"));
56965
+ for (const t2 of current) {
56966
+ if (!rules.has(t2)) rules.set(t2, { prereqs: [], recipe: [] });
56967
+ const r = rules.get(t2);
56968
+ r.prereqs.push(...prereqs);
56969
+ if (rule[3] !== void 0 && rule[3].trim() !== "") r.recipe.push({ line: startLine, text: rule[3] });
56970
+ if (first === null && !t2.startsWith(".") && !t2.includes("%")) first = t2;
55368
56971
  }
56972
+ continue;
55369
56973
  }
55370
- } else if (CONTAINERS.has(base)) {
55371
- const run = a.findIndex((x) => x === "run");
55372
- if (run !== -1) {
55373
- const rest = a.slice(run + 1);
55374
- const j = firstPositional(rest, DOCKER_VALUE_FLAGS);
55375
- if (j !== -1) {
55376
- names.push(dockerImage(rest[j]));
55377
- at = run + 1 + j;
56974
+ current = [];
56975
+ if (l.includes("$(shell") || l.includes("${shell")) outside.push({ line: startLine, text: l });
56976
+ }
56977
+ const roots = [...rules.keys()].filter((t2) => MAKE_ROOTS.has(t2));
56978
+ if (first) roots.push(first);
56979
+ if (defaultGoal) roots.push(defaultGoal);
56980
+ const reach = /* @__PURE__ */ new Set();
56981
+ const queue = [...roots];
56982
+ while (queue.length > 0 && reach.size < 200) {
56983
+ const t2 = queue.shift();
56984
+ if (reach.has(t2)) continue;
56985
+ reach.add(t2);
56986
+ for (const p of rules.get(t2)?.prereqs ?? []) queue.push(p);
56987
+ }
56988
+ const hits = [];
56989
+ for (const o of outside) {
56990
+ const v = shellVerdict(o.text);
56991
+ if (v) hits.push({ line: o.line, target: "$(shell ...)", v, cmd: o.text });
56992
+ }
56993
+ for (const t2 of reach) {
56994
+ for (const r of rules.get(t2)?.recipe ?? []) {
56995
+ const v = shellVerdict(r.text);
56996
+ if (v) {
56997
+ hits.push({ line: r.line, target: t2, v, cmd: r.text });
56998
+ break;
55378
56999
  }
55379
57000
  }
55380
- } else if (SCRIPT_RUNNERS.has(base)) {
55381
- const m = a.indexOf("-m");
55382
- if (m !== -1 && a[m + 1]) {
55383
- names.push(a[m + 1].toLowerCase());
55384
- at = m + 1;
55385
- } else {
55386
- const j = firstPositional(a.filter((x) => x !== "run"), /* @__PURE__ */ new Set(["--allow-read", "--config"]));
55387
- const script = j === -1 ? void 0 : a.filter((x) => x !== "run")[j];
55388
- if (script !== void 0) {
55389
- names.push(stripVersion(script.replace(/\\/g, "/")));
55390
- at = a.indexOf(script);
57001
+ }
57002
+ return hits;
57003
+ }
57004
+ function dockerfileHits(text) {
57005
+ const raw = text.split(/\r?\n/);
57006
+ const hits = [];
57007
+ for (let i = 0; i < raw.length; i++) {
57008
+ const startLine = i + 1;
57009
+ let l = raw[i] ?? "";
57010
+ while (/\\\s*$/.test(l) && i + 1 < raw.length) {
57011
+ l = `${l.replace(/\\\s*$/, "")} ${(raw[++i] ?? "").replace(/^\s*#.*$/, "").trim()}`;
57012
+ }
57013
+ const m = /^\s*(?:ONBUILD\s+)?RUN\b\s*(.*)$/i.exec(l);
57014
+ if (!m) continue;
57015
+ let cmd = (m[1] ?? "").replace(/^(?:--\S+\s+)+/, "");
57016
+ if (cmd.startsWith("[")) {
57017
+ try {
57018
+ const arr = JSON.parse(cmd);
57019
+ if (Array.isArray(arr)) cmd = arr.filter((x) => typeof x === "string").join(" ");
57020
+ } catch {
55391
57021
  }
55392
57022
  }
57023
+ const v = shellVerdict(cmd);
57024
+ if (v) hits.push({ line: startLine, v, cmd });
55393
57025
  }
55394
- if (!LAUNCHERS.has(base) && base !== "") names.push(base);
55395
- return { names, at };
57026
+ return hits;
55396
57027
  }
55397
- function serverIdentities(server2) {
55398
- if (server2.ability !== void 0) return [];
55399
- const out = [];
55400
- const l = unwrapLaunch(server2.command ?? "", server2.args ?? []);
55401
- const url = l.url ?? server2.url;
55402
- if (url) {
55403
- try {
55404
- const u = new URL(url);
55405
- out.push(`${u.hostname}${u.pathname}`.toLowerCase());
55406
- } catch {
55407
- out.push(url.toLowerCase());
57028
+ function gypHits(text) {
57029
+ const hits = [];
57030
+ const str3 = /'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"/g;
57031
+ for (const a of text.matchAll(/['"]action['"]\s*:\s*\[([\s\S]*?)\]/g)) {
57032
+ const joined = [...(a[1] ?? "").matchAll(str3)].map((m) => m[1] ?? m[2] ?? "").join(" ");
57033
+ const v = shellVerdict(joined);
57034
+ if (v) hits.push({ line: lineOf2(text, a.index ?? 0), v, cmd: joined });
57035
+ }
57036
+ if (hits.length > 0) return hits;
57037
+ for (const m of text.matchAll(str3)) {
57038
+ const s = m[1] ?? m[2] ?? "";
57039
+ if (!/<!@?\(|\b(?:curl|wget|base64|env|printenv)\b/.test(s)) continue;
57040
+ const v = shellVerdict(s.replace(/^<!@?\(|\)$/g, ""));
57041
+ if (v) {
57042
+ hits.push({ line: lineOf2(text, m.index ?? 0), v, cmd: s });
57043
+ break;
55408
57044
  }
55409
57045
  }
55410
- if (l.command) out.push(...packageNames(l).names);
55411
- return [...new Set(out.filter((n) => n.length > 0))];
57046
+ return hits;
55412
57047
  }
55413
- var CREDENTIALS = /^(?:\.ssh|\.aws|\.gnupg|\.gpg|\.kube|\.docker|\.azure|\.gcloud|\.password-store|\.netrc|\.npmrc|\.pypirc|\.git-credentials|keychains?)$/i;
55414
- var PERSONAL = /^(?:\.config|\.local|library|documents|desktop|downloads|pictures|mail|appdata|onedrive|dropbox|icloud drive)$/i;
55415
- var SYSTEM = /^(?:etc|var|private|proc|sys|boot|root|srv)$/i;
55416
- var HOME = /^(?:~|\$home|\$\{home\}|%userprofile%|%homepath%)$/i;
55417
- var PROJECT = /^(?:\$\{(?:workspacefolder|workspaceroot|pwd|projectroot|project_dir|cwd)\}|\$pwd|%cd%)$/i;
55418
- var homeOrPersonal = (rest) => rest.length === 0 || PERSONAL.test(rest[0]);
55419
- function isOutsideProject(raw) {
55420
- let p = raw.trim().replace(/^["']|["']$/g, "").replace(/\\/g, "/");
55421
- const absolute = p.startsWith("/");
55422
- p = p.replace(/(?:\/\*\*?)+$/, "");
55423
- if (p === "" && absolute) return true;
55424
- if (p === "" || p === "**" || p === "*") return false;
55425
- const segs = p.split("/").filter((x) => x !== "");
55426
- if (segs.some((x) => CREDENTIALS.test(x))) return true;
55427
- const first = segs[0] ?? "";
55428
- if (/^[a-z]:$/i.test(first)) {
55429
- if ((segs[1] ?? "").toLowerCase() === "users") return segs.length <= 3 || PERSONAL.test(segs[3]);
55430
- return segs.length === 1;
57048
+ var COMPOSER_EVENTS = /* @__PURE__ */ new Set([
57049
+ "pre-install-cmd",
57050
+ "post-install-cmd",
57051
+ "pre-update-cmd",
57052
+ "post-update-cmd",
57053
+ "pre-autoload-dump",
57054
+ "post-autoload-dump",
57055
+ "post-root-package-install",
57056
+ "post-create-project-cmd",
57057
+ "pre-package-install",
57058
+ "post-package-install",
57059
+ "pre-package-update",
57060
+ "post-package-update",
57061
+ "pre-archive-cmd",
57062
+ "post-archive-cmd"
57063
+ ]);
57064
+ function composerCommands(scripts, name, depth, seen) {
57065
+ if (seen.has(name) || depth > 3) return [];
57066
+ seen.add(name);
57067
+ const v = scripts[name];
57068
+ const list = typeof v === "string" ? [v] : Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
57069
+ const out = [];
57070
+ for (const c of list) {
57071
+ const ref = /^@([\w:.-]+)$/.exec(c.trim());
57072
+ if (ref && ref[1] !== void 0 && !/^(?:php|composer|putenv)$/.test(ref[1]) && Object.prototype.hasOwnProperty.call(scripts, ref[1])) out.push(...composerCommands(scripts, ref[1], depth + 1, seen));
57073
+ else out.push(c);
55431
57074
  }
55432
- if (p.startsWith("/")) {
55433
- if (segs.length === 0) return true;
55434
- const top = first.toLowerCase();
55435
- if (top === "home" || top === "users") return segs.length <= 2 || PERSONAL.test(segs[2]);
55436
- if (top === "volumes" || top === "mnt" || top === "media") return segs.length <= 2;
55437
- return SYSTEM.test(top);
57075
+ return out;
57076
+ }
57077
+ function composerHits(text, read) {
57078
+ let json2;
57079
+ try {
57080
+ json2 = parseJsonLoose(text);
57081
+ } catch {
57082
+ return [];
55438
57083
  }
55439
- if (HOME.test(first)) return homeOrPersonal(segs.slice(1));
55440
- let depth = 0;
55441
- for (const x of PROJECT.test(first) ? segs.slice(1) : segs) {
55442
- if (x === "..") depth--;
55443
- else if (x !== ".") depth++;
55444
- if (depth < 0) return true;
57084
+ if (typeof json2 !== "object" || json2 === null) return [];
57085
+ const scripts = json2["scripts"];
57086
+ if (typeof scripts !== "object" || scripts === null || Array.isArray(scripts)) return [];
57087
+ const s = scripts;
57088
+ const hits = [];
57089
+ for (const event of Object.keys(s).filter((k) => COMPOSER_EVENTS.has(k))) {
57090
+ for (const cmd of composerCommands(s, event, 0, /* @__PURE__ */ new Set())) {
57091
+ const plain2 = cmd.replace(/^@php\b/, "php").replace(/^@putenv\b.*$/, "");
57092
+ const inline = /\bphp\s+(?:-\w+\s+)*-r\s+(['"])([\s\S]*)\1/.exec(plain2);
57093
+ const v = shellVerdict(plain2) ?? phpVerdict(inline ? inline[2] ?? "" : plain2);
57094
+ if (v) {
57095
+ hits.push({ event, cmd, file: null, v });
57096
+ break;
57097
+ }
57098
+ const script = /^(?:php|sh|bash)\s+(?:-\w+\s+)*([\w./-]+\.(?:php|sh))\b/.exec(plain2);
57099
+ if (script && script[1] !== void 0 && !script[1].startsWith("/") && !script[1].includes("..")) {
57100
+ const body = read(script[1].replace(/^\.\//, ""));
57101
+ const fv = body === null ? null : script[1].endsWith(".php") ? phpVerdict(body) ?? shellVerdict(body) : shellVerdict(body);
57102
+ if (fv) {
57103
+ hits.push({ event, cmd, file: script[1].replace(/^\.\//, ""), v: fv });
57104
+ break;
57105
+ }
57106
+ }
57107
+ }
55445
57108
  }
55446
- return false;
57109
+ return hits;
55447
57110
  }
55448
- function pathArguments(server2) {
55449
- const l = unwrapLaunch(server2.command ?? "", server2.args ?? []);
55450
- const { at } = packageNames(l);
57111
+ function pyprojectEntries(text) {
55451
57112
  const out = [];
55452
- l.args.forEach((a, i) => {
55453
- if (i === at) return;
55454
- let v = a;
55455
- const eq = /^--?[A-Za-z][\w-]*=(.*)$/.exec(a);
55456
- if (eq) v = eq[1] ?? "";
55457
- const src = /(?:^|,)(?:src|source)=([^,]+)/.exec(v);
55458
- if (src) v = src[1] ?? "";
55459
- else {
55460
- const bind = /^([~/][^:]*):\/.*/.exec(v);
55461
- if (bind) v = bind[1] ?? "";
55462
- }
55463
- if (v.startsWith("-") || v.includes("://")) return;
55464
- if (/^(?:[/~.]|\$|%|[A-Za-z]:[\\/]?$|[A-Za-z]:[\\/])/.test(v)) out.push(v);
55465
- });
57113
+ const backend = /^\s*build-backend\s*=\s*["']([\w.:]+)["']/m.exec(text);
57114
+ const paths = /^\s*backend-path\s*=\s*\[([^\]]*)\]/m.exec(text);
57115
+ if (backend && paths) {
57116
+ const mod = (backend[1] ?? "").split(":")[0] ?? "";
57117
+ for (const p of (paths[1] ?? "").matchAll(/["']([^"']+)["']/g)) {
57118
+ const dir = (p[1] ?? "").replace(/^\.\/?/, "").replace(/\/$/, "");
57119
+ if (dir.startsWith("/") || dir.includes("..")) continue;
57120
+ const base = posix3.join(dir === "" ? "." : dir, mod.split(".").join("/"));
57121
+ out.push({ file: `${base}.py`, index: backend.index, hook: "build-backend" }, { file: `${base}/__init__.py`, index: backend.index, hook: "build-backend" });
57122
+ }
57123
+ }
57124
+ for (const h of text.matchAll(/^\s*\[tool\.hatch\.(?:build(?:\.targets\.\w+)?|metadata)\.hooks\.custom\]\s*$/gm)) {
57125
+ const after = text.slice((h.index ?? 0) + h[0].length);
57126
+ const section = after.split(/^\s*\[/m)[0] ?? "";
57127
+ const path = /^\s*path\s*=\s*["']([^"']+)["']/m.exec(section);
57128
+ const file = path ? path[1] ?? "" : "hatch_build.py";
57129
+ if (!file.startsWith("/") && !file.includes("..")) out.push({ file: file.replace(/^\.\//, ""), index: h.index ?? 0, hook: "hatch build hook" });
57130
+ }
55466
57131
  return out;
55467
57132
  }
55468
- function claudePath(p) {
55469
- if (p.startsWith("//")) return p.slice(1);
55470
- if (p.startsWith("/")) return `.${p}`;
55471
- return p;
57133
+ var DOCKERFILE = /(?:^|\/)(?:Dockerfile|Containerfile)(?:\.(?!(?:[\w.-]*\.)?(?:md|markdown|txt|rst|html?|json|ya?ml)$)[\w.-]+)?$|\.(?:dockerfile|containerfile)$/i;
57134
+ var MAKEFILE = /(?:^|\/)(?:GNUmakefile|[Mm]akefile)$/;
57135
+ function isBuildHookFile(rel) {
57136
+ const base = rel.replace(/\\/g, "/").split("/").pop() ?? "";
57137
+ return base === "setup.py" || base === "pyproject.toml" || base === "binding.gyp" || base === "build.rs" || base === "Cargo.toml" || base === "composer.json" || MAKEFILE.test(rel) || DOCKERFILE.test(rel);
55472
57138
  }
55473
- function ruleEvidence(rule, server2) {
55474
- if (server2.ability !== void 0) {
55475
- if (!rule.ability) return null;
55476
- const m = rule.ability.exec(server2.ability);
55477
- if (!m) return null;
55478
- if (rule.outsideOnly && !isOutsideProject(claudePath(m[1] ?? ""))) return null;
55479
- return server2.ability;
55480
- }
55481
- if (rule.package) {
55482
- for (const id of serverIdentities(server2)) {
55483
- if (!rule.package.test(id) || rule.exclude && rule.exclude.test(id)) continue;
55484
- if (rule.outsideOnly) {
55485
- const outside = pathArguments(server2).find(isOutsideProject);
55486
- if (outside !== void 0) return `${id} ${outside}`;
55487
- continue;
55488
- }
55489
- return id;
57139
+ var colOf = (text, line) => {
57140
+ const l = text.split("\n")[line - 1] ?? "";
57141
+ return l.search(/\S/) + 1 || 1;
57142
+ };
57143
+ var lineText = (text, line) => text.split(/\r?\n/)[line - 1] ?? "";
57144
+ function buildHookFindings(rel, text, read) {
57145
+ try {
57146
+ const base = rel.replace(/\\/g, "/").split("/").pop() ?? "";
57147
+ const out = [];
57148
+ const at2 = (hook, line, v, file, span) => {
57149
+ out.push({ hook, line, col: colOf(text, line), span: cap2(span ?? lineText(text, line)), file, secret: v.secret, send: v.send, ...v.kind ? { kind: v.kind } : {} });
57150
+ };
57151
+ if (base === "setup.py") {
57152
+ const own = pythonVerdict(text);
57153
+ if (own) {
57154
+ at2("setup.py", own.send.line, own, null);
57155
+ return out;
57156
+ }
57157
+ const chained = pythonChain("setup.py", (r) => r === "setup.py" ? text : read(r));
57158
+ if (chained && chained.file !== "setup.py") {
57159
+ const imp = new RegExp(`^\\s*(?:from|import)\\s+\\.?${posix3.basename(chained.file).replace(/\.py$|__init__\.py$/, "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&") || "\\w+"}`, "m").exec(text);
57160
+ at2("setup.py", imp ? lineOf2(text, imp.index) : 1, chained.v, chained.file);
57161
+ }
57162
+ return out;
57163
+ }
57164
+ if (base === "pyproject.toml") {
57165
+ const seen = /* @__PURE__ */ new Set();
57166
+ for (const e of pyprojectEntries(text)) {
57167
+ if (seen.has(e.hook)) continue;
57168
+ if (read(e.file) === null) continue;
57169
+ const c = pythonChain(e.file, read);
57170
+ if (c) {
57171
+ seen.add(e.hook);
57172
+ at2(e.hook, lineOf2(text, e.index), c.v, c.file);
57173
+ }
57174
+ }
57175
+ return out;
57176
+ }
57177
+ if (MAKEFILE.test(rel)) {
57178
+ for (const h of makefileHits(text)) at2(h.target === "$(shell ...)" ? "$(shell ...)" : `${h.target} target`, h.line, h.v, null, h.cmd);
57179
+ return out;
57180
+ }
57181
+ if (DOCKERFILE.test(rel)) {
57182
+ for (const h of dockerfileHits(text)) at2("RUN", h.line, h.v, null);
57183
+ return out;
57184
+ }
57185
+ if (base === "binding.gyp") {
57186
+ for (const h of gypHits(text)) at2("action", h.line, h.v, null);
57187
+ return out;
57188
+ }
57189
+ if (base === "build.rs") {
57190
+ const v = rustVerdict(text);
57191
+ if (v) at2("build.rs", v.send.line, v, null);
57192
+ return out;
57193
+ }
57194
+ if (base === "Cargo.toml") {
57195
+ const b = /^\s*build\s*=\s*["']([^"']+)["']/m.exec(text);
57196
+ const file = b?.[1];
57197
+ if (file && file !== "build.rs" && !file.startsWith("/") && !file.includes("..")) {
57198
+ const body = read(file.replace(/^\.\//, ""));
57199
+ const v = body === null ? null : rustVerdict(body);
57200
+ if (v && b) at2("build script", lineOf2(text, b.index), v, file.replace(/^\.\//, ""));
57201
+ }
57202
+ return out;
57203
+ }
57204
+ if (base === "composer.json") {
57205
+ for (const h of composerHits(text, read)) {
57206
+ const idx = text.indexOf(JSON.stringify(h.cmd).slice(1, -1));
57207
+ const evIdx = text.indexOf(`"${h.event}"`);
57208
+ at2(h.event, lineOf2(text, idx >= 0 ? idx : Math.max(0, evIdx)), h.v, h.file, h.cmd);
57209
+ }
57210
+ return out;
55490
57211
  }
57212
+ return out;
57213
+ } catch {
57214
+ return [];
55491
57215
  }
55492
- for (const t2 of server2.tools ?? []) {
55493
- if (rule.tool && rule.tool.test(t2.name)) return `tool ${t2.name}`;
55494
- if (rule.description && t2.description && rule.description.test(t2.description)) return `tool ${t2.name} (description)`;
55495
- }
55496
- return null;
55497
57216
  }
55498
- function classifyCapabilities(server2, rules) {
55499
- const reasons = [];
55500
- for (const rule of rules) {
55501
- const evidence = ruleEvidence(rule, server2);
55502
- if (evidence !== null) reasons.push({ capability: rule.capability, ruleId: rule.id, label: rule.label, evidence: evidence.slice(0, 120) });
55503
- }
55504
- const has = new Set(reasons.map((r) => r.capability));
55505
- return { capabilities: CAPABILITIES.filter((c) => has.has(c)), reasons };
57217
+ function describeBuildHit(h, rel) {
57218
+ const base = rel.split("/").pop() ?? rel;
57219
+ const when = {
57220
+ "setup.py": "setup.py runs when pip installs or builds this project from source.",
57221
+ "build-backend": "pyproject.toml names an in-tree build backend, which pip runs to build or install this project.",
57222
+ "hatch build hook": "pyproject.toml names a Hatch build hook, which runs when this project is built or installed.",
57223
+ RUN: "This RUN step runs every time the image is built.",
57224
+ action: "This node-gyp action runs when npm installs the native module.",
57225
+ "build.rs": "build.rs runs every time Cargo builds this crate (cargo build, cargo test, rust-analyzer).",
57226
+ "build script": "Cargo.toml names a build script, which runs every time Cargo builds this crate.",
57227
+ "$(shell ...)": `${base} runs this $(shell ...) every time make reads the file.`
57228
+ };
57229
+ const intro = when[h.hook] ?? (h.hook.endsWith(" target") ? `The "${h.hook.replace(/ target$/, "")}" target of ${base} runs on make, make install or make build.` : `The composer "${h.hook}" script runs by itself when composer installs or updates this project.`);
57230
+ const inFile = h.file === null ? "" : ` in ${h.file}`;
57231
+ if (h.kind === "obfuscated") return `${intro} Its code${inFile} (line ${h.secret.line}) decodes code hidden in an encoded string and runs it. Nothing a build needs is written that way.`;
57232
+ return `${intro} Its code${inFile} reads ${h.secret.label} (line ${h.secret.line}) and sends it out through ${h.send.label} (line ${h.send.line}).`;
55506
57233
  }
55507
57234
 
57235
+ // ../core/src/scanner/orchestrator.ts
57236
+ import { dirname as dirname3 } from "node:path";
57237
+ init_heuristic_engine();
57238
+
55508
57239
  // ../core/src/trifecta.ts
55509
57240
  var import_zod12 = __toESM(require_zod(), 1);
55510
57241
  import { constants as constants2 } from "node:fs";
@@ -55574,12 +57305,12 @@ function position(text, offset) {
55574
57305
  function anchorFor(text, keys) {
55575
57306
  for (const k of keys) {
55576
57307
  const span = JSON.stringify(k);
55577
- const at2 = text.indexOf(span);
55578
- if (at2 !== -1) return { ...position(text, at2), span };
57308
+ const at3 = text.indexOf(span);
57309
+ if (at3 !== -1) return { ...position(text, at3), span };
55579
57310
  }
55580
57311
  const firstLine = text.split("\n").find((l) => l.trim() !== "") ?? "";
55581
- const at = text.indexOf(firstLine.trim());
55582
- return { ...position(text, Math.max(0, at)), span: firstLine.trim().slice(0, 120) || "(empty file)" };
57312
+ const at2 = text.indexOf(firstLine.trim());
57313
+ return { ...position(text, Math.max(0, at2)), span: firstLine.trim().slice(0, 120) || "(empty file)" };
55583
57314
  }
55584
57315
  function serverEntries(servers) {
55585
57316
  const out = [];
@@ -55744,11 +57475,11 @@ async function readHeadTail(path, size) {
55744
57475
  if (tail.length > 0) await fh.read(tail, 0, tail.length, tailStart);
55745
57476
  let newlines = 0;
55746
57477
  const chunk = Buffer.alloc(1 << 20);
55747
- for (let at = hb; at < tailStart; ) {
55748
- const { bytesRead } = await fh.read(chunk, 0, Math.min(chunk.length, tailStart - at), at);
57478
+ for (let at2 = hb; at2 < tailStart; ) {
57479
+ const { bytesRead } = await fh.read(chunk, 0, Math.min(chunk.length, tailStart - at2), at2);
55749
57480
  if (bytesRead === 0) break;
55750
57481
  for (let i = 0; i < bytesRead; i++) if (chunk[i] === 10) newlines++;
55751
- at += bytesRead;
57482
+ at2 += bytesRead;
55752
57483
  }
55753
57484
  return Buffer.concat([head.subarray(0, hb), Buffer.from("\n".repeat(newlines)), tail]);
55754
57485
  } finally {
@@ -55871,6 +57602,21 @@ function lifecycleScanFindings(text, absPath, rel, def) {
55871
57602
  fix: `${describeHit(h)} ${def.fix}`
55872
57603
  }));
55873
57604
  }
57605
+ function buildHookScanFindings(text, absPath, rel, def) {
57606
+ const dir = dirname3(absPath);
57607
+ return buildHookFindings(rel, text, (r) => readLocalText(dir, r)).map((h) => ({
57608
+ source: "signature",
57609
+ ruleId: def.id,
57610
+ title: def.title,
57611
+ severity: def.severity,
57612
+ file: rel,
57613
+ line: h.line,
57614
+ col: h.col,
57615
+ span: h.span,
57616
+ owasp: def.owasp,
57617
+ fix: `${describeBuildHit(h, rel)} ${def.fix}`
57618
+ }));
57619
+ }
55874
57620
  async function* scanRepo(root, options) {
55875
57621
  const defs = await loadDefinitions(options.definitionsDir);
55876
57622
  const canaries = loadCanariesFile(canariesPath(root));
@@ -55890,6 +57636,7 @@ async function* scanRepo(root, options) {
55890
57636
  const ex036 = defs.find((d) => d.id === "EX-036" && d.enabled !== false && d.match.analysis === "lifecycle-scripts");
55891
57637
  const settingsDefs = defs.filter((d) => d.enabled !== false && d.match.analysis === "project-settings");
55892
57638
  const textDefs = defs.filter((d) => d.enabled !== false && d.applies_to.includes("instruction") && !d.applies_to.includes("hook") && !d.match.analysis);
57639
+ const imageTextDefs = defs.filter((d) => d.enabled !== false && d.applies_to.includes("instruction") && !d.match.analysis);
55893
57640
  const own = (id) => defs.find((d) => d.id === id);
55894
57641
  const notes = [];
55895
57642
  const raise = (id, file, span, severity, line = 1, col = 1, fixPrefix = "") => {
@@ -55962,7 +57709,7 @@ async function* scanRepo(root, options) {
55962
57709
  const sigs2 = [];
55963
57710
  if (carried !== "") {
55964
57711
  const sub = { path: file.path, rel: file.rel, role: "instruction", sizeBytes: carried.length };
55965
- for (const f of runSignatures(sub, normalize(carried, "instruction"), textDefs)) sigs2.push({ ...f, line: 1, col: 1 });
57712
+ for (const f of runSignatures(sub, normalize(carried, "instruction"), imageTextDefs)) sigs2.push({ ...f, line: 1, col: 1 });
55966
57713
  }
55967
57714
  if (AGENT_IMAGE_PATH.test(file.rel) && (kind !== "svg" && (kind !== "pdf" || carried === ""))) {
55968
57715
  const f = raise("EX-072", file.rel, `${kind === "pdf" ? "PDF" : "image"} under a path the agent reads: its pixels or pages are not read`);
@@ -55990,8 +57737,8 @@ async function* scanRepo(root, options) {
55990
57737
  }
55991
57738
  text = decoded.text;
55992
57739
  if (decoded.hasNul && agentFacing) {
55993
- const at = text.indexOf("\0");
55994
- const where = positionAt(buildLineIndex(text), at < 0 ? 0 : at);
57740
+ const at2 = text.indexOf("\0");
57741
+ const where = positionAt(buildLineIndex(text), at2 < 0 ? 0 : at2);
55995
57742
  const f = raise("EX-064", file.rel, "a NUL byte (U+0000) in a file an agent reads", void 0, where.line, where.col);
55996
57743
  if (f) extra.push(f);
55997
57744
  }
@@ -56004,7 +57751,8 @@ async function* scanRepo(root, options) {
56004
57751
  const traps = canaryFindings(text, file.rel, records, ex022);
56005
57752
  const isSourceFile = (file.role === "code" || file.role === "unknown") && languageOf(file.rel) !== null;
56006
57753
  const sourceTools = isSourceFile ? [...scanSourceTools(file, text, defs), ...scanDynamicToolDescriptions(file, text, defs)] : [];
56007
- const lifecycle = ex036 && file.role === "manifest" && file.rel.split("/").pop() === "package.json" ? lifecycleScanFindings(text, file.path, file.rel, ex036) : [];
57754
+ if ((file.role === "config" || file.role === "mcp-config") && /\.json$/i.test(file.rel)) sourceTools.push(...scanJsonToolManifest(file, text, defs, sigs));
57755
+ const lifecycle = !ex036 ? [] : file.role === "manifest" && file.rel.split("/").pop() === "package.json" ? lifecycleScanFindings(text, file.path, file.rel, ex036) : isBuildHookFile(file.rel) ? buildHookScanFindings(text, file.path, file.rel, ex036) : [];
56008
57756
  const hooks2 = file.role === "hook" ? hookTextFindings(file, text, textDefs) : [];
56009
57757
  const settings = settingsFindings(file, text, settingsDefs);
56010
57758
  let deduped = deduplicate([...extra, ...sigs, ...hooks2, ...settings, ...heurs, ...traps, ...sandboxFindings(text, file.rel), ...sourceTools, ...lifecycle]);
@@ -56136,7 +57884,7 @@ var ENTRIES = {
56136
57884
  },
56137
57885
  "EX-010": {
56138
57886
  headline: "This tool server is not locked to a version",
56139
- attack: "Without a version, every run fetches the latest release. If an attacker publishes a bad update, your agent starts running it automatically."
57887
+ attack: "Without an exact version (or with a tag such as @latest, a range such as ^1.2, or an image without a digest), every run fetches whatever was published last. If an attacker publishes a bad update, your agent starts running it automatically."
56140
57888
  },
56141
57889
  "EX-011": {
56142
57890
  headline: "Secrets are sitting where your AI can read them",
@@ -56224,7 +57972,7 @@ var ENTRIES = {
56224
57972
  },
56225
57973
  "EX-036": {
56226
57974
  headline: "A script that runs by itself sends your secrets out",
56227
- attack: 'This package has a script that npm, pnpm or yarn runs on its own (on install, or before or after "npm test"), and the file it runs reads your .env or other credentials and sends data to another computer. Your AI agent only has to run the tests or install the project; it does not have to obey anything.'
57975
+ attack: "This project has a script that runs on its own when it is installed, built or tested (an npm lifecycle script, setup.py, a build backend, a Makefile install target, a node-gyp action, build.rs, a composer script or a Dockerfile RUN step), and it reads your environment, .env or other credentials and sends them to another computer, or runs code hidden in an encoded string. Your AI agent only has to install, build or test the project; it does not have to obey anything."
56228
57976
  },
56229
57977
  "EX-037": {
56230
57978
  headline: "This text tells your AI to do something and not to tell you",
@@ -56303,12 +58051,20 @@ var ENTRIES = {
56303
58051
  attack: 'A rule such as find, awk, sed, git, env or "npm run" with a wildcard lets the agent run whatever it is given: through an exec flag, a script call or a config option. Together with network or write access it is a way to run anything with no prompt.'
56304
58052
  },
56305
58053
  "EX-074": {
56306
- headline: "This settings file makes Copilot approve every tool call",
56307
- attack: "A committed setting approves all tool calls of the chat agent, so it no longer asks before it runs commands, edits files or reaches the network."
58054
+ headline: "This settings file makes your AI approve every tool call",
58055
+ attack: "A committed setting (Copilot auto-approve, or Cline and Roo Code running every command) approves the tool calls of the chat agent, so it no longer asks before it runs commands, edits files or reaches the network."
56308
58056
  },
56309
58057
  "EX-075": {
56310
58058
  headline: "This instruction file tells your AI to do something that has nothing to do with the code",
56311
58059
  attack: "Agents follow their instruction files (steering files, AGENTS.md, CONTRIBUTING.md and the like) without asking. An order there to leave a marker file, skip or weaken a test or a check, run a command that is not a build, test or lint step, or fetch a web address is carried out quietly, even when nothing in the text hides it."
58060
+ },
58061
+ "EX-077": {
58062
+ headline: "A command here sends your environment or a secrets file to another computer",
58063
+ attack: "Piping the whole environment (printenv, env) or a file like .env into curl, wget or nc, or uploading it to a raw IP address, hands every key and token it holds to whoever runs that server. Your agent may run such a command if a file tells it to, or a script may run it for you."
58064
+ },
58065
+ "EX-076": {
58066
+ headline: "A note in this file is addressed to AI tools and asks for something dangerous",
58067
+ attack: 'Text that speaks to "AI assistants", "code reviewers" or "coding agents" is written for your agent, not for you. This one asks it to do something an attacker wants: run a downloaded script, force-push, turn off a security check, approve a review, use a different package registry or read your credentials. It can sit in a code comment, a config label or package details, where people rarely look.'
56312
58068
  }
56313
58069
  };
56314
58070
  function plainFor(ruleId, fallbackTitle) {
@@ -56326,7 +58082,7 @@ function plural(n, one, many = `${one}s`) {
56326
58082
  // ../core/src/exorcise.ts
56327
58083
  init_walker();
56328
58084
  var RULE_CLASSES = {
56329
- "EX-001": ["zero-width", "bidi-override", "tag-block", "invisible-format"],
58085
+ "EX-001": ["zero-width", "bidi-override", "tag-block", "invisible-format", "invisible-letter"],
56330
58086
  "EX-021": ["variation-selector"]
56331
58087
  };
56332
58088
  var ALL_CLASSES = /* @__PURE__ */ new Set([...RULE_CLASSES["EX-001"], ...RULE_CLASSES["EX-021"]]);
@@ -56714,7 +58470,7 @@ VALUE_FLAGS["gsed"] = VALUE_FLAGS["sed"] ?? /* @__PURE__ */ new Set();
56714
58470
 
56715
58471
  // ../shield/src/paraphrase.ts
56716
58472
  var W = String.raw`[\s\W_]{0,3}`;
56717
- var words = (...ws) => ws.join(`${W}`);
58473
+ var words2 = (...ws) => ws.join(`${W}`);
56718
58474
  var any = (...alts) => `(?:${alts.join("|")})`;
56719
58475
  var SET_ASIDE = any(
56720
58476
  "ignore",
@@ -56773,16 +58529,16 @@ var BEFORE = any(
56773
58529
  "the\\W{0,3}(?:conversation|chat)\\W{0,3}so\\W{0,3}far",
56774
58530
  "your\\W{0,3}(?:task|job|instructions)"
56775
58531
  );
56776
- var OVERRIDE3 = [
58532
+ var OVERRIDE4 = [
56777
58533
  new RegExp(`\\b${SET_ASIDE}${W}(?:${FILLER2}${W}){0,2}${PREVIOUS}${W}(?:${any(FILLER2, PREVIOUS)}${W}){0,2}${ORDERS}\\b`, "i"),
56778
58534
  new RegExp(`\\b${SET_ASIDE}${W}${BEFORE}`, "i"),
56779
58535
  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"),
56780
- new RegExp(`\\b${words("your", any("real", "actual", "true", "new", "only"), any("task", "job", "goal", "purpose", "instructions?", "mission"))}${W}(?:is|are|now)\\b`, "i"),
58536
+ new RegExp(`\\b${words2("your", any("real", "actual", "true", "new", "only"), any("task", "job", "goal", "purpose", "instructions?", "mission"))}${W}(?:is|are|now)\\b`, "i"),
56781
58537
  new RegExp(`(?:^|[\\s\\[<(*#])${any("system", "admin(?:istrator)?", "developer", "operator", "root", "security\\W{0,3}team", "anthropic", "openai")}${W}${any("override", "message", "note", "notice", "instructions?", "prompt", "command", "alert", "update")}\\s*[:\\]>]`, "i"),
56782
58538
  new RegExp(`<\\s*/?\\s*${any("system", "sys", "instructions?", "admin", "im_start", "assistant")}\\s*>`, "i"),
56783
- new RegExp(`\\b${words(any("instead", "rather"), any("of\\W{0,3}(?:that|answering|doing\\W{0,3}that|what\\W{0,3}the\\W{0,3}user\\W{0,3}(?:asked|wants))", "than\\W{0,3}(?:that|answering)"))}`, "i")
58539
+ new RegExp(`\\b${words2(any("instead", "rather"), any("of\\W{0,3}(?:that|answering|doing\\W{0,3}that|what\\W{0,3}the\\W{0,3}user\\W{0,3}(?:asked|wants))", "than\\W{0,3}(?:that|answering)"))}`, "i")
56784
58540
  ];
56785
- var CONCEAL = [
58541
+ var CONCEAL2 = [
56786
58542
  new RegExp(`\\b${any("do\\W{0,3}not", "don'?t", "never", "avoid", "without")}${W}${any("tell(?:ing)?", "inform(?:ing)?", "mention(?:ing)?", "alert(?:ing)?", "notify(?:ing)?", "show(?:ing)?", "reveal(?:ing)?", "disclos(?:e|ing)", "report(?:ing)?", "let(?:ting)?\\W{0,3}(?:the\\W{0,3})?(?:user|human)\\W{0,3}know", "ask(?:ing)?", "confirm(?:ing)?\\W{0,3}with", "bother(?:ing)?")}${W}(?:${any("this", "it", "that", "anything", "about\\W{0,3}(?:this|it)")}${W}){0,2}(?:to${W})?(?:the${W}|your${W})?${any("user", "human", "operator", "owner", "developer", "person", "them", "anyone")}`, "i"),
56787
58543
  new RegExp(`\\b${any("keep", "leave")}${W}(?:this|it|that)${W}${any("secret", "hidden", "quiet", "confidential", "between\\W{0,3}us", "to\\W{0,3}yourself", "out\\W{0,3}of\\W{0,3}(?:the\\W{0,3})?(?:response|reply|answer|summary|output)")}`, "i"),
56788
58544
  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"),
@@ -56835,6 +58591,12 @@ var ROLE = [
56835
58591
  new RegExp(`\\b${any("as\\W{0,3}an\\W{0,3}ai", "dear\\W{0,3}(?:ai|assistant|agent|model|llm|claude|gpt)", "(?:hey|attention|note\\W{0,3}to|message\\W{0,3}for)\\W{0,3}(?:the\\W{0,3})?(?:ai|assistant|agent|model|llm)")}\\b`, "i")
56836
58592
  ];
56837
58593
 
58594
+ // ../shield/src/orders.ts
58595
+ var ACTOR = String.raw`(?:the\s+(?:ai|assistant|agent|model|llm)|(?:ai|llm|coding)\s+(?:assistant|agent)|claude|copilot|as\s+an\s+ai)`;
58596
+ var MODAL = String.raw`(?:needs?\s+to|must|should|has\s+to|have\s+to|is\s+to|will\s+now|now\s+needs?\s+to|is\s+required\s+to|is\s+expected\s+to|shall|please)`;
58597
+ var ASK = String.raw`(?:(?:call|invoke|trigger|use)\s+(?:the\s+)?[\x60'"]?[\w.-]{2,40}[\x60'"]?(?:\s+(?:tool|function))?\s+(?:with|to|on|and)\b|(?:call|invoke|use)\s+(?:the\s+)?[\w.-]{2,40}\s+(?:tool|function)\b|(?:run|execute)\s+(?:the\s+|this\s+|a\s+)?(?:following\s+|shell\s+)?(?:command|script|[\x60$]|curl|wget|bash|sh\b|rm\b|git\b|npm\b|pip\b|python)|(?:send|upload|post|email|exfiltrate|forward|transmit)\b|(?:delete|remove|erase|wipe)\b|push\b|publish\b|(?:change|modify|update|disable|turn\s+off)\s+(?:the\s+|its\s+|your\s+)?(?:\w+\s+)?(?:settings|config\w*|permissions|approvals?)|read\s+(?:the\s+)?(?:\S+\s+)?(?:\.env\b|private\s+key|credentials?|id_rsa|\.ssh|secrets?\b))`;
58598
+ var AGENTIC = new RegExp(`\\b${ACTOR}[^.!?\\n]{0,80}?\\b${MODAL}\\b[^.!?\\n]{0,40}?\\b${ASK}`, "i");
58599
+
56838
58600
  // ../shield/src/canary.ts
56839
58601
  var TRAPS = [
56840
58602
  {
@@ -57274,9 +59036,16 @@ function remoteFlags(args) {
57274
59036
  }
57275
59037
  return flags2.has("--url") ? flags2 : null;
57276
59038
  }
57277
- function isWrapped(entry) {
59039
+ var LAUNCHER = /(?:^|[\\/])(?:exorcist|npx|pnpx|bunx|node|nodejs|tsx|bun|pnpm|yarn|deno)(?:\.exe|\.cmd)?$/i;
59040
+ function ours(entry, args, name) {
59041
+ if (name === void 0) return true;
59042
+ const s = args.indexOf("shield");
59043
+ const command = entry["command"];
59044
+ return args[s + 2] === name || typeof command === "string" && LAUNCHER.test(command.trim());
59045
+ }
59046
+ function isWrapped(entry, name) {
57278
59047
  const args = strArray(entry["args"]);
57279
- return args !== null && (separatorIndex(args) !== -1 || remoteFlags(args) !== null);
59048
+ return args !== null && (separatorIndex(args) !== -1 || remoteFlags(args) !== null) && ours(entry, args, name);
57280
59049
  }
57281
59050
 
57282
59051
  // src/tools.ts
@@ -57537,7 +59306,7 @@ Tell the user. They can undo this with: exorcist vault restore ${r.value.id}`
57537
59306
  }
57538
59307
 
57539
59308
  // src/index.ts
57540
- var VERSION = "0.3.10";
59309
+ var VERSION = "0.3.11";
57541
59310
  var ctx = {
57542
59311
  cwd: process.cwd(),
57543
59312
  approved: [],