@misconfig/cli 1.0.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/engine/index.js CHANGED
@@ -1,62 +1,162 @@
1
- // misconfig.ai rule engine. Runs only in the Worker, never in the browser.
1
+ // The misconfig rule engine. The same code runs in the command line tool, in the
2
+ // browser on misconfig.ai, and in the Worker that rebuilds shared reports.
2
3
 
3
4
  import { maskSecrets, looksLikeSecret, looksLikeToken, isMasked, isPathLike, describeMasks } from "./mask.js";
4
- import { parseJSONC, parseTOML } from "./parse.js";
5
+ import { parseJSONC, parseTOML, parseYAML, parseCodexRules } from "./parse.js";
6
+ import { namedInstructions, NAMING_SETTINGS } from "./named.js";
5
7
  import { RULES, CATEGORIES } from "./catalog.js";
6
-
7
- export const RULESET_VERSION = "2026.11.2";
8
+ import { explainFile, agentLines, hiddenComments, hiddenTags, hiddenZeroWidth, fenceAt, inCodeSpan, CAN_IMPORT, scopeOf, HOOK_EVENTS, SCOPES, anthropicMarketplace, marketplaceSource } from "./explain.js";
9
+ import { ignoreRules, isIgnored, globMatch } from "./glob.js";
10
+ import { HOME_MARKERS, DOWNLOADS_LIKE, SKILL_PROGRAM, TOOL_ROOT, visibleName } from "./paths.js";
11
+ import { findDangerFlag, trimWord, programName, COMMAND_BREAK, FLAG_NAMES, AGENT_NAMES } from "./flags.js";
12
+ import {
13
+ KNOWN_PACKAGES,
14
+ KNOWN_EXTENSIONS,
15
+ AGENT_EXTENSIONS,
16
+ AGENT_PACKAGES,
17
+ AGENT_ADVISORIES,
18
+ TRACES,
19
+ SHELL_TRACES,
20
+ WORKFLOW_TRACES,
21
+ KNOWN_BAD_HOSTS,
22
+ OFFICIAL_MCP_PACKAGES,
23
+ OFFICIAL_PYPI_MCP,
24
+ compareVersions,
25
+ VERSION_RE,
26
+ } from "./known.js";
27
+
28
+ export { findDangerFlag };
29
+
30
+ export const RULESET_VERSION = "2026.11.6";
31
+ const RULESET_RE = /^\d{4}\.\d{1,2}\.\d{1,3}$/;
32
+
33
+ // True when ruleset version a, such as "2026.11.4", is newer than b. A site
34
+ // on an older ruleset doesn't know every check a newer command runs.
35
+ export const rulesetIsNewer = (a, b) => typeof a === "string" && typeof b === "string" && RULESET_RE.test(a) && RULESET_RE.test(b) && compareVersions(a, b) > 0;
8
36
 
9
37
  const WEIGHT = { critical: 30, high: 15, medium: 6, low: 2, info: 0 };
10
38
  const SEVERITIES = ["critical", "high", "medium", "low", "info"];
39
+ // The lowest score for each grade. Below the last one is F.
40
+ const GRADES = [
41
+ ["A", 90],
42
+ ["B", 80],
43
+ ["C", 65],
44
+ ["D", 50],
45
+ ];
46
+
47
+ // How the score works, in the words reports and the rules page use.
48
+ export const SCORING = [
49
+ `The score starts at 100. The first finding from a rule takes off ${WEIGHT.critical} points if it's critical, ${WEIGHT.high} if it's high, ${WEIGHT.medium} if it's medium and ${WEIGHT.low} if it's low.`,
50
+ "Each repeat takes off a quarter of that again, up to twice that for one rule, so one noisy rule can't empty the score. Info findings take off nothing.",
51
+ `Grades: ${GRADES.map(([g, min]) => `${g} for ${min} or more`).join(", ")} and F below ${GRADES.at(-1)[1]}. Any critical finding caps the grade at D.`,
52
+ ].join(" ");
11
53
  const MAX_FILE_CHARS = 450_000;
12
54
 
13
- // Which agents read which files. Used for the control map and attribution.
55
+ // Which agents read which files, and what each file controls. Used for the
56
+ // control map and attribution. The first match wins, so specific paths come
57
+ // before general ones.
14
58
  const CONTROL = [
59
+ // Claude Code
15
60
  [/(^|\/)claude(\.local)?\.md$/i, ["Claude Code"], "Instructions"],
16
- [/(^|\/)\.codex\/agents(\.override)?\.md$/i, ["Codex"], "Instructions"],
17
- [/(^|\/)\.config\/opencode\/agents\.md$/i, ["OpenCode"], "Instructions"],
18
- [/(^|\/)agents(\.override)?\.md$/i, ["Codex", "OpenCode", "Cursor", "GitHub Copilot", "Zed"], "Instructions"],
19
- [/(^|\/)gemini\.md$/i, ["Gemini CLI"], "Instructions"],
20
61
  [/(^|\/)\.claude\/settings(\.local)?\.json$/i, ["Claude Code"], "Permissions & hooks"],
21
- [/(^|\/)managed-settings\.json$/i, ["Claude Code"], "Admin policy"],
22
- [/(^|\/)claude_desktop_config\.json$/i, ["Claude Desktop"], "MCP servers"],
23
- [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User\/settings\.json$/i, (p) => [editorTool(p)], "Editor settings"],
24
- [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor)\/User\/mcp\.json$/i, (p) => [editorTool(p)], "MCP servers"],
25
- [/(^|\/)saoudrizwan\.claude-dev\/settings\/cline_mcp_settings\.json$/i, ["Cline"], "MCP servers"],
26
- [/(^|\/)rooveterinaryinc\.roo-cline\/settings\/mcp_settings\.json$/i, ["Roo Code"], "MCP servers"],
27
- [/(^|\/)\.codeium\/windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
28
- [/(^|\/)(\.bashrc|\.zshrc|\.bash_profile|\.profile|\.zprofile|config\.fish|[^/]*profile\.ps1)$/i, ["Your shell"], "Shell profile"],
62
+ [/(^|\/)managed-settings(\.d\/[^/]+)?\.json$/i, ["Claude Code"], "Admin policy"],
63
+ [/(^|\/)managed-mcp\.json$/i, ["Claude Code"], "Admin MCP servers"],
29
64
  [/(^|\/)\.claude\/hooks\//i, ["Claude Code"], "Hook script"],
30
65
  [/(^|\/)\.claude\/(commands|agents|skills|output-styles)\//i, ["Claude Code"], "Commands & agents"],
31
- [/(^|\/)\.mcp\.json$/i, ["Claude Code"], "MCP servers"],
66
+ [/(^|\/)\.claude\/rules\//i, ["Claude Code"], "Rules"],
67
+ [/(^|\/)\.claude\/projects\/[^/]+\/memory\//i, ["Claude Code"], "Memory"],
68
+ [/(^|\/)\.claude\/plugins\/installed_plugins\.json$/i, ["Claude Code"], "Plugins"],
69
+ [/(^|\/)\.claude\/plugins\/known_marketplaces\.json$/i, ["Claude Code"], "Plugin marketplaces"],
70
+ [/(^|\/)\.claude\/plugins\/.+\/hooks\/hooks\.json$/i, ["Claude Code"], "Plugin hooks"],
71
+ [/(^|\/)\.claude\/plugins\/.+\/\.mcp\.json$/i, ["Claude Code"], "Plugin MCP servers"],
72
+ [/(^|\/)\.claude\/plugins\/.+\/(commands|agents|skills)\/.+\.md$/i, ["Claude Code"], "Plugin commands & agents"],
73
+ [/(^|\/)\.claude-plugin\/plugin\.json$/i, ["Claude Code"], "Plugin manifest"],
32
74
  [/(^|\/)\.claude\.json$/i, ["Claude Code"], "User config"],
75
+ [/(^|\/)\.mcp\.json$/i, ["Claude Code", "GitHub Copilot"], "MCP servers"],
76
+ [/(^|\/)claude_desktop_config\.json$/i, ["Claude Desktop"], "MCP servers"],
77
+ // Codex
78
+ [/(^|\/)\.codex\/agents(\.override)?\.md$/i, ["Codex"], "Instructions"],
33
79
  [/(^|\/)\.codex\/config\.toml$/i, ["Codex"], "Permissions & MCP"],
80
+ [/(^|\/)\.codex\/hooks\.json$/i, ["Codex"], "Hooks"],
81
+ [/(^|\/)\.codex\/rules\/[^/]+\.rules$/i, ["Codex"], "Command rules"],
82
+ [/(^|\/)\.codex\/[^/]+\.config\.toml$/i, ["Codex"], "Profile"],
83
+ [/(^|\/)codex\/requirements\.toml$/i, ["Codex"], "Admin policy"],
34
84
  [/(^|\/)\.codex\/.+\.md$/i, ["Codex"], "Prompts"],
35
- [/(^|\/)\.cursor\/mcp\.json$/i, ["Cursor"], "MCP servers"],
36
- [/(^|\/)\.cursor\/.+\.mdc?$/i, ["Cursor"], "Rules"],
37
- [/(^|\/)\.cursorrules$/i, ["Cursor"], "Rules (legacy)"],
85
+ [/(^|\/)\.agents\/skills\//i, ["Codex"], "Skills"],
86
+ // Shared instruction files
87
+ [/(^|\/)\.config\/opencode\/agents\.md$/i, ["OpenCode"], "Instructions"],
88
+ [/(^|\/)\.junie\/agents\.md$/i, ["Junie"], "Guidelines"],
89
+ [/(^|\/)agents(\.override)?\.md$/i, ["Codex", "OpenCode", "Cursor", "GitHub Copilot", "Zed"], "Instructions"],
90
+ // Gemini CLI
91
+ [/(^|\/)gemini\.md$/i, ["Gemini CLI"], "Instructions"],
92
+ [/(^|\/)\.gemini\/settings\.json$/i, ["Gemini CLI"], "Settings & MCP"],
93
+ [/(^|\/)(gemini-cli|GeminiCli)\/(system-)?settings\.json$/i, ["Gemini CLI"], "Admin settings"],
94
+ [/(^|\/)\.gemini\/trustedFolders\.json$/i, ["Gemini CLI"], "Trusted folders"],
95
+ [/(^|\/)\.gemini\/extensions\/[^/]+\/gemini-extension\.json$/i, ["Gemini CLI"], "Extension"],
96
+ [/(^|\/)\.gemini\/.+\.md$/i, ["Gemini CLI"], "Instructions"],
97
+ [/(^|\/)\.gemini\/commands\/.+\.toml$/i, ["Gemini CLI"], "Commands"],
98
+ // GitHub Copilot, in VS Code and on the command line
38
99
  [/(^|\/)\.github\/copilot-instructions\.md$/i, ["GitHub Copilot"], "Instructions"],
39
100
  [/(^|\/)\.github\/(instructions|prompts|chatmodes|agents)\//i, ["GitHub Copilot"], "Instructions & prompts"],
101
+ [/(^|\/)\.github\/hooks\/[^/]+\.json$/i, ["GitHub Copilot"], "Hooks"],
102
+ [/(^|\/)\.github\/mcp\.json$/i, ["GitHub Copilot"], "MCP servers"],
103
+ [/(^|\/)\.github\/copilot\/settings\.json$/i, ["GitHub Copilot"], "Settings"],
104
+ [/(^|\/)\.copilot\/config\.json$/i, ["GitHub Copilot"], "Settings & trusted folders"],
105
+ [/(^|\/)\.copilot\/mcp-config\.json$/i, ["GitHub Copilot"], "MCP servers"],
40
106
  [/(^|\/)\.vscode\/mcp\.json$/i, ["GitHub Copilot"], "MCP servers"],
41
107
  [/(^|\/)\.vscode\/settings\.json$/i, ["GitHub Copilot"], "Editor settings"],
42
- [/(^|\/)\.gemini\/settings\.json$/i, ["Gemini CLI"], "Settings & MCP"],
43
- [/(^|\/)\.gemini\/.+\.md$/i, ["Gemini CLI"], "Instructions"],
44
- [/(^|\/)opencode\.jsonc?$/i, ["OpenCode"], "Settings & MCP"],
45
- [/(^|\/)\.opencode\//i, ["OpenCode"], "Agents & commands"],
46
- [/(^|\/)\.grok\/settings\.json$/i, ["Grok CLI"], "Settings & MCP"],
47
- [/(^|\/)(\.grok\/.+|grok)\.md$/i, ["Grok CLI"], "Instructions"],
48
- [/(^|\/)(\.windsurfrules|\.windsurf\/rules\/.+)$/i, ["Windsurf"], "Rules"],
49
- [/(^|\/)\.windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
108
+ [/(^|\/)\.vscode\/tasks\.json$/i, ["Cursor", "Windsurf"], "Editor tasks"],
109
+ [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User\/settings\.json$/i, (p) => [editorTool(p)], "Editor settings"],
110
+ [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor)\/User\/mcp\.json$/i, (p) => [editorTool(p)], "MCP servers"],
111
+ // Cursor
112
+ [/(^|\/)\.cursor\/mcp\.json$/i, ["Cursor"], "MCP servers"],
113
+ [/(^|\/)\.cursor\/hooks\.json$/i, ["Cursor"], "Hooks"],
114
+ [/(^|\/)\.cursor\/environment\.json$/i, ["Cursor"], "Cloud agent setup"],
115
+ [/(^|\/)\.cursor\/(cli-config|cli)\.json$/i, ["Cursor"], "CLI permissions"],
116
+ [/(^|\/)\.cursor\/sandbox\.json$/i, ["Cursor"], "Sandbox"],
117
+ [/(^|\/)\.cursor\/permissions\.json$/i, ["Cursor"], "Permissions"],
118
+ [/(^|\/)\.cursor\/.+\.mdc?$/i, ["Cursor"], "Rules"],
119
+ [/(^|\/)\.cursorrules$/i, ["Cursor"], "Rules (legacy)"],
120
+ // Cline and Roo Code
121
+ [/(^|\/)saoudrizwan\.claude-dev\/settings\/cline_mcp_settings\.json$/i, ["Cline"], "MCP servers"],
122
+ [/(^|\/)\.cline\/data\/settings\/cline_mcp_settings\.json$/i, ["Cline"], "MCP servers"],
123
+ [/(^|\/)\.cline\/data\/globalState\.json$/i, ["Cline"], "Auto-approve settings"],
124
+ [/(^|\/)\.cline\/plugins\/[^/]+\.[cm]?[jt]sx?$/i, ["Cline"], "Plugin code"],
125
+ [/(^|\/)(Documents\/Cline\/Rules|\.cline\/rules)\//i, ["Cline"], "Rules"],
50
126
  [/(^|\/)\.clinerules/i, ["Cline"], "Rules"],
127
+ [/(^|\/)rooveterinaryinc\.roo-cline\/settings\/mcp_settings\.json$/i, ["Roo Code"], "MCP servers"],
51
128
  [/(^|\/)(\.roomodes|\.roo\/.+)$/i, ["Roo Code"], "Rules & modes"],
129
+ // Others
130
+ [/(^|\/)\.codeium\/windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
131
+ [/(^|\/)(\.windsurfrules|\.windsurf\/rules\/.+)$/i, ["Windsurf"], "Rules"],
132
+ [/(^|\/)\.windsurf\/workflows\/.+\.md$/i, ["Windsurf"], "Workflows"],
133
+ [/(^|\/)\.windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
134
+ [/(^|\/)(\.windsurf|\.codeium\/windsurf)\/hooks\.json$/i, ["Windsurf"], "Hooks"],
135
+ [/(^|\/)\.devin\/hooks\.v1\.json$/i, ["Windsurf"], "Hooks"],
136
+ [/(^|\/)opencode\.jsonc?$/i, ["OpenCode"], "Settings & MCP"],
137
+ [/(^|\/)\.opencode\/(plugins?|tools)\/[^/]+\.[cm]?[jt]sx?$/i, ["OpenCode"], "Plugin code"],
138
+ [/(^|\/)\.opencode\//i, ["OpenCode"], "Agents & commands"],
139
+ [/(^|\/)\.grok\/config\.toml$/i, ["Grok"], "Permissions & MCP"],
140
+ [/(^|\/)\.grok\/settings\.json$/i, ["Grok"], "Settings & MCP"],
141
+ [/(^|\/)\.grok\/hooks\/[^/]+\.json$/i, ["Grok"], "Hooks"],
142
+ [/(^|\/)(\.grok\/.+|grok)\.md$/i, ["Grok"], "Instructions"],
143
+ [/(^|\/)(\.amp|\.config\/amp)\/settings\.json$/i, ["Amp"], "Settings & MCP"],
144
+ [/(^|\/)(\.amp|\.config\/amp)\/plugins\/[^/]+\.[cm]?[jt]sx?$/i, ["Amp"], "Plugin code"],
145
+ [/(^|\/)goose\/config\.ya?ml$/i, ["Goose"], "Settings & extensions"],
146
+ [/(^|\/)\.goosehints$/i, ["Goose"], "Instructions"],
52
147
  [/(^|\/)\.kiro\/steering\//i, ["Kiro"], "Steering"],
53
148
  [/(^|\/)\.kiro\/settings\/mcp\.json$/i, ["Kiro"], "MCP servers"],
149
+ [/(^|\/)\.kiro\/hooks\/[^/]+\.(json|kiro\.hook)$/i, ["Kiro"], "Hooks"],
150
+ [/(^|\/)\.kiro\/agents\/[^/]+\.(json|md)$/i, ["Kiro"], "Agents"],
54
151
  [/(^|\/)\.amazonq\/rules\//i, ["Amazon Q"], "Rules"],
55
152
  [/(^|\/)\.?amazonq\/mcp\.json$/i, ["Amazon Q"], "MCP servers"],
153
+ [/(^|\/)\.?amazonq\/cli-agents\/[^/]+\.json$/i, ["Amazon Q"], "Agents"],
56
154
  [/(^|\/)\.continue\//i, ["Continue"], "Config & rules"],
57
155
  [/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i, ["Zed"], "Agent settings"],
58
- [/(^|\/)\.junie\/guidelines\.md$/i, ["Junie"], "Guidelines"],
156
+ [/(^|\/)\.junie\/mcp\/mcp\.json$/i, ["Junie"], "MCP servers"],
157
+ [/(^|\/)\.junie\/(guidelines\.md|rules\/)/i, ["Junie"], "Guidelines"],
59
158
  [/(^|\/)\.aider\.conf\.ya?ml$/i, ["Aider"], "Settings"],
159
+ [/(^|\/)(\.bashrc|\.zshrc|\.bash_profile|\.profile|\.zprofile|config\.fish|[^/]*profile\.ps1)$/i, ["Your shell"], "Shell profile"],
60
160
  ];
61
161
 
62
162
  function editorTool(path) {
@@ -72,66 +172,306 @@ export function controlFor(path) {
72
172
  return { tools: typeof hit[1] === "function" ? hit[1](path) : hit[1], kind: hit[2] };
73
173
  }
74
174
 
75
- const HOME_MARKERS = [".ssh", "AppData", "Library", "NTUSER.DAT", ".bashrc", ".zshrc", ".profile", "Downloads", "Documents", "Desktop", ".config", ".local", "Pictures", "Music", "Videos"];
76
- const DOWNLOADS_LIKE = /^(downloads?|desktop|temp|tmp)$/i;
77
175
  const KEY_FILE = /\.(pem|key|p12|pfx|jks|keystore|ppk)$|(^|\/)id_(rsa|dsa|ecdsa|ed25519)$|\.aws\/credentials$|service[-_]?account[^/]*\.json$|(^|\/)credentials\.json$|\.git-credentials$|\.codex\/auth\.json$|\.claude\/\.credentials\.json$|\.grok\/user-settings\.json$|\.kube\/config$|\.docker\/config\.json$/i;
78
- const EXAMPLE_ENV = /\.env\.(example|sample|template|dist|defaults)$/i;
176
+ const EXAMPLE_ENV = /(^|\/)\.env[\w.-]*\.(example|sample|template|dist|defaults)$/i;
177
+ // .pem files are often public certificates, such as cert.pem or ca-bundle.pem,
178
+ // which aren't secret. A name that mentions a key still counts as a key.
179
+ const CERT_NAME = /cert|crt|chain|bundle|intermediate|leaf|issuer|(^|[-_.])(root|ca|pub|public)([-_.]|$)|ca\.pem$/i;
180
+ const KEY_NAME = /privkey|private|(^|[-_.])key([-_.]|$)/i;
181
+ // A project's .npmrc usually holds registry settings, not tokens, and keys in
182
+ // test and example folders are fixtures.
183
+ const USUALLY_HARMLESS = /(^|\/)\.npmrc$|(^|\/)(tests?|__tests__|specs?|fixtures?|testdata|test-data|examples?|samples?|mocks?|demo)\//i;
184
+ const isCertificate = (path) => {
185
+ const name = path.split("/").pop();
186
+ return /\.pem$/i.test(name) && (/pub(?:lic)?[-_.]?key/i.test(name) || (CERT_NAME.test(name) && !KEY_NAME.test(name)));
187
+ };
79
188
 
80
189
  // --- Text patterns -----------------------------------------------------------
190
+ //
191
+ // These run on untrusted text, so every repeat is bounded or can't overlap
192
+ // the next part of its pattern, and matching time grows with the text.
81
193
 
82
194
  const RX_REMOTE_EXEC =
83
- /\b(?:curl|wget)\b[^\n|;&]{0,300}\|\s*(?:sudo\s+)?(?:ba|z|da|k|fi)?sh\b|\b(?:iwr|irm|Invoke-WebRequest|Invoke-RestMethod)\b[^\n|]{0,300}\|\s*(?:iex|Invoke-Expression)\b|\b(?:iex|Invoke-Expression)\b[^\n]{0,20}(?:Net\.WebClient|DownloadString|iwr|irm|Invoke-WebRequest|Invoke-RestMethod)|\bbase64\s+(?:-d|--decode)\b[^\n|]{0,120}\|\s*(?:ba)?sh\b|\b(?:bash|sh|zsh)\s+<\(\s*(?:curl|wget)\b|\bpowershell(?:\.exe)?\b[^\n]{0,60}\s-(?:e|enc|encodedcommand)\s+[A-Za-z0-9+/=]{20,}/i;
195
+ /\b(?:curl|wget)\b[^\n|;&]{0,300}\|\s*(?:sudo(?:\s+-[A-Za-z]+)*\s+)?(?:(?:ba|z|da|k|fi)?sh|python[0-9.]*|node|perl|ruby)\b|\b(?:(?:ba|z|da|k)?sh\s+-c|eval)\s+["']?\$\(\s*(?:curl|wget)\b|\bsource\s+<\(\s*(?:curl|wget)\b|\b(?:iwr|irm|Invoke-WebRequest|Invoke-RestMethod)\b[^\n|]{0,300}\|\s*(?:iex|Invoke-Expression)\b|\b(?:iex|Invoke-Expression)\b[^\n]{0,20}(?:Net\.WebClient|DownloadString|iwr|irm|Invoke-WebRequest|Invoke-RestMethod)|\bbase64\s+(?:-d|--decode)\b[^\n|]{0,120}\|\s*(?:ba)?sh\b|\b(?:bash|sh|zsh)\s+<\(\s*(?:curl|wget)\b|\bpowershell(?:\.exe)?\b[^\n]{0,60}\s-(?:e|enc|encodedcommand)\s+[A-Za-z0-9+/=]{20,}|\b(?:python[0-9.]*|node|perl|ruby|php)\s+-[ce]\s+["']?(?:\$\(|`)\s*(?:curl|wget)\b|\b(?:curl|wget)\b[^\n|;&]{0,300}?\s(?:-[A-Za-z]{0,8}[oO]|--output|--output-document)[= ]?\s*["']?([\w./~][\w./~-]{0,99})["']?[^\n]{0,120}?(?:&&|;)\s*(?:sudo\s+)?(?:(?:(?:ba|z|da|k)?sh|python[0-9.]*|node|perl|ruby|source|\.|chmod\s+\+?[0-7]*x?)\s+)?["']?(?:\.\/)?\1(?![\w./-])|\b(?:curl|wget)\b[^\n|;&]{0,300}?https?:\/\/[^\s"'|;&]{0,200}\/([\w.-]{1,100})["']?[^\n]{0,120}?(?:&&|;)\s*(?:sudo\s+)?(?:(?:ba|z|da|k)?sh|python[0-9.]*|node|perl|ruby|source|\.|chmod\s+\+?[0-7]*x?)\s+["']?(?:\.\/)?\2(?![\w./-])|\bdeno\s+run\b[^\n|;&]{0,120}?\shttps?:\/\/|\b(?:npx|bunx|pnpx)\b(?:\s+-{1,2}[\w-]+)*\s+https?:\/\//i;
196
+ // --- Commands ------------------------------------------------------------------
197
+ //
198
+ // Hooks, scripts and settings that run commands are read one command at a
199
+ // time: a command ends at && || ; | or a new line.
200
+
201
+ function commandsOf(text) {
202
+ const out = [];
203
+ let start = 0;
204
+ for (const m of String(text).matchAll(COMMAND_BREAK)) {
205
+ out.push(text.slice(start, m.index));
206
+ start = m.index + m[0].length;
207
+ }
208
+ out.push(String(text).slice(start));
209
+ return out.filter((c) => c.trim());
210
+ }
211
+ const wordsOf = (command) => command.trim().split(/\s+/).map((w) => trimWord(w, "\"'", "\"'"));
212
+
213
+ // curl's options are case-sensitive: -d sends data, -D only saves headers.
214
+ const RX_CURL_SEND = /\bcurl\b[^\n]{0,200}\s(?:-[a-zA-Z]*[dFT]|--data(?:-binary|-raw|-urlencode|-ascii)?|--form(?:-string)?|--upload-file|--json|-X\s*["']?(?:POST|PUT|PATCH))\b/;
84
215
  const RX_NET_SEND =
85
- /\bcurl\b[^\n]{0,200}\s(?:-d|--data(?:-binary|-raw|-urlencode)?|-F|--form|-T|--upload-file|-X\s*(?:POST|PUT))\b|\bwget\b[^\n]{0,200}--post-(?:data|file)\b|\b(?:Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[^\n]{0,200}-(?:Method\s+(?:Post|Put)|Body|InFile)\b|\b(?:nc|ncat|netcat)\s+[^\n]{0,80}\b\d{2,5}\b|\bscp\s+\S+\s+\S+@|\brsync\b[^\n]{0,100}\s[\w.-]+@[\w.-]+:/i;
86
- const RX_DESTRUCTIVE =
87
- /\brm\s+-[a-z]*(?:rf|fr)\b|\bRemove-Item\b[^\n]{0,80}-Recurse[^\n]{0,40}-Force|\bdel\s+\/[sq]\b|\brmdir\s+\/s\b|\bgit\s+push\b[^\n]*\s--force\b|\bgit\s+reset\s+--hard\b|\bgit\s+clean\s+-[a-z]*f|\bmkfs\b|\bdd\s+if=/i;
88
- const RX_OUTSIDE_SCRIPT =
89
- /(?:^|[\s"'=])((?:\/tmp|\/var\/tmp|~\/Downloads|\$HOME\/Downloads|%TEMP%|%TMP%|\$env:TEMP|[A-Za-z]:[\\/]Users[\\/][^\\/\s"']+[\\/](?:Downloads|AppData[\\/]Local[\\/]Temp))[\\/][^\s"']+)/i;
216
+ /\bwget\b[^\n]{0,200}--post-(?:data|file)\b|\b(?:Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[^\n]{0,200}-(?:Method\s+(?:Post|Put|Patch)|Body|InFile)\b|\b(?:nc|ncat|netcat)\s+[^\n]{0,80}\b\d{2,5}\b|\bscp\s+\S+\s+\S+@|\brsync\b[^\n]{0,100}\s[\w.-]+@[\w.-]+:/i;
217
+
218
+ // A command that sends data somewhere other than this computer.
219
+ function sendsData(text) {
220
+ for (const command of commandsOf(text)) {
221
+ if (!RX_CURL_SEND.test(command) && !RX_NET_SEND.test(command)) continue;
222
+ const hosts = [...command.matchAll(/\bhttps?:\/\/([^\s/:"'`]+)/gi)].map((m) => m[1]);
223
+ if (hosts.length && hosts.every(isLocalHost)) continue;
224
+ return true;
225
+ }
226
+ return false;
227
+ }
228
+
229
+ const RX_DESTRUCTIVE = /\bgit\s+push\b[^\n|;&]{0,200}\s(?:--force\b|-f\b)|\bgit\s+reset\s+--hard\b|\bgit\s+clean\s+-[a-z]*f|\bmkfs\b|\bdd\s+if=/i;
230
+ // Deleting the root of a drive, the home folder or everything in the current
231
+ // folder, or "$VAR/", which becomes / when the variable is empty. Cleaning up
232
+ // a named folder, such as rm -rf /tmp/build, isn't flagged.
233
+ const RISKY_TARGET =
234
+ /^(?:\/\*?|\\\*?|~[\\/]?\*?|\$\{?HOME\}?[\\/]?\*?|\$env:(?:USERPROFILE|HOMEPATH|HOME)[\\/]?\*?|%(?:USERPROFILE|HOMEPATH)%[\\/]?\*?|[A-Za-z]:[\\/]?\*?|\*|\.[\\/]?\*?|\.\.[\\/]?\*?|\$\{?\w+\}?[\\/]\*?)$/i;
235
+ function removesTooMuch(text) {
236
+ for (const command of commandsOf(text)) {
237
+ const words = wordsOf(command);
238
+ const at = words.findIndex((w) => /^(?:rm|Remove-Item|ri|rd|rmdir|del|erase)$/i.test(w));
239
+ if (at < 0) continue;
240
+ const args = words.slice(at + 1);
241
+ const cmdStyle = /^(?:rd|rmdir|del|erase)$/i.test(words[at]) && args.some((a) => /^\/[a-z]$/i.test(a));
242
+ const flags = cmdStyle ? args.filter((a) => /^\/[a-z]$/i.test(a)) : args.filter((a) => a.startsWith("-"));
243
+ const targets = cmdStyle ? args.filter((a) => !/^\/[a-z]$/i.test(a)) : args.filter((a) => !a.startsWith("-"));
244
+ const recursive = cmdStyle ? flags.some((a) => /^\/s$/i.test(a)) : flags.some((a) => /^-[a-z]*r[a-z]*$/i.test(a) || /^-(?:-recursive|rec(?:u(?:r(?:s(?:e)?)?)?)?)$/i.test(a));
245
+ if (recursive && targets.some((t) => RISKY_TARGET.test(t))) return true;
246
+ }
247
+ return false;
248
+ }
249
+ const isDestructive = (text) => RX_DESTRUCTIVE.test(text) || removesTooMuch(text);
250
+
251
+ // A script run from Downloads or a temp folder, which isn't reviewed with
252
+ // the project. Only the program or script being run counts, not a file a
253
+ // command writes to.
254
+ const OUTSIDE_PATH = /^(?:\/tmp|\/var\/tmp|~\/Downloads|\$HOME\/Downloads|%TEMP%|%TMP%|\$env:TEMP|[A-Za-z]:[\\/]Users[\\/][^\\/]+[\\/](?:Downloads|AppData[\\/]Local[\\/]Temp))[\\/]\S+$/i;
255
+ const INTERPRETERS = /^(?:bash|sh|zsh|fish|dash|python[0-9.]*|node|deno|bun|ruby|perl|php|pwsh|powershell(?:\.exe)?|source|\.)$/i;
256
+ function runsOutsideScript(text) {
257
+ for (const command of commandsOf(text)) {
258
+ const words = wordsOf(command).filter((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w));
259
+ while (/^(?:sudo|exec|nohup|time|env)$/i.test(words[0] ?? "")) words.shift();
260
+ let script = words[0];
261
+ if (INTERPRETERS.test(script ?? "")) script = words.slice(1).find((w) => !w.startsWith("-"));
262
+ if (script && OUTSIDE_PATH.test(script)) return true;
263
+ }
264
+ return false;
265
+ }
90
266
  const RX_EXFIL_HOST =
91
- /\b(webhook\.site|requestbin\.(?:com|net)|[a-z0-9-]+\.pipedream\.net|[a-z0-9-]+\.ngrok(?:-free)?\.(?:app|io|dev)|interact\.sh|[a-z0-9-]+\.oast\.(?:fun|live|me|online|pro|site)|burpcollaborator\.net|canarytokens\.(?:com|org)|discord(?:app)?\.com\/api\/webhooks|hooks\.slack\.com\/services|pastebin\.com|transfer\.sh|0x0\.st|requestcatcher\.com|beeceptor\.com|hookbin\.com|ptsv[23]\.com|postb\.in)\b/i;
267
+ /(?:^|[^a-z0-9.-])((?:[a-z0-9-]{1,63}\.){0,8}(?:webhook\.site|requestbin\.(?:com|net)|pipedream\.net|ngrok(?:-free)?\.(?:app|io|dev)|interact\.sh|oast\.(?:fun|live|me|online|pro|site)|burpcollaborator\.net|canarytokens\.(?:com|org)|discord(?:app)?\.com\/api\/webhooks|hooks\.slack\.com\/services|pastebin\.com|transfer\.sh|0x0\.st|requestcatcher\.com|beeceptor\.com|hookbin\.com|ptsv[23]\.com|postb\.in))\b/i;
92
268
  const RX_OVERRIDE =
93
- /\b(?:ignore|disregard|forget|override)\b[^.\n]{0,40}\b(?:previous|prior|above|earlier|system|safety|your|developer)\b[^.\n]{0,20}\b(?:instructions?|rules|prompts?|guidelines|guardrails)\b|\bdo not (?:tell|inform|alert|notify|show|mention (?:this|it) to) the user\b|\bwithout (?:asking|telling|notifying|confirmation|consent|permission)\b|\bnever ask (?:the user )?(?:for )?(?:permission|confirmation|approval)\b|\b(?:always|automatically) (?:approve|accept|allow)\b|\b(?:disable|turn off|bypass|skip)\b[^.\n]{0,20}\b(?:sandbox|approvals?|permissions?|confirmations?|safety checks?|guardrails)\b/gi;
269
+ /\b(?:ignore|disregard|forget|override)\b[^.\n]{0,40}\b(?:previous|prior|above|earlier|preceding|system|safety|developer)\b[^.\n]{0,20}\b(?:instructions?|rules|prompts?|guidelines|guardrails)\b|\bdo not (?:tell|inform|alert|notify|show|mention (?:this|it) to) the user\b|\bwithout (?:telling|informing|notifying|alerting) the user\b|\bwithout the user(?:'s)? (?:knowing|knowledge|noticing|consent|permission)\b|\bnever ask (?:the user )?(?:for )?(?:permission|confirmation|approval)\b|\b(?:always|automatically|auto-)\s?(?:approve|accept|allow)\s+(?:all\s+|every\s+|any\s+)?(?:the\s+)?(?:tools?(?: (?:calls?|use|uses|requests?))?|commands?|actions?|edits?|file changes|changes|permissions?|permission (?:prompts|requests)|confirmations?|prompts|everything)\b|\b(?:disable|turn off|bypass|skip)\b[^.\n]{0,20}\b(?:sandbox|approvals?|permissions?|confirmations?|safety checks?|guardrails)\b/gi;
94
270
  const RX_SECRET_ACCESS =
95
- /\b(?:cat|read|print|output|copy|send|upload|post|include|paste|exfiltrat\w*|grab|collect|dump)\b[^\n]{0,60}(?:~\/\.ssh|\bid_rsa\b|\bid_ed25519\b|\.aws\/credentials|\.env\b|\.npmrc|\.git-credentials|auth\.json|\.credentials\.json|keychain|browser (?:cookies|passwords))/ig;
271
+ /\b(?:cat|read|print|output|copy|send|upload|post|include|paste|exfiltrat\w*|grab|collect|dump)\b[^\n]{0,60}(?:~\/\.ssh|\bid_rsa\b|\bid_ed25519\b|\.aws\/credentials|(?:^|[\s"'`(\[/=:,])\.env\b|\.npmrc|\.git-credentials|\bauth\.json|\.credentials\.json|keychain|browser (?:cookies|passwords))/ig;
96
272
  const RX_INJECT_WORDS =
97
273
  /\b(?:ignore|disregard|override|secretly|silently|quietly|without (?:asking|telling)|do not (?:tell|mention|reveal|ask)|exfiltrat\w*|curl|wget|upload|send (?:it|this|the|them|all|everything)|token|api key|password|ssh|credentials?|base64|you are now|new instructions)\b/i;
98
274
  const RX_BENIGN_COMMENT = /^\s*(?:markdownlint|prettier|toc|end ?toc|eslint|cspell|vale|begin|end|lint|todo|fixme|note)\b/i;
99
- const RX_DANGER_FLAGS =
100
- /--dangerously-skip-permissions|--allow-dangerously-skip-permissions|--dangerously-bypass-approvals-and-sandbox|--permission-mode[= ]+["']?bypassPermissions|--approval-mode[= ]+["']?yolo|\b(?:codex|gemini|qwen)\b[^\n]{0,80}\s--yolo\b|\bgemini\b[^\n]{0,80}\s-y\b/i;
101
275
  const RX_IMPORT_OUTSIDE = /(?:^|\s)@((?:~\/|\.\.\/|[A-Za-z]:[\\/]|\/(?:Users|home|etc|tmp|var|opt|root|mnt)\/)[^\s)\]]+)/g;
102
- const RX_BLOB = /[A-Za-z0-9+/]{300,}={0,2}/;
276
+ const RX_BASE64_RUN = /[A-Za-z0-9+/]+={0,2}/g;
103
277
  const RX_DIRECTIVE = /\byou are (?:an?|the) (?:ai|assistant|agent|coding)|\bas an ai\b|\bsystem prompt\b|\b(?:claude|codex|copilot|cursor|gemini|the agent|assistant)\b[^.\n]{0,40}\b(?:must|should|always|never)\b|\binstructions? for (?:the )?(?:ai|agent|assistant|llm)\b/i;
278
+ // Paste sites, where text can change after anyone has looked at it.
279
+ // pastebin.com is reported as a data-collection endpoint instead.
280
+ const RX_PASTE_SITE =
281
+ /(?:^|[^a-z0-9.-])((?:[a-z0-9-]{1,63}\.){0,3}(?:glot\.io|paste\.ee|hastebin\.(?:com|skyra\.pw)|rentry\.(?:co|org)|ghostbin\.[a-z]{2,6}|termbin\.com|dpaste\.(?:com|org)|paste\.rs|controlc\.com|justpaste\.it|pastes\.dev|privatebin\.net))(?![a-z0-9-])/i;
282
+ // Telling the agent to take its instructions from a web page: "follow the
283
+ // steps at https://...", or "fetch https://... and do what it says". Whoever
284
+ // runs the page decides what the agent does, after the file was reviewed.
285
+ const RX_REMOTE_INSTRUCTIONS =
286
+ /\b(?:follow|obey|apply|carry out|execute|run|do)\b[^.\n]{0,40}?\b(?:instructions|steps|commands|directions|rules|guidance)\b[^.\n]{0,30}?\b(?:at|in|from|on)\s+<?https?:\/\/([a-z0-9.-]{1,253})|\b(?:fetch|read|load|open|download|get|visit|retrieve|curl|browse to|go to)\s+<?https?:\/\/([a-z0-9.-]{1,253})[^\s)>]{0,200}>?[^.\n]{0,80}?\b(?:and|then)\s+(?:follow|obey|apply|carry out|execute|do what|run what|run)\b[^.\n]{0,30}?\b(?:instructions|steps|commands|it says|they say|the page says|what it says|says|there|them|it)\b/i;
287
+ // A download that needs a password, the way malware hides from scanners.
288
+ // It has to give the password, as lures do: talking about password-protected
289
+ // archives isn't asking for one.
290
+ const ARCHIVE = String.raw`(?:\.(?:zip|7z|rar)\b|\b(?:zip|7z|rar|archive)\b)`;
291
+ const PASSWORD_GIVEN = String.raw`\b(?:password|passphrase|passwd)\b(?:\s*(?:is|:|=)\s*|\s+(?=["'\`“]))["'\`“]?([^\s"'\`”]{2,40})`;
292
+ const RX_ARCHIVE_PASSWORD = new RegExp(
293
+ [
294
+ `${ARCHIVE}[^\\n]{0,120}(?:\\n[^\\n]{0,80})?${PASSWORD_GIVEN}`,
295
+ `${PASSWORD_GIVEN}[^\\n]{0,80}(?:\\n[^\\n]{0,80})?${ARCHIVE}`,
296
+ String.raw`\bunzip\s+(?:-\w+\s+)*-P\s*\S+`,
297
+ String.raw`\b7z\s+[ex]\b[^\n]{0,80}\s-p\S+`,
298
+ ].join("|"),
299
+ "i",
300
+ );
301
+ // A lure gives the password and says to download, extract or run the file.
302
+ // "The password is in 1Password", a login password, or "move it to the
303
+ // archive folder" doesn't.
304
+ const NOT_A_PASSWORD = new Set(["in", "on", "at", "the", "a", "an", "your", "my", "our", "their", "its", "this", "that", "stored", "kept", "saved", "required", "needed", "set", "not", "available", "managed", "provided", "shared", "sent", "given", "see", "ask", "from", "via", "under", "below", "above", "same", "there", "here", "located", "written", "listed", "unknown", "optional", "empty", "blank", "none", "n/a", "changed", "rotated", "reset", "expired", "correct", "wrong", "invalid", "missing"]);
305
+ const NOT_A_GIVEN_PASSWORD = new Set(["see", "ask", "none", "n/a", "in", "your", "the"]);
306
+ const LURE_VERB = /\b(?:download|extract|unzip|unpack|decompress|open|run|install|launch|execute)/i;
307
+ const LOGIN = /\b(?:log\s?in|sign\s?in|user(?:name)?|account|admin|database|db|ssh|mysql|postgres|redis|wi-?fi)\b/i;
308
+ function givesArchivePassword(text, m) {
309
+ // unzip -P and 7z -p extract with a password: a lure on their own.
310
+ if (/^(?:unzip|7z)\b/i.test(m[0])) return true;
311
+ const value = (m[1] ?? m[2] ?? "").replace(/[.,;:!?)\]]+$/, "").toLowerCase();
312
+ const stated = /\bpass(?:word|phrase|wd)\s+is\s/i.test(m[0]);
313
+ if (value && (stated ? NOT_A_PASSWORD : NOT_A_GIVEN_PASSWORD).has(value)) return false;
314
+ const word = m[0].search(/\b(?:password|passphrase|passwd)\b/i);
315
+ if (LOGIN.test(sameLineBefore(text, m.index + Math.max(0, word), 60))) return false;
316
+ const from = Math.max(0, m.index - 200);
317
+ const window = text.slice(from, Math.min(text.length, m.index + m[0].length + 200));
318
+ return LURE_VERB.test(window);
319
+ }
320
+ // Removing macOS's quarantine flag or turning off Gatekeeper.
321
+ // Clearing every attribute is also a step before code signing, so that only
322
+ // counts on something in Downloads.
323
+ const RX_QUARANTINE = /\bxattr\s+(?:-[a-z]{1,8}\s+){0,4}com\.apple\.quarantine\b|\bxattr\s+-[a-z]{0,6}c[a-z]{0,6}\s[^\n]{0,60}\bDownloads\b|\bspctl\s+--(?:master|global)-disable\b|--no-quarantine\b/i;
324
+ // Servers named in attack reports, as hosts or addresses in any agent file.
325
+ const RX_KNOWN_BAD_HOST = new RegExp(
326
+ // No lookbehind, so the engine also loads in older Safari.
327
+ `(?:^|[^\\w.-])((?:[a-z0-9-]{1,63}\\.){0,4}?(${Object.keys(KNOWN_BAD_HOSTS).map((h) => h.replace(/[.]/g, "\\.")).join("|")}))(?![\\w-]|\\.\\w)`,
328
+ "i",
329
+ );
330
+ // The lists in a file whose names say they block things, such as
331
+ // permissions.deny in Claude Code's settings or a TOML deny = [...], as
332
+ // [start, end] spans. Found once per file, and brackets inside quoted
333
+ // entries don't end a list.
334
+ function blockSpans(text) {
335
+ const spans = [];
336
+ for (const m of text.matchAll(/["']?([\w.-]{1,60})["']?\s*[:=]\s*\[/g)) {
337
+ if (!/deny|block|disallow|forbid|exclude|reject|ban/i.test(m[1])) continue;
338
+ const start = m.index + m[0].length;
339
+ if (spans.length && start < spans.at(-1)[1]) continue;
340
+ let quote = null;
341
+ let depth = 1;
342
+ let i = start;
343
+ for (; i < text.length && depth > 0; i++) {
344
+ const c = text[i];
345
+ if (quote) {
346
+ if (c === "\\") i++;
347
+ else if (c === quote) quote = null;
348
+ } else if (c === '"' || c === "'") quote = c;
349
+ else if (c === "[") depth++;
350
+ else if (c === "]") depth--;
351
+ }
352
+ spans.push([start, i]);
353
+ }
354
+ return spans;
355
+ }
356
+ const RX_KNOWN_BAD_HOSTS = new RegExp(RX_KNOWN_BAD_HOST.source, "gi");
357
+ // The first mention of a known malware server that's a real use: not on a
358
+ // block list and not warned against. Every mention is looked at, so warnings
359
+ // and block-list entries can't hide a use after them.
360
+ function knownBadHost(text) {
361
+ const content = String(text ?? "");
362
+ let spans = null;
363
+ let at = 0;
364
+ for (const m of content.matchAll(RX_KNOWN_BAD_HOSTS)) {
365
+ const index = m.index + m[0].length - m[1].length;
366
+ spans ??= blockSpans(content);
367
+ while (at < spans.length && spans[at][1] <= index) at++;
368
+ if (at < spans.length && spans[at][0] <= index) continue;
369
+ if (negated(content, index)) continue;
370
+ return { index, host: m[2].toLowerCase(), campaign: KNOWN_BAD_HOSTS[m[2].toLowerCase()] };
371
+ }
372
+ return null;
373
+ }
104
374
  const SHELL_SERVER = /(?:^|[-_/@.])(?:shell|terminal|exec|executor|commands?|cmd|desktop-commander|ssh|powershell|bash|zsh|run-command)(?:[-_.]|$)/i;
105
375
 
106
376
  // --- Entry point -------------------------------------------------------------
107
377
 
108
378
  export function analyze(input) {
109
379
  const ctx = buildContext(input ?? {});
110
- collectMcpServers(ctx);
380
+ // A file that trips up a check is reported as unchecked. It can't stop
381
+ // the rest of the report.
382
+ const guard = (f, check) => {
383
+ try {
384
+ check();
385
+ } catch {
386
+ f.failed = true;
387
+ }
388
+ };
389
+ for (const f of ctx.files) if (f.content) guard(f, () => collectMcpServers(ctx, f));
390
+ for (const f of ctx.files) if (f.content) guard(f, () => checkFile(ctx, f));
111
391
  for (const f of ctx.files) {
112
- if (!f.content) continue;
113
- if (/(^|\/)(\.claude\/settings(\.local)?|managed-settings)\.json$/i.test(f.path)) checkClaudeSettings(ctx, f);
114
- else if (/(^|\/)\.claude\.json$/i.test(f.path)) checkClaudeUserConfig(ctx, f);
115
- else if (/(^|\/)\.codex\/config\.toml$/i.test(f.path)) checkCodex(ctx, f);
116
- else if (/(^|\/)\.gemini\/settings\.json$/i.test(f.path)) checkGemini(ctx, f);
117
- else if (/(^|\/)(\.vscode|(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User)\/settings\.json$/i.test(f.path)) checkVSCode(ctx, f);
118
- else if (/(^|\/)opencode\.jsonc?$/i.test(f.path)) checkOpenCode(ctx, f);
119
- else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(f.path)) checkZed(ctx, f);
120
- else if (f.kind === "Shell profile") checkShellProfile(ctx, f);
121
- else if (/(^|\/)\.aider\.conf\.ya?ml$/i.test(f.path)) checkAider(ctx, f);
122
- else if (/^package\.json$/i.test(f.path)) checkPackageJson(ctx, f);
123
-
124
- if (/(^|\/)\.claude\/hooks\//i.test(f.path)) checkHookScript(ctx, f);
125
- else if (isInstructionFile(f)) checkInstructionText(ctx, f);
126
- }
127
- for (const server of ctx.mcpServers) checkMcpServer(ctx, server);
128
- const enabled = ctx.mcpServers.filter((s) => !s.disabled).length;
129
- if (enabled > 12) add(ctx, "MCP-MANY", { vars: { count: enabled } });
392
+ if (f.content && f.kind && (f.failed || (/\.(jsonc?|toml)$/i.test(f.path) && parsed(f) == null))) add(ctx, "WS-UNPARSED", { file: f });
393
+ }
394
+ for (const server of ctx.mcpServers) guard(server.file, () => checkMcpServer(ctx, server));
395
+ // Each agent's servers, wherever it reads them from. Servers that belong
396
+ // to different agents aren't all in front of any one of them.
397
+ // Agents that read the same file, such as Claude Code and Copilot with
398
+ // .mcp.json, are reported once.
399
+ const perAgent = new Map();
400
+ for (const s of ctx.mcpServers) {
401
+ if (s.disabled) continue;
402
+ for (const t of s.file.tools ?? []) perAgent.set(t, [...(perAgent.get(t) ?? []), `${s.file.path}#${s.name}`]);
403
+ }
404
+ const reported = new Set();
405
+ for (const [tool, servers] of perAgent) {
406
+ const key = servers.sort().join("\n");
407
+ if (servers.length <= 12 || reported.has(key)) continue;
408
+ reported.add(key);
409
+ add(ctx, "MCP-MANY", { tool, vars: { tool, count: servers.length } });
410
+ }
130
411
  checkWorkspace(ctx);
131
412
  checkSprawl(ctx);
413
+ checkExtensions(ctx);
414
+ checkInstalls(ctx);
415
+ checkLocked(ctx);
416
+ checkTraces(ctx);
417
+ checkSkillPrograms(ctx);
418
+ checkPluginCode(ctx);
419
+ checkAutorun(ctx);
420
+ checkNamed(ctx);
132
421
  return summarize(ctx);
133
422
  }
134
423
 
424
+ function checkFile(ctx, f) {
425
+ const p = f.path;
426
+ if (/(^|\/)(\.claude\/settings(\.local)?\.json|managed-settings(\.d\/[^/]+)?\.json)$/i.test(p)) checkClaudeSettings(ctx, f);
427
+ else if (/(^|\/)\.claude\/plugins\/.+\/hooks\/hooks\.json$/i.test(p) || f.role === "claude-hooks") checkClaudeHooks(ctx, f, hooksOf(parsed(f)));
428
+ else if (/(^|\/)\.claude-plugin\/plugin\.json$/i.test(p)) checkClaudeHooks(ctx, f, hooksOf(parsed(f)?.hooks));
429
+ else if (/(^|\/)\.claude\.json$/i.test(p)) checkClaudeUserConfig(ctx, f);
430
+ else if (/(^|\/)\.codex\/([^/]+\.)?config\.toml$/i.test(p)) checkCodex(ctx, f);
431
+ else if (/(^|\/)(\.gemini|gemini-cli|GeminiCli)\/(system-)?settings\.json$/i.test(p)) checkGemini(ctx, f);
432
+ else if (/(^|\/)\.gemini\/trustedFolders\.json$/i.test(p)) checkTrustedFolders(ctx, f, "Gemini CLI", geminiTrusted(parsed(f)));
433
+ else if (/(^|\/)\.copilot\/config\.json$/i.test(p)) checkTrustedFolders(ctx, f, "GitHub Copilot", copilotTrusted(parsed(f)));
434
+ else if (/(^|\/)\.github\/hooks\/[^/]+\.json$/i.test(p)) checkJsonHooks(ctx, f, "A GitHub Copilot hook");
435
+ else if (/(^|\/)\.cursor\/hooks\.json$/i.test(p)) checkJsonHooks(ctx, f, "A Cursor hook");
436
+ else if (/(^|\/)\.cursor\/environment\.json$/i.test(p)) checkCursorEnvironment(ctx, f);
437
+ else if (/(^|\/)\.vscode\/tasks\.json$/i.test(p)) checkVsCodeTasks(ctx, f);
438
+ else if (/(^|\/)\.codex\/hooks\.json$/i.test(p)) checkJsonHooks(ctx, f, "A Codex hook");
439
+ else if (/(^|\/)\.codex\/rules\/[^/]+\.rules$/i.test(p)) checkCodexRules(ctx, f);
440
+ else if (/(^|\/)((\.windsurf|\.codeium\/windsurf)\/hooks|\.devin\/hooks\.v1)\.json$/i.test(p)) checkJsonHooks(ctx, f, "A Windsurf hook");
441
+ else if (/(^|\/)\.kiro\/hooks\//i.test(p)) checkJsonHooks(ctx, f, "A Kiro hook");
442
+ else if (/(^|\/)\.kiro\/agents\/[^/]+\.json$/i.test(p)) checkAgentFile(ctx, f, "A Kiro hook");
443
+ else if (/(^|\/)\.?amazonq\/cli-agents\//i.test(p)) checkAgentFile(ctx, f, "An Amazon Q hook");
444
+ else if (/(^|\/)\.grok\/hooks\//i.test(p)) checkJsonHooks(ctx, f, "A Grok hook");
445
+ else if (/(^|\/)\.cursor\/(cli-config|cli)\.json$/i.test(p)) checkCursorCli(ctx, f);
446
+ else if (/(^|\/)\.cursor\/sandbox\.json$/i.test(p)) checkCursorSandbox(ctx, f);
447
+ else if (/(^|\/)(\.vscode|(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User)\/settings\.json$/i.test(p)) checkVSCode(ctx, f);
448
+ else if (/(^|\/)opencode\.jsonc?$/i.test(p)) checkOpenCode(ctx, f);
449
+ else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(p)) checkZed(ctx, f);
450
+ else if (/(^|\/)\.cline\/data\/globalState\.json$/i.test(p)) checkCline(ctx, f);
451
+ else if (/(^|\/)\.grok\/config\.toml$/i.test(p)) checkGrok(ctx, f);
452
+ else if (/(^|\/)(\.amp|\.config\/amp)\/settings\.json$/i.test(p)) checkAmp(ctx, f);
453
+ else if (/(^|\/)goose\/config\.ya?ml$/i.test(p)) checkGoose(ctx, f);
454
+ else if (/(^|\/)\.continue\/(?:.+\/)?[^/]+\.(?:ya?ml|json)$/i.test(p)) checkContinue(ctx, f);
455
+ else if (f.kind === "Shell profile") checkShellProfile(ctx, f);
456
+ else if (/(^|\/)\.aider\.conf\.ya?ml$/i.test(p)) checkAider(ctx, f);
457
+ else if (/^package\.json$/i.test(p)) checkPackageJson(ctx, f);
458
+ else if (/(^|\/)\.claude\/plugins\/known_marketplaces\.json$/i.test(p)) checkMarketplaces(ctx, f);
459
+ else if (/(^|\/)\.github\/workflows\//i.test(p)) checkWorkflowTrace(ctx, f);
460
+
461
+ const bad = knownBadHost(f.content);
462
+ if (bad) {
463
+ const line = lineAt(f.content, bad.index);
464
+ add(ctx, "TXT-KNOWN-C2", { file: f, line, evidence: evidenceLine(f, line), vars: { host: bad.host, campaign: bad.campaign } });
465
+ }
466
+
467
+ if (/(^|\/)\.claude\/hooks\//i.test(f.path)) checkHookScript(ctx, f);
468
+ else if (isInstructionFile(f)) checkInstructionText(ctx, f);
469
+ }
470
+
471
+ // Claude Code hooks, written as { hooks: { Event: [...] } } in hooks.json, or
472
+ // as { Event: [...] } inside a plugin's plugin.json.
473
+ const hooksOf = (json) => (isObj(json?.hooks) ? json.hooks : isObj(json) ? json : null);
474
+
135
475
  // --- Context -----------------------------------------------------------------
136
476
 
137
477
  function buildContext(input) {
@@ -139,54 +479,112 @@ function buildContext(input) {
139
479
  const seenPaths = new Set();
140
480
  for (const raw of Array.isArray(input.files) ? input.files : []) {
141
481
  if (!raw || typeof raw.path !== "string") continue;
142
- const path = cleanPath(raw.path);
143
- if (!path || seenPaths.has(path)) continue;
144
- seenPaths.add(path);
482
+ const cleaned = cleanPath(raw.path);
483
+ if (!cleaned || seenPaths.has(cleaned)) continue;
484
+ seenPaths.add(cleaned);
485
+ const path = visibleName(cleaned);
145
486
  const file = {
146
487
  path,
147
488
  size: toInt(raw.size),
148
489
  sensitive: raw.sensitive === true,
149
490
  tooLarge: raw.tooLarge === true,
150
491
  loose: raw.loose === true,
492
+ // A program inside a skill folder, listed by name and never read.
493
+ listed: raw.listed === true,
494
+ // A link the command didn't follow: to a file outside the project, or
495
+ // to a credential file.
496
+ linked: raw.linked === "outside" || raw.linked === "secret" ? raw.linked : null,
497
+ // Too large to read whole, so only its start was read.
498
+ partial: raw.partial === true,
499
+ // A link to a folder, listed by the command and never followed.
500
+ folder: raw.folder === true && raw.linked === "outside",
501
+ // Set by the command for a plugin's hooks or MCP servers kept at a
502
+ // path its plugin.json names.
503
+ role: raw.role === "claude-hooks" || raw.role === "mcp-servers" ? raw.role : null,
151
504
  };
152
- if (typeof raw.content === "string" && !file.sensitive) {
153
- file.content = maskSecrets(raw.content.slice(0, MAX_FILE_CHARS)).text;
505
+ // Files past the size limit are listed as too large rather than half checked.
506
+ if (typeof raw.content === "string" && raw.content.length > MAX_FILE_CHARS) file.tooLarge = true;
507
+ else if (typeof raw.content === "string" && !file.sensitive && !file.listed && !file.linked) {
508
+ file.content = maskSecrets(raw.content).text;
154
509
  file.lines = file.content.split(/\r?\n/);
155
510
  }
156
- const control = controlFor(path);
511
+ const control = controlFor(path) ?? (file.role ? { tools: ["Claude Code"], kind: file.role === "claude-hooks" ? "Plugin hooks" : "Plugin MCP servers" } : null);
157
512
  file.tools = control ? control.tools : file.loose ? ["Any agent started there"] : [];
158
513
  file.kind = control ? control.kind : file.loose ? "Loose file" : null;
159
514
  files.push(file);
160
515
  }
516
+ // Files that settings name as instructions, such as Gemini CLI's
517
+ // context.fileName, are instructions for that agent whatever their name.
518
+ const named = namedInstructions(files.filter((f) => f.content && NAMING_SETTINGS.some((re) => re.test(f.path))));
519
+ for (const f of files) {
520
+ if ((f.kind && !f.loose) || f.sensitive || f.listed || f.linked || !f.content) continue;
521
+ const hit = named.find((n) => n.test(f.path));
522
+ if (!hit) continue;
523
+ f.kind = "Instructions";
524
+ f.tools = [hit.tool];
525
+ f.loose = false;
526
+ f.named = true;
527
+ }
161
528
  const shape = input.shape && typeof input.shape === "object" ? input.shape : {};
529
+ const topLevel = Array.isArray(shape.topLevel) ? shape.topLevel.filter((s) => typeof s === "string").slice(0, 200) : [];
162
530
  return {
163
531
  root: typeof input.root === "string" ? input.root.slice(0, 120) : null,
164
532
  files,
165
533
  shape: {
166
534
  entries: toInt(shape.entries),
167
- topLevel: Array.isArray(shape.topLevel) ? shape.topLevel.filter((s) => typeof s === "string").slice(0, 200) : [],
535
+ topLevel,
168
536
  rootGit: shape.rootGit === true,
169
537
  gitRepos: toInt(shape.gitRepos),
170
538
  truncated: shape.truncated === true,
171
539
  },
540
+ // git's own ignore lists, read by the command: .git/info/exclude and
541
+ // the global list in ~/.config/git/ignore. Text only, never shown.
542
+ ignoreLists: (Array.isArray(input.ignoreLists) ? input.ignoreLists : [])
543
+ .filter((l) => typeof l?.content === "string")
544
+ .slice(0, 4)
545
+ .map((l) => l.content.slice(0, 64 * 1024)),
172
546
  maskedInBrowser: toInt(input.masked?.count),
547
+ // Found by the command on this computer: agent installs, editor
548
+ // extensions and files attacks leave. Each is checked against what
549
+ // known.js expects, so nothing else can get through.
550
+ installs: installsFrom(input.installs),
551
+ locked: lockedFrom(input.locked),
552
+ extensions: extensionsFrom(input.extensions),
553
+ traces: new Set((Array.isArray(input.traces) ? input.traces : []).filter((p) => typeof p === "string" && TRACE_PATHS.has(p))),
554
+ packages: [],
555
+ homeLike: topLevel.filter((n) => HOME_MARKERS.has(n)).length >= 3,
556
+ // Glob matching work allowed for the whole check.
557
+ ignoreBudget: { left: 8_000_000 },
173
558
  findings: [],
174
559
  seen: new Set(),
175
560
  mcpServers: [],
176
561
  claudeDeny: [],
177
562
  claudeSettingsFiles: [],
563
+ // Project files whose settings run commands on their own: the first one each.
564
+ autorun: new Map(),
565
+ named,
178
566
  };
179
567
  }
180
568
 
181
569
  function cleanPath(p) {
182
570
  const unix = p.replace(/\\/g, "/");
183
571
  const parts = unix.split("/").filter((s) => s && s !== ".");
184
- if (!parts.length || parts.includes("..") || parts.join("/").length > 400) return null;
572
+ // As long as a path can be. Shorter would let a deep folder hide a file.
573
+ if (!parts.length || parts.includes("..") || parts.join("/").length > 4096) return null;
185
574
  // Keep the leading slash of system files such as /etc/claude-code/managed-settings.json.
186
575
  return (unix.startsWith("/") ? "/" : "") + parts.join("/");
187
576
  }
188
577
 
189
- const toInt = (n) => (Number.isFinite(Number(n)) ? Math.max(0, Math.floor(Number(n))) : 0);
578
+ // Strings and numbers from a JSON list, as text. Anything else is dropped.
579
+ const scalars = (x) => (Array.isArray(x) ? x.filter((v) => typeof v === "string" || typeof v === "number").map(String) : []);
580
+ // A value from a settings file as text, or "" when it isn't a string, number or boolean.
581
+ const asText = (v) => (typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : "");
582
+ // Only numbers and number strings count: Number() on an object can call its
583
+ // own conversion code or throw.
584
+ const toInt = (n) => {
585
+ const x = typeof n === "number" || typeof n === "string" ? Number(n) : NaN;
586
+ return Number.isFinite(x) ? Math.max(0, Math.floor(x)) : 0;
587
+ };
190
588
  const arr = (x) => (Array.isArray(x) ? x.filter((s) => typeof s === "string") : []);
191
589
  const isObj = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
192
590
  const clip = (s, n = 180) => {
@@ -195,9 +593,9 @@ const clip = (s, n = 180) => {
195
593
  };
196
594
 
197
595
  function isInstructionFile(f) {
198
- if (f.loose) return true;
596
+ if (f.loose || f.named) return true;
199
597
  if (!f.kind) return false;
200
- return /\.(md|mdc|txt)$/i.test(f.path) || /(^|\/)\.(cursorrules|windsurfrules|clinerules)$/i.test(f.path) || /(^|\/)\.clinerules\//i.test(f.path);
598
+ return /\.(md|mdc|txt)$/i.test(f.path) || /(^|\/)\.gemini\/commands\/.+\.toml$/i.test(f.path) || /(^|\/)\.(cursorrules|windsurfrules|clinerules|goosehints)$/i.test(f.path) || /(^|\/)\.clinerules\//i.test(f.path);
201
599
  }
202
600
 
203
601
  // The line that names a folder as a key. Quoted first, so "~" doesn't match
@@ -212,20 +610,78 @@ function lineOf(file, test) {
212
610
  return idx >= 0 ? idx + 1 : 0;
213
611
  }
214
612
 
215
- const NEGATED = /\b(?:never|don['’]t|do not|does not|must not|mustn['’]t|should not|shouldn['’]t|avoid|refuse to|forbidden|prohibited|no need to)\b[^.!?\n]{0,30}$/i;
613
+ // The first line at or after `from` that matches, else the first anywhere.
614
+ // Two servers can use the same package or key; each finding should point at
615
+ // its own server's lines.
616
+ function lineAfter(file, test, from) {
617
+ if (!file.lines || !from) return lineOf(file, test);
618
+ const idx = file.lines.findIndex((line, i) => i >= from - 1 && (typeof test === "string" ? line.includes(test) : test.test(line)));
619
+ return idx >= 0 ? idx + 1 : lineOf(file, test);
620
+ }
621
+
622
+ // The warning has to reach the match: a sentence end, a semicolon or a word
623
+ // like "instead" or "then" starts something new. A dot inside a name, as in
624
+ // paste.ee, doesn't.
625
+ const NEGATED = /\b(?:never|don['’]t|do not|does not|must not|mustn['’]t|should not|shouldn['’]t|avoid|refuse to|forbidden|prohibited|no need to)\b(?:(?!\b(?:but|instead|then|rather|except|however)\b)(?:[^.!?;\n]|\.(?=\w))){0,40}$/i;
626
+
627
+ // True when the words just before `index`, on the same line, warn against it.
628
+ function negated(text, index) {
629
+ return NEGATED.test(sameLineBefore(text, index, 60));
630
+ }
631
+
632
+ // Up to `max` characters before `index`, back to the start of its line. Only
633
+ // that much is looked at, so many matches on one long line stay fast.
634
+ function sameLineBefore(text, index, max) {
635
+ const before = text.slice(Math.max(0, index - max), index);
636
+ return before.slice(before.lastIndexOf("\n") + 1);
637
+ }
216
638
 
217
- function firstMatch(text, re, affirmative) {
639
+ function firstMatch(text, re, affirmative, reject) {
218
640
  const global = new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g");
219
641
  for (const m of text.matchAll(global)) {
220
- if (affirmative) {
221
- const lineStart = text.lastIndexOf("\n", m.index) + 1;
222
- if (NEGATED.test(text.slice(Math.max(lineStart, m.index - 60), m.index))) continue;
223
- }
642
+ if (affirmative && negated(text, m.index)) continue;
643
+ if (reject && reject(m)) continue;
224
644
  return m;
225
645
  }
226
646
  return null;
227
647
  }
228
648
 
649
+ // True when a match is quoted as an example rather than said: it follows
650
+ // "e.g." or "such as", or sits inside quotes.
651
+ function quotedExample(text, m, quotes) {
652
+ const before = text.slice(Math.max(0, m.index - 24), m.index);
653
+ if (/(?:e\.g\.|i\.e\.|for example|such as|like)[,:]?\s*["'“‘(`]?\s*$/i.test(before)) return true;
654
+ const open = before.match(/(\S)\s*$/)?.[1];
655
+ if (!open || !quotes.includes(open)) return false;
656
+ const close = { "“": "”", "‘": "’" }[open] ?? open;
657
+ const after = text.slice(m.index + m[0].length, m.index + m[0].length + 40);
658
+ const end = after.indexOf(close);
659
+ if (end < 0 || end > 30 || after.slice(0, end).includes("\n")) return false;
660
+ // Quotes alone don't make an example: the sentence has to say it's one.
661
+ return RX_EXAMPLE_CONTEXT.test(sameLineBefore(text, m.index, 120));
662
+ }
663
+ const RX_EXAMPLE_CONTEXT =
664
+ /\b(?:if|contains?|says?|such as|phrases?|text|attacks?|injections?|untrusted|examples?|patterns?|watch for|look for|don't follow|do not follow|never follow|ignore requests)\b/i;
665
+
666
+ // True when a match sits in a code block that the text just before it
667
+ // introduces as an example, as in "An injection looks like this:".
668
+ function fencedExample(text, index, fence) {
669
+ const block = fence(index);
670
+ return block !== null && RX_EXAMPLE_CONTEXT.test(text.slice(Math.max(0, block[0] - 160), block[0]));
671
+ }
672
+
673
+ // The first run of 300 or more base64 characters, skipping images embedded
674
+ // as data: URLs.
675
+ function longBase64(text) {
676
+ RX_BASE64_RUN.lastIndex = 0;
677
+ for (let m = RX_BASE64_RUN.exec(text); m; m = RX_BASE64_RUN.exec(text)) {
678
+ if (m[0].length < 300) continue;
679
+ if (/data:image\/[\w.+-]+;base64,$/i.test(text.slice(Math.max(0, m.index - 40), m.index))) continue;
680
+ return { index: m.index, length: m[0].length };
681
+ }
682
+ return null;
683
+ }
684
+
229
685
  function lineAt(text, index) {
230
686
  let n = 1;
231
687
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
@@ -236,16 +692,21 @@ function evidenceLine(file, line) {
236
692
  return line && file.lines ? clip(file.lines[line - 1] ?? "") : undefined;
237
693
  }
238
694
 
239
- function add(ctx, id, { file, line = 0, evidence, vars = {}, tool } = {}) {
695
+ function add(ctx, id, opts = {}) {
696
+ const { file, line = 0, vars = {} } = opts;
697
+ const key = [id, file?.path ?? null, line, ...["server", "key", "rule", "place", "ext", "pkg", "known", "name", "skill", "campaign", "path"].map((k) => vars[k] ?? "")].join("|");
698
+ if (ctx.seen.has(key)) return;
699
+ ctx.seen.add(key);
700
+ ctx.findings.push(makeFinding(id, opts));
701
+ }
702
+
703
+ function makeFinding(id, { file, line = 0, evidence, vars = {}, tool } = {}) {
240
704
  const rule = RULES[id];
241
705
  if (!rule) throw new Error(`Unknown rule ${id}`);
242
706
  const filePath = file?.path ?? null;
243
- const key = `${id}|${filePath}|${line}|${vars.server ?? ""}|${vars.key ?? ""}|${vars.rule ?? ""}|${vars.place ?? ""}`;
244
- if (ctx.seen.has(key)) return;
245
- ctx.seen.add(key);
246
707
  const values = Object.fromEntries(Object.entries({ file: filePath ?? "", ...vars }).map(([k, v]) => [k, String(v ?? "")]));
247
708
  const fill = (text) => fillTemplate(text, values);
248
- ctx.findings.push({
709
+ return {
249
710
  id,
250
711
  severity: rule.severity,
251
712
  category: rule.category,
@@ -257,21 +718,51 @@ function add(ctx, id, { file, line = 0, evidence, vars = {}, tool } = {}) {
257
718
  line: line || null,
258
719
  evidence: evidence ? describeMasks(clip(evidence, 220)) : null,
259
720
  vars: values,
260
- });
721
+ };
261
722
  }
262
723
 
263
724
  function fillTemplate(text, values) {
264
- return text.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? "");
725
+ return text.replace(/\{(\w+)\}/g, (_, k) => {
726
+ const v = values[k] ?? "";
727
+ if (FROM_FILES.has(k)) return fileValue(v, k);
728
+ // "where" is a fixed phrase that can quote a name, as in The “deploy” script.
729
+ if (k === "where") return v.replace(/“([^”]*)”/g, (_, name) => `“${fileValue(name, "server")}”`);
730
+ return v;
731
+ });
265
732
  }
266
733
 
267
- // Parts of a finding that quote file contents or reveal local paths. Shared
268
- // reports replace them, so a public link shows the issue without the details.
269
- const PRIVATE_VARS = new Set(["cmd", "decoded", "phrase", "host", "ref", "path", "dir", "command"]);
734
+ // Text from the user's files inside one of misconfig's own sentences: names,
735
+ // paths, commands and quoted phrases. It's kept to one line, without double
736
+ // quotes or direction marks, and cut to size, so a name in a hostile file, or
737
+ // in a crafted private link, can't close misconfig's quotes or carry a
738
+ // sentence of its own.
739
+ const FROM_FILES = new Set(["cmd", "decoded", "phrase", "host", "ref", "path", "dir", "command", "rule", "files", "list", "key", "server", "pkg", "skill"]);
740
+ const FILE_VALUE_MAX = { key: 80, server: 40, skill: 40, pkg: 80, host: 100, folder: 80 };
741
+ function fileValue(value, k) {
742
+ let text = String(value)
743
+ .replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, " ")
744
+ .replace(/["“”„‟]/g, "'")
745
+ .replace(/\s+/g, " ")
746
+ .trim();
747
+ // Variable and header names have no spaces, so a space ends the name.
748
+ if (k === "key") text = text.split(" ")[0];
749
+ const max = FILE_VALUE_MAX[k] ?? 120;
750
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
751
+ }
752
+
753
+ // Parts of a finding that come from the user's own files: quoted text, paths,
754
+ // commands and the names people choose for servers, packages, variables and
755
+ // files. They never leave the computer. Shared reports show "[hidden]".
756
+ const PRIVATE_VARS = new Set(["cmd", "decoded", "phrase", "host", "ref", "path", "dir", "command", "rule", "files", "list", "key", "server", "pkg", "lookup", "skill", "ext", "name", "summary", "worst"]);
757
+
758
+ // "where" is a fixed phrase that can quote a name, as in The “deploy” script.
759
+ const hideNames = (text) => String(text).replace(/“[^”]*”/g, "“[hidden]”");
270
760
 
271
761
  export function publicFinding(f) {
272
762
  const rule = RULES[f.id];
273
763
  const values = { ...(f.vars ?? {}) };
274
- for (const k of PRIVATE_VARS) values[k] = "[redacted]";
764
+ for (const k of PRIVATE_VARS) values[k] = "[hidden]";
765
+ if (typeof values.where === "string") values.where = hideNames(values.where);
275
766
  const fill = (text, fallback) => (rule ? fillTemplate(text, values) : fallback);
276
767
  return {
277
768
  id: f.id,
@@ -286,33 +777,148 @@ export function publicFinding(f) {
286
777
  };
287
778
  }
288
779
 
780
+ // The worst finding in its own words, then how many more like it. Titles
781
+ // start with names such as Codex or ~/.zshrc, so they're never lowercased.
289
782
  export function headlineFor(counts, top, hasControlFiles) {
290
- const lower = (t) => t.charAt(0).toLowerCase() + t.slice(1);
291
783
  const minor = counts.medium + counts.low;
292
784
  if (!hasControlFiles && !top) return "No agent setup files found here.";
293
- if (counts.critical === 1) return top.title;
294
- if (counts.critical) return `${counts.critical} critical issues, starting with: ${lower(top.title)}`;
295
- if (counts.high) return `${counts.high} high-risk issue${counts.high === 1 ? "" : "s"}, starting with: ${lower(top.title)}`;
785
+ const lead = (n, level) => (n > 1 ? `${top.title}, and ${n - 1} more ${level} issue${n === 2 ? "" : "s"}.` : `${top.title}.`);
786
+ if (counts.critical) return lead(counts.critical, "critical");
787
+ if (counts.high) return lead(counts.high, "high-risk");
296
788
  if (minor) return `No critical issues. ${minor} thing${minor === 1 ? "" : "s"} worth tightening.`;
297
789
  return "No issues found in these agent files.";
298
790
  }
299
791
 
300
- // --- Claude Code ---------------------------------------------------------------
792
+ // --- Claude Code -------------------------------------------------------------
301
793
 
302
794
  function parsed(file) {
303
- if (file.parsed === undefined) file.parsed = /\.toml$/i.test(file.path) ? parseTOML(file.content) : parseJSONC(file.content) ?? null;
795
+ if (file.parsed === undefined) file.parsed = (/\.toml$/i.test(file.path) ? parseTOML(file.content) : /\.ya?ml$/i.test(file.path) ? parseYAML(file.content) : parseJSONC(file.content)) ?? null;
304
796
  return file.parsed;
305
797
  }
306
798
 
799
+ // Environment variables that make the programs an agent runs load other
800
+ // code as they start: a Node module, a shared library, a shell script, a
801
+ // Java agent, a .NET hook, or a command git runs. Values that only tune a
802
+ // program, such as NODE_OPTIONS=--max-old-space-size=4096, don't count.
803
+ const JAVA_AGENT = (v) => /-(?:javaagent|agentpath|agentlib)[:=]/i.test(v);
804
+ const CODE_LOADING_ENV = {
805
+ NODE_OPTIONS: (v) => /(?:^|\s)(?:-r|--require|--import|--loader|--experimental-loader)(?:[\s=]|$)/.test(v),
806
+ LD_PRELOAD: () => true,
807
+ LD_AUDIT: () => true,
808
+ DYLD_INSERT_LIBRARIES: () => true,
809
+ BASH_ENV: () => true,
810
+ ZDOTDIR: () => true,
811
+ PERL5OPT: (v) => /-[MmIdx]/.test(v),
812
+ RUBYOPT: (v) => /(?:^|\s)-(?:r|I)/.test(v),
813
+ JAVA_TOOL_OPTIONS: JAVA_AGENT,
814
+ _JAVA_OPTIONS: JAVA_AGENT,
815
+ JDK_JAVA_OPTIONS: JAVA_AGENT,
816
+ DOTNET_STARTUP_HOOKS: () => true,
817
+ // Plain ssh with options is how deploy keys are chosen; anything else runs a program.
818
+ GIT_SSH_COMMAND: (v) => !/^\s*ssh(?:\.exe)?(?:\s+-[A-Za-z](?:\s+[^\s;&|`$()<>]+)?)*\s*$/.test(v),
819
+ GIT_SSH: () => true,
820
+ GIT_EXTERNAL_DIFF: () => true,
821
+ GIT_CONFIG_PARAMETERS: (v) => /core\.(?:fsmonitor|hookspath|sshcommand|pager|editor|askpass)|alias\./i.test(v),
822
+ CLAUDE_CODE_SHELL_PREFIX: () => true,
823
+ // A folder named relative to wherever a command runs, or an empty entry,
824
+ // which means the current folder: a project's own programs then stand in
825
+ // for git, npm and the rest.
826
+ PATH: (v) => {
827
+ const windows = v.includes(";");
828
+ return v.length > 0 && v.split(windows ? ";" : ":").some((p) => (p.trim() ? !/^(?:\/|~|[A-Za-z]:[\\/]|\$|%)/.test(p.trim()) : !windows));
829
+ },
830
+ };
831
+ // The variable that loads code, or null.
832
+ function codeLoadingVariable(key, value) {
833
+ if (typeof key !== "string" || (typeof value !== "string" && typeof value !== "number")) return null;
834
+ const v = String(value);
835
+ if (Object.hasOwn(CODE_LOADING_ENV, key)) return CODE_LOADING_ENV[key](v) ? key : null;
836
+ // git reads GIT_CONFIG_KEY_0=core.fsmonitor with GIT_CONFIG_VALUE_0.
837
+ if (/^GIT_CONFIG_KEY_\d{1,3}$/.test(key) && /^(?:core\.(?:fsmonitor|hookspath|sshcommand|pager|editor|askpass)|alias\.)/i.test(v)) return key;
838
+ return null;
839
+ }
840
+
841
+ // Where an agent sends its requests. A base address, a proxy or a telemetry
842
+ // collector set by a project hands that host the prompts, the code and often
843
+ // the API key once the folder is trusted. In your own settings it's usually
844
+ // a company gateway, so there it's only noted.
845
+ const ENDPOINT_VARIABLES = new Set([
846
+ "ANTHROPIC_BASE_URL", "ANTHROPIC_BEDROCK_BASE_URL", "ANTHROPIC_VERTEX_BASE_URL", "ANTHROPIC_FOUNDRY_BASE_URL",
847
+ "OPENAI_BASE_URL", "OPENAI_API_BASE", "GOOGLE_GEMINI_BASE_URL", "GEMINI_BASE_URL",
848
+ "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
849
+ "HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY",
850
+ ]);
851
+ // Settings files' own names for a base address.
852
+ const ENDPOINT_SETTINGS = new Set(["base_url", "openai-api-base", "baseURL", "apiBase"]);
853
+ const CA_VARIABLES = new Set(["NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"]);
854
+ // The services' own addresses, and cloud providers that host them.
855
+ const OFFICIAL_ENDPOINT = /(?:^|\.)(?:anthropic\.com|claude\.ai|openai\.com|googleapis\.com|amazonaws\.com|azure\.com|azure\.net|windows\.net)$/i;
856
+ function endpointHost(value) {
857
+ if (typeof value !== "string" || !value.trim() || value.length > 2000) return null;
858
+ let url;
859
+ try {
860
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(value.trim()) ? value.trim() : `http://${value.trim()}`);
861
+ } catch {
862
+ return null;
863
+ }
864
+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
865
+ return !host || isLocalHost(host) || isLocalHost(`[${host}]`) || OFFICIAL_ENDPOINT.test(host) ? null : host;
866
+ }
867
+ // { variable, host } when an environment variable points the agent elsewhere.
868
+ function endpointVariable(key, value) {
869
+ const name = typeof key === "string" ? key.toUpperCase() : "";
870
+ if (!ENDPOINT_VARIABLES.has(name)) return null;
871
+ const host = endpointHost(typeof value === "number" ? String(value) : value);
872
+ return host ? { variable: name, host } : null;
873
+ }
874
+ const tlsOff = (key, value) => typeof key === "string" && key.toUpperCase() === "NODE_TLS_REJECT_UNAUTHORIZED" && String(value).trim() === "0";
875
+ // A file in the project folder, as opposed to the settings on the computer.
876
+ const inProject = (ctx, f) => !ctx.homeLike && !/^(~|\/|[A-Za-z]:)/.test(f.path);
877
+ // Environment variables that send requests elsewhere or weaken TLS, from any
878
+ // setting that sets them for the agent.
879
+ function checkEnvironment(ctx, f, where, key, value, line) {
880
+ const at = { file: f, line, evidence: evidenceLine(f, line) };
881
+ const endpoint = endpointVariable(key, value);
882
+ if (endpoint) add(ctx, inProject(ctx, f) ? "AGENT-ENDPOINT" : "AGENT-ENDPOINT-USER", { ...at, vars: { where, ...endpoint } });
883
+ if (tlsOff(key, value)) add(ctx, "ENV-TLS-OFF", { ...at, vars: { where, variable: "NODE_TLS_REJECT_UNAUTHORIZED" } });
884
+ const ca = typeof key === "string" ? key.toUpperCase() : "";
885
+ if (CA_VARIABLES.has(ca) && inProject(ctx, f) && String(value).trim()) add(ctx, "ENV-CA-PROJECT", { ...at, vars: { where, variable: ca } });
886
+ }
887
+ function checkEndpointSetting(ctx, f, where, setting, value, line) {
888
+ const host = endpointHost(value);
889
+ if (host) add(ctx, inProject(ctx, f) ? "AGENT-ENDPOINT" : "AGENT-ENDPOINT-USER", { file: f, line, evidence: evidenceLine(f, line), vars: { where, variable: setting, host } });
890
+ }
891
+
892
+ // Settings that make Claude Code run a command, and the ones it ignores in a
893
+ // project's own settings files.
894
+ const CLAUDE_COMMAND_KEYS = ["apiKeyHelper", "awsAuthRefresh", "awsCredentialExport", "gcpAuthRefresh", "otelHeadersHelper", "statusLine", "subagentStatusLine", "fileSuggestion", "processWrapper", "policyHelper", "sshHostCommands"];
895
+ const CLAUDE_USER_ONLY_KEYS = new Set(["processWrapper", "policyHelper", "sshHostCommands"]);
896
+
897
+ // A project's own .claude/settings.json or settings.local.json, as opposed to
898
+ // the user's ~/.claude/settings.json or an administrator's managed settings.
899
+ function isProjectSettings(ctx, f) {
900
+ return !ctx.homeLike && !/^(~|\/|[A-Za-z]:)/.test(f.path) && !/(^|\/)managed-settings/i.test(f.path);
901
+ }
902
+
903
+ // The commands in a setting's value: a string, { command } or { path }, or a list of those.
904
+ function commandsIn(value, depth = 0) {
905
+ if (typeof value === "string") return [value];
906
+ if (Array.isArray(value) && depth < 4) return value.flatMap((v) => commandsIn(v, depth + 1));
907
+ if (isObj(value)) return [value.command, value.path].filter((c) => typeof c === "string");
908
+ return [];
909
+ }
910
+
307
911
  function checkClaudeSettings(ctx, f) {
308
912
  const json = parsed(f);
309
913
  if (!isObj(json)) return;
310
914
  ctx.claudeSettingsFiles.push(f);
311
915
  const p = isObj(json.permissions) ? json.permissions : {};
916
+ const shared = isProjectSettings(ctx, f);
312
917
 
313
918
  if (p.defaultMode === "bypassPermissions") {
919
+ // Claude Code 2.1.257 and later ignore this in project settings.
314
920
  const line = lineOf(f, /bypassPermissions/);
315
- add(ctx, "CC-BYPASS", { file: f, line, evidence: evidenceLine(f, line) });
921
+ add(ctx, shared ? "CC-BYPASS-PROJECT" : "CC-BYPASS", { file: f, line, evidence: evidenceLine(f, line) });
316
922
  } else if (p.defaultMode === "acceptEdits") {
317
923
  const line = lineOf(f, /acceptEdits/);
318
924
  add(ctx, "CC-ACCEPT-EDITS", { file: f, line, evidence: evidenceLine(f, line) });
@@ -351,23 +957,62 @@ function checkClaudeSettings(ctx, f) {
351
957
  const line = lineOf(f, `"${key}"`);
352
958
  add(ctx, "CC-ENV-SECRET", { file: f, line, evidence: `${key} = ${redact(value)}`, vars: { key } });
353
959
  }
960
+ const variable = codeLoadingVariable(key, value);
961
+ if (variable) {
962
+ const line = lineOf(f, `"${key}"`);
963
+ add(ctx, "ENV-CODE-LOAD", { file: f, line, evidence: evidenceLine(f, line), vars: { where: "Claude Code's env setting", variable } });
964
+ }
965
+ checkEnvironment(ctx, f, "Claude Code's env setting", key, value, lineOf(f, `"${key}"`));
354
966
  }
355
967
  }
968
+ // Claude Code keeps each person's approvals in settings.local.json. In the
969
+ // shared settings, a project approves its own servers for everyone.
970
+ if (shared && !/settings\.local\.json$/i.test(f.path) && arr(json.enabledMcpjsonServers).length) {
971
+ const line = lineOf(f, /enabledMcpjsonServers/);
972
+ add(ctx, "CC-MCP-PROJECT-APPROVED", { file: f, line, evidence: evidenceLine(f, line) });
973
+ }
356
974
 
357
- if (isObj(json.hooks)) {
358
- for (const [event, entries] of Object.entries(json.hooks)) {
359
- for (const entry of Array.isArray(entries) ? entries : []) {
360
- const hooks = Array.isArray(entry?.hooks) ? entry.hooks : [entry];
361
- for (const h of hooks) {
362
- if (typeof h?.command === "string") checkCommand(ctx, h.command, f, `A Claude Code ${event} hook`);
363
- }
975
+ for (const key of CLAUDE_COMMAND_KEYS) {
976
+ if (shared && CLAUDE_USER_ONLY_KEYS.has(key)) continue;
977
+ for (const command of commandsIn(json[key])) checkCommand(ctx, command, f, `Claude Code's ${key} setting`);
978
+ }
979
+ checkClaudeHooks(ctx, f, json.hooks);
980
+ }
981
+
982
+ // Hooks in Claude Code settings and in plugins' hooks/hooks.json. Command
983
+ // hooks run on this computer; http hooks post what Claude is doing to a URL.
984
+ function checkClaudeHooks(ctx, f, hooks) {
985
+ if (!isObj(hooks)) return;
986
+ for (const [event, entries] of Object.entries(hooks)) {
987
+ const where = Object.hasOwn(HOOK_EVENTS, event) ? `A Claude Code ${event} hook` : "A Claude Code hook";
988
+ for (const entry of Array.isArray(entries) ? entries : []) {
989
+ for (const h of Array.isArray(entry?.hooks) ? entry.hooks : [entry]) {
990
+ if (typeof h?.command === "string") checkCommand(ctx, h.command, f, where);
991
+ if (h?.type === "http" && typeof h.url === "string") checkHookUrl(ctx, h.url, f, where);
364
992
  }
365
993
  }
366
994
  }
367
995
  }
368
996
 
997
+ function checkHookUrl(ctx, url, f, where) {
998
+ let host;
999
+ try {
1000
+ host = new URL(url).hostname;
1001
+ } catch {
1002
+ return;
1003
+ }
1004
+ if (isLocalHost(host)) return;
1005
+ const line = lineOf(f, url.slice(0, 60)) || lineOf(f, /"url"/);
1006
+ add(ctx, "HOOK-HTTP", { file: f, line, evidence: evidenceLine(f, line), vars: { where, host } });
1007
+ }
1008
+
1009
+ const isLocalHost = (host) => /^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?|0\.0\.0\.0|host\.docker\.internal)$/i.test(host);
1010
+
369
1011
  function checkClaudeUserConfig(ctx, f) {
370
- if (isMasked(f.content)) add(ctx, "CC-USER-SECRET", { file: f, line: lineOf(f, /«masked:/) });
1012
+ // ~/.claude.json is where Claude Code keeps its account data. A copy in a
1013
+ // project folder is the problem.
1014
+ const inProject = !/^(~|\/|[A-Za-z]:)/.test(f.path) && !ctx.homeLike;
1015
+ if (inProject && isMasked(f.content)) add(ctx, "CC-USER-SECRET", { file: f, line: lineOf(f, /«masked:/) });
371
1016
  const json = parsed(f);
372
1017
  if (!isObj(json)) return;
373
1018
  if (isObj(json.projects)) {
@@ -386,7 +1031,7 @@ function checkClaudeUserConfig(ctx, f) {
386
1031
  }
387
1032
  }
388
1033
 
389
- // --- Codex ---------------------------------------------------------------------
1034
+ // --- Codex -------------------------------------------------------------------
390
1035
 
391
1036
  function checkCodex(ctx, f) {
392
1037
  const toml = parsed(f);
@@ -411,6 +1056,36 @@ function checkCodex(ctx, f) {
411
1056
  }
412
1057
  const notify = arr(toml.notify).join(" ");
413
1058
  if (notify) checkCommand(ctx, notify, f, "Codex's notify command");
1059
+ if (isObj(toml.hooks)) checkJsonHooks(ctx, f, "A Codex hook", toml.hooks);
1060
+ for (const provider of isObj(toml.model_providers) ? Object.values(toml.model_providers) : []) {
1061
+ const auth = provider?.auth;
1062
+ const command = isObj(auth) && typeof auth.command === "string" ? [auth.command, ...arr(auth.args)].join(" ") : "";
1063
+ if (command) checkCommand(ctx, command, f, "Codex's model provider login command");
1064
+ }
1065
+ for (const server of isObj(toml.mcp_servers) ? Object.values(toml.mcp_servers) : []) {
1066
+ for (const command of commandsIn(server?.http_headers_helper)) checkCommand(ctx, command, f, "Codex's MCP header command");
1067
+ }
1068
+ const set = toml.shell_environment_policy?.set;
1069
+ if (isObj(set)) {
1070
+ for (const [key, value] of Object.entries(set)) {
1071
+ const variable = codeLoadingVariable(key, value);
1072
+ if (variable) {
1073
+ const line = lineOf(f, key);
1074
+ add(ctx, "ENV-CODE-LOAD", { file: f, line, evidence: evidenceLine(f, line), vars: { where: "Codex's shell_environment_policy", variable } });
1075
+ }
1076
+ // It sets the commands Codex runs, not Codex itself, so only TLS counts here.
1077
+ if (tlsOff(key, value)) {
1078
+ const line = lineOf(f, key);
1079
+ add(ctx, "ENV-TLS-OFF", { file: f, line, evidence: evidenceLine(f, line), vars: { where: "Codex's shell_environment_policy", variable: "NODE_TLS_REJECT_UNAUTHORIZED" } });
1080
+ }
1081
+ }
1082
+ }
1083
+ for (const provider of isObj(toml.model_providers) ? Object.values(toml.model_providers).slice(0, 20) : []) {
1084
+ if (typeof provider?.base_url === "string") checkEndpointSetting(ctx, f, "Codex's model_providers setting", "base_url", provider.base_url, lineOf(f, provider.base_url.slice(0, 60)) || lineOf(f, /base_url/));
1085
+ }
1086
+ for (const key of ["openai_base_url", "chatgpt_base_url"]) {
1087
+ if (typeof toml[key] === "string") checkEndpointSetting(ctx, f, "Codex's model_providers setting", "base_url", toml[key], lineOf(f, key));
1088
+ }
414
1089
  if (isObj(toml.projects)) {
415
1090
  for (const [dir, settings] of Object.entries(toml.projects)) {
416
1091
  const place = riskyPlace(dir);
@@ -420,65 +1095,96 @@ function checkCodex(ctx, f) {
420
1095
  }
421
1096
 
422
1097
  // Folders an agent should never be started in. Accepts absolute and ~ paths.
1098
+ const RISK_HOME = "It can read everything there, including SSH keys, cloud credentials and your other projects.";
1099
+ const RISK_DOWNLOADS = "Files saved there from websites, chats and email become context the agent reads and may act on.";
1100
+ const RISK_DRIVE = "It can read and change anything on that drive.";
1101
+
423
1102
  export function riskyPlace(dir) {
424
- const d = String(dir).replace(/\\/g, "/").replace(/\/+$/, "");
1103
+ const d = trimWord(String(dir).replace(/\\/g, "/").replace(/\/{2,}/g, "/"), "", "/");
425
1104
  const last = d.split("/").pop();
426
- if (/^(~|\/Users\/[^/]+|\/home\/[^/]+|\/root|[A-Za-z]:\/Users\/[^/]+)$/i.test(d)) {
427
- return { name: "your home folder", risk: "It can read everything there, including SSH keys, cloud credentials and your other projects." };
428
- }
429
- if (/^(Downloads|Desktop)$/i.test(last)) {
430
- return { name: `your ${last} folder`, risk: "Files saved there from websites, chats and email become context the agent reads and may act on." };
431
- }
432
- if (d === "" || /^[A-Za-z]:$/.test(d)) return { name: "the root of a drive", risk: "It can read and change anything on that drive." };
1105
+ if (/^(~|\/Users\/[^/]+|\/home\/[^/]+|\/root|[A-Za-z]:\/Users\/[^/]+)$/i.test(d)) return { name: "your home folder", risk: RISK_HOME };
1106
+ if (/^(Downloads|Desktop)$/i.test(last)) return { name: `your ${folderName(last)} folder`, risk: RISK_DOWNLOADS };
1107
+ if (d === "" || /^[A-Za-z]:$/.test(d)) return { name: "the root of a drive", risk: RISK_DRIVE };
433
1108
  return null;
434
1109
  }
435
1110
 
436
1111
  function checkShellProfile(ctx, f) {
437
1112
  for (const [i, line] of f.lines.entries()) {
438
1113
  if (/^\s*#/.test(line)) continue;
439
- const flag = line.match(RX_DANGER_FLAGS);
440
- if (!flag) continue;
441
- const agent = line.match(/\b(claude|codex|gemini|qwen|opencode|cursor-agent|amp)\b/i)?.[1]?.toLowerCase();
442
- const names = { claude: "Claude Code", codex: "Codex", gemini: "Gemini CLI", qwen: "Qwen Code", opencode: "OpenCode", "cursor-agent": "Cursor", amp: "Amp" };
443
- add(ctx, "FLAG-ALIAS", { file: f, line: i + 1, evidence: line, tool: names[agent] ?? null, vars: { agent: names[agent] ?? "an agent", flag: flag[0].trim(), cmd: clip(line, 120) } });
1114
+ const trace = SHELL_TRACES.find((t) => t.line.test(line));
1115
+ if (trace) add(ctx, "ATTACK-SHELL-LINE", { file: f, line: i + 1, evidence: line, vars: { campaign: trace.campaign, what: trace.what, advice: trace.fix } });
1116
+ const hit = findDangerFlag(line);
1117
+ if (hit) add(ctx, "FLAG-ALIAS", { file: f, line: i + 1, evidence: line, tool: hit.agent, vars: { agent: hit.agent, flag: hit.flag, cmd: clip(line, 120) } });
444
1118
  }
445
1119
  }
446
1120
 
447
- // --- Gemini, VS Code, OpenCode, Zed, Aider -------------------------------------
1121
+ // --- Gemini, VS Code, OpenCode, Zed, Aider -----------------------------------
448
1122
 
449
1123
  function checkGemini(ctx, f) {
450
1124
  const json = parsed(f);
451
1125
  if (!isObj(json)) return;
452
1126
  let yolo = false;
453
1127
  let autoAccept = false;
1128
+ let autoEdit = false;
454
1129
  walk(json, (key, value) => {
455
1130
  if (/^yolo$/i.test(key) && value === true) yolo = true;
456
- if (/approvalMode$/i.test(key) && /^yolo$/i.test(String(value))) yolo = true;
1131
+ if (/approvalMode$/i.test(key) && /^yolo$/i.test(asText(value))) yolo = true;
1132
+ if (/approvalMode$/i.test(key) && /^auto_edit$/i.test(asText(value))) autoEdit = true;
457
1133
  if (key === "autoAccept" && value === true) autoAccept = true;
458
1134
  });
1135
+ // Commands Gemini CLI runs itself: to find and call project tools, and hooks.
1136
+ const at = (...keys) => keys.reduce((o, k) => (isObj(o) ? o[k] : undefined), json);
1137
+ for (const [value, where] of [
1138
+ [at("tools", "discoveryCommand"), "Gemini CLI's tool discovery command"],
1139
+ [at("toolDiscoveryCommand"), "Gemini CLI's tool discovery command"],
1140
+ [at("tools", "callCommand"), "Gemini CLI's tool call command"],
1141
+ [at("toolCallCommand"), "Gemini CLI's tool call command"],
1142
+ ]) {
1143
+ for (const command of commandsIn(value)) checkCommand(ctx, command, f, where);
1144
+ }
1145
+ if (isObj(json.hooks)) checkJsonHooks(ctx, f, "A Gemini CLI hook", json.hooks);
1146
+ // Gemini CLI ignores YOLO mode in settings, so asking for it there doesn't
1147
+ // hide the settings it does apply.
459
1148
  if (yolo) {
460
1149
  const line = lineOf(f, /yolo/i);
461
1150
  add(ctx, "GM-YOLO", { file: f, line, evidence: evidenceLine(f, line) });
462
- } else if (autoAccept) {
1151
+ }
1152
+ if (autoAccept) {
463
1153
  const line = lineOf(f, /autoAccept/);
464
1154
  add(ctx, "GM-AUTO-ACCEPT", { file: f, line, evidence: evidenceLine(f, line) });
465
1155
  }
1156
+ if (autoEdit) {
1157
+ const line = lineOf(f, /auto_edit/);
1158
+ add(ctx, "GM-AUTO-EDIT", { file: f, line, evidence: evidenceLine(f, line) });
1159
+ }
466
1160
  }
467
1161
 
1162
+ const VS_CODE_AUTO_APPROVE = ["chat.tools.autoApprove", "chat.tools.global.autoApprove", "chat.permissions.default"];
1163
+ const ALWAYS_ALLOW_KEYS = ["alwaysAllow", "autoApprove", "auto_approve", "trust"];
1164
+
468
1165
  function checkVSCode(ctx, f) {
469
1166
  const json = parsed(f);
470
1167
  if (!isObj(json)) return;
471
- for (const key of ["chat.tools.autoApprove", "chat.tools.global.autoApprove"]) {
472
- if (json[key] === true) {
473
- const line = lineOf(f, key);
474
- add(ctx, "VS-AUTO-APPROVE", { file: f, line, evidence: evidenceLine(f, line), vars: { key } });
475
- }
1168
+ const at = (key) => {
1169
+ const line = lineOf(f, key);
1170
+ return { file: f, line, evidence: evidenceLine(f, line) };
1171
+ };
1172
+ for (const key of VS_CODE_AUTO_APPROVE) {
1173
+ if (json[key] === true || json[key] === "autoApprove") add(ctx, "VS-AUTO-APPROVE", { ...at(key), vars: { setting: key } });
476
1174
  }
1175
+ if (json["github.copilot.chat.claudeAgent.allowDangerouslySkipPermissions"] === true) add(ctx, "VS-CLAUDE-SKIP", at("allowDangerouslySkipPermissions"));
1176
+ if (json["chat.tools.terminal.ignoreDefaultAutoApproveRules"] === true) add(ctx, "VS-NO-DEFAULT-RULES", at("ignoreDefaultAutoApproveRules"));
1177
+ // VS Code asks before an agent edits its own settings. Approving those
1178
+ // edits lets an agent turn on its own auto-approval.
1179
+ // The last pattern that matches a file decides, as in VS Code.
1180
+ const edits = json["chat.tools.edits.autoApprove"];
1181
+ const approves = (p) => Object.entries(edits).filter(([glob]) => globMatch(glob.replace(/^\.\//, ""), p)).pop()?.[1] === true;
1182
+ if (isObj(edits) && [".vscode/settings.json", ".vscode/mcp.json"].some(approves)) add(ctx, "VS-EDITS-AUTO", at("chat.tools.edits.autoApprove"));
477
1183
  const terminal = json["chat.tools.terminal.autoApprove"] ?? json["github.copilot.chat.agent.terminal.allowList"];
478
1184
  if (isObj(terminal)) {
479
1185
  for (const [pattern, allowed] of Object.entries(terminal)) {
480
1186
  const on = allowed === true || (isObj(allowed) && allowed.approve === true);
481
- if (on && (/^\/\.\*\/|^\*$|^\.\*$/.test(pattern) || /\b(rm|curl|wget|sudo|bash|sh|pwsh|powershell|iex|python|node|npx|ssh|scp|git push)\b/i.test(pattern))) {
1187
+ if (on && (matchesEverything(pattern) || /\b(rm|curl|wget|sudo|bash|sh|pwsh|powershell|iex|python|node|npx|ssh|scp|git push)\b/i.test(pattern))) {
482
1188
  const line = lineOf(f, JSON.stringify(pattern)) || lineOf(f, pattern);
483
1189
  add(ctx, "VS-TERMINAL-AUTO", { file: f, line, evidence: evidenceLine(f, line), vars: { rule: pattern } });
484
1190
  }
@@ -486,9 +1192,19 @@ function checkVSCode(ctx, f) {
486
1192
  }
487
1193
  }
488
1194
 
1195
+ // A terminal rule written to match every command: *, .*, /.*/, /^.*$/ or /.+/.
1196
+ function matchesEverything(pattern) {
1197
+ const body = pattern.startsWith("/") && pattern.lastIndexOf("/") > 0 ? pattern.slice(1, pattern.lastIndexOf("/")) : pattern;
1198
+ return ["", "*", ".*", ".+", "[\\s\\S]*", "[\\s\\S]+"].includes(trimWord(body, "^", "$"));
1199
+ }
1200
+
489
1201
  function checkOpenCode(ctx, f) {
490
1202
  const json = parsed(f);
491
1203
  if (!isObj(json)) return;
1204
+ for (const provider of isObj(json.provider) ? Object.values(json.provider).slice(0, 20) : []) {
1205
+ const url = provider?.options?.baseURL;
1206
+ if (typeof url === "string") checkEndpointSetting(ctx, f, "OpenCode's provider setting", "baseURL", url, lineOf(f, url.slice(0, 60)) || lineOf(f, /baseURL/));
1207
+ }
492
1208
  if (json.share === "auto") {
493
1209
  const line = lineOf(f, /"share"/);
494
1210
  add(ctx, "OC-AUTO-SHARE", { file: f, line, evidence: evidenceLine(f, line) });
@@ -510,58 +1226,423 @@ function checkOpenCode(ctx, f) {
510
1226
  function checkZed(ctx, f) {
511
1227
  const json = parsed(f);
512
1228
  if (!isObj(json)) return;
513
- if (json.agent?.always_allow_tool_actions === true || json.assistant?.always_allow_tool_actions === true) {
514
- const line = lineOf(f, /always_allow_tool_actions/);
1229
+ if (json.agent?.always_allow_tool_actions === true || json.assistant?.always_allow_tool_actions === true || json.agent?.tool_permissions?.default === "allow") {
1230
+ const line = lineOf(f, /always_allow_tool_actions|"default"\s*:\s*"allow"/);
515
1231
  add(ctx, "ZED-ALWAYS-ALLOW", { file: f, line, evidence: evidenceLine(f, line) });
516
1232
  }
1233
+ if (json.session?.trust_all_worktrees === true) {
1234
+ const line = lineOf(f, /trust_all_worktrees/);
1235
+ add(ctx, "ZED-TRUST-ALL", { file: f, line, evidence: evidenceLine(f, line) });
1236
+ }
517
1237
  }
518
1238
 
1239
+ // --- Trusted folders, hooks and settings of other agents ---------------------
1240
+
1241
+ // Gemini CLI: { "/path": "TRUST_FOLDER" | "TRUST_PARENT" | "DO_NOT_TRUST" }.
1242
+ function geminiTrusted(json) {
1243
+ if (!isObj(json)) return [];
1244
+ const parent = (d) => trimWord(d, "", "/\\").replace(/[\\/][^\\/]*$/, "") || "/";
1245
+ return Object.entries(json).flatMap(([dir, level]) => (level === "TRUST_FOLDER" ? [[dir, dir]] : level === "TRUST_PARENT" ? [[parent(dir), dir]] : []));
1246
+ }
1247
+
1248
+ // GitHub Copilot CLI: a list of trusted folders in ~/.copilot/config.json.
1249
+ function copilotTrusted(json) {
1250
+ return arr(json?.trusted_folders ?? json?.trustedFolders).map((dir) => [dir, dir]);
1251
+ }
1252
+
1253
+ // Folders the settings on this computer say agents have been started in or
1254
+ // trust. The command also checks the loose files in the risky ones.
1255
+ export function agentFolders(path, content) {
1256
+ const json = /\.toml$/i.test(path) ? parseTOML(content) : parseJSONC(content);
1257
+ if (!isObj(json)) return [];
1258
+ if (/(^|\/)\.claude\.json$/i.test(path)) return isObj(json.projects) ? Object.keys(json.projects) : [];
1259
+ if (/(^|\/)\.codex\/config\.toml$/i.test(path)) return isObj(json.projects) ? Object.entries(json.projects).filter(([, s]) => s?.trust_level === "trusted").map(([d]) => d) : [];
1260
+ if (/(^|\/)\.gemini\/trustedFolders\.json$/i.test(path)) return geminiTrusted(json).map(([d]) => d);
1261
+ if (/(^|\/)\.copilot\/config\.json$/i.test(path)) return copilotTrusted(json).map(([d]) => d);
1262
+ return [];
1263
+ }
1264
+
1265
+ // [folder trusted, folder as written in the file] pairs.
1266
+ function checkTrustedFolders(ctx, f, tool, trusted) {
1267
+ for (const [dir, written] of trusted) {
1268
+ const place = riskyPlace(dir);
1269
+ if (place) add(ctx, "WS-TRUSTED-DIR", { file: f, line: keyLine(f, written), tool, vars: { tool, place: place.name, risk: place.risk, dir } });
1270
+ }
1271
+ }
1272
+
1273
+ // Every command in a hooks file, such as .github/hooks/*.json or Cursor's
1274
+ // hooks.json, or in `value` when hooks sit inside other settings. Hooks name
1275
+ // their command "command", "bash" or "powershell".
1276
+ function checkJsonHooks(ctx, f, where, value = parsed(f)) {
1277
+ const visit = (v, key, depth) => {
1278
+ if (depth > 8) return;
1279
+ if (typeof v === "string" && ["command", "bash", "powershell"].includes(key)) checkCommand(ctx, v, f, where);
1280
+ else if (Array.isArray(v)) {
1281
+ // A command written as a list of arguments.
1282
+ if (key === "command" && v.length && v.every((x) => typeof x === "string")) checkCommand(ctx, v.join(" "), f, where);
1283
+ else for (const x of v) visit(x, key, depth + 1);
1284
+ } else if (isObj(v)) for (const [k, x] of Object.entries(v)) visit(x, k, depth + 1);
1285
+ };
1286
+ visit(value, "", 0);
1287
+ }
1288
+
1289
+ // Cursor's cloud agents run install on every build, start on every boot and
1290
+ // each terminal's command, in a virtual machine with the repo's secrets.
1291
+ function checkCursorEnvironment(ctx, f) {
1292
+ const json = parsed(f);
1293
+ if (!isObj(json)) return;
1294
+ const where = "Cursor's cloud agent setup";
1295
+ for (const key of ["install", "start"]) for (const command of commandsIn(json[key])) checkCommand(ctx, command, f, where);
1296
+ for (const t of Array.isArray(json.terminals) ? json.terminals.slice(0, 20) : []) for (const command of commandsIn(t?.command)) checkCommand(ctx, command, f, where);
1297
+ }
1298
+
1299
+ // Codex rules that let a command run outside the sandbox without asking:
1300
+ // prefix_rule(pattern = ["git", "push"], decision = "allow"). Only programs
1301
+ // that run other code, change or delete files broadly, or reach the network
1302
+ // are reported.
1303
+ const RISKY_PROGRAM = /^(?:sudo|su|doas|rm|dd|chmod|chown|bash|sh|zsh|fish|dash|pwsh|powershell|cmd|python3?|node|deno|bun|npx|npm|pnpm|yarn|perl|ruby|php|eval|exec|env|xargs|find|docker|kubectl|curl|wget|ssh|scp|sftp|rsync|nc|ncat|netcat|ftp|telnet|git)$/i;
1304
+ // The words a rule's pattern matches at one place: a word, or a list of
1305
+ // alternatives. A program is matched by its name, so /bin/bash and bash.exe
1306
+ // count as bash.
1307
+ const ruleWords = (pattern, i) => (Array.isArray(pattern[i]) ? pattern[i] : [pattern[i]]).filter((w) => typeof w === "string").map((w) => w.trim());
1308
+ // True when rule a matches every command rule b matches: a is no longer than
1309
+ // b, and at each place a allows every word b does.
1310
+ const ruleCovers = (a, b) => a.length <= b.length && a.every((_, i) => ruleWords(b, i).every((w) => ruleWords(a, i).includes(w)));
1311
+ // git is only risky when every git command is allowed, or one that pushes,
1312
+ // changes settings or brings in code from elsewhere.
1313
+ const RISKY_GIT = /^(?:push|config|submodule|clone|fetch|pull|remote|-c|filter-branch|filter-repo)$/i;
1314
+
1315
+ function checkCodexRules(ctx, f) {
1316
+ const all = parseCodexRules(f.content);
1317
+ // A rule that may allow something, built in a way this check can't follow.
1318
+ const hidden = all.find((r) => r.unread && r.decision !== "prompt" && r.decision !== "forbidden");
1319
+ if (hidden) {
1320
+ const line = lineAt(f.content, hidden.index);
1321
+ add(ctx, "CX-RULES-UNREAD", { file: f, line, evidence: evidenceLine(f, line) });
1322
+ }
1323
+ const rules = all.filter((r) => !r.unread && r.pattern?.length && r.pattern.every((w) => w !== null && (!Array.isArray(w) || w.length)));
1324
+ const allowing = [];
1325
+ for (const rule of rules) {
1326
+ if (rule.decision !== "allow") continue;
1327
+ // When rules overlap, Codex applies the strictest one.
1328
+ if (rules.some((r) => (r.decision === "prompt" || r.decision === "forbidden") && ruleCovers(r.pattern, rule.pattern))) continue;
1329
+ const program = ruleWords(rule.pattern, 0).map(programName).find((p) => RISKY_PROGRAM.test(p) && (!/^git$/i.test(p) || rule.pattern.length === 1 || ruleWords(rule.pattern, 1).some((w) => RISKY_GIT.test(w))));
1330
+ if (!program) continue;
1331
+ // The command as the rule allows it, naming the risky choice where it
1332
+ // gives several, as in git push.
1333
+ const pick = (i) => (i === 1 && /^git$/i.test(program) ? ruleWords(rule.pattern, 1).find((w) => RISKY_GIT.test(w)) : null) ?? ruleWords(rule.pattern, i)[0] ?? "";
1334
+ allowing.push({ line: lineAt(f.content, rule.index), start: [program, pick(1)].filter(Boolean).join(" ") });
1335
+ }
1336
+ // One finding for the file: a Codex user can have dozens of these rules,
1337
+ // one for each command they approved. The patterns are named by program
1338
+ // and first word, such as powershell -Command; --explain lists each rule.
1339
+ if (allowing.length) {
1340
+ const starts = [...new Set(allowing.map((a) => clip(a.start, 40)))];
1341
+ const { line } = allowing[0];
1342
+ add(ctx, "CX-RULE-ALLOW", {
1343
+ file: f,
1344
+ line,
1345
+ evidence: evidenceLine(f, line),
1346
+ vars: { commands: allowing.length === 1 ? "a command" : `${allowing.length} commands`, list: listNames(starts, 4) },
1347
+ });
1348
+ }
1349
+ }
1350
+
1351
+ // Kiro and Amazon Q agent files: hooks, and tools the agent uses without
1352
+ // asking. Kiro's shell tool is "shell", also known by its Amazon Q names.
1353
+ // allowedTools entries can use * and ? as wildcards. Commands allowed in
1354
+ // toolsSettings are regular expressions that must match the whole command,
1355
+ // and the newer permissions rules match commands by prefix.
1356
+ const SHELL_TOOLS = ["shell", "execute_bash", "execute_cmd"];
1357
+ function wildcardMatch(glob, text) {
1358
+ let g = 0;
1359
+ let t = 0;
1360
+ let star = -1;
1361
+ let mark = 0;
1362
+ while (t < text.length) {
1363
+ if (g < glob.length && (glob[g] === "?" || glob[g] === text[t])) {
1364
+ g++;
1365
+ t++;
1366
+ } else if (g < glob.length && glob[g] === "*") {
1367
+ star = g++;
1368
+ mark = t;
1369
+ } else if (star >= 0) {
1370
+ g = star + 1;
1371
+ t = ++mark;
1372
+ } else return false;
1373
+ }
1374
+ while (glob[g] === "*") g++;
1375
+ return g === glob.length;
1376
+ }
1377
+ // A command pattern that lets through any command, or any use of a program
1378
+ // that can run anything: ".*", "curl .*", "bash*".
1379
+ const MATCH_ALL = /^\^?(?:\.\*|\.\+|\(\.\*\)|\[\\s\\S\]\*)\??\$?$/;
1380
+ function openCommand(pattern, regex) {
1381
+ const text = pattern.trim();
1382
+ if (!text || text === "*" || text === "**" || (regex && MATCH_ALL.test(text))) return true;
1383
+ const word = programName(/^\^?([^\s*.\\(]+)/.exec(text)?.[1] ?? "");
1384
+ const rest = text.slice(text.indexOf(word) + word.length);
1385
+ const open = regex ? /^(?:\s|\\s|\[ \])*(?:\.\*|\.\+|\(\.\*\))/.test(rest) || rest === "" : /^\s*\*/.test(rest) || rest.trim() === "";
1386
+ return RISKY_PROGRAM.test(word) && open;
1387
+ }
1388
+ function checkAgentFile(ctx, f, where) {
1389
+ checkJsonHooks(ctx, f, where);
1390
+ const json = parsed(f);
1391
+ if (!isObj(json)) return;
1392
+ const found = [];
1393
+ for (const tool of arr(json.allowedTools).slice(0, 200)) {
1394
+ const t = tool.trim();
1395
+ if (t === "*" || t === "@builtin" || SHELL_TOOLS.some((name) => wildcardMatch(t, name) || wildcardMatch(t, `@builtin/${name}`))) found.push({ rule: t, setting: "allowedTools" });
1396
+ }
1397
+ for (const name of SHELL_TOOLS) {
1398
+ const pattern = arr(json.toolsSettings?.[name]?.allowedCommands).slice(0, 200).find((c) => openCommand(c, true));
1399
+ if (pattern !== undefined) found.push({ rule: pattern.trim(), setting: "toolsSettings" });
1400
+ }
1401
+ for (const rule of Array.isArray(json.permissions?.rules) ? json.permissions.rules.slice(0, 200) : []) {
1402
+ if (!isObj(rule) || rule.capability !== "shell" || rule.effect !== "allow") continue;
1403
+ // A rule with no commands to match matches every one.
1404
+ const match = arr(rule.match);
1405
+ const open = match.length === 0 ? "*" : match.find((m) => openCommand(m, false));
1406
+ if (open !== undefined) found.push({ rule: open.trim(), setting: "permissions" });
1407
+ }
1408
+ if (!found.length) return;
1409
+ const line = lineOf(f, new RegExp(`"${found[0].setting}"`));
1410
+ add(ctx, "AGENT-ALLOW-SHELL", { file: f, line, evidence: evidenceLine(f, line), vars: found[0] });
1411
+ }
1412
+
1413
+ function checkCursorCli(ctx, f) {
1414
+ const json = parsed(f);
1415
+ for (const rule of arr(json?.permissions?.allow)) {
1416
+ if (/^Shell(\((\*|\*\*|\*:\*)?\))?$/i.test(rule.trim())) {
1417
+ const line = lineOf(f, rule);
1418
+ add(ctx, "CU-ALLOW-ALL-SHELL", { file: f, line, evidence: evidenceLine(f, line), vars: { rule } });
1419
+ }
1420
+ }
1421
+ }
1422
+
1423
+ function checkCursorSandbox(ctx, f) {
1424
+ if (parsed(f)?.type === "insecure_none") {
1425
+ const line = lineOf(f, /insecure_none/);
1426
+ add(ctx, "CU-NO-SANDBOX", { file: f, line, evidence: evidenceLine(f, line) });
1427
+ }
1428
+ }
1429
+
1430
+ // Cline keeps its approval settings in ~/.cline/data/globalState.json.
1431
+ function checkCline(ctx, f) {
1432
+ const json = parsed(f);
1433
+ if (!isObj(json)) return;
1434
+ if (json.yoloModeToggled === true) {
1435
+ const line = lineOf(f, /yoloModeToggled/);
1436
+ add(ctx, "CL-YOLO", { file: f, line, evidence: evidenceLine(f, line) });
1437
+ } else if (json.autoApprovalSettings?.enabled !== false && json.autoApprovalSettings?.actions?.executeAllCommands === true) {
1438
+ const line = lineOf(f, /executeAllCommands/);
1439
+ add(ctx, "CL-AUTO-COMMANDS", { file: f, line, evidence: evidenceLine(f, line) });
1440
+ }
1441
+ }
1442
+
1443
+ function checkGrok(ctx, f) {
1444
+ const toml = parsed(f);
1445
+ for (const command of commandsIn(toml?.ui?.status_line?.command)) checkCommand(ctx, command, f, "Grok's status line command");
1446
+ const mode = toml?.ui?.permission_mode ?? toml?.permission_mode;
1447
+ if (mode === "always-approve" || mode === "yolo") {
1448
+ const line = lineOf(f, /permission_mode/);
1449
+ add(ctx, "GROK-ALWAYS-APPROVE", { file: f, line, evidence: evidenceLine(f, line), vars: { mode } });
1450
+ }
1451
+ }
1452
+
1453
+ function checkAmp(ctx, f) {
1454
+ if (parsed(f)?.["amp.dangerouslyAllowAll"] === true) {
1455
+ const line = lineOf(f, /dangerouslyAllowAll/);
1456
+ add(ctx, "AMP-ALLOW-ALL", { file: f, line, evidence: evidenceLine(f, line) });
1457
+ }
1458
+ }
1459
+
1460
+ // YAML, read line by line: GOOSE_MODE sits at the top level.
1461
+ function checkGoose(ctx, f) {
1462
+ const line = lineOf(f, /^GOOSE_MODE\s*:\s*["']?auto["']?\s*(#.*)?$/);
1463
+ if (line) add(ctx, "GOOSE-AUTO", { file: f, line, evidence: evidenceLine(f, line) });
1464
+ }
1465
+
1466
+ // Continue's data destinations send session events to a URL.
1467
+ function checkContinue(ctx, f) {
1468
+ for (const [i, text] of f.lines.entries()) {
1469
+ const api = text.match(/^\s*(?:-\s*)?["']?apiBase["']?\s*:\s*["']?([^\s"',#]+)/);
1470
+ if (api) checkEndpointSetting(ctx, f, "Continue's model settings", "apiBase", api[1], i + 1);
1471
+ const m = text.match(/^\s*(?:-\s*)?destination\s*:\s*["']?(https?:\/\/[^\s"'#]+)/i);
1472
+ if (!m) continue;
1473
+ let host;
1474
+ try {
1475
+ host = new URL(m[1]).hostname;
1476
+ } catch {
1477
+ continue;
1478
+ }
1479
+ if (!isLocalHost(host)) add(ctx, "CONT-DATA", { file: f, line: i + 1, evidence: text, vars: { host } });
1480
+ }
1481
+ }
1482
+
1483
+ // YAML, read line by line. lint-cmd runs after every change Aider makes
1484
+ // (auto-lint is on by default), test-cmd after changes when auto-test is on,
1485
+ // and the notification command when Aider is waiting.
1486
+ const AIDER_COMMANDS = { "lint-cmd": "Aider's lint command", "test-cmd": "Aider's test command", "notifications-command": "Aider's notification command" };
1487
+ const unquote = (v) => v.trim().replace(/^(["'])(.*)\1$/, "$2");
519
1488
  function checkAider(ctx, f) {
1489
+ const yaml = parsed(f);
1490
+ if (!isObj(yaml)) return checkAiderLines(ctx, f);
1491
+ // The line a key is on, for keys written plain or quoted.
1492
+ const keyAt = (key) => lineOf(f, new RegExp(`^[ \\t]*(?:-[ \\t]+)?["']?${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["']?[ \\t]*:`, "m")) || lineOf(f, key);
1493
+ const valueAt = (key, value) => (typeof value === "string" && value.trim() && lineOf(f, value.trim().split("\n")[0].slice(0, 60))) || keyAt(key);
1494
+ if (yaml["yes-always"] === true) {
1495
+ const line = keyAt("yes-always");
1496
+ add(ctx, "AIDER-YES", { file: f, line, evidence: evidenceLine(f, line) });
1497
+ }
1498
+ for (const key of [...Object.keys(AIDER_COMMANDS), "set-env", "openai-api-base"]) {
1499
+ const raw = yaml[key];
1500
+ // One value, a list of them, or "- python: flake8" items read as mappings.
1501
+ const values = (Array.isArray(raw) ? raw : [raw]).flatMap((v) => (isObj(v) ? Object.entries(v).map(([k, x]) => (key === "lint-cmd" ? `${k}: ${x}` : `${k}=${x}`)) : typeof v === "string" || typeof v === "number" ? [String(v)] : [])).slice(0, 50);
1502
+ for (const value of values) aiderValue(ctx, f, key, value, valueAt(key, value));
1503
+ }
1504
+ }
1505
+ // Aider's settings read line by line, for a file the YAML reader can't read.
1506
+ function checkAiderLines(ctx, f) {
520
1507
  const line = lineOf(f, /^\s*yes-always\s*:\s*true\b/i);
521
1508
  if (line) add(ctx, "AIDER-YES", { file: f, line, evidence: evidenceLine(f, line) });
1509
+ let key = null;
1510
+ for (const [i, text] of f.lines.entries()) {
1511
+ const top = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(text);
1512
+ if (top) {
1513
+ key = top[1].toLowerCase();
1514
+ const value = unquote(top[2].replace(/\s+#.*$/, ""));
1515
+ if (value) aiderValue(ctx, f, key, value, i + 1);
1516
+ continue;
1517
+ }
1518
+ // A list under the key: lint-cmd as "- python: flake8 --select", set-env as "- NAME=value".
1519
+ const item = /^\s+-\s+(.*)$/.exec(text);
1520
+ if (item && key) aiderValue(ctx, f, key, unquote(item[1]), i + 1);
1521
+ }
1522
+ }
1523
+ function aiderValue(ctx, f, key, value, line) {
1524
+ if (key === "openai-api-base") checkEndpointSetting(ctx, f, "Aider's openai-api-base setting", "openai-api-base", value, line);
1525
+ if (Object.hasOwn(AIDER_COMMANDS, key)) {
1526
+ const command = key === "lint-cmd" ? value.replace(/^[\w+#.-]{1,30}:\s+/, "") : value;
1527
+ if (command && !command.startsWith("[")) checkCommand(ctx, command, f, AIDER_COMMANDS[key], { line });
1528
+ } else if (key === "set-env") {
1529
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(value);
1530
+ const variable = m && codeLoadingVariable(m[1], unquote(m[2]));
1531
+ if (variable) add(ctx, "ENV-CODE-LOAD", { file: f, line, evidence: evidenceLine(f, line), vars: { where: "Aider's set-env setting", variable } });
1532
+ if (m) checkEnvironment(ctx, f, "Aider's set-env setting", m[1], unquote(m[2]), line);
1533
+ }
522
1534
  }
523
1535
 
524
1536
  function checkPackageJson(ctx, f) {
525
1537
  const json = parsed(f);
526
1538
  if (!isObj(json?.scripts)) return;
527
1539
  for (const [name, script] of Object.entries(json.scripts)) {
528
- const m = typeof script === "string" && script.match(RX_DANGER_FLAGS);
529
- if (m) {
1540
+ const hit = typeof script === "string" && findDangerFlag(script);
1541
+ if (hit) {
530
1542
  const line = lineOf(f, `"${name}"`);
531
- add(ctx, "FLAG-SCRIPT", { file: f, line, evidence: evidenceLine(f, line), vars: { flag: m[0].trim(), rule: name, where: `The “${name}” script in package.json` } });
1543
+ add(ctx, "FLAG-SCRIPT", { file: f, line, evidence: evidenceLine(f, line), tool: hit.agent, vars: { flag: hit.flag, rule: name, where: `The “${name}” script in package.json` } });
532
1544
  }
533
1545
  }
534
1546
  }
535
1547
 
536
- // --- Commands run by hooks -----------------------------------------------------
1548
+ // --- Commands run by hooks ---------------------------------------------------
537
1549
 
538
- function checkCommand(ctx, command, f, where) {
539
- const line = lineOf(f, command.split("\n")[0].slice(0, 60)) || lineOf(f, /"command"/);
1550
+ function checkCommand(ctx, command, f, where, { autorun = true, line: near = 0 } = {}) {
1551
+ const line = lineOf(f, command.split("\n")[0].slice(0, 60)) || near || lineOf(f, /"command"/);
540
1552
  const cmd = clip(command, 140);
541
1553
  const vars = { where, cmd };
542
- if (RX_REMOTE_EXEC.test(command)) add(ctx, "HOOK-REMOTE-EXEC", { file: f, line, evidence: command, vars });
543
- else if (RX_NET_SEND.test(command)) add(ctx, "HOOK-NETWORK", { file: f, line, evidence: command, vars });
544
- if (RX_DESTRUCTIVE.test(command)) add(ctx, "HOOK-DESTRUCTIVE", { file: f, line, evidence: command, vars });
545
- if (RX_OUTSIDE_SCRIPT.test(command)) add(ctx, "HOOK-OUTSIDE", { file: f, line, evidence: command, vars });
546
- const flag = command.match(RX_DANGER_FLAGS);
547
- if (flag) add(ctx, "FLAG-SCRIPT", { file: f, line, evidence: command, vars: { flag: flag[0].trim(), where } });
1554
+ const remote = RX_REMOTE_EXEC.test(command);
1555
+ const sends = !remote && sendsData(command);
1556
+ if (remote) add(ctx, "HOOK-REMOTE-EXEC", { file: f, line, evidence: command, vars });
1557
+ else if (sends) add(ctx, "HOOK-NETWORK", { file: f, line, evidence: command, vars });
1558
+ const destructive = isDestructive(command);
1559
+ if (destructive) add(ctx, "HOOK-DESTRUCTIVE", { file: f, line, evidence: command, vars });
1560
+ const outside = runsOutsideScript(command);
1561
+ if (outside) add(ctx, "HOOK-OUTSIDE", { file: f, line, evidence: command, vars });
1562
+ const hit = findDangerFlag(command);
1563
+ if (hit) add(ctx, "FLAG-SCRIPT", { file: f, line, evidence: command, tool: hit.agent, vars: { flag: hit.flag, where } });
1564
+ // Anything else a project's settings run on their own is still the
1565
+ // project's code running on this computer, reported once per file.
1566
+ if (autorun && !remote && !sends && !destructive && !outside && !hit && inProject(ctx, f) && !harmlessCommand(command)) {
1567
+ if (!ctx.autorun.has(f)) ctx.autorun.set(f, { line, evidence: command, vars });
1568
+ }
1569
+ }
1570
+
1571
+ // Commands that only print, wait or make a sound, such as a notification.
1572
+ const HARMLESS_PROGRAMS = new Set(["echo", "printf", "true", "false", ":", "date", "pwd", "exit", "sleep", "notify-send", "terminal-notifier", "say", "afplay", "paplay", "aplay", "tput", "clear"]);
1573
+ function harmlessCommand(command) {
1574
+ if (/\$\(|`|<\(|>\(/.test(command)) return false;
1575
+ const segments = commandSegments(shellWords(command));
1576
+ return (
1577
+ segments.length > 0 &&
1578
+ segments.every((segment) => {
1579
+ let i = 0;
1580
+ while (i < segment.length - 1 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(segment[i])) i++;
1581
+ return HARMLESS_PROGRAMS.has(segment[i].split(/[\\/]/).pop().toLowerCase()) && !segment.slice(i + 1).some((w) => /^[<>]|^\d?>/.test(w));
1582
+ })
1583
+ );
1584
+ }
1585
+
1586
+ // A settings file that has the agent read instructions from outside the
1587
+ // project, or from a web page.
1588
+ function checkNamed(ctx) {
1589
+ for (const n of ctx.named) {
1590
+ const f = ctx.files.find((x) => x.path === n.from);
1591
+ if (!f || (!n.outside && !n.web)) continue;
1592
+ const line = lineOf(f, n.name.slice(0, 60));
1593
+ if (n.web) {
1594
+ let host = "";
1595
+ try {
1596
+ host = new URL(n.name).hostname;
1597
+ } catch {}
1598
+ if (host) add(ctx, "TXT-REMOTE-INSTRUCTIONS", { file: f, line, evidence: evidenceLine(f, line), vars: { host } });
1599
+ } else add(ctx, "TXT-IMPORT-OUTSIDE", { file: f, line, evidence: evidenceLine(f, line), vars: { ref: clip(n.name, 80) } });
1600
+ }
1601
+ }
1602
+
1603
+ function checkAutorun(ctx) {
1604
+ for (const [f, found] of ctx.autorun) add(ctx, "PROJECT-AUTORUN", { file: f, ...found });
1605
+ }
1606
+
1607
+ // VS Code tasks, which every editor built on VS Code runs. A task with
1608
+ // runOn: folderOpen runs when the folder opens: in Cursor without asking,
1609
+ // since Workspace Trust is off there by default.
1610
+ function checkVsCodeTasks(ctx, f) {
1611
+ const json = parsed(f);
1612
+ const tasks = Array.isArray(json?.tasks) ? json.tasks.slice(0, 200) : [];
1613
+ for (const task of tasks) {
1614
+ if (!isObj(task) || task.runOptions?.runOn !== "folderOpen") continue;
1615
+ const commands = [task, task.windows, task.osx, task.linux]
1616
+ .filter(isObj)
1617
+ .map((t) => [t.command, ...(Array.isArray(t.args) ? t.args : [])].filter((w) => typeof w === "string" || (isObj(w) && typeof w.value === "string")).map((w) => (typeof w === "string" ? w : w.value)).join(" ").trim())
1618
+ .filter(Boolean);
1619
+ const label = typeof task.label === "string" ? task.label : "";
1620
+ // The "folderOpen" line nearest the task's label, so the evidence is the
1621
+ // setting itself.
1622
+ const labelLine = label ? lineOf(f, `"${label.slice(0, 60)}"`) : 0;
1623
+ const opens = (f.lines ?? []).flatMap((l, i) => (/"folderOpen"/.test(l) ? [i + 1] : []));
1624
+ const line = opens.length ? opens.reduce((a, b) => (labelLine && Math.abs(b - labelLine) < Math.abs(a - labelLine) ? b : a)) : labelLine || lineOf(f, /folderOpen/);
1625
+ const command = commands[0] ?? label;
1626
+ add(ctx, "TASK-FOLDER-OPEN", { file: f, line, evidence: evidenceLine(f, line), vars: { cmd: clip(command || "a task", 140) } });
1627
+ for (const c of new Set(commands)) checkCommand(ctx, c, f, "A task that runs when the folder opens", { autorun: false });
1628
+ }
548
1629
  }
549
1630
 
550
1631
  function checkHookScript(ctx, f) {
551
- const where = `The hook script ${f.path}`;
1632
+ const where = "This hook script";
552
1633
  for (const [i, line] of f.lines.entries()) {
553
1634
  if (!line.trim() || /^\s*(#|\/\/|REM\b)/i.test(line)) continue;
554
1635
  const vars = { where, cmd: clip(line, 140) };
555
1636
  const opts = { file: f, line: i + 1, evidence: line, vars };
556
1637
  if (RX_REMOTE_EXEC.test(line)) add(ctx, "HOOK-REMOTE-EXEC", opts);
557
- else if (RX_NET_SEND.test(line)) add(ctx, "HOOK-NETWORK", opts);
558
- if (RX_DESTRUCTIVE.test(line)) add(ctx, "HOOK-DESTRUCTIVE", opts);
559
- const flag = line.match(RX_DANGER_FLAGS);
560
- if (flag) add(ctx, "FLAG-SCRIPT", { ...opts, vars: { flag: flag[0].trim(), where } });
1638
+ else if (sendsData(line)) add(ctx, "HOOK-NETWORK", opts);
1639
+ if (isDestructive(line)) add(ctx, "HOOK-DESTRUCTIVE", opts);
1640
+ const hit = findDangerFlag(line);
1641
+ if (hit) add(ctx, "FLAG-SCRIPT", { ...opts, tool: hit.agent, vars: { flag: hit.flag, where } });
561
1642
  }
562
1643
  }
563
1644
 
564
- // --- Instruction files -----------------------------------------------------------
1645
+ // --- Instruction files -------------------------------------------------------
565
1646
 
566
1647
  function checkInstructionText(ctx, f) {
567
1648
  const text = f.content;
@@ -570,80 +1651,111 @@ function checkInstructionText(ctx, f) {
570
1651
  return { file: f, line, evidence: evidenceLine(f, line) };
571
1652
  };
572
1653
 
573
- const tags = [...text.matchAll(/[\u{E0000}-\u{E007F}]/gu)];
1654
+ const tags = hiddenTags(text);
574
1655
  if (tags.length) {
575
- const decoded = tags
576
- .map((m) => String.fromCharCode(m[0].codePointAt(0) - 0xe0000))
577
- .join("")
578
- .replace(/[^\x20-\x7e]/g, "");
579
- add(ctx, "TXT-TAGS", { ...at(tags[0].index), evidence: null, vars: { count: tags.length, decoded: clip(maskSecrets(decoded).text, 140) } });
1656
+ const decoded = tags.map((t) => t.decoded).join("");
1657
+ const count = tags.reduce((n, t) => n + t.length, 0);
1658
+ add(ctx, "TXT-TAGS", { ...at(tags[0].index), evidence: null, vars: { count, decoded: clip(maskSecrets(decoded).text, 140) } });
580
1659
  }
581
- const bidi = text.search(/[‪-‮⁦-⁩]/);
1660
+ const bidi = text.search(/[\u202a-\u202e\u2066-\u2069]/);
582
1661
  if (bidi >= 0) add(ctx, "TXT-BIDI", { ...at(bidi), evidence: null });
583
- const zeroWidth = [...text.slice(1).matchAll(/[​-‍⁠᠎]/g)];
584
- if (zeroWidth.length >= 3) add(ctx, "TXT-ZERO-WIDTH", { ...at(zeroWidth[0].index + 1), evidence: null, vars: { count: zeroWidth.length } });
1662
+ const zeroWidth = hiddenZeroWidth(text);
1663
+ if (zeroWidth.length >= 3) add(ctx, "TXT-ZERO-WIDTH", { ...at(zeroWidth[0]), evidence: null, vars: { count: zeroWidth.length } });
585
1664
 
586
- for (const m of text.matchAll(/<!--([\s\S]*?)-->/g)) {
587
- const inner = m[1].trim();
1665
+ for (const c of hiddenComments(text)) {
1666
+ const inner = c.inner.trim();
588
1667
  if (inner && !RX_BENIGN_COMMENT.test(inner) && RX_INJECT_WORDS.test(inner)) {
589
- add(ctx, "TXT-HIDDEN-COMMENT", { ...at(m.index), evidence: inner });
1668
+ add(ctx, "TXT-HIDDEN-COMMENT", { ...at(c.index), evidence: inner });
590
1669
  break;
591
1670
  }
592
1671
  }
593
1672
 
594
1673
  // Rules marked `affirmative` ignore lines that warn against the thing,
595
1674
  // such as "Never read .env files" or "Do not disable the sandbox".
596
- const textRule = (id, re, varsFrom, { affirmative = false } = {}) => {
597
- const m = firstMatch(text, re, affirmative);
1675
+ const textRule = (id, re, varsFrom, { affirmative = false, reject } = {}) => {
1676
+ const m = firstMatch(text, re, affirmative, reject);
598
1677
  if (m) add(ctx, id, { ...at(m.index + (m[0].length - m[0].trimStart().length)), vars: varsFrom ? varsFrom(m) : {} });
599
1678
  };
600
1679
  textRule("TXT-REMOTE-EXEC", RX_REMOTE_EXEC, null, { affirmative: true });
601
1680
  textRule("TXT-EXFIL", RX_EXFIL_HOST, (m) => ({ host: m[1] }));
602
- textRule("TXT-OVERRIDE", RX_OVERRIDE, (m) => ({ phrase: clip(m[0], 80) }), { affirmative: true });
603
- textRule("TXT-SECRET-ACCESS", RX_SECRET_ACCESS, (m) => ({ phrase: clip(m[0], 80) }), { affirmative: true });
604
- textRule("TXT-BLOB", RX_BLOB, (m) => ({ length: m[0].length.toLocaleString("en-US") }));
605
- textRule("TXT-IMPORT-OUTSIDE", RX_IMPORT_OUTSIDE, (m) => ({ ref: "@" + clip(m[1], 80) }));
606
- textRule("FLAG-DOCS", RX_DANGER_FLAGS, (m) => ({ flag: m[0].trim() }), { affirmative: true });
1681
+ textRule("TXT-PASTE-SITE", RX_PASTE_SITE, (m) => ({ host: m[1].toLowerCase() }), { affirmative: true });
1682
+ // A paste site already has its own finding.
1683
+ textRule("TXT-REMOTE-INSTRUCTIONS", RX_REMOTE_INSTRUCTIONS, (m) => ({ host: (m[1] ?? m[2]).toLowerCase() }), { affirmative: true, reject: (m) => RX_PASTE_SITE.test(` ${m[1] ?? m[2]}`) });
1684
+ textRule("TXT-ARCHIVE-PASSWORD", RX_ARCHIVE_PASSWORD, null, { affirmative: true, reject: (m) => !givesArchivePassword(text, m) });
1685
+ textRule("TXT-QUARANTINE", RX_QUARANTINE, null, { affirmative: true });
1686
+ // Defensive instructions quote injections as examples, as in: if a page
1687
+ // says "ignore previous instructions", don't follow it.
1688
+ let fence = null;
1689
+ textRule("TXT-OVERRIDE", RX_OVERRIDE, (m) => ({ phrase: clip(m[0], 80) }), {
1690
+ affirmative: true,
1691
+ reject: (m) => quotedExample(text, m, "\"'“‘`") || fencedExample(text, m.index, (fence ??= fenceAt(text))),
1692
+ });
1693
+ // Setting up a project ("copy .env.example to .env", "add .env to
1694
+ // .gitignore") isn't handing secrets to the agent.
1695
+ textRule("TXT-SECRET-ACCESS", RX_SECRET_ACCESS, (m) => ({ phrase: clip(m[0], 80) }), {
1696
+ affirmative: true,
1697
+ reject: (m) =>
1698
+ quotedExample(text, m, "\"'“‘") ||
1699
+ /\.env\.(?:example|sample|template|dist|defaults)\b|gitignore/i.test(text.slice(m.index, m.index + m[0].length + 40)) ||
1700
+ // "Settings are read from .env" says what a program does, not what the agent should.
1701
+ /\b(?:is|are|be|been|being|was|were|gets?|got)\s+(?:\w+ly\s+)?$/i.test(text.slice(Math.max(text.lastIndexOf("\n", m.index - 1) + 1, m.index - 40), m.index)),
1702
+ });
1703
+ const blob = longBase64(text);
1704
+ if (blob) add(ctx, "TXT-BLOB", { ...at(blob.index), vars: { length: blob.length.toLocaleString("en-US") } });
1705
+ // Only files that import can pull a file in, and never from inside code.
1706
+ if (CAN_IMPORT.test(f.path)) {
1707
+ textRule("TXT-IMPORT-OUTSIDE", RX_IMPORT_OUTSIDE, (m) => ({ ref: "@" + clip(m[1], 80) }), {
1708
+ reject: (m) => (fence ??= fenceAt(text))(m.index) !== null || inCodeSpan(text, m.index),
1709
+ });
1710
+ }
1711
+ const flag = findDangerFlag(text, (index) => negated(text, index));
1712
+ if (flag) add(ctx, "FLAG-DOCS", { ...at(flag.index), tool: flag.agent, vars: { flag: flag.flag } });
607
1713
 
608
- if (text.length > 60_000 && !f.loose) add(ctx, "TXT-HUGE", { file: f, vars: { size: `${Math.round(text.length / 1024)} KB` } });
1714
+ // A file read only in part is reported as that instead.
1715
+ if (text.length > 60_000 && !f.loose && !f.partial) add(ctx, "TXT-HUGE", { file: f, vars: { size: `${Math.round(text.length / 1024)} KB` } });
609
1716
  }
610
1717
 
611
- // --- MCP servers -------------------------------------------------------------------
612
-
613
- function collectMcpServers(ctx) {
614
- for (const f of ctx.files) {
615
- if (!f.content) continue;
616
- const p = f.path;
617
- let groups = [];
618
- if (/(^|\/)\.codex\/config\.toml$/i.test(p)) groups = [parsed(f)?.mcp_servers];
619
- else if (/\.jsonc?$/i.test(p)) {
620
- const json = parsed(f);
621
- if (!isObj(json)) continue;
622
- if (/(^|\/)\.vscode\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
623
- else if (/(^|\/)opencode\.jsonc?$/i.test(p)) groups = [json.mcp];
624
- else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(p)) groups = [json.context_servers];
625
- else if (/\/User\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
626
- else if (/\/User\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
627
- else if (/(^|\/)\.claude\.json$/i.test(p)) groups = [json.mcpServers, ...(isObj(json.projects) ? Object.values(json.projects).map((x) => x?.mcpServers) : [])];
628
- else if (/(^|\/)\.vscode\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
629
- else groups = [json.mcpServers];
630
- }
631
- for (const group of groups) {
632
- if (!isObj(group)) continue;
633
- for (const [name, def] of Object.entries(group)) ctx.mcpServers.push(normalizeServer(name, def, f));
634
- }
1718
+ // --- MCP servers -------------------------------------------------------------
1719
+
1720
+ // The MCP servers a file defines, wherever its agent keeps them.
1721
+ function collectMcpServers(ctx, f) {
1722
+ const p = f.path;
1723
+ let groups = [];
1724
+ if (/(^|\/)(\.codex\/([^/]+\.)?config|\.grok\/config)\.toml$/i.test(p)) groups = [parsed(f)?.mcp_servers];
1725
+ // Continue lists servers with a name each; Goose calls them extensions.
1726
+ else if (/(^|\/)\.continue\/(config|mcpServers\/[^/]+)\.ya?ml$/i.test(p)) {
1727
+ const list = parsed(f)?.mcpServers;
1728
+ groups = [Array.isArray(list) ? Object.fromEntries(list.slice(0, 200).filter(isObj).map((x, n) => [typeof x.name === "string" ? x.name : `server ${n + 1}`, x])) : null];
1729
+ } else if (/(^|\/)goose\/config\.ya?ml$/i.test(p)) groups = [parsed(f)?.extensions];
1730
+ else if (/\.jsonc?$/i.test(p)) {
1731
+ const json = parsed(f);
1732
+ if (!isObj(json)) return;
1733
+ if (/(^|\/)(\.vscode|\.github)\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
1734
+ else if (/(^|\/)(\.amp|\.config\/amp)\/settings\.json$/i.test(p)) groups = [json["amp.mcpServers"]];
1735
+ else if (/(^|\/)opencode\.jsonc?$/i.test(p)) groups = [json.mcp];
1736
+ else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(p)) groups = [json.context_servers];
1737
+ else if (/\/User\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
1738
+ else if (/\/User\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
1739
+ else if (/(^|\/)\.claude\.json$/i.test(p)) groups = [json.mcpServers, ...(isObj(json.projects) ? Object.values(json.projects).map((x) => x?.mcpServers) : [])];
1740
+ else if (/(^|\/)\.vscode\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
1741
+ else if (f.role === "mcp-servers") groups = [json.mcpServers ?? json];
1742
+ else groups = [json.mcpServers];
1743
+ }
1744
+ for (const group of groups) {
1745
+ if (!isObj(group)) continue;
1746
+ for (const [name, def] of Object.entries(group)) ctx.mcpServers.push(normalizeServer(name, def, f));
635
1747
  }
636
1748
  }
637
1749
 
638
1750
  function normalizeServer(name, def, file) {
639
1751
  const d = isObj(def) ? def : {};
640
- let command = d.command;
641
- let args = Array.isArray(d.args) ? d.args.map(String) : [];
1752
+ let command = d.command ?? d.cmd;
1753
+ let args = scalars(d.args);
642
1754
  if (Array.isArray(command)) {
643
- args = [...command.slice(1).map(String), ...args];
1755
+ args = [...scalars(command.slice(1)), ...args];
644
1756
  command = command[0];
645
1757
  } else if (isObj(command)) {
646
- args = Array.isArray(command.args) ? command.args.map(String) : args;
1758
+ args = Array.isArray(command.args) ? scalars(command.args) : args;
647
1759
  command = command.path ?? command.command;
648
1760
  }
649
1761
  const url = [d.url, d.serverUrl, d.httpUrl].find((u) => typeof u === "string") ?? null;
@@ -652,23 +1764,30 @@ function normalizeServer(name, def, file) {
652
1764
  file,
653
1765
  command: typeof command === "string" ? command : null,
654
1766
  args,
655
- env: isObj(d.env) ? d.env : isObj(d.environment) ? d.environment : {},
1767
+ env: isObj(d.env) ? d.env : isObj(d.environment) ? d.environment : isObj(d.envs) ? d.envs : {},
656
1768
  headers: isObj(d.headers) ? d.headers : isObj(d.http_headers) ? d.http_headers : {},
657
1769
  extra: d,
658
1770
  url,
659
1771
  alwaysAllow: d.alwaysAllow ?? d.autoApprove ?? d.auto_approve ?? (d.trust === true ? true : undefined),
660
- alwaysAllowKey: ["alwaysAllow", "autoApprove", "auto_approve", "trust"].find((k) => d[k] !== undefined) ?? null,
1772
+ alwaysAllowKey: ALWAYS_ALLOW_KEYS.find((k) => d[k] !== undefined) ?? null,
661
1773
  disabled: d.disabled === true || d.enabled === false,
662
1774
  };
663
1775
  }
664
1776
 
665
1777
  const REFERENCE = /^\$\{[^}]+\}$|^\$[A-Za-z_][A-Za-z0-9_]*$|^\{env:[^}]+\}$|^%[A-Za-z_][A-Za-z0-9_]*%$|\$\{(?:env|input):/i;
666
1778
 
1779
+ // References such as ${GITHUB_TOKEN}, {env:KEY} or %API_KEY%, anywhere in a value.
1780
+ const REFERENCES = /\$\{[^}]{0,200}\}|\{env:[^}]{0,200}\}|%[A-Za-z_][A-Za-z0-9_]{0,100}%|\$[A-Za-z_][A-Za-z0-9_]*/g;
1781
+
667
1782
  function isSecretValue(key, value) {
668
1783
  if (typeof value !== "string" || REFERENCE.test(value.trim()) || isPathLike(value)) return false;
669
1784
  if (isMasked(value)) return true;
670
- if (/^(true|false|\d+|https?:\/\/[^@]*)$/i.test(value)) return false;
671
- return /(token|secret|key|password|passwd|auth|credential|bearer|cookie|session)/i.test(key) ? looksLikeSecret(value) || value.length >= 20 : looksLikeToken(value) && value.length >= 24;
1785
+ // What's left once references and an auth scheme are taken out, so
1786
+ // "Bearer ${GITHUB_TOKEN}" counts as a reference too.
1787
+ const rest = value.replace(REFERENCES, "").replace(/^\s*(?:Bearer|Basic|Token|Bot)\b\s*/i, "").trim();
1788
+ if (rest.length < 8 || /^(true|false|\d+|https?:\/\/[^@]*)$/i.test(rest)) return false;
1789
+ if (/(token|secret|key|password|passwd|auth|credential|bearer|cookie|session)/i.test(key)) return looksLikeSecret(rest) || (rest.length >= 20 && !/\s/.test(rest));
1790
+ return looksLikeToken(rest) && rest.length >= 24;
672
1791
  }
673
1792
 
674
1793
  function redact(value) {
@@ -680,21 +1799,27 @@ function checkMcpServer(ctx, s) {
680
1799
  const tool = f.tools[0] ?? null;
681
1800
  const nameLine = lineOf(f, `"${s.name}"`) || lineOf(f, s.name);
682
1801
  const base = (line = nameLine) => ({ file: f, line, tool, evidence: evidenceLine(f, line) });
1802
+ const near = (test) => lineAfter(f, test, nameLine);
683
1803
 
684
1804
  for (const [key, value] of [...Object.entries(s.env), ...Object.entries(s.headers)]) {
685
1805
  if (isSecretValue(key, value)) {
686
- const line = lineOf(f, `"${key}"`) || lineOf(f, key) || nameLine;
1806
+ const line = near(`"${key}"`) || near(key) || nameLine;
687
1807
  add(ctx, "MCP-SECRET", { ...base(line), evidence: `${key} = ${redact(value)}`, vars: { server: s.name, key } });
688
1808
  }
689
1809
  }
1810
+ for (const [key, value] of Object.entries(s.env)) {
1811
+ const variable = codeLoadingVariable(key, value);
1812
+ if (variable) add(ctx, "MCP-ENV-CODE-LOAD", { ...base(near(`"${key}"`) || near(key) || nameLine), vars: { server: s.name, variable } });
1813
+ if (tlsOff(key, value)) add(ctx, "ENV-TLS-OFF", { ...base(near(`"${key}"`) || near(key) || nameLine), vars: { where: "An MCP server's env setting", variable: "NODE_TLS_REJECT_UNAUTHORIZED" } });
1814
+ }
690
1815
  for (const key of ["bearer_token", "bearerToken", "apiKey", "api_key", "token"]) {
691
1816
  const value = s.extra[key];
692
1817
  if (typeof value === "string" && isSecretValue(key, value)) {
693
- add(ctx, "MCP-SECRET", { ...base(lineOf(f, key) || nameLine), evidence: `${key} = ${redact(value)}`, vars: { server: s.name, key } });
1818
+ add(ctx, "MCP-SECRET", { ...base(near(key) || nameLine), evidence: `${key} = ${redact(value)}`, vars: { server: s.name, key } });
694
1819
  }
695
1820
  }
696
1821
  const secretArg = s.args.find((a) => isMasked(a) || (looksLikeToken(a) && a.length >= 24 && !a.includes("/")));
697
- if (secretArg) add(ctx, "MCP-SECRET", { ...base(lineOf(f, secretArg.slice(0, 20)) || nameLine), evidence: `args contain ${redact(secretArg)}`, vars: { server: s.name, key: "args" } });
1822
+ if (secretArg) add(ctx, "MCP-SECRET", { ...base(near(secretArg.slice(0, 20)) || nameLine), evidence: `args contain ${redact(secretArg)}`, vars: { server: s.name, key: "args" } });
698
1823
 
699
1824
  if (s.url) {
700
1825
  let u = null;
@@ -702,95 +1827,241 @@ function checkMcpServer(ctx, s) {
702
1827
  u = new URL(s.url);
703
1828
  } catch {}
704
1829
  if (u) {
705
- const local = /^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?|0\.0\.0\.0|host\.docker\.internal)$/i.test(u.hostname);
706
- if (u.protocol === "http:" && !local) add(ctx, "MCP-HTTP", { ...base(lineOf(f, s.url) || nameLine), vars: { server: s.name, host: u.hostname } });
1830
+ if (u.protocol === "http:" && !isLocalHost(u.hostname)) add(ctx, "MCP-HTTP", { ...base(near(s.url) || nameLine), vars: { server: s.name, host: u.hostname } });
707
1831
  if ([...u.searchParams.keys()].some((k) => /token|key|secret|auth|sig|password/i.test(k)) || u.password || isMasked(s.url)) {
708
- add(ctx, "MCP-URL-TOKEN", { ...base(lineOf(f, u.hostname) || nameLine), vars: { server: s.name } });
1832
+ add(ctx, "MCP-URL-TOKEN", { ...base(near(u.hostname) || nameLine), vars: { server: s.name } });
709
1833
  }
710
1834
  }
711
1835
  }
712
1836
 
713
1837
  const pkg = packageSpec(s.command, s.args);
714
- if (pkg && !pkg.pinned) {
1838
+ const flagged = checkMcpPackage(ctx, s, base, near);
1839
+ if (pkg && !pkg.pinned && !flagged) {
715
1840
  add(ctx, "MCP-UNPINNED", {
716
- ...base(lineOf(f, pkg.spec) || nameLine),
717
- vars: { server: s.name, command: clip([s.command, ...s.args].join(" "), 90), pkg: pkg.name },
1841
+ ...base(near(pkg.spec) || nameLine),
1842
+ vars: { server: s.name, command: clip([s.command, ...s.args].join(" "), 90), pkg: pkg.name, lookup: pkg.python ? `pip index versions ${pkg.name}` : `npm view ${pkg.name} version` },
718
1843
  });
719
1844
  }
720
1845
 
721
1846
  if (/(^|[\\/])(docker|podman)(\.exe)?$/i.test(s.command ?? "")) {
722
- const flag = dockerRisk(s.args);
723
- if (flag) add(ctx, "MCP-DOCKER", { ...base(lineOf(f, flag.split(" ")[0]) || nameLine), vars: { server: s.name, flag } });
1847
+ const risk = dockerRisk(s.args);
1848
+ if (risk) add(ctx, "MCP-DOCKER", { ...base(near(risk.arg) || nameLine), vars: { server: s.name, flag: risk.flag } });
1849
+ }
1850
+
1851
+ // What the command runs, whatever launches it: a download piped into a
1852
+ // shell, or, in a project's own settings, a file from the project.
1853
+ if (typeof s.command === "string" && s.command) {
1854
+ const line = [s.command, ...s.args].join(" ");
1855
+ if (RX_REMOTE_EXEC.test(line)) add(ctx, "HOOK-REMOTE-EXEC", { ...base(near(s.command) || nameLine), evidence: line, vars: { where: "An MCP server's command", cmd: clip(line, 140) } });
1856
+ else if (!pkg && inProject(ctx, f)) {
1857
+ const local = localCode(s.command, s.args);
1858
+ if (local) add(ctx, "MCP-LOCAL-CODE", { ...base(near(local.slice(0, 60)) || nameLine), vars: { server: s.name, path: clip(local, 120) } });
1859
+ }
724
1860
  }
725
1861
 
726
1862
  const broad = s.args.find((a) => isBroadPath(a));
727
1863
  if (broad && !/(^|[\\/])(docker|podman)(\.exe)?$/i.test(s.command ?? "")) {
728
- add(ctx, "MCP-FS-BROAD", { ...base(lineOf(f, `"${broad}"`) || nameLine), vars: { server: s.name, path: broad } });
1864
+ add(ctx, "MCP-FS-BROAD", { ...base(near(`"${broad}"`) || nameLine), vars: { server: s.name, path: broad } });
729
1865
  }
730
1866
 
731
1867
  if (SHELL_SERVER.test(s.name) || (pkg && SHELL_SERVER.test(pkg.name))) add(ctx, "MCP-SHELL", { ...base(), vars: { server: s.name } });
732
1868
 
733
1869
  if (s.alwaysAllow === true || (Array.isArray(s.alwaysAllow) && s.alwaysAllow.length)) {
734
1870
  const count = s.alwaysAllow === true ? "every tool" : `${s.alwaysAllow.length} tool${s.alwaysAllow.length === 1 ? "" : "s"}`;
735
- add(ctx, "MCP-ALWAYS-ALLOW", { ...base(lineOf(f, s.alwaysAllowKey) || nameLine), vars: { server: s.name, key: s.alwaysAllowKey, count } });
1871
+ add(ctx, "MCP-ALWAYS-ALLOW", { ...base(near(s.alwaysAllowKey) || nameLine), vars: { server: s.name, setting: s.alwaysAllowKey, count } });
736
1872
  }
737
1873
  }
738
1874
 
1875
+ // The project file an MCP server's command runs, or the code a shell is given
1876
+ // inline: ./server.js, node tools/server.js, python3 -m pkg isn't one.
1877
+ const RUNS_FILES = /^(?:node|nodejs|deno|bun|python[0-9.]*|py|ruby|perl|php|bash|sh|zsh|dash|pwsh|powershell|cmd|tsx|ts-node)$/i;
1878
+ const relativeFile = (w) => typeof w === "string" && !/^(?:~|\/|[A-Za-z]:|-|[a-z][a-z0-9+.-]*:)/i.test(w) && (/^\.{1,2}[\\/]/.test(w) || /[\\/]/.test(w) || /\.(?:[cm]?[jt]sx?|py|rb|pl|php|sh|bash|ps1|bat|cmd)$/i.test(w));
1879
+ function localCode(command, args) {
1880
+ const name = command.split(/[\\/]/).pop().replace(/\.(?:exe|cmd|bat)$/i, "");
1881
+ if (relativeFile(command) && !RUNS_FILES.test(name)) return command;
1882
+ // uv run server.py runs a file from the project too.
1883
+ if (/^uv$/i.test(name) && args[0] === "run") return args.slice(1).find((a) => relativeFile(a)) ?? null;
1884
+ if (!RUNS_FILES.test(name)) return null;
1885
+ const inline = args.findIndex((a) => /^(?:-c|\/c|\/k|-Command|-e|--eval)$/i.test(a));
1886
+ if (inline >= 0 && typeof args[inline + 1] === "string") return args[inline + 1];
1887
+ return args.find((a) => relativeFile(a)) ?? null;
1888
+ }
1889
+
1890
+ // Launcher options that name the package, and options that take a value, so
1891
+ // the value isn't read as the package (npx --registry URL pkg, uvx --python
1892
+ // 3.12 pkg). For uvx, -p is the Python version.
1893
+ const LAUNCHER_OPTIONS = {
1894
+ node: { pkg: ["-p", "--package"], valued: ["--registry", "--cache", "--prefix", "--userconfig", "-c", "--call", "--node-options", "-w", "--workspace"] },
1895
+ python: {
1896
+ pkg: ["--from", "--spec"],
1897
+ valued: ["-p", "--python", "--with", "--with-editable", "--with-requirements", "--index", "--index-url", "--extra-index-url", "--default-index", "--find-links", "--constraints", "--overrides", "--cache-dir", "--directory", "--project", "--env-file", "--pip-args"],
1898
+ },
1899
+ };
1900
+
739
1901
  export function packageSpec(command, args) {
740
- if (!command) return null;
1902
+ const raw = launcherSpec(command, args);
1903
+ return raw ? judgeSpec(raw.spec, raw.python) : null;
1904
+ }
1905
+
1906
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish", "ash"]);
1907
+
1908
+ // A command line split into words the way a shell would, for simple quoting:
1909
+ // "a b" and 'a b' are one word. Kept short, since it runs on untrusted text.
1910
+ function shellWords(text) {
1911
+ const words = [];
1912
+ let word = null;
1913
+ let quote = null;
1914
+ for (const ch of String(text).slice(0, 2000)) {
1915
+ if (quote) {
1916
+ if (ch === quote) quote = null;
1917
+ else word += ch;
1918
+ } else if (ch === '"' || ch === "'") {
1919
+ quote = ch;
1920
+ word ??= "";
1921
+ } else if (/\s/.test(ch)) {
1922
+ if (word !== null) words.push(word);
1923
+ word = null;
1924
+ } else if (";|&".includes(ch)) {
1925
+ if (word !== null) words.push(word);
1926
+ words.push(ch);
1927
+ word = null;
1928
+ } else word = (word ?? "") + ch;
1929
+ }
1930
+ if (word !== null) words.push(word);
1931
+ return words;
1932
+ }
1933
+
1934
+ // The separate commands in a list of words: a; b && c | d.
1935
+ function commandSegments(words) {
1936
+ const segments = [[]];
1937
+ for (const w of words) {
1938
+ if (w === ";" || w === "|" || w === "&") segments.push([]);
1939
+ else segments.at(-1).push(w);
1940
+ }
1941
+ return segments.filter((s) => s.length).slice(0, 10);
1942
+ }
1943
+
1944
+ // The argument a launcher such as npx or uvx runs, as { spec, python }. A
1945
+ // launcher can sit inside a wrapper: cmd /c, a shell's -c string,
1946
+ // PowerShell's -Command, env, npm exec, bun x or deno's npm: names.
1947
+ function launcherSpec(command, args, depth = 0) {
1948
+ if (typeof command !== "string" || !command || depth > 3) return null;
741
1949
  const base = command.split(/[\\/]/).pop().replace(/\.(cmd|exe|bat)$/i, "").toLowerCase();
742
- let rest = [...args];
743
- if (base === "cmd" && /^\/c$/i.test(rest[0] ?? "")) return packageSpec(rest[1], rest.slice(2));
1950
+ let rest = args.filter((a) => typeof a === "string").slice(0, 60);
1951
+ const inner = (words) => {
1952
+ for (const segment of commandSegments(words)) {
1953
+ // Past FOO=1 and exec, command, nohup or time in front of the command.
1954
+ let i = 0;
1955
+ while (i < segment.length - 1 && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(segment[i]) || /^(?:exec|command|nohup|time|builtin)$/.test(segment[i]))) i++;
1956
+ const found = launcherSpec(segment[i], segment.slice(i + 1), depth + 1);
1957
+ if (found) return found;
1958
+ }
1959
+ return null;
1960
+ };
1961
+ if (base === "cmd") {
1962
+ const c = rest.findIndex((a) => /^\/[ck]$/i.test(a));
1963
+ return c < 0 ? null : inner(rest.slice(c + 1).flatMap(shellWords));
1964
+ }
1965
+ if (SHELLS.has(base)) {
1966
+ const c = rest.findIndex((a) => /^-[a-z]*c[a-z]*$/i.test(a));
1967
+ return c < 0 || typeof rest[c + 1] !== "string" ? null : inner(shellWords(rest[c + 1]));
1968
+ }
1969
+ if (base === "pwsh" || base === "powershell") {
1970
+ const c = rest.findIndex((a) => /^-(?:c|command)$/i.test(a));
1971
+ return c < 0 ? null : inner(rest.slice(c + 1).flatMap(shellWords));
1972
+ }
1973
+ if (base === "env") {
1974
+ let i = 0;
1975
+ while (i < rest.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(rest[i]) || rest[i].startsWith("-"))) {
1976
+ if (/^(?:-S|--split-string)$/.test(rest[i])) return inner(shellWords(rest[i + 1] ?? ""));
1977
+ i += /^(?:-u|--unset|-C|--chdir)$/.test(rest[i]) ? 2 : 1;
1978
+ }
1979
+ return inner(rest.slice(i));
1980
+ }
1981
+ if (base === "deno") {
1982
+ const spec = rest.find((a) => /^npm:/i.test(a));
1983
+ return spec ? { spec: spec.slice(4), python: false } : null;
1984
+ }
1985
+ if ((base === "npm" && (rest[0] === "exec" || rest[0] === "x")) || (base === "bun" && rest[0] === "x")) return launcherSpec("npx", rest.slice(1), depth + 1);
744
1986
  if (base === "pnpm" || base === "yarn") {
745
1987
  if (rest[0] !== "dlx") return null;
746
1988
  rest = rest.slice(1);
747
1989
  } else if (base === "pipx") {
748
1990
  if (rest[0] !== "run") return null;
749
1991
  rest = rest.slice(1);
1992
+ } else if (base === "uv") {
1993
+ if (rest[0] !== "tool" || rest[1] !== "run") return null;
1994
+ rest = rest.slice(2);
750
1995
  } else if (!["npx", "bunx", "pnpx", "uvx"].includes(base)) return null;
751
1996
 
752
- const python = base === "uvx" || base === "pipx";
1997
+ const python = ["uvx", "pipx", "uv"].includes(base);
1998
+ const { pkg, valued } = LAUNCHER_OPTIONS[python ? "python" : "node"];
753
1999
  for (let i = 0; i < rest.length; i++) {
754
2000
  const a = rest[i];
755
- if (["-p", "--package", "--from", "--spec"].includes(a)) return judgeSpec(rest[i + 1], python);
756
- const eq = a.match(/^--(?:package|from|spec)=(.+)$/);
757
- if (eq) return judgeSpec(eq[1], python);
758
- if (a.startsWith("-")) continue;
759
- return judgeSpec(a, python);
2001
+ const eq = a.startsWith("--") ? a.indexOf("=") : -1;
2002
+ const name = eq > 0 ? a.slice(0, eq) : a;
2003
+ if (pkg.includes(name)) {
2004
+ const spec = eq > 0 ? a.slice(eq + 1) : rest[i + 1];
2005
+ return spec ? { spec, python } : null;
2006
+ }
2007
+ if (a.startsWith("-")) {
2008
+ if (eq < 0 && valued.includes(name)) i++;
2009
+ continue;
2010
+ }
2011
+ return { spec: a, python };
760
2012
  }
761
2013
  return null;
762
2014
  }
763
2015
 
764
2016
  function judgeSpec(spec, python) {
765
2017
  if (!spec) return null;
2018
+ // Local paths and URLs, such as ./server or git+https://..., aren't from a registry.
2019
+ if (/^(\.|\/|~|%|\$|[a-z][a-z0-9+.-]*:)/i.test(spec) || spec.includes("\\")) return null;
766
2020
  if (python) {
767
2021
  const name = spec.split(/[=@<>~!\[]/)[0];
768
- return { name, spec, pinned: /==\s*\d|@\s*\d/.test(spec) };
2022
+ const exact = spec.match(/(?:==|@)\s*(\d+(?:\.\d+){1,3})\s*$/);
2023
+ return { name, spec, pinned: /==\s*\d|@\s*\d/.test(spec), python: true, version: exact ? exact[1] : "" };
769
2024
  }
770
- if (/^(\.|\/|[a-z]+:|~)/i.test(spec)) return null; // local path or URL
771
2025
  const at = spec.lastIndexOf("@");
772
2026
  const name = at > 0 ? spec.slice(0, at) : spec;
773
2027
  const version = at > 0 ? spec.slice(at + 1) : "";
774
- return { name, spec, pinned: /^\d+\.\d+\.\d+([-+][\w.]+)?$/.test(version) };
2028
+ const pinned = /^\d+\.\d+\.\d+([-+][\w.]+)?$/.test(version);
2029
+ return { name, spec, pinned, version: pinned ? version : "" };
775
2030
  }
776
2031
 
2032
+ // The Docker option that gives a container control of the host, as
2033
+ // { flag, arg }. `flag` is a fixed description such as "--network=host" or
2034
+ // "-v ~", so the folder names in the real option never reach a report.
777
2035
  function dockerRisk(args) {
778
2036
  for (let i = 0; i < args.length; i++) {
779
2037
  const a = args[i];
780
2038
  const next = args[i + 1] ?? "";
781
- if (/^--privileged$/i.test(a)) return a;
782
- if (/^--(pid|network|net|ipc|uts)=host$/i.test(a)) return a;
783
- if (/^--(pid|network|net|ipc|uts)$/i.test(a) && next === "host") return `${a} host`;
784
- if (/^--cap-add=(ALL|SYS_ADMIN)$/i.test(a)) return a;
785
- if (a === "--cap-add" && /^(ALL|SYS_ADMIN)$/i.test(next)) return `${a} ${next}`;
2039
+ if (/^--privileged$/i.test(a)) return { flag: "--privileged", arg: a };
2040
+ let m = a.match(/^--(pid|network|net|ipc|uts)=host$/i) ?? (next === "host" ? a.match(/^--(pid|network|net|ipc|uts)$/i) : null);
2041
+ if (m) return { flag: `--${m[1].toLowerCase() === "net" ? "network" : m[1].toLowerCase()}=host`, arg: a };
2042
+ m = a.match(/^--cap-add=(ALL|SYS_ADMIN)$/i) ?? (a === "--cap-add" ? next.match(/^(ALL|SYS_ADMIN)$/i) : null);
2043
+ if (m) return { flag: `--cap-add=${m[1].toUpperCase()}`, arg: a };
786
2044
  const volume = a === "-v" || a === "--volume" ? next : a.startsWith("--volume=") ? a.slice(9) : null;
787
2045
  const mount = a === "--mount" ? next : a.startsWith("--mount=") ? a.slice(8) : null;
788
2046
  const source = volume ? mountSource(volume) : mount ? (mount.match(/(?:^|,)(?:source|src)=([^,]+)/)?.[1] ?? "") : null;
789
- if (source && (isBroadPath(source) || /docker\.sock|docker_engine/i.test(source))) return `${a === "--mount" || a.startsWith("--mount") ? "--mount" : "-v"} ${volume ?? mount}`;
2047
+ const label = source ? hostPathLabel(source) : null;
2048
+ if (label) return { flag: `${mount !== null ? "--mount" : "-v"} ${label}`, arg: a };
790
2049
  }
791
2050
  return null;
792
2051
  }
793
2052
 
2053
+ // "/", "~", "/etc", "C:\" or the Docker socket, for a mount source that
2054
+ // exposes the host. Null for anything narrower.
2055
+ function hostPathLabel(source) {
2056
+ if (/docker\.sock|docker_engine/i.test(source)) return "/var/run/docker.sock";
2057
+ if (!isBroadPath(source)) return null;
2058
+ const v = trimWord(String(source).trim().replace(/\\/g, "/"), "", "/");
2059
+ if (v === "") return "/";
2060
+ if (/^[A-Za-z]:$/.test(v)) return `${v.toUpperCase()}\\`;
2061
+ const system = v.match(/^\/(root|etc|var|opt|usr)$/i);
2062
+ return system ? `/${system[1].toLowerCase()}` : "~";
2063
+ }
2064
+
794
2065
  function mountSource(volume) {
795
2066
  const win = volume.match(/^([A-Za-z]:[\\/][^:]*)/);
796
2067
  return win ? win[1] : volume.split(":")[0];
@@ -799,7 +2070,7 @@ function mountSource(volume) {
799
2070
  export function isBroadPath(value) {
800
2071
  const raw = String(value).trim();
801
2072
  if (raw === "/" || raw === "\\") return true;
802
- const v = raw.replace(/\\/g, "/").replace(/\/+$/, "");
2073
+ const v = trimWord(raw.replace(/\\/g, "/"), "", "/");
803
2074
  return (
804
2075
  /^(~|\$HOME|\$\{HOME\}|%USERPROFILE%|%HOMEPATH%|\$env:USERPROFILE|[A-Za-z]:)$/i.test(v) ||
805
2076
  /^\/(Users|home)(\/[^/]+)?$/i.test(v) ||
@@ -808,20 +2079,20 @@ export function isBroadPath(value) {
808
2079
  );
809
2080
  }
810
2081
 
811
- // --- Workspace -------------------------------------------------------------------
2082
+ // --- Workspace ---------------------------------------------------------------
812
2083
 
813
2084
  function checkWorkspace(ctx) {
814
2085
  const root = ctx.root ?? "";
815
- const markers = HOME_MARKERS.filter((m) => ctx.shape.topLevel.includes(m));
816
- const homeLike = markers.length >= 3;
2086
+ const markers = [...HOME_MARKERS].filter((m) => ctx.shape.topLevel.includes(m));
2087
+ const homeLike = ctx.homeLike;
817
2088
  const downloadsLike = DOWNLOADS_LIKE.test(root);
818
2089
 
819
2090
  if (homeLike) add(ctx, "WS-HOME", { vars: { markers: listNames(markers.filter((m) => m.startsWith(".") || m === "AppData").concat(markers).slice(0, 3)) } });
820
- if (downloadsLike) add(ctx, "WS-DOWNLOADS", { vars: { root } });
2091
+ if (downloadsLike) add(ctx, "WS-DOWNLOADS", { vars: { root: folderName(root) } });
821
2092
 
822
2093
  if (downloadsLike) {
823
2094
  const steering = ctx.files.filter((f) => f.content && (f.kind || f.loose) && isInstructionFile(f) && (!f.loose || steers(ctx, f)));
824
- if (steering.length) add(ctx, "WS-POISON-RISK", { vars: { files: listNames(steering.map((f) => f.path), 3), place: `your ${root} folder` } });
2095
+ if (steering.length) add(ctx, "WS-POISON-RISK", { vars: { files: listNames(steering.map((f) => f.path), 3), place: `your ${folderName(root)} folder` } });
825
2096
  }
826
2097
 
827
2098
  const looseByDir = new Map();
@@ -839,12 +2110,12 @@ function checkWorkspace(ctx) {
839
2110
 
840
2111
  if (ctx.shape.gitRepos >= 3) add(ctx, "WS-MULTI-REPO", { vars: { count: ctx.shape.gitRepos } });
841
2112
 
842
- const sensitive = ctx.files.filter((f) => f.sensitive && !EXAMPLE_ENV.test(f.path));
2113
+ const sensitive = ctx.files.filter((f) => f.sensitive && !EXAMPLE_ENV.test(f.path) && !isCertificate(f.path) && !USUALLY_HARMLESS.test(f.path));
843
2114
  const keys = sensitive.filter((f) => KEY_FILE.test(f.path));
844
2115
  const others = sensitive.filter((f) => !KEY_FILE.test(f.path));
845
2116
  if (keys.length) add(ctx, "WS-KEYS", { vars: { files: listNames(keys.map((f) => f.path), 4) } });
846
2117
  if (others.length) {
847
- const denied = (f) => ctx.claudeDeny.some((d) => denyCovers(d, f.path));
2118
+ const denied = (f) => ctx.claudeDeny.some((d) => denyCovers(d, f.path, ctx.ignoreBudget));
848
2119
  const exposed = others.filter((f) => !denied(f));
849
2120
  if (ctx.claudeSettingsFiles.length && exposed.length) {
850
2121
  add(ctx, "CC-NO-SECRET-DENY", { file: ctx.claudeSettingsFiles[0], vars: { files: listNames(exposed.map((f) => f.path), 4) } });
@@ -855,32 +2126,58 @@ function checkWorkspace(ctx) {
855
2126
 
856
2127
  const gitignore = ctx.files.find((f) => f.path === ".gitignore" && f.content);
857
2128
  if (ctx.shape.rootGit) {
858
- const envFiles = others.filter((f) => /(^|\/)\.env(\.|$)/i.test(f.path));
859
- if (envFiles.length && !(gitignore && /^\s*\/?(\*\*\/)?(\.env\b|\.env\*|\*\.env)/m.test(gitignore.content))) {
860
- add(ctx, "WS-ENV-COMMITTED", { file: gitignore ?? null, vars: { files: listNames(envFiles.map((f) => f.path), 3) } });
861
- }
862
- const local = ctx.files.filter((f) => /(^|\/)(\.claude\/settings\.local\.json|claude\.local\.md)$/i.test(f.path));
863
- const ignored = (f) => gitignore && (gitignore.content.includes(f.path) || gitignore.content.includes(f.path.split("/").pop()));
864
- const exposedLocal = local.filter((f) => !ignored(f));
865
- if (exposedLocal.length) add(ctx, "WS-LOCAL-SETTINGS", { file: gitignore ?? null, vars: { files: listNames(exposedLocal.map((f) => f.path), 3) } });
2129
+ const rules = gitIgnoreRules(ctx);
2130
+ const exposed = (list) => list.filter((f) => !isIgnored(rules, f.path, ctx.ignoreBudget));
2131
+ const envFiles = exposed(others.filter((f) => /(^|\/)\.env(\.|$)/i.test(f.path)));
2132
+ if (envFiles.length) add(ctx, "WS-ENV-COMMITTED", { file: gitignore ?? null, vars: { files: listNames(envFiles.map((f) => f.path), 3) } });
2133
+ const local = exposed(ctx.files.filter((f) => /(^|\/)(\.claude\/settings\.local\.json|claude\.local\.md)$/i.test(f.path)));
2134
+ if (local.length) add(ctx, "WS-LOCAL-SETTINGS", { file: gitignore ?? null, vars: { files: listNames(local.map((f) => f.path), 3) } });
866
2135
  }
867
2136
 
868
- const tooLarge = ctx.files.filter((f) => f.tooLarge);
869
- if (tooLarge.length) add(ctx, "WS-TOO-LARGE", { vars: { count: tooLarge.length } });
2137
+ for (const f of ctx.files.filter((x) => x.tooLarge && x.kind).slice(0, 5)) add(ctx, "WS-TOO-LARGE", { file: f });
2138
+ for (const f of ctx.files.filter((x) => x.partial && !x.tooLarge && x.kind).slice(0, 5)) add(ctx, "WS-PARTLY-CHECKED", { file: f });
2139
+ for (const f of ctx.files.filter((x) => x.linked && x.kind).slice(0, 20)) add(ctx, f.linked === "secret" ? "WS-LINK-SECRET" : "WS-LINK-OUTSIDE", { file: f });
2140
+ for (const f of ctx.files.filter((x) => x.linked === "outside" && x.folder && agentFolder(x.path)).slice(0, 20)) add(ctx, "WS-LINK-FOLDER", { file: f });
2141
+ }
2142
+
2143
+ // Ignore rules for the project, lowest precedence first: git's global list,
2144
+ // .git/info/exclude, then .gitignore files from the top folder down.
2145
+ function gitIgnoreRules(ctx) {
2146
+ const rules = ctx.ignoreLists.flatMap((text) => ignoreRules(text, ""));
2147
+ const files = ctx.files
2148
+ .filter((f) => f.content && /(^|\/)\.gitignore$/.test(f.path) && !/^(~|\/|[A-Za-z]:)/.test(f.path))
2149
+ .sort((a, b) => a.path.split("/").length - b.path.split("/").length);
2150
+ for (const f of files) rules.push(...ignoreRules(f.content, f.path.includes("/") ? f.path.slice(0, f.path.lastIndexOf("/")) : ""));
2151
+ return rules;
870
2152
  }
871
2153
 
872
- function denyCovers(rule, path) {
873
- const m = rule.match(/^Read\((.+)\)$/i);
2154
+ // Whether a Read(...) deny rule in Claude Code settings covers a project file.
2155
+ // The patterns follow .gitignore syntax: "//" starts an absolute path, "~/"
2156
+ // the home folder, "/" and "./" the project, and a bare name matches at any
2157
+ // depth. A rule outside the project covers it only through **, as in ~/**/.env.
2158
+ const denyCache = new Map();
2159
+ function denyCovers(rule, path, budget) {
2160
+ const m = /^Read\((.+)\)$/i.exec(rule.trim());
874
2161
  if (!m) return false;
875
- const pattern = m[1].trim().replace(/^\.\//, "");
876
- if (pattern === "**" || pattern === "./**") return true;
877
- const name = path.split("/").pop();
878
- const toRegex = (glob) => new RegExp("^" + glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\/?/g, "§").replace(/\*/g, "[^/]*").replace(/§/g, ".*") + "$", "i");
879
- try {
880
- return toRegex(pattern).test(path) || toRegex(pattern).test(name);
881
- } catch {
882
- return false;
2162
+ let pattern = m[1].trim();
2163
+ if (/^(?:\/\/|~\/)/.test(pattern)) {
2164
+ pattern = pattern.replace(/^(?:\/\/|~\/)/, "");
2165
+ if (!pattern.startsWith("**")) return false;
883
2166
  }
2167
+ pattern = pattern.replace(/^\.\//, "/");
2168
+ if (!denyCache.has(pattern)) {
2169
+ if (denyCache.size > 500) denyCache.clear();
2170
+ denyCache.set(pattern, ignoreRules(pattern));
2171
+ }
2172
+ return isIgnored(denyCache.get(pattern), path, budget);
2173
+ }
2174
+
2175
+ // A plugin's plugin.json that sets no hooks or MCP servers only names the
2176
+ // plugin. The plugin's skills, commands and agents are listed on their own.
2177
+ function emptyManifest(ctx, f) {
2178
+ if (!/(^|\/)\.claude-plugin\/plugin\.json$/i.test(f.path) || !f.content) return false;
2179
+ const json = parsed(f);
2180
+ return isObj(json) && json.hooks == null && json.mcpServers == null && !ctx.findings.some((x) => x.file === f.path);
884
2181
  }
885
2182
 
886
2183
  // A loose file counts as steering an agent only when it reads like orders to
@@ -908,17 +2205,466 @@ function walk(obj, visit, depth = 0) {
908
2205
  }
909
2206
  }
910
2207
 
911
- // --- Sprawl ------------------------------------------------------------------------
2208
+ // --- Sprawl ------------------------------------------------------------------
912
2209
 
2210
+ // Instruction files at the top of the project that different agents read
2211
+ // first, counting a rules folder once. A short file that only points to
2212
+ // another, such as a CLAUDE.md that says "@AGENTS.md", and an exact copy or
2213
+ // link of another file, don't count.
913
2214
  function checkSprawl(ctx) {
914
- const steering = ctx.files.filter((f) => f.content && f.kind && !f.loose && isInstructionFile(f) && !/(^|\/)\.(claude|github|codex|opencode)\/(commands|prompts|agents|chatmodes|skills|output-styles)\//i.test(f.path));
915
- const tools = new Set(steering.flatMap((f) => f.tools));
916
- if (steering.length >= 4 && tools.size >= 3) {
917
- add(ctx, "SPRAWL", { vars: { count: steering.length, list: listNames(steering.map((f) => f.path), 4) } });
2215
+ const entries = new Map();
2216
+ const seen = new Set();
2217
+ for (const f of ctx.files) {
2218
+ if (!f.content || !f.kind || f.loose || !isInstructionFile(f) || /^(~|\/|[A-Za-z]:)/.test(f.path)) continue;
2219
+ const key = entryPoint(f.path);
2220
+ if (!key || seen.has(f.content) || pointsElsewhere(f.content)) continue;
2221
+ seen.add(f.content);
2222
+ if (!entries.has(key)) entries.set(key, new Set());
2223
+ for (const t of f.tools) entries.get(key).add(t);
2224
+ }
2225
+ const tools = new Set([...entries.values()].flatMap((t) => [...t]));
2226
+ if (entries.size >= 3 && tools.size >= 3) add(ctx, "SPRAWL", { vars: { count: entries.size, list: listNames([...entries.keys()], 4) } });
2227
+ }
2228
+
2229
+ function entryPoint(path) {
2230
+ if (!path.includes("/")) return path;
2231
+ if (/^\.github\/copilot-instructions\.md$/i.test(path)) return path;
2232
+ if (/^\.roo\/rules[^/]*\//i.test(path)) return ".roo/rules/";
2233
+ const folder = path.match(/^(\.clinerules|\.cursor\/rules|\.windsurf\/rules|\.kiro\/steering|\.amazonq\/rules|\.github\/instructions|\.claude\/rules|\.continue\/rules|\.junie)\//i);
2234
+ return folder ? `${folder[1]}/` : null;
2235
+ }
2236
+
2237
+ const pointsElsewhere = (text) => {
2238
+ const t = text.trim();
2239
+ return t.length < 300 && /(^|\s)@\S+\.md\b|\b(?:AGENTS|CLAUDE|GEMINI|README)\.md\b/i.test(t);
2240
+ };
2241
+
2242
+ // --- Installed code ----------------------------------------------------------
2243
+ //
2244
+ // MCP packages, editor extensions, agent installs, skills and files attacks
2245
+ // leave behind, checked against known.js with no network requests. With
2246
+ // --lookup, the command adds OSV.dev's answers afterwards (applyLookup).
2247
+
2248
+ const TRACE_PATHS = new Set(TRACES.flatMap((t) => t.paths));
2249
+ const EDITORS = new Set(["VS Code", "VS Code Insiders", "VSCodium", "Cursor", "Windsurf", "Kiro"]);
2250
+ const EXT_ID = /^[a-z0-9][a-z0-9-]{0,99}\.[a-z0-9][a-z0-9._-]{0,99}$/i;
2251
+ // How an agent was installed, in words.
2252
+ export const INSTALLED_BY = { npm: "npm", native: "Claude Code's installer", local: "local install", homebrew: "Homebrew", volta: "Volta", bun: "bun", pnpm: "pnpm", project: "in this project", app: "app" };
2253
+ const INSTALL_VIA = new Set(Object.keys(INSTALLED_BY));
2254
+ const PLATFORMS = new Set(["mac", "windows", "linux"]);
2255
+ const cleanVersion = (v) => (typeof v === "string" && VERSION_RE.test(v) ? v.replace(/^v/, "") : "");
2256
+
2257
+ function installsFrom(list) {
2258
+ return (Array.isArray(list) ? list : [])
2259
+ .slice(0, 200)
2260
+ .filter((i) => isObj(i) && typeof i.package === "string" && (Object.hasOwn(AGENT_PACKAGES, i.package) || knownPackage("npm", i.package)))
2261
+ .filter((i) => cleanVersion(i.version) && INSTALL_VIA.has(i.via) && typeof i.path === "string" && cleanPath(i.path))
2262
+ .map((i) => ({ package: i.package, version: cleanVersion(i.version), via: i.via, path: cleanPath(i.path), platform: PLATFORMS.has(i.platform) ? i.platform : null }));
2263
+ }
2264
+
2265
+ // Versions pinned in the project's lockfile, by name and version. Only known
2266
+ // lockfile names and packages known.js lists get through.
2267
+ export const LOCKFILES = new Set(["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock"]);
2268
+ function lockedFrom(list) {
2269
+ return (Array.isArray(list) ? list : [])
2270
+ .slice(0, 500)
2271
+ .filter((l) => isObj(l) && LOCKFILES.has(l.file) && typeof l.package === "string" && knownPackage("npm", l.package) && cleanVersion(l.version))
2272
+ .map((l) => ({ file: l.file, package: l.package, version: cleanVersion(l.version) }));
2273
+ }
2274
+
2275
+ function extensionsFrom(list) {
2276
+ return (Array.isArray(list) ? list : [])
2277
+ .slice(0, 12)
2278
+ .filter((g) => isObj(g) && EDITORS.has(g.editor) && typeof g.dir === "string" && cleanPath(g.dir))
2279
+ .map((g) => ({
2280
+ editor: g.editor,
2281
+ dir: cleanPath(g.dir),
2282
+ items: (Array.isArray(g.items) ? g.items : [])
2283
+ .slice(0, 3000)
2284
+ .filter((x) => isObj(x) && typeof x.id === "string" && EXT_ID.test(x.id))
2285
+ .map((x) => ({ id: x.id.toLowerCase(), version: cleanVersion(x.version), source: x.source === "vsix" || x.source === "gallery" ? x.source : null })),
2286
+ }));
2287
+ }
2288
+
2289
+ // The name known.js lists a package under: Python names are compared the way
2290
+ // PyPI compares them.
2291
+ const knownName = (ecosystem, name) => (ecosystem === "PyPI" ? String(name).toLowerCase().replace(/[-_.]+/g, "-") : String(name));
2292
+ const knownPackage = (ecosystem, name) => {
2293
+ const key = `${ecosystem}:${knownName(ecosystem, name)}`;
2294
+ return Object.hasOwn(KNOWN_PACKAGES, key) ? KNOWN_PACKAGES[key] : null;
2295
+ };
2296
+ const KNOWN_NAMES = new Set(Object.keys(KNOWN_PACKAGES).map((k) => k.slice(k.indexOf(":") + 1)));
2297
+ const affects = (entry, version) => entry.versions === "all" || Boolean(version && entry.versions.includes(version));
2298
+ // "Version 1.12.14 ... was" or "Versions 20.9.0, 20.10.0 and 21.5.0 ... were".
2299
+ function badVersions(entry) {
2300
+ const list = Array.isArray(entry.versions) ? entry.versions : [];
2301
+ const one = list.length === 1;
2302
+ const versions = one ? `Version ${list[0]}` : `Versions ${list.slice(0, -1).join(", ")} and ${list.at(-1)}`;
2303
+ return { versions, were: one ? "was" : "were", one: one ? "it" : "one of them" };
2304
+ }
2305
+
2306
+ // Damerau-Levenshtein distance between two names, giving up past `max`.
2307
+ function nearness(a, b, max = 2) {
2308
+ if (Math.abs(a.length - b.length) > max) return max + 1;
2309
+ let prev2 = null;
2310
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
2311
+ for (let i = 1; i <= a.length; i++) {
2312
+ const row = [i];
2313
+ let low = i;
2314
+ for (let j = 1; j <= b.length; j++) {
2315
+ let d = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
2316
+ if (prev2 && i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d = Math.min(d, prev2[j - 2] + 1);
2317
+ row.push(d);
2318
+ low = Math.min(low, d);
2319
+ }
2320
+ if (low > max) return max + 1;
2321
+ prev2 = prev;
2322
+ prev = row;
2323
+ }
2324
+ return prev[b.length];
2325
+ }
2326
+
2327
+ const OFFICIAL_SCOPES = [...new Set(OFFICIAL_MCP_PACKAGES.filter((n) => n.startsWith("@")).map((n) => n.split("/")[0]))];
2328
+ // Unscoped copies of the official reference servers, such as mcp-server-github.
2329
+ const SCOPE_COPIES = new Map(
2330
+ OFFICIAL_MCP_PACKAGES.filter((n) => n.startsWith("@modelcontextprotocol/server-")).flatMap((n) => {
2331
+ const short = n.split("/")[1];
2332
+ return [short, `mcp-${short}`, `modelcontextprotocol-${short}`].map((copy) => [copy, n]);
2333
+ }),
2334
+ );
2335
+
2336
+ // The official package or scope a package name imitates, or null.
2337
+ function lookalikeOf(name, python) {
2338
+ const lower = python ? knownName("PyPI", name) : String(name).toLowerCase();
2339
+ const official = python ? OFFICIAL_PYPI_MCP : OFFICIAL_MCP_PACKAGES;
2340
+ if (official.includes(lower) || lower.length > 100) return null;
2341
+ if (!python && SCOPE_COPIES.has(lower)) return SCOPE_COPIES.get(lower);
2342
+ for (const o of official) if (o.length >= 8 && nearness(lower, o) <= 2) return o;
2343
+ if (!python && lower.startsWith("@") && lower.includes("/")) {
2344
+ const scope = lower.split("/")[0];
2345
+ // One letter off for a short scope, two for a long one: @strapi is a real
2346
+ // scope two letters from @stripe.
2347
+ for (const s of OFFICIAL_SCOPES) if (scope !== s && s.length >= 6 && nearness(scope, s) <= (s.length >= 10 ? 2 : 1)) return s;
918
2348
  }
2349
+ return null;
919
2350
  }
920
2351
 
921
- // --- Score -------------------------------------------------------------------------
2352
+ // "a git repository" or "a web address" for a launcher argument that runs
2353
+ // code from outside a registry, unless it's pinned to a commit.
2354
+ function remoteOrigin(spec, python) {
2355
+ if (typeof spec !== "string" || /[#@][0-9a-f]{40}$/i.test(spec)) return null;
2356
+ if (/^(?:git\+|git:|github:|gitlab:|bitbucket:|gist:)/i.test(spec)) return "a git repository";
2357
+ if (/^https?:\/\//i.test(spec)) return /\.git(?:$|[#@])|^https?:\/\/(?:www\.)?(?:github\.com|gitlab\.com|bitbucket\.org)\/[^/]+\/[^/]+\/?$/i.test(spec) ? "a git repository" : "a web address";
2358
+ // npx user/repo installs straight from GitHub.
2359
+ if (!python && /^[a-z0-9][\w.-]{0,38}\/[\w.-]{1,100}$/i.test(spec)) return "a git repository";
2360
+ return null;
2361
+ }
2362
+
2363
+ // Where a server's program lives, when that's a downloads, desktop or temp folder.
2364
+ function programPlace(command, args) {
2365
+ let program = command ?? "";
2366
+ if (INTERPRETERS.test(program.split(/[\\/]/).pop() ?? "")) program = args.find((a) => !a.startsWith("-")) ?? "";
2367
+ const p = program.replace(/\\/g, "/");
2368
+ if (/^(?:~|\$HOME|%USERPROFILE%|\/(?:Users|home)\/[^/]+|[A-Za-z]:\/Users\/[^/]+)\/Downloads\//i.test(p)) return "your Downloads folder";
2369
+ if (/^(?:~|\$HOME|%USERPROFILE%|\/(?:Users|home)\/[^/]+|[A-Za-z]:\/Users\/[^/]+)\/Desktop\//i.test(p)) return "your Desktop folder";
2370
+ if (/^(?:\/tmp|\/var\/tmp|\/private\/tmp|%TEMP%|%TMP%|\$env:TEMP|[A-Za-z]:\/Users\/[^/]+\/AppData\/Local\/Temp|[A-Za-z]:\/Windows\/Temp)\//i.test(p)) return "a temp folder";
2371
+ return null;
2372
+ }
2373
+
2374
+ // True when the package itself is flagged: known malware or a lookalike.
2375
+ function checkMcpPackage(ctx, s, base, near) {
2376
+ const raw = launcherSpec(s.command, s.args);
2377
+ const pkg = raw ? judgeSpec(raw.spec, raw.python) : null;
2378
+ let flagged = false;
2379
+ if (pkg) {
2380
+ const ecosystem = pkg.python ? "PyPI" : "npm";
2381
+ ctx.packages.push({ ecosystem, name: pkg.name, version: pkg.version || null, where: `Used by MCP server “${s.name}” in ${s.file.path}`, file: s.file.path, via: "mcp" });
2382
+ const known = knownPackage(ecosystem, pkg.name);
2383
+ const line = near(pkg.name) || undefined;
2384
+ const official = known ? null : lookalikeOf(pkg.name, pkg.python);
2385
+ const name = knownName(ecosystem, pkg.name);
2386
+ if (known && affects(known, pkg.version)) add(ctx, "PKG-MALICIOUS", { ...base(line), vars: { server: s.name, known: name, what: known.what, source: known.source } });
2387
+ else if (known && !pkg.version) add(ctx, "PKG-MALICIOUS-VERSION", { ...base(line), vars: { server: s.name, known: name, ...badVersions(known), source: known.source } });
2388
+ else if (official) add(ctx, "PKG-LOOKALIKE", { ...base(line), vars: { server: s.name, pkg: pkg.name, official } });
2389
+ flagged = Boolean((known && (affects(known, pkg.version) || !pkg.version)) || official);
2390
+ }
2391
+ const origin = raw ? remoteOrigin(raw.spec, raw.python) : null;
2392
+ if (origin) add(ctx, "PKG-REMOTE-SOURCE", { ...base(near(raw.spec.slice(0, 40)) || undefined), vars: { server: s.name, origin } });
2393
+ const place = programPlace(s.command, s.args);
2394
+ if (place) add(ctx, "PKG-RISKY-PLACE", { ...base(), vars: { server: s.name, place } });
2395
+ return flagged;
2396
+ }
2397
+
2398
+ // The official agent extension an extension's ID copies, or null: the same
2399
+ // name from another publisher, or the name with something added from a
2400
+ // publisher whose name starts the same way.
2401
+ function imitates(id) {
2402
+ if (Object.hasOwn(AGENT_EXTENSIONS, id)) return null;
2403
+ const dot = id.indexOf(".");
2404
+ const publisher = id.slice(0, dot);
2405
+ const name = id.slice(dot + 1);
2406
+ for (const [officialId, label] of Object.entries(AGENT_EXTENSIONS)) {
2407
+ const od = officialId.indexOf(".");
2408
+ const op = officialId.slice(0, od);
2409
+ const on = officialId.slice(od + 1);
2410
+ if (publisher === op) continue;
2411
+ const sameStart = [...op].findIndex((c, i) => publisher[i] !== c);
2412
+ if ((name === on && on !== "continue") || (on.length >= 6 && name.startsWith(on) && (sameStart < 0 ? op.length : sameStart) >= 5)) return { officialId, label };
2413
+ }
2414
+ return null;
2415
+ }
2416
+
2417
+ function checkExtensions(ctx) {
2418
+ for (const group of ctx.extensions) {
2419
+ const file = { path: group.dir, tools: group.editor === "Cursor" || group.editor === "Windsurf" ? [group.editor] : [] };
2420
+ const fromFiles = [];
2421
+ for (const x of group.items) {
2422
+ ctx.packages.push({ ecosystem: "VSCode", name: x.id, version: x.version || null, where: `Installed as a ${group.editor} extension`, file: group.dir, via: "extension" });
2423
+ const known = Object.hasOwn(KNOWN_EXTENSIONS, x.id) ? KNOWN_EXTENSIONS[x.id] : null;
2424
+ // A bad build one marketplace served doesn't apply to a copy installed from a file.
2425
+ if (known && (!known.editors || (known.editors.includes(group.editor) && x.source !== "vsix")) && affects(known, x.version)) {
2426
+ const advice = known.advice ?? EXT_ADVICE;
2427
+ add(ctx, "EXT-MALICIOUS", { file, vars: { editor: group.editor, ext: x.id, version: x.version || "", what: known.what, source: known.source, advice } });
2428
+ continue;
2429
+ }
2430
+ const copy = imitates(x.id);
2431
+ if (copy) add(ctx, "EXT-IMPERSONATION", { file, tool: copy.label in AGENT_LABEL_TOOLS ? AGENT_LABEL_TOOLS[copy.label] : null, vars: { editor: group.editor, ext: x.id, official: copy.label, officialId: copy.officialId } });
2432
+ if (x.source === "vsix") fromFiles.push(x.id);
2433
+ }
2434
+ if (fromFiles.length) {
2435
+ const shown = fromFiles.slice(0, 4).join(", ") + (fromFiles.length > 4 ? ` and ${fromFiles.length - 4} more` : "");
2436
+ add(ctx, "EXT-VSIX", { file, vars: { editor: group.editor, list: shown, fromFiles: fromFiles.length === 1 ? "an extension installed from a file" : `${fromFiles.length} extensions installed from files` } });
2437
+ }
2438
+ }
2439
+ }
2440
+ const EXT_ADVICE = "Uninstall it, then change the keys and tokens on this computer it could reach";
2441
+ const AGENT_LABEL_TOOLS = { "Claude Code": "Claude Code", Cline: "Cline", "Roo Code": "Roo Code", "GitHub Copilot": "GitHub Copilot", "GitHub Copilot Chat": "GitHub Copilot", Continue: "Continue", "Amazon Q": "Amazon Q" };
2442
+
2443
+ const SEVERITY_RANK = { critical: 0, high: 1, medium: 2, low: 3, info: 4 };
2444
+
2445
+ // What an agent version is missing, from known.js: the rule, and the words
2446
+ // that go in it. Null when it has every known fix.
2447
+ function agentAdvice(pkg, version, platform) {
2448
+ const advisories = (Object.hasOwn(AGENT_ADVISORIES, pkg) ? AGENT_ADVISORIES[pkg] : []).filter((a) => !a.platforms || a.platforms.includes(platform));
2449
+ const affected = (v) => advisories.filter((a) => compareVersions(v, a.introduced) >= 0 && compareVersions(v, a.fixed) < 0);
2450
+ const hits = affected(version);
2451
+ if (!hits.length) return null;
2452
+ hits.sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || compareVersions(b.fixed, a.fixed));
2453
+ const worst = hits[0];
2454
+ // The first version with none of the known problems: past every fix this
2455
+ // install is missing, and past any problem a later version brought in.
2456
+ let fixed = hits.reduce((top, a) => (compareVersions(a.fixed, top) > 0 ? a.fixed : top), "0.0.0");
2457
+ for (let later = affected(fixed), rounds = 0; later.length && rounds < 50; later = affected(fixed), rounds++) {
2458
+ fixed = later.reduce((top, a) => (compareVersions(a.fixed, top) > 0 ? a.fixed : top), fixed);
2459
+ }
2460
+ const one = hits.length === 1;
2461
+ return {
2462
+ worst,
2463
+ id: worst.severity === "high" ? "AGENT-VULN" : worst.severity === "medium" ? "AGENT-VULN-MINOR" : "AGENT-VULN-LOW",
2464
+ vars: { fixes: one ? "a security fix" : `${hits.length} security fixes`, lead: one ? "The issue" : "The most serious", worst: worst.title, ref: worst.cve ?? worst.id, fixed, every: one ? "the fix" : "every fix" },
2465
+ };
2466
+ }
2467
+ // How to update a package installed globally with something other than npm.
2468
+ const GLOBAL_UPDATE = { pnpm: (p) => `pnpm add -g ${p}@latest`, bun: (p) => `bun add -g ${p}@latest`, volta: (p) => `volta install ${p}` };
2469
+
2470
+ function checkInstalls(ctx) {
2471
+ for (const inst of ctx.installs) {
2472
+ const file = { path: inst.path, tools: [] };
2473
+ const known = knownPackage("npm", inst.package);
2474
+ if (known && affects(known, inst.version)) {
2475
+ add(ctx, "DEP-MALICIOUS", { file, vars: { known: inst.package, version: inst.version, status: known.versions === "all" ? "a package listed as malicious" : "a version that was malware", what: known.what, source: known.source } });
2476
+ continue;
2477
+ }
2478
+ const meta = Object.hasOwn(AGENT_PACKAGES, inst.package) ? AGENT_PACKAGES[inst.package] : null;
2479
+ if (!meta) continue;
2480
+ if (inst.package !== "Claude Desktop") ctx.packages.push({ ecosystem: "npm", name: inst.package, version: inst.version, where: `This is your ${meta.tool} install`, file: inst.path, via: "install" });
2481
+ const advice = agentAdvice(inst.package, inst.version, inst.platform);
2482
+ if (!advice) continue;
2483
+ add(ctx, advice.id, {
2484
+ file: { path: inst.path, tools: [meta.tool] },
2485
+ tool: meta.tool,
2486
+ vars: {
2487
+ tool: meta.tool,
2488
+ version: inst.version,
2489
+ ...advice.vars,
2490
+ update: meta.update[inst.via] ?? GLOBAL_UPDATE[inst.via]?.(inst.package) ?? Object.values(meta.update)[0],
2491
+ },
2492
+ });
2493
+ }
2494
+ }
2495
+
2496
+ // A lockfile that pins a version that was malware installs it on the next
2497
+ // clean install, in CI or on a teammate's computer.
2498
+ function checkLocked(ctx) {
2499
+ // A version installed in the project is reported already, with a fix that
2500
+ // covers the lockfile, so the lockfile's copy of it adds nothing.
2501
+ const installed = new Set(ctx.installs.filter((i) => i.via === "project").map((i) => `${i.package}@${i.version}`));
2502
+ for (const l of ctx.locked) {
2503
+ const known = knownPackage("npm", l.package);
2504
+ if (!affects(known, l.version) || installed.has(`${l.package}@${l.version}`)) continue;
2505
+ add(ctx, "DEP-LOCKFILE", {
2506
+ file: { path: l.file, tools: [] },
2507
+ vars: { known: l.package, version: l.version, status: known.versions === "all" ? "a package listed as malicious" : "a version that was malware", what: known.what, source: known.source, remedy: lockRemedy(l.package, known) },
2508
+ });
2509
+ }
2510
+ }
2511
+ // A package that's malicious in every version has to go; otherwise a version
2512
+ // that wasn't malware will do.
2513
+ const lockRemedy = (name, entry) => (entry.versions === "all" ? `Remove ${name} from the project and update the lockfile` : `Move ${name} to a version that wasn't malware and update the lockfile`);
2514
+
2515
+ function checkTraces(ctx) {
2516
+ const strong = new Set();
2517
+ for (const t of TRACES) {
2518
+ const found = t.paths.filter((p) => ctx.traces.has(p));
2519
+ if (!found.length || (!t.strong && strong.has(t.campaign))) continue;
2520
+ if (t.strong) strong.add(t.campaign);
2521
+ add(ctx, t.strong ? "ATTACK-TRACE" : "ATTACK-TRACE-WEAK", { file: { path: found[0], tools: [] }, vars: { campaign: t.campaign, what: t.what, files: found.join(", "), advice: t.fix } });
2522
+ }
2523
+ }
2524
+
2525
+ // A workflow a worm adds, by its name and, where it helps, its content.
2526
+ function checkWorkflowTrace(ctx, f) {
2527
+ const t = WORKFLOW_TRACES.find((w) => w.name.test(f.path) && (!w.content || w.content(f.content)));
2528
+ if (t) add(ctx, t.strong ? "ATTACK-WORKFLOW" : "ATTACK-WORKFLOW-WEAK", { file: f, vars: { campaign: t.campaign, what: t.what, advice: t.fix } });
2529
+ }
2530
+
2531
+ // Programs listed by name inside skill folders, one finding per skill.
2532
+ // Plugins and tools a project gives OpenCode, Amp or the Cline command line,
2533
+ // which load them as code when they start, without asking. Listed by name,
2534
+ // never read. The user's own, in the home folder, aren't reported.
2535
+ function checkPluginCode(ctx) {
2536
+ for (const f of ctx.files.filter((x) => x.listed && x.kind === "Plugin code" && !/^(~|\/|[A-Za-z]:)/.test(x.path)).slice(0, 10)) {
2537
+ add(ctx, "PLUGIN-CODE", { file: f, vars: { tool: f.tools[0] } });
2538
+ }
2539
+ }
2540
+
2541
+ function checkSkillPrograms(ctx) {
2542
+ const bySkill = new Map();
2543
+ for (const f of ctx.files) {
2544
+ if (!f.listed) continue;
2545
+ const m = f.path.match(/^(.*?\/skills\/([^/]+))\/(.+)$/i);
2546
+ if (!m) continue;
2547
+ if (!bySkill.has(m[1])) bySkill.set(m[1], { skill: m[2], file: f, names: [] });
2548
+ // An app bundle is one program, however many files are inside it.
2549
+ const name = m[3].replace(/^(.*?\.app)\/.*$/i, "$1");
2550
+ if (!bySkill.get(m[1]).names.includes(name)) bySkill.get(m[1]).names.push(name);
2551
+ }
2552
+ for (const [dir, { skill, file, names }] of bySkill) {
2553
+ const files = names.slice(0, 3).join(", ") + (names.length > 3 ? ` and ${names.length - 3} more` : "");
2554
+ // The finding points at the skill's SKILL.md when there is one, an agent
2555
+ // file a share may name, rather than at the program.
2556
+ // Without one, it points at the skill's folder, never at a program.
2557
+ const skillMd = ctx.files.find((x) => x.path.toLowerCase() === `${dir}/skill.md`.toLowerCase());
2558
+ const one = names.length === 1;
2559
+ add(ctx, "SKILL-BINARY", { file: skillMd ?? { path: dir, tools: file.tools }, vars: { skill, files, programs: one ? "a program" : `${names.length} programs`, them: one ? "it" : "them" } });
2560
+ }
2561
+ }
2562
+
2563
+ // Claude Code's plugin marketplaces. Anthropic's own come from GitHub's
2564
+ // anthropics organization.
2565
+ function checkMarketplaces(ctx, f) {
2566
+ const json = parsed(f);
2567
+ if (!isObj(json)) return;
2568
+ const others = [];
2569
+ for (const [name, m] of Object.entries(json).slice(0, 200)) {
2570
+ if (!isObj(m) || anthropicMarketplace(m)) continue;
2571
+ const from = marketplaceSource(m);
2572
+ others.push(`${clip(name, 60)}${from ? ` (${clip(from, 80)})` : ""}`);
2573
+ }
2574
+ if (!others.length) return;
2575
+ const line = lineOf(f, `"${others[0].split(" (")[0]}"`);
2576
+ const list = others.slice(0, 4).join(", ") + (others.length > 4 ? ` and ${others.length - 4} more` : "");
2577
+ add(ctx, "PLUGIN-MARKETPLACE", { file: f, line, evidence: evidenceLine(f, line), vars: { list, marketplaces: others.length === 1 ? "a marketplace" : `${others.length} marketplaces` } });
2578
+ }
2579
+
2580
+ // OSV.dev's answers about the packages, extensions and installs a result
2581
+ // names, added as findings: one per package, for each place it's used.
2582
+ // `hits` comes from the network, so each one must name a package the result
2583
+ // already lists, and every value is checked. What the bundled list already
2584
+ // reported (a package it knows is malware, an agent advisory it already
2585
+ // counted) isn't repeated.
2586
+ const LOOKUP_REF = /^[A-Z][A-Z0-9]{1,9}-[A-Za-z0-9._:-]{1,60}$/;
2587
+ const MALWARE_RULES = new Set(["PKG-MALICIOUS", "PKG-MALICIOUS-VERSION", "DEP-MALICIOUS", "EXT-MALICIOUS"]);
2588
+ const LOOKUP_RANK = { high: 0, medium: 1, low: 2 };
2589
+ const LOOKUP_RULES = ["LOOKUP-VULN", "LOOKUP-VULN-MINOR", "LOOKUP-VULN-LOW"];
2590
+ const LOOKUP_NO_FIX = "No fixed version is listed yet. Update when one is out, and until then limit what it can reach";
2591
+ const LOOKUP_SOME_FIXED = " for the ones that are fixed. The rest have no fix listed yet, so limit what it can reach";
2592
+ const LOOKUP_UNKNOWN = "Update to the newest version. Some details didn't load from OSV.dev, so run --lookup again to see which version fixes each one";
2593
+ // OSV.dev's summaries are shown as text, without links or anything that
2594
+ // reads as a command.
2595
+ const SAFE_SUMMARY = /^(?![\s\S]*(?::\/\/|www\.))[^|`$\n]{1,200}$/;
2596
+ function safeSummary(text) {
2597
+ return String(text ?? "")
2598
+ .replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, " ")
2599
+ .replace(/\b(?:[a-z][a-z0-9+.-]*:\/\/|www\.)\S*/gi, "a link")
2600
+ .replace(/[|`$]/g, " ")
2601
+ .replace(/\s+/g, " ")
2602
+ .trim();
2603
+ }
2604
+ export function applyLookup(result, hits) {
2605
+ if (!isObj(result) || !Array.isArray(result.findings)) return result;
2606
+ const packages = Array.isArray(result.packages) ? result.packages.filter(isObj) : [];
2607
+ const flagged = new Set(result.findings.filter((f) => MALWARE_RULES.has(f.id)).map((f) => `${f.vars?.known ?? f.vars?.ext}|${f.file}`));
2608
+ const counted = (name) => new Set((Object.hasOwn(AGENT_ADVISORIES, name) ? AGENT_ADVISORIES[name] : []).flatMap((a) => [a.id, a.cve]).filter(Boolean));
2609
+ const uses = new Map();
2610
+ for (const h of (Array.isArray(hits) ? hits : []).slice(0, 300)) {
2611
+ if (!isObj(h) || typeof h.ref !== "string" || !LOOKUP_REF.test(h.ref)) continue;
2612
+ const malicious = h.malicious === true;
2613
+ for (const pkg of packages) {
2614
+ if (pkg.ecosystem !== h.ecosystem || pkg.name !== h.name || (pkg.version ?? null) !== (h.version ?? null)) continue;
2615
+ // Without a version, only "this package is malware" applies.
2616
+ if (!malicious && !pkg.version) continue;
2617
+ if (malicious && flagged.has(`${pkg.name}|${pkg.file}`)) continue;
2618
+ if (!malicious && pkg.via === "install" && counted(pkg.name).has(h.ref)) continue;
2619
+ const use = uses.get(pkg) ?? { malicious: null, vulns: new Map() };
2620
+ if (malicious) use.malicious ??= h;
2621
+ else if (!use.vulns.has(h.ref)) use.vulns.set(h.ref, h);
2622
+ uses.set(pkg, use);
2623
+ }
2624
+ }
2625
+
2626
+ const extra = [];
2627
+ for (const [pkg, use] of uses) {
2628
+ const file = { path: typeof pkg.file === "string" ? pkg.file : null, tools: [] };
2629
+ const common = { name: pkg.name, version: pkg.version ?? "", where: pkg.where };
2630
+ if (use.malicious) {
2631
+ extra.push(makeFinding("LOOKUP-MALICIOUS", { file, vars: { ...common, ref: use.malicious.ref } }));
2632
+ continue;
2633
+ }
2634
+ const vulns = [...use.vulns.values()];
2635
+ if (!vulns.length) continue;
2636
+ const rank = (h) => LOOKUP_RANK[h.severity] ?? 1;
2637
+ vulns.sort((a, b) => rank(a) - rank(b));
2638
+ const worst = vulns[0];
2639
+ const one = vulns.length === 1;
2640
+ // The newest fixed version fixes every one that has a fix.
2641
+ const fixes = vulns.map((h) => cleanVersion(h.fixed));
2642
+ const newest = fixes.filter(Boolean).reduce((top, v) => (!top || compareVersions(v, top) > 0 ? v : top), "");
2643
+ const unknown = vulns.some((h) => h.detailed === false);
2644
+ const advice = unknown ? LOOKUP_UNKNOWN : !newest ? LOOKUP_NO_FIX : `Update to ${newest} or later${fixes.every(Boolean) ? "" : LOOKUP_SOME_FIXED}`;
2645
+ const summary = safeSummary(typeof worst.summary === "string" ? worst.summary : "");
2646
+ extra.push(
2647
+ makeFinding(LOOKUP_RULES[rank(worst)], {
2648
+ file,
2649
+ vars: {
2650
+ ...common,
2651
+ vulns: one ? "a published vulnerability" : `${vulns.length} published vulnerabilities`,
2652
+ lead: one ? "The issue" : "The most serious",
2653
+ summary: clip(summary || (worst.detailed === false ? "Its details didn't load from OSV.dev" : "No summary was published"), 200).replace(/[.\s]+$/, "") || "No summary was published",
2654
+ ref: worst.ref,
2655
+ advice,
2656
+ },
2657
+ }),
2658
+ );
2659
+ }
2660
+ if (!extra.length) return result;
2661
+ const findings = [...result.findings, ...extra].sort(bySeverity);
2662
+ const controlMap = (result.controlMap ?? []).map((f) => ({ ...f, findings: findings.filter((x) => x.file === f.path).length }));
2663
+ const { counts, score, grade } = scoreFindings(findings, controlMap.length > 0);
2664
+ return { ...result, findings, controlMap, counts, score, grade, headline: headlineFor(counts, findings[0], controlMap.length > 0), lookedUp: true };
2665
+ }
2666
+
2667
+ // --- Score -------------------------------------------------------------------
922
2668
 
923
2669
  const bySeverity = (a, b) =>
924
2670
  SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity) || a.category.localeCompare(b.category) || (a.file ?? "").localeCompare(b.file ?? "");
@@ -933,21 +2679,43 @@ export function scoreFindings(findings, hasControlFiles) {
933
2679
  let penalty = 0;
934
2680
  for (const [id, n] of byRule) penalty += WEIGHT[RULES[id].severity] * Math.min(2, 1 + 0.25 * (n - 1));
935
2681
  const score = Math.max(0, Math.min(100, Math.round(100 - penalty)));
936
- let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 65 ? "C" : score >= 50 ? "D" : "F";
2682
+ let grade = GRADES.find(([, min]) => score >= min)?.[0] ?? "F";
937
2683
  if (counts.critical && "ABC".includes(grade)) grade = "D";
938
2684
  if (!hasControlFiles && !findings.length) grade = "–";
939
2685
  return { counts, score: grade === "–" ? null : score, grade };
940
2686
  }
941
2687
 
942
2688
  function agentsIn(controlMap) {
943
- // Agents with their own config files. AGENTS.md alone doesn't mean an agent is in use.
944
- const specific = controlMap.filter((f) => !/(^|\/)agents(\.override)?\.md$/i.test(f.path));
2689
+ // Agents with files of their own. A file several agents read, such as
2690
+ // AGENTS.md or .mcp.json, doesn't show that each of them is in use.
2691
+ const specific = controlMap.filter((f) => f.tools.length === 1);
945
2692
  return [...new Set((specific.length ? specific : controlMap).flatMap((f) => f.tools))].filter((t) => t !== "Any agent started there" && t !== "Your shell");
946
2693
  }
947
2694
 
2695
+ function explainSafely(f, ctx) {
2696
+ try {
2697
+ return explainFile(f, { json: f.content && /\.(jsonc?|toml|kiro\.hook)$/i.test(f.path) ? parsed(f) : null, servers: ctx.mcpServers.filter((s) => s.file === f) });
2698
+ } catch {
2699
+ return { scope: scopeOf(f), summary: "Couldn't be summarized.", details: [] };
2700
+ }
2701
+ }
2702
+
948
2703
  function summarize(ctx) {
949
2704
  const findings = ctx.findings.sort(bySeverity);
950
- const controlFiles = ctx.files.filter((f) => f.kind && (!f.loose || steers(ctx, f)));
2705
+ // Plugin code is listed by name, never read, but it controls the agent
2706
+ // that loads it, so it's in the map.
2707
+ const controlFiles = ctx.files.filter(
2708
+ (f) =>
2709
+ f.kind &&
2710
+ (!f.listed || f.kind === "Plugin code") &&
2711
+ (!f.loose || steers(ctx, f)) &&
2712
+ (f.kind !== "Shell profile" || !f.content || agentLines(f).length) &&
2713
+ !emptyManifest(ctx, f),
2714
+ );
2715
+ // Each agent's files together, agents in the order they were first found.
2716
+ const firstSeen = new Map();
2717
+ for (const f of controlFiles) if (!firstSeen.has(f.tools.join())) firstSeen.set(f.tools.join(), firstSeen.size);
2718
+ controlFiles.sort((a, b) => firstSeen.get(a.tools.join()) - firstSeen.get(b.tools.join()));
951
2719
  const { counts, score, grade } = scoreFindings(findings, controlFiles.length > 0);
952
2720
  const toolNames = agentsIn(controlFiles);
953
2721
  const headline = headlineFor(counts, findings[0], controlFiles.length > 0);
@@ -963,6 +2731,8 @@ function summarize(ctx) {
963
2731
  findings,
964
2732
  categories: CATEGORIES,
965
2733
  tools: toolNames,
2734
+ // What each file tells its agents, worked out here. A share keeps just
2735
+ // the path; only an --open report, encrypted here, carries the rest.
966
2736
  controlMap: controlFiles.map((f) => ({
967
2737
  path: f.path,
968
2738
  kind: f.kind,
@@ -970,86 +2740,561 @@ function summarize(ctx) {
970
2740
  size: f.size,
971
2741
  lines: f.lines ? f.lines.length : null,
972
2742
  findings: findings.filter((x) => x.file === f.path).length,
2743
+ ...(f.listed ? { listed: true } : {}),
2744
+ ...explainSafely(f, ctx),
973
2745
  })),
974
2746
  stats: {
975
- filesChecked: ctx.files.filter((f) => f.content).length,
2747
+ // Agent files read and checked. Files read only for a check, such as
2748
+ // .gitignore, and plugin code, which is listed, aren't counted.
2749
+ filesChecked: controlFiles.filter((f) => f.content).length,
976
2750
  secretFilesListed: ctx.files.filter((f) => f.sensitive).length,
977
2751
  maskedInBrowser: ctx.maskedInBrowser,
978
2752
  mcpServers: ctx.mcpServers.length,
979
2753
  entriesScanned: ctx.shape.entries,
980
2754
  truncated: ctx.shape.truncated,
2755
+ agentInstalls: ctx.installs.filter((i) => Object.hasOwn(AGENT_PACKAGES, i.package)).length,
2756
+ extensions: ctx.extensions.reduce((n, g) => n + g.items.length, 0),
2757
+ },
2758
+ // What's installed, for --explain and --lookup. Never part of a share.
2759
+ installed: {
2760
+ agents: ctx.installs.filter((i) => Object.hasOwn(AGENT_PACKAGES, i.package)).map((i) => ({ tool: AGENT_PACKAGES[i.package].tool, version: i.version, via: i.via, path: i.path })),
2761
+ editors: ctx.extensions.map((g) => ({
2762
+ editor: g.editor,
2763
+ dir: g.dir,
2764
+ count: g.items.length,
2765
+ agents: g.items.filter((x) => Object.hasOwn(AGENT_EXTENSIONS, x.id)).map((x) => ({ name: AGENT_EXTENSIONS[x.id], id: x.id, version: x.version })),
2766
+ })),
981
2767
  },
2768
+ packages: ctx.packages.slice(0, 2000),
982
2769
  };
983
2770
  }
984
2771
 
985
- // --- Sharing -------------------------------------------------------------------------
2772
+ // --- Sharing -----------------------------------------------------------------
2773
+ //
2774
+ // What leaves the computer when someone chooses to share: rule IDs, the names
2775
+ // of agent files inside the project, line numbers and values from the fixed
2776
+ // lists below. Nothing quotes a file, names a local path, or carries a name
2777
+ // the user chose. A value that isn't on the lists drops its finding, so a
2778
+ // share link can't make a signed report say something no check would say.
2779
+
2780
+ const FOLDER_NAMES = { downloads: "Downloads", download: "Downloads", desktop: "Desktop", temp: "Temp", tmp: "tmp" };
2781
+ const folderName = (name) => FOLDER_NAMES[String(name).toLowerCase()] ?? String(name);
2782
+ const PLACES = new Set(["your home folder", "the root of a drive", "a temp folder", ...Object.values(FOLDER_NAMES).map((n) => `your ${n} folder`)]);
2783
+ const RISKS = new Set([RISK_HOME, RISK_DOWNLOADS, RISK_DRIVE]);
2784
+ const AGENT_SETTINGS = ["allowedTools", "toolsSettings", "permissions"];
2785
+ const SETTING_NAMES = new Set([...VS_CODE_AUTO_APPROVE, ...ALWAYS_ALLOW_KEYS, ...AGENT_SETTINGS]);
2786
+ const DOCKER_FLAGS = /^(?:--privileged|--(?:pid|network|ipc|uts)=host|--cap-add=(?:ALL|SYS_ADMIN)|(?:-v|--mount) (?:\/|~|\/(?:etc|var|opt|usr|root)|\/var\/run\/docker\.sock|[A-Z]:\\))$/;
2787
+ // The phrases each rule's {where} can be, with names already hidden.
2788
+ const claudeHook = (v) => v === "A Claude Code hook" || (/^A Claude Code \w+ hook$/.test(v) && Object.hasOwn(HOOK_EVENTS, v.split(" ")[3]));
2789
+ const ENV_WHERE = ["Claude Code's env setting", "Codex's shell_environment_policy", "Aider's set-env setting"];
2790
+ const ENDPOINT_WHERE = [...ENV_WHERE, "An MCP server's env setting", "Codex's model_providers setting", "Aider's openai-api-base setting", "OpenCode's provider setting", "Continue's model settings"];
2791
+ const COMMAND_SOURCES = [
2792
+ "Codex's notify command",
2793
+ "This hook script",
2794
+ "A GitHub Copilot hook",
2795
+ "A Cursor hook",
2796
+ "Cursor's cloud agent setup",
2797
+ "A Codex hook",
2798
+ "Codex's model provider login command",
2799
+ "Codex's MCP header command",
2800
+ "A Gemini CLI hook",
2801
+ "Gemini CLI's tool discovery command",
2802
+ "Gemini CLI's tool call command",
2803
+ "A Windsurf hook",
2804
+ "A Kiro hook",
2805
+ "An Amazon Q hook",
2806
+ "A Grok hook",
2807
+ "Grok's status line command",
2808
+ "A task that runs when the folder opens",
2809
+ "An MCP server's command",
2810
+ ...Object.values(AIDER_COMMANDS),
2811
+ ];
2812
+ const runsCommands = (v) =>
2813
+ claudeHook(v) ||
2814
+ COMMAND_SOURCES.includes(v) ||
2815
+ CLAUDE_COMMAND_KEYS.some((key) => v === `Claude Code's ${key} setting`);
2816
+ const WHERE = {
2817
+ "CX-YOLO": (v) => v === "" || v === " in profile “[hidden]”",
2818
+ "CX-FULL-ACCESS": (v) => v === "" || v === " in profile “[hidden]”",
2819
+ "CX-NEVER-ASK": (v) => v === "" || v === " in profile “[hidden]”",
2820
+ "OC-BASH-ALLOW": (v) => v === "" || v === " for the “[hidden]” agent",
2821
+ "FLAG-SCRIPT": (v) => runsCommands(v) || v === "The “[hidden]” script in package.json",
2822
+ "HOOK-REMOTE-EXEC": runsCommands,
2823
+ "HOOK-NETWORK": runsCommands,
2824
+ "HOOK-DESTRUCTIVE": runsCommands,
2825
+ "HOOK-OUTSIDE": runsCommands,
2826
+ "HOOK-HTTP": claudeHook,
2827
+ "ENV-CODE-LOAD": (v) => ENV_WHERE.includes(v),
2828
+ "PROJECT-AUTORUN": runsCommands,
2829
+ "AGENT-ENDPOINT": (v) => ENDPOINT_WHERE.includes(v),
2830
+ "AGENT-ENDPOINT-USER": (v) => ENDPOINT_WHERE.includes(v),
2831
+ "ENV-TLS-OFF": (v) => ENDPOINT_WHERE.includes(v),
2832
+ "ENV-CA-PROJECT": (v) => ENDPOINT_WHERE.includes(v),
2833
+ };
2834
+
2835
+ const KNOWN_TOOLS = new Set([...AGENT_NAMES, ...CONTROL.flatMap(([, tools]) => (Array.isArray(tools) ? tools : [])), "Cursor", "Windsurf"]);
2836
+
2837
+ // Numbers within what the checks can produce: files over 450,000 characters
2838
+ // aren't read, so nothing larger can come out of one.
2839
+ const between = (v, min, max) => Number(v.replace(/,/g, "")) >= min && Number(v.replace(/,/g, "")) <= max;
2840
+ const PUBLIC_VARS = {
2841
+ where: (v, id) => WHERE[id]?.(v) === true,
2842
+ setting: (v) => SETTING_NAMES.has(v),
2843
+ flag: (v) => FLAG_NAMES.has(v) || DOCKER_FLAGS.test(v),
2844
+ count: (v) => (/^\d{1,5}$/.test(v) && between(v, 1, 99_999)) || /^(?:every tool|[1-9]\d{0,3} tools?)$/.test(v),
2845
+ length: (v) => /^\d{1,3}(?:,\d{3})?$/.test(v) && between(v, 300, 450_000),
2846
+ size: (v) => /^\d{1,3} KB$/.test(v) && between(v.slice(0, -3), 1, 450),
2847
+ agent: (v) => AGENT_NAMES.has(v),
2848
+ tool: (v) => KNOWN_TOOLS.has(v),
2849
+ markers: (v) => v.split(/, | and /).every((m) => HOME_MARKERS.has(m)),
2850
+ place: (v) => PLACES.has(v),
2851
+ risk: (v) => RISKS.has(v),
2852
+ root: (v) => Object.values(FOLDER_NAMES).includes(v),
2853
+ mode: (v) => v === "always-approve" || v === "yolo",
2854
+ what: (v) => KNOWN_PHRASES.what.has(v),
2855
+ source: (v) => KNOWN_PHRASES.source.has(v),
2856
+ campaign: (v) => KNOWN_PHRASES.campaign.has(v),
2857
+ advice: (v) => KNOWN_PHRASES.advice.has(v),
2858
+ official: (v) => OFFICIAL_MCP_PACKAGES.includes(v) || OFFICIAL_PYPI_MCP.includes(v) || OFFICIAL_SCOPES.includes(v),
2859
+ origin: (v) => v === "a git repository" || v === "a web address",
2860
+ version: (v) => VERSION_RE.test(v),
2861
+ known: (v) => KNOWN_NAMES.has(v),
2862
+ status: (v) => v === "a package listed as malicious" || v === "a version that was malware",
2863
+ versions: (v) => /^Versions? [0-9][0-9A-Za-z., -]{0,400}$/.test(v),
2864
+ were: (v) => v === "was" || v === "were",
2865
+ one: (v) => v === "it" || v === "one of them",
2866
+ programs: (v) => /^(?:a program|[1-9]\d{0,3} programs)$/.test(v),
2867
+ them: (v) => v === "it" || v === "them",
2868
+ commands: (v) => /^(?:a command|[1-9]\d{0,3} commands)$/.test(v),
2869
+ remedy: (v) => /^(?:Remove \S{1,214} from the project|Move \S{1,214} to a version that wasn't malware) and update the lockfile$/.test(v),
2870
+ variable: (v) => Object.hasOwn(CODE_LOADING_ENV, v) || /^GIT_CONFIG_KEY_\d{1,3}$/.test(v) || ENDPOINT_VARIABLES.has(v) || ENDPOINT_SETTINGS.has(v) || CA_VARIABLES.has(v) || v === "NODE_TLS_REJECT_UNAUTHORIZED",
2871
+ };
2872
+ // A fact as known.js words it now, or as an earlier release worded it.
2873
+ const said = (entry, field, value) => entry?.[field] === value || (Array.isArray(entry?.was?.[field]) && entry.was[field].includes(value));
2874
+ const phrases = (entries, field) => entries.flatMap((e) => [e[field], ...(Array.isArray(e.was?.[field]) ? e.was[field] : [])]).filter((v) => typeof v === "string");
2875
+ // The fixed phrases known.js uses, which a shared report may repeat.
2876
+ const KNOWN_PHRASES = {
2877
+ what: new Set([...phrases(Object.values(KNOWN_PACKAGES), "what"), ...phrases(WORKFLOW_TRACES, "what"), ...phrases(SHELL_TRACES, "what")]),
2878
+ source: new Set(phrases(Object.values(KNOWN_PACKAGES), "source")),
2879
+ campaign: new Set([...phrases(WORKFLOW_TRACES, "campaign"), ...phrases(SHELL_TRACES, "campaign"), ...Object.values(KNOWN_BAD_HOSTS)]),
2880
+ advice: new Set([...phrases(WORKFLOW_TRACES, "fix"), ...phrases(SHELL_TRACES, "fix")]),
2881
+ };
2882
+
2883
+ const templateVars = new Map(Object.entries(RULES).map(([id, r]) => [id, [...new Set([...`${r.title} ${r.why} ${r.fix}`.matchAll(/\{(\w+)\}/g)].map((m) => m[1]))]]));
2884
+
2885
+ // A folder agents read their settings from, such as .claude or .cursor/rules.
2886
+ const agentFolder = (p) => typeof p === "string" && TOOL_ROOT.test(p.split("/")[0]) && p.split("/").length <= 4;
2887
+
2888
+ // A project path as the command and the browser check send it in a share.
2889
+ // In each name, anything but letters, digits and ._@+- becomes _, and a long
2890
+ // name keeps its start and its end, so a finding in "my rules.mdc" is still
2891
+ // shared, as my_rules.mdc, and a name can't keep a finding out of a share.
2892
+ const shareName = (part) => {
2893
+ const plain = part.replace(/[^A-Za-z0-9._@+-]/g, "_");
2894
+ return plain.length <= 80 ? plain : `${plain.slice(0, 60)}_${plain.slice(-19)}`;
2895
+ };
2896
+ const plainPath = (p) => (typeof p === "string" && !/^(\/|~|[A-Za-z]:)/.test(p) ? p.split("/").map(shareName).join("/") : p);
2897
+
2898
+ // Whether a path can be shown on a shared page, which takes only plain names
2899
+ // in project folders, as plainPath makes them, of files agents read under
2900
+ // their usual names. Other names, such as a file a setting names as
2901
+ // instructions, stay on the computer like any other file name.
2902
+ function shareablePath(p) {
2903
+ if (typeof p !== "string" || p.length > 1000) return null;
2904
+ const clean = cleanPath(p);
2905
+ if (!clean || /^(\/|~|[A-Za-z]:)/.test(clean)) return null;
2906
+ const parts = clean.split("/");
2907
+ if (parts.length > 12 || !parts.every((part) => /^[A-Za-z0-9._@+-]{1,80}$/.test(part))) return null;
2908
+ if (/(^|\/)\.claude\/(projects|plugins)\//i.test(clean)) return null;
2909
+ // Also the workflows worms add, and the project's copy of a package that
2910
+ // was malware: both are names from known.js.
2911
+ const workflow = WORKFLOW_TRACES.some((t) => t.name.test(clean));
2912
+ const knownCopy = /^node_modules\/(?:\.pnpm\/[^/]+\/node_modules\/)?((?:@[^/]+\/)?[^/]+)$/.exec(clean)?.[1];
2913
+ return controlFor(clean) || workflow || (knownCopy && knownPackage("npm", knownCopy)) || LOCKFILES.has(clean) || /^(?:[^/]+\/){0,3}\.gitignore$/i.test(clean) || clean === "package.json" || agentFolder(clean) ? clean : null;
2914
+ }
2915
+
2916
+ // Facts from known.js come as a set. A finding can't pair one package's name
2917
+ // with another's description, name a version that wasn't malware, or credit
2918
+ // an attack with another's files, so a share or a private link can't make
2919
+ // misconfig accuse a package of something it never reported. Used for shares
2920
+ // and private reports; values that are hidden in a share aren't checked here.
2921
+ function knownFactsAgree(id, vars, file) {
2922
+ const has = (k) => typeof vars[k] === "string" && vars[k] !== "" && vars[k] !== "[hidden]";
2923
+ switch (id) {
2924
+ case "PKG-MALICIOUS":
2925
+ case "PKG-MALICIOUS-VERSION":
2926
+ case "DEP-MALICIOUS":
2927
+ case "DEP-LOCKFILE": {
2928
+ const entry = knownPackage("npm", vars.known) ?? (id.startsWith("DEP-") ? null : knownPackage("PyPI", vars.known));
2929
+ if (!entry || !said(entry, "source", vars.source)) return false;
2930
+ if (id === "PKG-MALICIOUS") return said(entry, "what", vars.what);
2931
+ if (id === "PKG-MALICIOUS-VERSION") {
2932
+ if (!Array.isArray(entry.versions)) return false;
2933
+ const want = badVersions(entry);
2934
+ return want.versions === vars.versions && want.were === vars.were && want.one === vars.one;
2935
+ }
2936
+ const place = typeof file === "string" ? file : "";
2937
+ return (
2938
+ said(entry, "what", vars.what) &&
2939
+ affects(entry, vars.version) &&
2940
+ vars.status === (entry.versions === "all" ? "a package listed as malicious" : "a version that was malware") &&
2941
+ (id === "DEP-LOCKFILE" ? LOCKFILES.has(place) && vars.remedy === lockRemedy(vars.known, entry) : place === `node_modules/${vars.known}` || place.endsWith(`/${vars.known}`))
2942
+ );
2943
+ }
2944
+ case "EXT-MALICIOUS": {
2945
+ const entry = Object.hasOwn(KNOWN_EXTENSIONS, vars.ext) ? KNOWN_EXTENSIONS[vars.ext] : null;
2946
+ return Boolean(
2947
+ entry &&
2948
+ said(entry, "what", vars.what) &&
2949
+ said(entry, "source", vars.source) &&
2950
+ (entry.advice ? said(entry, "advice", vars.advice) : vars.advice === EXT_ADVICE) &&
2951
+ (!entry.editors || entry.editors.includes(vars.editor)) &&
2952
+ (!has("version") || affects(entry, vars.version)),
2953
+ );
2954
+ }
2955
+ case "ATTACK-TRACE":
2956
+ case "ATTACK-TRACE-WEAK": {
2957
+ const t = TRACES.find((x) => said(x, "campaign", vars.campaign) && said(x, "what", vars.what) && said(x, "fix", vars.advice) && Boolean(x.strong) === (id === "ATTACK-TRACE"));
2958
+ return Boolean(t && (!has("files") || vars.files.split(", ").every((p) => t.paths.includes(p))));
2959
+ }
2960
+ case "ATTACK-SHELL-LINE":
2961
+ return SHELL_TRACES.some((x) => said(x, "campaign", vars.campaign) && said(x, "what", vars.what) && said(x, "fix", vars.advice));
2962
+ case "ATTACK-WORKFLOW":
2963
+ case "ATTACK-WORKFLOW-WEAK":
2964
+ return WORKFLOW_TRACES.some((x) => x.name.test(file ?? "") && Boolean(x.strong) === (id === "ATTACK-WORKFLOW") && said(x, "campaign", vars.campaign) && said(x, "what", vars.what) && said(x, "fix", vars.advice));
2965
+ case "TXT-KNOWN-C2":
2966
+ return Object.values(KNOWN_BAD_HOSTS).includes(vars.campaign) && (!has("host") || KNOWN_BAD_HOSTS[vars.host.toLowerCase()] === vars.campaign);
2967
+ case "SKILL-BINARY":
2968
+ return (
2969
+ (vars.programs === "a program") === (vars.them === "it") &&
2970
+ (!has("files") || vars.files.replace(/ and \d+ more$/, "").split(", ").every((p) => SKILL_PROGRAM.test(p) || SKILL_PROGRAM.test(`${p}/`)))
2971
+ );
2972
+ case "AGENT-VULN":
2973
+ case "AGENT-VULN-MINOR":
2974
+ case "AGENT-VULN-LOW":
2975
+ // Worked out again from the tool and version, for each platform.
2976
+ return Object.entries(AGENT_PACKAGES).some(
2977
+ ([pkg, meta]) =>
2978
+ meta.tool === vars.tool &&
2979
+ [...Object.values(meta.update), ...Object.values(GLOBAL_UPDATE).map((make) => make(pkg))].includes(vars.update) &&
2980
+ [undefined, "mac", "windows", "linux"].some((platform) => {
2981
+ const advice = agentAdvice(pkg, vars.version, platform);
2982
+ return advice?.id === id && Object.entries(advice.vars).every(([k, v]) => (k === "worst" ? said(advice.worst, "title", vars.worst) : vars[k] === v));
2983
+ }),
2984
+ );
2985
+ default:
2986
+ return true;
2987
+ }
2988
+ }
2989
+
2990
+ // The shareable form of one finding, or null when it can't be shared. The
2991
+ // command and the browser use it to build the preview, and the Worker uses it
2992
+ // again on what arrives, so the preview is exactly what a report will say.
2993
+ function shareFinding(f) {
2994
+ if (!isObj(f) || typeof f.id !== "string" || !Object.hasOwn(RULES, f.id)) return null;
2995
+ const file = f.file == null ? null : shareablePath(f.file);
2996
+ if (f.file != null && !file) return null;
2997
+ const given = isObj(f.vars) ? f.vars : {};
2998
+ const vars = {};
2999
+ for (const k of templateVars.get(f.id)) {
3000
+ if (k === "file" || PRIVATE_VARS.has(k)) continue;
3001
+ const value = given[k];
3002
+ if ((typeof value !== "string" && typeof value !== "number") || String(value).length > 200) return null;
3003
+ const v = k === "where" ? hideNames(String(value)) : String(value);
3004
+ if (!PUBLIC_VARS[k]?.(v, f.id)) return null;
3005
+ vars[k] = v;
3006
+ }
3007
+ if (!knownFactsAgree(f.id, vars, file)) return null;
3008
+ const out = { id: f.id, file, line: Number.isInteger(f.line) && f.line > 0 && f.line < 1e7 ? f.line : null, vars };
3009
+ if (typeof f.tool === "string" && KNOWN_TOOLS.has(f.tool)) out.tool = f.tool;
3010
+ return out;
3011
+ }
3012
+
3013
+ // Which agent a shared finding is about: the rule's own, else the one the
3014
+ // check named, else the first agent that reads the file.
3015
+ function sharedTool(f, rule) {
3016
+ if (rule.tool) return rule.tool;
3017
+ if (f.tool) return f.tool;
3018
+ return (f.file && controlFor(f.file)?.tools[0]) ?? null;
3019
+ }
986
3020
 
987
- // What leaves the computer when someone chooses to share: rule IDs, file names,
988
- // line numbers and the non-private details. No file contents, no evidence lines,
989
- // nothing that quotes a file or reveals a local path.
990
3021
  export function toShareable(result) {
991
3022
  return {
992
3023
  version: result.version,
993
- findings: result.findings.map((f) => ({
994
- id: f.id,
995
- file: f.file,
996
- line: f.line,
997
- // The file name travels once, as file; the report rebuilds the rest.
998
- vars: Object.fromEntries(Object.entries(f.vars ?? {}).filter(([k]) => k !== "file" && !PRIVATE_VARS.has(k))),
999
- })),
1000
- controlMap: result.controlMap.map((f) => f.path),
3024
+ findings: result.findings.map((f) => shareFinding(f.file == null ? f : { ...f, file: plainPath(f.file) })).filter(Boolean),
3025
+ controlMap: result.controlMap.map((f) => plainPath(f.path)).filter((p) => shareablePath(p) && controlFor(p)),
1001
3026
  stats: { filesChecked: result.stats.filesChecked, mcpServers: result.stats.mcpServers },
1002
3027
  };
1003
3028
  }
1004
3029
 
3030
+ // A shared report holds at most this many findings. The command and the
3031
+ // browser check won't share a check with more, and the site refuses one.
3032
+ export const SHARE_MAX_FINDINGS = 400;
3033
+
3034
+ // How many findings in a shareable payload a report rebuilt here would leave
3035
+ // out: ones from checks this copy doesn't know, or with values it won't show.
3036
+ export function unshareable(payload) {
3037
+ if (!isObj(payload) || !Array.isArray(payload.findings)) return 0;
3038
+ return payload.findings.slice(0, SHARE_MAX_FINDINGS).filter((f) => !shareFinding(f)).length;
3039
+ }
3040
+
1005
3041
  // Rebuilds a public report from a shareable payload. Every title and sentence
1006
- // comes from the rule catalog, so a shared page can only say what a real check
1007
- // would say. Unknown rules and oversized values are dropped.
3042
+ // comes from the rule catalog.
1008
3043
  export function publicReportFrom(payload) {
1009
3044
  if (!isObj(payload) || !Array.isArray(payload.findings) || !Array.isArray(payload.controlMap)) return null;
1010
- const safe = (v, n = 120) => String(v ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, n);
1011
- // Shared reports cover a project, so only paths inside one are kept.
1012
- const projectPath = (p) => {
1013
- const clean = cleanPath(String(p));
1014
- return clean && !/^(\/|~|[A-Za-z]:)/.test(clean) ? clean : null;
1015
- };
1016
- const paths = [...new Set(payload.controlMap.slice(0, 300).map(projectPath).filter(Boolean))];
3045
+ const paths = [...new Set(payload.controlMap.slice(0, 300).map(shareablePath).filter((p) => p && controlFor(p)))];
1017
3046
  const findings = payload.findings
1018
- .slice(0, 400)
1019
- .filter((f) => isObj(f) && RULES[f.id] && (f.file == null || projectPath(f.file)))
3047
+ .slice(0, SHARE_MAX_FINDINGS)
3048
+ .map(shareFinding)
3049
+ .filter(Boolean)
1020
3050
  .map((f) => {
1021
3051
  const rule = RULES[f.id];
1022
- const allowed = new Set([...`${rule.title} ${rule.why} ${rule.fix}`.matchAll(/\{(\w+)\}/g)].map((m) => m[1]));
1023
- const vars = {};
1024
- for (const [k, v] of Object.entries(isObj(f.vars) ? f.vars : {})) if (allowed.has(k) && !PRIVATE_VARS.has(k)) vars[k] = safe(v);
1025
- const file = typeof f.file === "string" ? projectPath(f.file) : null;
1026
- vars.file = file ?? "";
1027
- const control = file ? controlFor(file) : null;
1028
- return publicFinding({
1029
- id: f.id,
1030
- severity: rule.severity,
1031
- category: rule.category,
1032
- tool: rule.tool ?? control?.tools?.[0] ?? (typeof vars.tool === "string" && vars.tool) ?? null,
1033
- file,
1034
- line: Number.isInteger(f.line) && f.line > 0 && f.line < 1e7 ? f.line : null,
1035
- vars,
1036
- });
3052
+ return publicFinding({ id: f.id, severity: rule.severity, category: rule.category, tool: sharedTool(f, rule), file: f.file, line: f.line, vars: { ...f.vars, file: f.file ?? "" } });
1037
3053
  })
1038
3054
  .sort(bySeverity);
1039
3055
  const controlMap = paths
1040
- .map((path) => ({ path, ...(controlFor(path) ?? { tools: ["Any agent started there"], kind: "Loose file" }) }))
3056
+ .map((path) => ({ path, ...controlFor(path) }))
1041
3057
  .map((f) => ({ ...f, findings: findings.filter((x) => x.file === f.path).length }));
1042
3058
  const { counts, score, grade } = scoreFindings(findings, controlMap.length > 0);
1043
3059
  const stats = isObj(payload.stats) ? payload.stats : {};
1044
3060
  return {
1045
- version: safe(payload.version, 20),
3061
+ version: typeof payload.version === "string" && RULESET_RE.test(payload.version) ? payload.version : "",
1046
3062
  score,
1047
3063
  grade,
1048
3064
  headline: headlineFor(counts, findings[0], controlMap.length > 0),
1049
3065
  counts,
1050
3066
  tools: agentsIn(controlMap),
1051
- stats: { filesChecked: toInt(stats.filesChecked), mcpServers: toInt(stats.mcpServers) },
3067
+ stats: { filesChecked: Math.min(toInt(stats.filesChecked), 100_000), mcpServers: Math.min(toInt(stats.mcpServers), 10_000) },
1052
3068
  findings,
1053
3069
  controlMap,
1054
3070
  };
1055
3071
  }
3072
+
3073
+ // --- Private reports -----------------------------------------------------------
3074
+ //
3075
+ // The page at misconfig.ai/p/ shows a report the command encrypted. Anyone can
3076
+ // make a link like that with any content in it, so nothing in it is trusted.
3077
+ // Findings are rebuilt from the rule catalog by ID, so every title, severity
3078
+ // and fix is the catalog's own; the grade and headline are worked out again;
3079
+ // and text from the files (names, summaries, what each file says) is kept as
3080
+ // plain text, cut to size. Whatever doesn't fit is dropped and counted.
3081
+
3082
+ const PRIVATE_LIMITS = { findings: 1000, files: 1000, lines: 20_000, value: 400, text: 400, line: 1000, evidence: 600 };
3083
+ const KNOWN_KINDS = new Set([...CONTROL.map(([, , kind]) => kind), "Loose file", "Plugin hooks", "Plugin MCP servers"]);
3084
+ const LOOSE_TOOL = "Any agent started there";
3085
+ const plainText = (v, max) => (typeof v === "string" ? v : typeof v === "number" && Number.isFinite(v) ? String(v) : "").slice(0, max);
3086
+
3087
+ // Words a report says in misconfig's own voice: commands to run, advice, what
3088
+ // known malware does and where that's reported. A private link can't put
3089
+ // other words there, so a crafted link can't tell its reader to run something
3090
+ // misconfig never suggested. A finding with anything else is dropped, as in a
3091
+ // share link. Names from the user's own files stay as text.
3092
+ const UPDATE_COMMANDS = new Set([
3093
+ ...Object.values(AGENT_PACKAGES).flatMap((m) => Object.values(m.update)),
3094
+ ...Object.keys(AGENT_PACKAGES).flatMap((p) => Object.values(GLOBAL_UPDATE).map((make) => make(p))),
3095
+ ]);
3096
+ const OWN_WORDS = {
3097
+ what: new Set([...KNOWN_PHRASES.what, ...phrases(Object.values(KNOWN_EXTENSIONS), "what"), ...phrases(TRACES, "what")]),
3098
+ source: new Set([...KNOWN_PHRASES.source, ...phrases(Object.values(KNOWN_EXTENSIONS), "source")]),
3099
+ campaign: new Set([...KNOWN_PHRASES.campaign, ...phrases(TRACES, "campaign")]),
3100
+ advice: new Set([
3101
+ ...KNOWN_PHRASES.advice,
3102
+ ...phrases(TRACES, "fix"),
3103
+ ...phrases(Object.values(KNOWN_EXTENSIONS), "advice"),
3104
+ EXT_ADVICE,
3105
+ LOOKUP_NO_FIX,
3106
+ LOOKUP_UNKNOWN,
3107
+ ]),
3108
+ worst: new Set(phrases(Object.values(AGENT_ADVISORIES).flat(), "title")),
3109
+ };
3110
+ const LOOKUP_ADVICE = /^Update to (\S{1,80}) or later(.*)$/s;
3111
+ const PRIVATE_OWN = {
3112
+ what: (v) => OWN_WORDS.what.has(v),
3113
+ source: (v) => OWN_WORDS.source.has(v),
3114
+ campaign: (v) => OWN_WORDS.campaign.has(v),
3115
+ worst: (v) => OWN_WORDS.worst.has(v),
3116
+ advice: (v) => {
3117
+ const m = LOOKUP_ADVICE.exec(v);
3118
+ return OWN_WORDS.advice.has(v) || Boolean(m && VERSION_RE.test(m[1]) && (m[2] === "" || m[2] === LOOKUP_SOME_FIXED));
3119
+ },
3120
+ update: (v) => UPDATE_COMMANDS.has(v),
3121
+ lookup: (v, values) => /^@?[A-Za-z0-9._/-]{1,214}$/.test(values.pkg ?? "") && (v === `npm view ${values.pkg} version` || v === `pip index versions ${values.pkg}`),
3122
+ tool: (v) => KNOWN_TOOLS.has(v),
3123
+ version: (v) => VERSION_RE.test(v),
3124
+ fixed: (v) => VERSION_RE.test(v),
3125
+ // Names that are package names or extension IDs in a real report.
3126
+ name: (v) => PACKAGE_NAME.test(v),
3127
+ known: (v) => KNOWN_NAMES.has(v),
3128
+ ext: (v) => EXT_ID.test(v),
3129
+ editor: (v) => EDITORS.has(v),
3130
+ official: (v) => PUBLIC_VARS.official(v) || Object.values(AGENT_EXTENSIONS).includes(v),
3131
+ officialId: (v) => Object.hasOwn(AGENT_EXTENSIONS, v),
3132
+ origin: (v) => PUBLIC_VARS.origin(v),
3133
+ fixes: (v) => /^(?:a security fix|[1-9]\d{0,2} security fixes)$/.test(v),
3134
+ vulns: (v) => /^(?:a published vulnerability|[1-9]\d{0,2} published vulnerabilities)$/.test(v),
3135
+ marketplaces: (v) => /^(?:a marketplace|[1-9]\d{0,2} marketplaces)$/.test(v),
3136
+ lead: (v) => v === "The issue" || v === "The most serious",
3137
+ every: (v) => v === "the fix" || v === "every fix",
3138
+ fromFiles: (v) => /^(?:an extension installed from a file|[1-9]\d{0,3} extensions installed from files)$/.test(v),
3139
+ summary: (v) => SAFE_SUMMARY.test(v),
3140
+ status: (v) => PUBLIC_VARS.status(v),
3141
+ versions: (v) => PUBLIC_VARS.versions(v),
3142
+ were: (v) => PUBLIC_VARS.were(v),
3143
+ one: (v) => PUBLIC_VARS.one(v),
3144
+ programs: (v) => PUBLIC_VARS.programs(v),
3145
+ them: (v) => PUBLIC_VARS.them(v),
3146
+ };
3147
+ // The rules whose `ref` and `where` come from a lookup or an advisory, not
3148
+ // from the user's files.
3149
+ const LOOKUP_IDS = new Set(["LOOKUP-MALICIOUS", "LOOKUP-VULN", "LOOKUP-VULN-MINOR", "LOOKUP-VULN-LOW"]);
3150
+ const LOOKUP_WHERE = new RegExp(
3151
+ `^(?:Used by MCP server “[^\\n]{1,300}” in [^\\n]{1,300}|Installed as an? (?:${[...EDITORS].join("|")}) extension|This is your (?:${[...new Set(Object.values(AGENT_PACKAGES).map((m) => m.tool))].join("|")}) install)$`,
3152
+ );
3153
+ const PACKAGE_NAME = /^@?[A-Za-z0-9._~-]{1,214}(?:\/[A-Za-z0-9._~-]{1,214})?$/;
3154
+
3155
+ // A path in a private report: cleaned, its control characters made
3156
+ // visible, and no longer than a real path needs to be shown.
3157
+ const privatePath = (p) => {
3158
+ const clean = typeof p === "string" ? cleanPath(p) : null;
3159
+ return clean && clean.length <= 1000 ? visibleName(clean) : null;
3160
+ };
3161
+
3162
+ function privateFinding(f) {
3163
+ if (!isObj(f) || typeof f.id !== "string" || !Object.hasOwn(RULES, f.id)) return null;
3164
+ const rule = RULES[f.id];
3165
+ const file = privatePath(f.file);
3166
+ const given = isObj(f.vars) ? f.vars : {};
3167
+ const values = { file: file ?? "" };
3168
+ for (const k of templateVars.get(f.id)) {
3169
+ if (k !== "file" && Object.hasOwn(given, k)) values[k] = plainText(given[k], PRIVATE_LIMITS.value);
3170
+ }
3171
+ for (const [k, own] of Object.entries(PRIVATE_OWN)) {
3172
+ if (Object.hasOwn(values, k) && values[k] !== "" && !own(values[k], values)) return null;
3173
+ }
3174
+ // Values a share link checks against fixed lists are checked the same way,
3175
+ // since they're the same in a private report. Package names are checked
3176
+ // as names, whether or not the command to look one up came with them.
3177
+ for (const [k, v] of Object.entries(values)) {
3178
+ if (k === "file" || v === "" || PRIVATE_VARS.has(k) || Object.hasOwn(PRIVATE_OWN, k) || !PUBLIC_VARS[k]) continue;
3179
+ // A lookup's "where" is checked below; it's never in a share.
3180
+ if (k === "where" && !WHERE[f.id]) continue;
3181
+ if (!PUBLIC_VARS[k](k === "where" ? hideNames(v) : v, f.id)) return null;
3182
+ }
3183
+ if (values.pkg && !/^@?[A-Za-z0-9._/-]{1,214}$/.test(values.pkg)) return null;
3184
+ if (LOOKUP_IDS.has(f.id)) {
3185
+ const where = values.where ?? "";
3186
+ if (!LOOKUP_REF.test(values.ref ?? "") || !LOOKUP_WHERE.test(where)) return null;
3187
+ if (where.startsWith("Used by MCP server “") && (!file || !where.endsWith(`” in ${file}`) || where.slice(0, -` in ${file}`.length).includes("” in "))) return null;
3188
+ }
3189
+ if (!knownFactsAgree(f.id, values, file)) return null;
3190
+ const tool = typeof f.tool === "string" && KNOWN_TOOLS.has(f.tool) ? f.tool : (rule.tool ?? (file ? controlFor(file)?.tools[0] : null) ?? null);
3191
+ return {
3192
+ id: f.id,
3193
+ severity: rule.severity,
3194
+ category: rule.category,
3195
+ tool,
3196
+ title: fillTemplate(rule.title, values),
3197
+ why: fillTemplate(rule.why, values),
3198
+ fix: fillTemplate(rule.fix, values),
3199
+ file,
3200
+ line: Number.isInteger(f.line) && f.line > 0 && f.line < 1e7 ? f.line : null,
3201
+ evidence: plainText(f.evidence, PRIVATE_LIMITS.evidence) || null,
3202
+ };
3203
+ }
3204
+
3205
+ function privateFile(f, budget) {
3206
+ if (!isObj(f) || typeof f.path !== "string") return null;
3207
+ const path = privatePath(f.path);
3208
+ if (!path) return null;
3209
+ const control = controlFor(path);
3210
+ const tools = control?.tools ?? arr(f.tools).filter((t) => KNOWN_TOOLS.has(t) || t === LOOSE_TOOL).slice(0, 20);
3211
+ const lines = arr(f.details);
3212
+ const kept = lines.slice(0, Math.max(0, Math.min(lines.length, budget.left)));
3213
+ budget.left -= kept.length;
3214
+ const kind = control?.kind ?? (KNOWN_KINDS.has(f.kind) ? f.kind : "Agent file");
3215
+ return {
3216
+ path,
3217
+ kind,
3218
+ tools,
3219
+ // Plugin code is listed by name and never read.
3220
+ ...(f.listed === true && kind === "Plugin code" ? { listed: true } : {}),
3221
+ scope: Object.hasOwn(SCOPES, f.scope) ? f.scope : scopeOf({ path, loose: tools.length === 1 && tools[0] === LOOSE_TOOL }),
3222
+ summary: plainText(f.summary, PRIVATE_LIMITS.text),
3223
+ details: kept.map((d) => d.slice(0, PRIVATE_LIMITS.line)),
3224
+ // Lines left out to keep the page a size a browser can draw.
3225
+ moreDetails: lines.length - kept.length,
3226
+ };
3227
+ }
3228
+
3229
+ // A private report as the page draws it, or null when the decrypted data
3230
+ // isn't one.
3231
+ export function privateReportFrom(data) {
3232
+ if (!isObj(data) || data.v !== 1 || !isObj(data.result)) return null;
3233
+ const r = data.result;
3234
+ const givenFindings = Array.isArray(r.findings) ? r.findings : [];
3235
+ const givenFiles = Array.isArray(r.controlMap) ? r.controlMap : [];
3236
+ const findings = givenFindings.slice(0, PRIVATE_LIMITS.findings).map(privateFinding).filter(Boolean).sort(bySeverity);
3237
+ const budget = { left: PRIVATE_LIMITS.lines };
3238
+ const seen = new Set();
3239
+ const controlMap = givenFiles
3240
+ .slice(0, PRIVATE_LIMITS.files)
3241
+ .map((f) => privateFile(f, budget))
3242
+ .filter((f) => f && !seen.has(f.path) && seen.add(f.path))
3243
+ .map((f) => ({ ...f, findings: findings.filter((x) => x.file === f.path).length }));
3244
+ const { counts, score, grade } = scoreFindings(findings, controlMap.length > 0);
3245
+ const scanned = isObj(data.scanned) ? data.scanned : {};
3246
+ const stats = isObj(r.stats) ? r.stats : {};
3247
+ return {
3248
+ createdAt: Number.isFinite(data.createdAt) && data.createdAt > 0 ? data.createdAt : null,
3249
+ version: typeof data.version === "string" && /^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(data.version) ? data.version : "",
3250
+ scanned: {
3251
+ // The folder the check ran in, as the command writes it: ~/..., /...
3252
+ // or a drive letter. Anything else isn't shown.
3253
+ project: /^(?:~\/|\/|[A-Za-z]:\/)/.test(plainText(scanned.project, 300)) ? fileValue(plainText(scanned.project, 300), "folder") : "",
3254
+ projectSkipped: scanned.projectSkipped === true,
3255
+ user: scanned.user === true,
3256
+ },
3257
+ // What was left out, so the page can say so rather than drop it quietly.
3258
+ dropped: { findings: givenFindings.length - findings.length, files: givenFiles.length - controlMap.length },
3259
+ result: {
3260
+ score,
3261
+ grade,
3262
+ headline: headlineFor(counts, findings[0], controlMap.length > 0),
3263
+ counts,
3264
+ tools: agentsIn(controlMap),
3265
+ stats: {
3266
+ filesChecked: Math.min(toInt(stats.filesChecked), 100_000),
3267
+ mcpServers: Math.min(toInt(stats.mcpServers), 10_000),
3268
+ agentInstalls: Math.min(toInt(stats.agentInstalls), 200),
3269
+ extensions: Math.min(toInt(stats.extensions), 30_000),
3270
+ },
3271
+ findings,
3272
+ controlMap,
3273
+ installed: privateInstalled(r.installed),
3274
+ },
3275
+ };
3276
+ }
3277
+
3278
+ // What's installed, rebuilt from the fixed lists: agents and editors
3279
+ // misconfig knows, extension IDs from its list of agent extensions,
3280
+ // versions that look like versions and cleaned paths. Anything else is
3281
+ // left out.
3282
+ const AGENT_TOOLS = new Set(Object.values(AGENT_PACKAGES).map((m) => m.tool));
3283
+ function privateInstalled(given) {
3284
+ const g = isObj(given) ? given : {};
3285
+ const list = (x, max) => (Array.isArray(x) ? x.slice(0, max).filter(isObj) : []);
3286
+ const agents = list(g.agents, 50)
3287
+ .filter((a) => AGENT_TOOLS.has(a.tool) && cleanVersion(a.version) && INSTALL_VIA.has(a.via) && privatePath(a.path))
3288
+ .map((a) => ({ tool: a.tool, version: cleanVersion(a.version), via: a.via, path: privatePath(a.path) }));
3289
+ const editors = list(g.editors, 12)
3290
+ .filter((e) => EDITORS.has(e.editor) && privatePath(e.dir))
3291
+ .map((e) => ({
3292
+ editor: e.editor,
3293
+ dir: privatePath(e.dir),
3294
+ count: Math.min(toInt(e.count), 3000),
3295
+ agents: list(e.agents, 30)
3296
+ .filter((x) => typeof x.id === "string" && Object.hasOwn(AGENT_EXTENSIONS, x.id))
3297
+ .map((x) => ({ name: AGENT_EXTENSIONS[x.id], id: x.id, version: cleanVersion(x.version) })),
3298
+ }));
3299
+ return { agents, editors };
3300
+ }