@misconfig/cli 1.1.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/engine/index.js CHANGED
@@ -1,63 +1,160 @@
1
- // misconfig.ai rule engine. Runs only in the Worker, never in the browser.
1
+ // The misconfig rule engine. It runs in the command, on the user's computer.
2
+ // The Worker uses its rules version, scoring text and catalog for the rules
3
+ // page, and the site publishes it so anyone can read it.
2
4
 
3
5
  import { maskSecrets, looksLikeSecret, looksLikeToken, isMasked, isPathLike, describeMasks } from "./mask.js";
4
- import { parseJSONC, parseTOML } from "./parse.js";
6
+ import { parseJSONC, parseTOML, parseYAML, parseCodexRules } from "./parse.js";
7
+ import { namedInstructions, NAMING_SETTINGS } from "./named.js";
5
8
  import { RULES, CATEGORIES } from "./catalog.js";
6
- import { explainFile, agentLines } from "./explain.js";
7
-
8
- export const RULESET_VERSION = "2026.11.2";
9
+ import { explainFile, agentLines, hiddenComments, hiddenTags, hiddenZeroWidth, fenceAt, inCodeSpan, CAN_IMPORT, scopeOf, HOOK_EVENTS, anthropicMarketplace, marketplaceSource } from "./explain.js";
10
+ import { ignoreRules, isIgnored, globMatch } from "./glob.js";
11
+ import { HOME_MARKERS, DOWNLOADS_LIKE, TOOL_ROOT, visibleName } from "./paths.js";
12
+ import { findDangerFlag, trimWord, programName, COMMAND_BREAK } from "./flags.js";
13
+ import {
14
+ KNOWN_PACKAGES,
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
+ OPEN_VSX_EDITORS,
25
+ addKnownMalware,
26
+ extensionListing,
27
+ compareVersions,
28
+ VERSION_RE,
29
+ } from "./known.js";
30
+
31
+ export { findDangerFlag };
32
+
33
+ export const RULESET_VERSION = "2026.11.7";
9
34
 
10
35
  const WEIGHT = { critical: 30, high: 15, medium: 6, low: 2, info: 0 };
11
36
  const SEVERITIES = ["critical", "high", "medium", "low", "info"];
37
+ // The lowest score for each grade. Below the last one is F.
38
+ const GRADES = [
39
+ ["A", 90],
40
+ ["B", 80],
41
+ ["C", 65],
42
+ ["D", 50],
43
+ ];
44
+
45
+ // How the score works, in the words reports and the rules page use.
46
+ export const SCORING = [
47
+ `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.`,
48
+ "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.",
49
+ `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.`,
50
+ ].join(" ");
12
51
  const MAX_FILE_CHARS = 450_000;
13
52
 
14
- // Which agents read which files. Used for the control map and attribution.
53
+ // Which agents read which files, and what each file controls. Used for the
54
+ // control map and attribution. The first match wins, so specific paths come
55
+ // before general ones.
15
56
  const CONTROL = [
57
+ // Claude Code
16
58
  [/(^|\/)claude(\.local)?\.md$/i, ["Claude Code"], "Instructions"],
17
- [/(^|\/)\.codex\/agents(\.override)?\.md$/i, ["Codex"], "Instructions"],
18
- [/(^|\/)\.config\/opencode\/agents\.md$/i, ["OpenCode"], "Instructions"],
19
- [/(^|\/)agents(\.override)?\.md$/i, ["Codex", "OpenCode", "Cursor", "GitHub Copilot", "Zed"], "Instructions"],
20
- [/(^|\/)gemini\.md$/i, ["Gemini CLI"], "Instructions"],
21
59
  [/(^|\/)\.claude\/settings(\.local)?\.json$/i, ["Claude Code"], "Permissions & hooks"],
22
- [/(^|\/)managed-settings\.json$/i, ["Claude Code"], "Admin policy"],
23
- [/(^|\/)claude_desktop_config\.json$/i, ["Claude Desktop"], "MCP servers"],
24
- [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User\/settings\.json$/i, (p) => [editorTool(p)], "Editor settings"],
25
- [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor)\/User\/mcp\.json$/i, (p) => [editorTool(p)], "MCP servers"],
26
- [/(^|\/)saoudrizwan\.claude-dev\/settings\/cline_mcp_settings\.json$/i, ["Cline"], "MCP servers"],
27
- [/(^|\/)rooveterinaryinc\.roo-cline\/settings\/mcp_settings\.json$/i, ["Roo Code"], "MCP servers"],
28
- [/(^|\/)\.codeium\/windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
29
- [/(^|\/)(\.bashrc|\.zshrc|\.bash_profile|\.profile|\.zprofile|config\.fish|[^/]*profile\.ps1)$/i, ["Your shell"], "Shell profile"],
60
+ [/(^|\/)managed-settings(\.d\/[^/]+)?\.json$/i, ["Claude Code"], "Admin policy"],
61
+ [/(^|\/)managed-mcp\.json$/i, ["Claude Code"], "Admin MCP servers"],
30
62
  [/(^|\/)\.claude\/hooks\//i, ["Claude Code"], "Hook script"],
31
63
  [/(^|\/)\.claude\/(commands|agents|skills|output-styles)\//i, ["Claude Code"], "Commands & agents"],
32
- [/(^|\/)\.mcp\.json$/i, ["Claude Code"], "MCP servers"],
64
+ [/(^|\/)\.claude\/rules\//i, ["Claude Code"], "Rules"],
65
+ [/(^|\/)\.claude\/projects\/[^/]+\/memory\//i, ["Claude Code"], "Memory"],
66
+ [/(^|\/)\.claude\/plugins\/installed_plugins\.json$/i, ["Claude Code"], "Plugins"],
67
+ [/(^|\/)\.claude\/plugins\/known_marketplaces\.json$/i, ["Claude Code"], "Plugin marketplaces"],
68
+ [/(^|\/)\.claude\/plugins\/.+\/hooks\/hooks\.json$/i, ["Claude Code"], "Plugin hooks"],
69
+ [/(^|\/)\.claude\/plugins\/.+\/\.mcp\.json$/i, ["Claude Code"], "Plugin MCP servers"],
70
+ [/(^|\/)\.claude\/plugins\/.+\/(commands|agents|skills)\/.+\.md$/i, ["Claude Code"], "Plugin commands & agents"],
71
+ [/(^|\/)\.claude-plugin\/plugin\.json$/i, ["Claude Code"], "Plugin manifest"],
33
72
  [/(^|\/)\.claude\.json$/i, ["Claude Code"], "User config"],
73
+ [/(^|\/)\.mcp\.json$/i, ["Claude Code", "GitHub Copilot"], "MCP servers"],
74
+ [/(^|\/)claude_desktop_config\.json$/i, ["Claude Desktop"], "MCP servers"],
75
+ // Codex
76
+ [/(^|\/)\.codex\/agents(\.override)?\.md$/i, ["Codex"], "Instructions"],
34
77
  [/(^|\/)\.codex\/config\.toml$/i, ["Codex"], "Permissions & MCP"],
78
+ [/(^|\/)\.codex\/hooks\.json$/i, ["Codex"], "Hooks"],
79
+ [/(^|\/)\.codex\/rules\/[^/]+\.rules$/i, ["Codex"], "Command rules"],
80
+ [/(^|\/)\.codex\/[^/]+\.config\.toml$/i, ["Codex"], "Profile"],
81
+ [/(^|\/)codex\/requirements\.toml$/i, ["Codex"], "Admin policy"],
35
82
  [/(^|\/)\.codex\/.+\.md$/i, ["Codex"], "Prompts"],
36
- [/(^|\/)\.cursor\/mcp\.json$/i, ["Cursor"], "MCP servers"],
37
- [/(^|\/)\.cursor\/.+\.mdc?$/i, ["Cursor"], "Rules"],
38
- [/(^|\/)\.cursorrules$/i, ["Cursor"], "Rules (legacy)"],
83
+ [/(^|\/)\.agents\/skills\//i, ["Codex"], "Skills"],
84
+ // Shared instruction files
85
+ [/(^|\/)\.config\/opencode\/agents\.md$/i, ["OpenCode"], "Instructions"],
86
+ [/(^|\/)\.junie\/agents\.md$/i, ["Junie"], "Guidelines"],
87
+ [/(^|\/)agents(\.override)?\.md$/i, ["Codex", "OpenCode", "Cursor", "GitHub Copilot", "Zed"], "Instructions"],
88
+ // Gemini CLI
89
+ [/(^|\/)gemini\.md$/i, ["Gemini CLI"], "Instructions"],
90
+ [/(^|\/)\.gemini\/settings\.json$/i, ["Gemini CLI"], "Settings & MCP"],
91
+ [/(^|\/)(gemini-cli|GeminiCli)\/(system-)?settings\.json$/i, ["Gemini CLI"], "Admin settings"],
92
+ [/(^|\/)\.gemini\/trustedFolders\.json$/i, ["Gemini CLI"], "Trusted folders"],
93
+ [/(^|\/)\.gemini\/extensions\/[^/]+\/gemini-extension\.json$/i, ["Gemini CLI"], "Extension"],
94
+ [/(^|\/)\.gemini\/.+\.md$/i, ["Gemini CLI"], "Instructions"],
95
+ [/(^|\/)\.gemini\/commands\/.+\.toml$/i, ["Gemini CLI"], "Commands"],
96
+ // GitHub Copilot, in VS Code and on the command line
39
97
  [/(^|\/)\.github\/copilot-instructions\.md$/i, ["GitHub Copilot"], "Instructions"],
40
98
  [/(^|\/)\.github\/(instructions|prompts|chatmodes|agents)\//i, ["GitHub Copilot"], "Instructions & prompts"],
99
+ [/(^|\/)\.github\/hooks\/[^/]+\.json$/i, ["GitHub Copilot"], "Hooks"],
100
+ [/(^|\/)\.github\/mcp\.json$/i, ["GitHub Copilot"], "MCP servers"],
101
+ [/(^|\/)\.github\/copilot\/settings\.json$/i, ["GitHub Copilot"], "Settings"],
102
+ [/(^|\/)\.copilot\/config\.json$/i, ["GitHub Copilot"], "Settings & trusted folders"],
103
+ [/(^|\/)\.copilot\/mcp-config\.json$/i, ["GitHub Copilot"], "MCP servers"],
41
104
  [/(^|\/)\.vscode\/mcp\.json$/i, ["GitHub Copilot"], "MCP servers"],
42
105
  [/(^|\/)\.vscode\/settings\.json$/i, ["GitHub Copilot"], "Editor settings"],
43
- [/(^|\/)\.gemini\/settings\.json$/i, ["Gemini CLI"], "Settings & MCP"],
44
- [/(^|\/)\.gemini\/.+\.md$/i, ["Gemini CLI"], "Instructions"],
45
- [/(^|\/)opencode\.jsonc?$/i, ["OpenCode"], "Settings & MCP"],
46
- [/(^|\/)\.opencode\//i, ["OpenCode"], "Agents & commands"],
47
- [/(^|\/)\.grok\/settings\.json$/i, ["Grok CLI"], "Settings & MCP"],
48
- [/(^|\/)(\.grok\/.+|grok)\.md$/i, ["Grok CLI"], "Instructions"],
49
- [/(^|\/)(\.windsurfrules|\.windsurf\/rules\/.+)$/i, ["Windsurf"], "Rules"],
50
- [/(^|\/)\.windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
106
+ [/(^|\/)\.vscode\/tasks\.json$/i, ["Cursor", "Windsurf"], "Editor tasks"],
107
+ [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User\/settings\.json$/i, (p) => [editorTool(p)], "Editor settings"],
108
+ [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor)\/User\/mcp\.json$/i, (p) => [editorTool(p)], "MCP servers"],
109
+ // Cursor
110
+ [/(^|\/)\.cursor\/mcp\.json$/i, ["Cursor"], "MCP servers"],
111
+ [/(^|\/)\.cursor\/hooks\.json$/i, ["Cursor"], "Hooks"],
112
+ [/(^|\/)\.cursor\/environment\.json$/i, ["Cursor"], "Cloud agent setup"],
113
+ [/(^|\/)\.cursor\/(cli-config|cli)\.json$/i, ["Cursor"], "CLI permissions"],
114
+ [/(^|\/)\.cursor\/sandbox\.json$/i, ["Cursor"], "Sandbox"],
115
+ [/(^|\/)\.cursor\/permissions\.json$/i, ["Cursor"], "Permissions"],
116
+ [/(^|\/)\.cursor\/.+\.mdc?$/i, ["Cursor"], "Rules"],
117
+ [/(^|\/)\.cursorrules$/i, ["Cursor"], "Rules (legacy)"],
118
+ // Cline and Roo Code
119
+ [/(^|\/)saoudrizwan\.claude-dev\/settings\/cline_mcp_settings\.json$/i, ["Cline"], "MCP servers"],
120
+ [/(^|\/)\.cline\/data\/settings\/cline_mcp_settings\.json$/i, ["Cline"], "MCP servers"],
121
+ [/(^|\/)\.cline\/data\/globalState\.json$/i, ["Cline"], "Auto-approve settings"],
122
+ [/(^|\/)\.cline\/plugins\/[^/]+\.[cm]?[jt]sx?$/i, ["Cline"], "Plugin code"],
123
+ [/(^|\/)(Documents\/Cline\/Rules|\.cline\/rules)\//i, ["Cline"], "Rules"],
51
124
  [/(^|\/)\.clinerules/i, ["Cline"], "Rules"],
125
+ [/(^|\/)rooveterinaryinc\.roo-cline\/settings\/mcp_settings\.json$/i, ["Roo Code"], "MCP servers"],
52
126
  [/(^|\/)(\.roomodes|\.roo\/.+)$/i, ["Roo Code"], "Rules & modes"],
127
+ // Others
128
+ [/(^|\/)\.codeium\/windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
129
+ [/(^|\/)(\.windsurfrules|\.windsurf\/rules\/.+)$/i, ["Windsurf"], "Rules"],
130
+ [/(^|\/)\.windsurf\/workflows\/.+\.md$/i, ["Windsurf"], "Workflows"],
131
+ [/(^|\/)\.windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
132
+ [/(^|\/)(\.windsurf|\.codeium\/windsurf)\/hooks\.json$/i, ["Windsurf"], "Hooks"],
133
+ [/(^|\/)\.devin\/hooks\.v1\.json$/i, ["Windsurf"], "Hooks"],
134
+ [/(^|\/)opencode\.jsonc?$/i, ["OpenCode"], "Settings & MCP"],
135
+ [/(^|\/)\.opencode\/(plugins?|tools)\/[^/]+\.[cm]?[jt]sx?$/i, ["OpenCode"], "Plugin code"],
136
+ [/(^|\/)\.opencode\//i, ["OpenCode"], "Agents & commands"],
137
+ [/(^|\/)\.grok\/config\.toml$/i, ["Grok"], "Permissions & MCP"],
138
+ [/(^|\/)\.grok\/settings\.json$/i, ["Grok"], "Settings & MCP"],
139
+ [/(^|\/)\.grok\/hooks\/[^/]+\.json$/i, ["Grok"], "Hooks"],
140
+ [/(^|\/)(\.grok\/.+|grok)\.md$/i, ["Grok"], "Instructions"],
141
+ [/(^|\/)(\.amp|\.config\/amp)\/settings\.json$/i, ["Amp"], "Settings & MCP"],
142
+ [/(^|\/)(\.amp|\.config\/amp)\/plugins\/[^/]+\.[cm]?[jt]sx?$/i, ["Amp"], "Plugin code"],
143
+ [/(^|\/)goose\/config\.ya?ml$/i, ["Goose"], "Settings & extensions"],
144
+ [/(^|\/)\.goosehints$/i, ["Goose"], "Instructions"],
53
145
  [/(^|\/)\.kiro\/steering\//i, ["Kiro"], "Steering"],
54
146
  [/(^|\/)\.kiro\/settings\/mcp\.json$/i, ["Kiro"], "MCP servers"],
147
+ [/(^|\/)\.kiro\/hooks\/[^/]+\.(json|kiro\.hook)$/i, ["Kiro"], "Hooks"],
148
+ [/(^|\/)\.kiro\/agents\/[^/]+\.(json|md)$/i, ["Kiro"], "Agents"],
55
149
  [/(^|\/)\.amazonq\/rules\//i, ["Amazon Q"], "Rules"],
56
150
  [/(^|\/)\.?amazonq\/mcp\.json$/i, ["Amazon Q"], "MCP servers"],
151
+ [/(^|\/)\.?amazonq\/cli-agents\/[^/]+\.json$/i, ["Amazon Q"], "Agents"],
57
152
  [/(^|\/)\.continue\//i, ["Continue"], "Config & rules"],
58
153
  [/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i, ["Zed"], "Agent settings"],
59
- [/(^|\/)\.junie\/guidelines\.md$/i, ["Junie"], "Guidelines"],
154
+ [/(^|\/)\.junie\/mcp\/mcp\.json$/i, ["Junie"], "MCP servers"],
155
+ [/(^|\/)\.junie\/(guidelines\.md|rules\/)/i, ["Junie"], "Guidelines"],
60
156
  [/(^|\/)\.aider\.conf\.ya?ml$/i, ["Aider"], "Settings"],
157
+ [/(^|\/)(\.bashrc|\.zshrc|\.bash_profile|\.profile|\.zprofile|config\.fish|[^/]*profile\.ps1)$/i, ["Your shell"], "Shell profile"],
61
158
  ];
62
159
 
63
160
  function editorTool(path) {
@@ -73,66 +170,306 @@ export function controlFor(path) {
73
170
  return { tools: typeof hit[1] === "function" ? hit[1](path) : hit[1], kind: hit[2] };
74
171
  }
75
172
 
76
- const HOME_MARKERS = [".ssh", "AppData", "Library", "NTUSER.DAT", ".bashrc", ".zshrc", ".profile", "Downloads", "Documents", "Desktop", ".config", ".local", "Pictures", "Music", "Videos"];
77
- const DOWNLOADS_LIKE = /^(downloads?|desktop|temp|tmp)$/i;
78
173
  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;
79
- const EXAMPLE_ENV = /\.env\.(example|sample|template|dist|defaults)$/i;
174
+ const EXAMPLE_ENV = /(^|\/)\.env[\w.-]*\.(example|sample|template|dist|defaults)$/i;
175
+ // .pem files are often public certificates, such as cert.pem or ca-bundle.pem,
176
+ // which aren't secret. A name that mentions a key still counts as a key.
177
+ const CERT_NAME = /cert|crt|chain|bundle|intermediate|leaf|issuer|(^|[-_.])(root|ca|pub|public)([-_.]|$)|ca\.pem$/i;
178
+ const KEY_NAME = /privkey|private|(^|[-_.])key([-_.]|$)/i;
179
+ // A project's .npmrc usually holds registry settings, not tokens, and keys in
180
+ // test and example folders are fixtures.
181
+ const USUALLY_HARMLESS = /(^|\/)\.npmrc$|(^|\/)(tests?|__tests__|specs?|fixtures?|testdata|test-data|examples?|samples?|mocks?|demo)\//i;
182
+ const isCertificate = (path) => {
183
+ const name = path.split("/").pop();
184
+ return /\.pem$/i.test(name) && (/pub(?:lic)?[-_.]?key/i.test(name) || (CERT_NAME.test(name) && !KEY_NAME.test(name)));
185
+ };
80
186
 
81
187
  // --- Text patterns -----------------------------------------------------------
188
+ //
189
+ // These run on untrusted text, so every repeat is bounded or can't overlap
190
+ // the next part of its pattern, and matching time grows with the text.
82
191
 
83
192
  const RX_REMOTE_EXEC =
84
- /\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;
193
+ /\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;
194
+ // --- Commands ------------------------------------------------------------------
195
+ //
196
+ // Hooks, scripts and settings that run commands are read one command at a
197
+ // time: a command ends at && || ; | or a new line.
198
+
199
+ function commandsOf(text) {
200
+ const out = [];
201
+ let start = 0;
202
+ for (const m of String(text).matchAll(COMMAND_BREAK)) {
203
+ out.push(text.slice(start, m.index));
204
+ start = m.index + m[0].length;
205
+ }
206
+ out.push(String(text).slice(start));
207
+ return out.filter((c) => c.trim());
208
+ }
209
+ const wordsOf = (command) => command.trim().split(/\s+/).map((w) => trimWord(w, "\"'", "\"'"));
210
+
211
+ // curl's options are case-sensitive: -d sends data, -D only saves headers.
212
+ 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/;
85
213
  const RX_NET_SEND =
86
- /\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;
87
- const RX_DESTRUCTIVE =
88
- /\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;
89
- const RX_OUTSIDE_SCRIPT =
90
- /(?:^|[\s"'=])((?:\/tmp|\/var\/tmp|~\/Downloads|\$HOME\/Downloads|%TEMP%|%TMP%|\$env:TEMP|[A-Za-z]:[\\/]Users[\\/][^\\/\s"']+[\\/](?:Downloads|AppData[\\/]Local[\\/]Temp))[\\/][^\s"']+)/i;
214
+ /\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;
215
+
216
+ // A command that sends data somewhere other than this computer.
217
+ function sendsData(text) {
218
+ for (const command of commandsOf(text)) {
219
+ if (!RX_CURL_SEND.test(command) && !RX_NET_SEND.test(command)) continue;
220
+ const hosts = [...command.matchAll(/\bhttps?:\/\/([^\s/:"'`]+)/gi)].map((m) => m[1]);
221
+ if (hosts.length && hosts.every(isLocalHost)) continue;
222
+ return true;
223
+ }
224
+ return false;
225
+ }
226
+
227
+ 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;
228
+ // Deleting the root of a drive, the home folder or everything in the current
229
+ // folder, or "$VAR/", which becomes / when the variable is empty. Cleaning up
230
+ // a named folder, such as rm -rf /tmp/build, isn't flagged.
231
+ const RISKY_TARGET =
232
+ /^(?:\/\*?|\\\*?|~[\\/]?\*?|\$\{?HOME\}?[\\/]?\*?|\$env:(?:USERPROFILE|HOMEPATH|HOME)[\\/]?\*?|%(?:USERPROFILE|HOMEPATH)%[\\/]?\*?|[A-Za-z]:[\\/]?\*?|\*|\.[\\/]?\*?|\.\.[\\/]?\*?|\$\{?\w+\}?[\\/]\*?)$/i;
233
+ function removesTooMuch(text) {
234
+ for (const command of commandsOf(text)) {
235
+ const words = wordsOf(command);
236
+ const at = words.findIndex((w) => /^(?:rm|Remove-Item|ri|rd|rmdir|del|erase)$/i.test(w));
237
+ if (at < 0) continue;
238
+ const args = words.slice(at + 1);
239
+ const cmdStyle = /^(?:rd|rmdir|del|erase)$/i.test(words[at]) && args.some((a) => /^\/[a-z]$/i.test(a));
240
+ const flags = cmdStyle ? args.filter((a) => /^\/[a-z]$/i.test(a)) : args.filter((a) => a.startsWith("-"));
241
+ const targets = cmdStyle ? args.filter((a) => !/^\/[a-z]$/i.test(a)) : args.filter((a) => !a.startsWith("-"));
242
+ 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));
243
+ if (recursive && targets.some((t) => RISKY_TARGET.test(t))) return true;
244
+ }
245
+ return false;
246
+ }
247
+ const isDestructive = (text) => RX_DESTRUCTIVE.test(text) || removesTooMuch(text);
248
+
249
+ // A script run from Downloads or a temp folder, which isn't reviewed with
250
+ // the project. Only the program or script being run counts, not a file a
251
+ // command writes to.
252
+ const OUTSIDE_PATH = /^(?:\/tmp|\/var\/tmp|~\/Downloads|\$HOME\/Downloads|%TEMP%|%TMP%|\$env:TEMP|[A-Za-z]:[\\/]Users[\\/][^\\/]+[\\/](?:Downloads|AppData[\\/]Local[\\/]Temp))[\\/]\S+$/i;
253
+ const INTERPRETERS = /^(?:bash|sh|zsh|fish|dash|python[0-9.]*|node|deno|bun|ruby|perl|php|pwsh|powershell(?:\.exe)?|source|\.)$/i;
254
+ function runsOutsideScript(text) {
255
+ for (const command of commandsOf(text)) {
256
+ const words = wordsOf(command).filter((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w));
257
+ while (/^(?:sudo|exec|nohup|time|env)$/i.test(words[0] ?? "")) words.shift();
258
+ let script = words[0];
259
+ if (INTERPRETERS.test(script ?? "")) script = words.slice(1).find((w) => !w.startsWith("-"));
260
+ if (script && OUTSIDE_PATH.test(script)) return true;
261
+ }
262
+ return false;
263
+ }
91
264
  const RX_EXFIL_HOST =
92
- /\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;
265
+ /(?:^|[^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;
93
266
  const RX_OVERRIDE =
94
- /\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;
267
+ /\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;
95
268
  const RX_SECRET_ACCESS =
96
- /\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;
269
+ /\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;
97
270
  const RX_INJECT_WORDS =
98
271
  /\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;
99
272
  const RX_BENIGN_COMMENT = /^\s*(?:markdownlint|prettier|toc|end ?toc|eslint|cspell|vale|begin|end|lint|todo|fixme|note)\b/i;
100
- const RX_DANGER_FLAGS =
101
- /--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;
102
273
  const RX_IMPORT_OUTSIDE = /(?:^|\s)@((?:~\/|\.\.\/|[A-Za-z]:[\\/]|\/(?:Users|home|etc|tmp|var|opt|root|mnt)\/)[^\s)\]]+)/g;
103
- const RX_BLOB = /[A-Za-z0-9+/]{300,}={0,2}/;
274
+ const RX_BASE64_RUN = /[A-Za-z0-9+/]+={0,2}/g;
104
275
  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;
276
+ // Paste sites, where text can change after anyone has looked at it.
277
+ // pastebin.com is reported as a data-collection endpoint instead.
278
+ const RX_PASTE_SITE =
279
+ /(?:^|[^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;
280
+ // Telling the agent to take its instructions from a web page: "follow the
281
+ // steps at https://...", or "fetch https://... and do what it says". Whoever
282
+ // runs the page decides what the agent does, after the file was reviewed.
283
+ const RX_REMOTE_INSTRUCTIONS =
284
+ /\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;
285
+ // A download that needs a password, the way malware hides from scanners.
286
+ // It has to give the password, as lures do: talking about password-protected
287
+ // archives isn't asking for one.
288
+ const ARCHIVE = String.raw`(?:\.(?:zip|7z|rar)\b|\b(?:zip|7z|rar|archive)\b)`;
289
+ const PASSWORD_GIVEN = String.raw`\b(?:password|passphrase|passwd)\b(?:\s*(?:is|:|=)\s*|\s+(?=["'\`“]))["'\`“]?([^\s"'\`”]{2,40})`;
290
+ const RX_ARCHIVE_PASSWORD = new RegExp(
291
+ [
292
+ `${ARCHIVE}[^\\n]{0,120}(?:\\n[^\\n]{0,80})?${PASSWORD_GIVEN}`,
293
+ `${PASSWORD_GIVEN}[^\\n]{0,80}(?:\\n[^\\n]{0,80})?${ARCHIVE}`,
294
+ String.raw`\bunzip\s+(?:-\w+\s+)*-P\s*\S+`,
295
+ String.raw`\b7z\s+[ex]\b[^\n]{0,80}\s-p\S+`,
296
+ ].join("|"),
297
+ "i",
298
+ );
299
+ // A lure gives the password and says to download, extract or run the file.
300
+ // "The password is in 1Password", a login password, or "move it to the
301
+ // archive folder" doesn't.
302
+ 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"]);
303
+ const NOT_A_GIVEN_PASSWORD = new Set(["see", "ask", "none", "n/a", "in", "your", "the"]);
304
+ const LURE_VERB = /\b(?:download|extract|unzip|unpack|decompress|open|run|install|launch|execute)/i;
305
+ const LOGIN = /\b(?:log\s?in|sign\s?in|user(?:name)?|account|admin|database|db|ssh|mysql|postgres|redis|wi-?fi)\b/i;
306
+ function givesArchivePassword(text, m) {
307
+ // unzip -P and 7z -p extract with a password: a lure on their own.
308
+ if (/^(?:unzip|7z)\b/i.test(m[0])) return true;
309
+ const value = (m[1] ?? m[2] ?? "").replace(/[.,;:!?)\]]+$/, "").toLowerCase();
310
+ const stated = /\bpass(?:word|phrase|wd)\s+is\s/i.test(m[0]);
311
+ if (value && (stated ? NOT_A_PASSWORD : NOT_A_GIVEN_PASSWORD).has(value)) return false;
312
+ const word = m[0].search(/\b(?:password|passphrase|passwd)\b/i);
313
+ if (LOGIN.test(sameLineBefore(text, m.index + Math.max(0, word), 60))) return false;
314
+ const from = Math.max(0, m.index - 200);
315
+ const window = text.slice(from, Math.min(text.length, m.index + m[0].length + 200));
316
+ return LURE_VERB.test(window);
317
+ }
318
+ // Removing macOS's quarantine flag or turning off Gatekeeper.
319
+ // Clearing every attribute is also a step before code signing, so that only
320
+ // counts on something in Downloads.
321
+ 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;
322
+ // Servers named in attack reports, as hosts or addresses in any agent file.
323
+ const RX_KNOWN_BAD_HOST = new RegExp(
324
+ // No lookbehind, so the engine also loads in older Safari.
325
+ `(?:^|[^\\w.-])((?:[a-z0-9-]{1,63}\\.){0,4}?(${Object.keys(KNOWN_BAD_HOSTS).map((h) => h.replace(/[.]/g, "\\.")).join("|")}))(?![\\w-]|\\.\\w)`,
326
+ "i",
327
+ );
328
+ // The lists in a file whose names say they block things, such as
329
+ // permissions.deny in Claude Code's settings or a TOML deny = [...], as
330
+ // [start, end] spans. Found once per file, and brackets inside quoted
331
+ // entries don't end a list.
332
+ function blockSpans(text) {
333
+ const spans = [];
334
+ for (const m of text.matchAll(/["']?([\w.-]{1,60})["']?\s*[:=]\s*\[/g)) {
335
+ if (!/deny|block|disallow|forbid|exclude|reject|ban/i.test(m[1])) continue;
336
+ const start = m.index + m[0].length;
337
+ if (spans.length && start < spans.at(-1)[1]) continue;
338
+ let quote = null;
339
+ let depth = 1;
340
+ let i = start;
341
+ for (; i < text.length && depth > 0; i++) {
342
+ const c = text[i];
343
+ if (quote) {
344
+ if (c === "\\") i++;
345
+ else if (c === quote) quote = null;
346
+ } else if (c === '"' || c === "'") quote = c;
347
+ else if (c === "[") depth++;
348
+ else if (c === "]") depth--;
349
+ }
350
+ spans.push([start, i]);
351
+ }
352
+ return spans;
353
+ }
354
+ const RX_KNOWN_BAD_HOSTS = new RegExp(RX_KNOWN_BAD_HOST.source, "gi");
355
+ // The first mention of a known malware server that's a real use: not on a
356
+ // block list and not warned against. Every mention is looked at, so warnings
357
+ // and block-list entries can't hide a use after them.
358
+ function knownBadHost(text) {
359
+ const content = String(text ?? "");
360
+ let spans = null;
361
+ let at = 0;
362
+ for (const m of content.matchAll(RX_KNOWN_BAD_HOSTS)) {
363
+ const index = m.index + m[0].length - m[1].length;
364
+ spans ??= blockSpans(content);
365
+ while (at < spans.length && spans[at][1] <= index) at++;
366
+ if (at < spans.length && spans[at][0] <= index) continue;
367
+ if (negated(content, index)) continue;
368
+ return { index, host: m[2].toLowerCase(), campaign: KNOWN_BAD_HOSTS[m[2].toLowerCase()] };
369
+ }
370
+ return null;
371
+ }
105
372
  const SHELL_SERVER = /(?:^|[-_/@.])(?:shell|terminal|exec|executor|commands?|cmd|desktop-commander|ssh|powershell|bash|zsh|run-command)(?:[-_.]|$)/i;
106
373
 
107
374
  // --- Entry point -------------------------------------------------------------
108
375
 
109
376
  export function analyze(input) {
110
377
  const ctx = buildContext(input ?? {});
111
- collectMcpServers(ctx);
378
+ // A file that trips up a check is reported as unchecked. It can't stop
379
+ // the rest of the report.
380
+ const guard = (f, check) => {
381
+ try {
382
+ check();
383
+ } catch {
384
+ f.failed = true;
385
+ }
386
+ };
387
+ for (const f of ctx.files) if (f.content) guard(f, () => collectMcpServers(ctx, f));
388
+ for (const f of ctx.files) if (f.content) guard(f, () => checkFile(ctx, f));
112
389
  for (const f of ctx.files) {
113
- if (!f.content) continue;
114
- if (/(^|\/)(\.claude\/settings(\.local)?|managed-settings)\.json$/i.test(f.path)) checkClaudeSettings(ctx, f);
115
- else if (/(^|\/)\.claude\.json$/i.test(f.path)) checkClaudeUserConfig(ctx, f);
116
- else if (/(^|\/)\.codex\/config\.toml$/i.test(f.path)) checkCodex(ctx, f);
117
- else if (/(^|\/)\.gemini\/settings\.json$/i.test(f.path)) checkGemini(ctx, f);
118
- else if (/(^|\/)(\.vscode|(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User)\/settings\.json$/i.test(f.path)) checkVSCode(ctx, f);
119
- else if (/(^|\/)opencode\.jsonc?$/i.test(f.path)) checkOpenCode(ctx, f);
120
- else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(f.path)) checkZed(ctx, f);
121
- else if (f.kind === "Shell profile") checkShellProfile(ctx, f);
122
- else if (/(^|\/)\.aider\.conf\.ya?ml$/i.test(f.path)) checkAider(ctx, f);
123
- else if (/^package\.json$/i.test(f.path)) checkPackageJson(ctx, f);
124
-
125
- if (/(^|\/)\.claude\/hooks\//i.test(f.path)) checkHookScript(ctx, f);
126
- else if (isInstructionFile(f)) checkInstructionText(ctx, f);
127
- }
128
- for (const server of ctx.mcpServers) checkMcpServer(ctx, server);
129
- const enabled = ctx.mcpServers.filter((s) => !s.disabled).length;
130
- if (enabled > 12) add(ctx, "MCP-MANY", { vars: { count: enabled } });
390
+ if (f.content && f.kind && (f.failed || (/\.(jsonc?|toml)$/i.test(f.path) && parsed(f) == null))) add(ctx, "WS-UNPARSED", { file: f });
391
+ }
392
+ for (const server of ctx.mcpServers) guard(server.file, () => checkMcpServer(ctx, server));
393
+ // Each agent's servers, wherever it reads them from. Servers that belong
394
+ // to different agents aren't all in front of any one of them.
395
+ // Agents that read the same file, such as Claude Code and Copilot with
396
+ // .mcp.json, are reported once.
397
+ const perAgent = new Map();
398
+ for (const s of ctx.mcpServers) {
399
+ if (s.disabled) continue;
400
+ for (const t of s.file.tools ?? []) perAgent.set(t, [...(perAgent.get(t) ?? []), `${s.file.path}#${s.name}`]);
401
+ }
402
+ const reported = new Set();
403
+ for (const [tool, servers] of perAgent) {
404
+ const key = servers.sort().join("\n");
405
+ if (servers.length <= 12 || reported.has(key)) continue;
406
+ reported.add(key);
407
+ add(ctx, "MCP-MANY", { tool, vars: { tool, count: servers.length } });
408
+ }
131
409
  checkWorkspace(ctx);
132
410
  checkSprawl(ctx);
411
+ checkExtensions(ctx);
412
+ checkInstalls(ctx);
413
+ checkLocked(ctx);
414
+ checkTraces(ctx);
415
+ checkSkillPrograms(ctx);
416
+ checkPluginCode(ctx);
417
+ checkAutorun(ctx);
418
+ checkNamed(ctx);
133
419
  return summarize(ctx);
134
420
  }
135
421
 
422
+ function checkFile(ctx, f) {
423
+ const p = f.path;
424
+ if (/(^|\/)(\.claude\/settings(\.local)?\.json|managed-settings(\.d\/[^/]+)?\.json)$/i.test(p)) checkClaudeSettings(ctx, f);
425
+ else if (/(^|\/)\.claude\/plugins\/.+\/hooks\/hooks\.json$/i.test(p) || f.role === "claude-hooks") checkClaudeHooks(ctx, f, hooksOf(parsed(f)));
426
+ else if (/(^|\/)\.claude-plugin\/plugin\.json$/i.test(p)) checkClaudeHooks(ctx, f, hooksOf(parsed(f)?.hooks));
427
+ else if (/(^|\/)\.claude\.json$/i.test(p)) checkClaudeUserConfig(ctx, f);
428
+ else if (/(^|\/)\.codex\/([^/]+\.)?config\.toml$/i.test(p)) checkCodex(ctx, f);
429
+ else if (/(^|\/)(\.gemini|gemini-cli|GeminiCli)\/(system-)?settings\.json$/i.test(p)) checkGemini(ctx, f);
430
+ else if (/(^|\/)\.gemini\/trustedFolders\.json$/i.test(p)) checkTrustedFolders(ctx, f, "Gemini CLI", geminiTrusted(parsed(f)));
431
+ else if (/(^|\/)\.copilot\/config\.json$/i.test(p)) checkTrustedFolders(ctx, f, "GitHub Copilot", copilotTrusted(parsed(f)));
432
+ else if (/(^|\/)\.github\/hooks\/[^/]+\.json$/i.test(p)) checkJsonHooks(ctx, f, "A GitHub Copilot hook");
433
+ else if (/(^|\/)\.cursor\/hooks\.json$/i.test(p)) checkJsonHooks(ctx, f, "A Cursor hook");
434
+ else if (/(^|\/)\.cursor\/environment\.json$/i.test(p)) checkCursorEnvironment(ctx, f);
435
+ else if (/(^|\/)\.vscode\/tasks\.json$/i.test(p)) checkVsCodeTasks(ctx, f);
436
+ else if (/(^|\/)\.codex\/hooks\.json$/i.test(p)) checkJsonHooks(ctx, f, "A Codex hook");
437
+ else if (/(^|\/)\.codex\/rules\/[^/]+\.rules$/i.test(p)) checkCodexRules(ctx, f);
438
+ else if (/(^|\/)((\.windsurf|\.codeium\/windsurf)\/hooks|\.devin\/hooks\.v1)\.json$/i.test(p)) checkJsonHooks(ctx, f, "A Windsurf hook");
439
+ else if (/(^|\/)\.kiro\/hooks\//i.test(p)) checkJsonHooks(ctx, f, "A Kiro hook");
440
+ else if (/(^|\/)\.kiro\/agents\/[^/]+\.json$/i.test(p)) checkAgentFile(ctx, f, "A Kiro hook");
441
+ else if (/(^|\/)\.?amazonq\/cli-agents\//i.test(p)) checkAgentFile(ctx, f, "An Amazon Q hook");
442
+ else if (/(^|\/)\.grok\/hooks\//i.test(p)) checkJsonHooks(ctx, f, "A Grok hook");
443
+ else if (/(^|\/)\.cursor\/(cli-config|cli)\.json$/i.test(p)) checkCursorCli(ctx, f);
444
+ else if (/(^|\/)\.cursor\/sandbox\.json$/i.test(p)) checkCursorSandbox(ctx, f);
445
+ else if (/(^|\/)(\.vscode|(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User)\/settings\.json$/i.test(p)) checkVSCode(ctx, f);
446
+ else if (/(^|\/)opencode\.jsonc?$/i.test(p)) checkOpenCode(ctx, f);
447
+ else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(p)) checkZed(ctx, f);
448
+ else if (/(^|\/)\.cline\/data\/globalState\.json$/i.test(p)) checkCline(ctx, f);
449
+ else if (/(^|\/)\.grok\/config\.toml$/i.test(p)) checkGrok(ctx, f);
450
+ else if (/(^|\/)(\.amp|\.config\/amp)\/settings\.json$/i.test(p)) checkAmp(ctx, f);
451
+ else if (/(^|\/)goose\/config\.ya?ml$/i.test(p)) checkGoose(ctx, f);
452
+ else if (/(^|\/)\.continue\/(?:.+\/)?[^/]+\.(?:ya?ml|json)$/i.test(p)) checkContinue(ctx, f);
453
+ else if (f.kind === "Shell profile") checkShellProfile(ctx, f);
454
+ else if (/(^|\/)\.aider\.conf\.ya?ml$/i.test(p)) checkAider(ctx, f);
455
+ else if (/^package\.json$/i.test(p)) checkPackageJson(ctx, f);
456
+ else if (/(^|\/)\.claude\/plugins\/known_marketplaces\.json$/i.test(p)) checkMarketplaces(ctx, f);
457
+ else if (/(^|\/)\.github\/workflows\//i.test(p)) checkWorkflowTrace(ctx, f);
458
+
459
+ const bad = knownBadHost(f.content);
460
+ if (bad) {
461
+ const line = lineAt(f.content, bad.index);
462
+ add(ctx, "TXT-KNOWN-C2", { file: f, line, evidence: evidenceLine(f, line), vars: { host: bad.host, campaign: bad.campaign } });
463
+ }
464
+
465
+ if (/(^|\/)\.claude\/hooks\//i.test(f.path)) checkHookScript(ctx, f);
466
+ else if (isInstructionFile(f)) checkInstructionText(ctx, f);
467
+ }
468
+
469
+ // Claude Code hooks, written as { hooks: { Event: [...] } } in hooks.json, or
470
+ // as { Event: [...] } inside a plugin's plugin.json.
471
+ const hooksOf = (json) => (isObj(json?.hooks) ? json.hooks : isObj(json) ? json : null);
472
+
136
473
  // --- Context -----------------------------------------------------------------
137
474
 
138
475
  function buildContext(input) {
@@ -140,54 +477,116 @@ function buildContext(input) {
140
477
  const seenPaths = new Set();
141
478
  for (const raw of Array.isArray(input.files) ? input.files : []) {
142
479
  if (!raw || typeof raw.path !== "string") continue;
143
- const path = cleanPath(raw.path);
144
- if (!path || seenPaths.has(path)) continue;
145
- seenPaths.add(path);
480
+ const cleaned = cleanPath(raw.path);
481
+ if (!cleaned || seenPaths.has(cleaned)) continue;
482
+ seenPaths.add(cleaned);
483
+ const path = visibleName(cleaned);
146
484
  const file = {
147
485
  path,
148
486
  size: toInt(raw.size),
149
487
  sensitive: raw.sensitive === true,
150
488
  tooLarge: raw.tooLarge === true,
151
489
  loose: raw.loose === true,
490
+ // A program inside a skill folder, listed by name and never read.
491
+ listed: raw.listed === true,
492
+ // A link the command didn't follow: to a file outside the project, or
493
+ // to a credential file.
494
+ linked: raw.linked === "outside" || raw.linked === "secret" ? raw.linked : null,
495
+ // Too large to read whole, so only its start was read.
496
+ partial: raw.partial === true,
497
+ // A link to a folder, listed by the command and never followed.
498
+ folder: raw.folder === true && raw.linked === "outside",
499
+ // Set by the command for a plugin's hooks or MCP servers kept at a
500
+ // path its plugin.json names.
501
+ role: raw.role === "claude-hooks" || raw.role === "mcp-servers" ? raw.role : null,
152
502
  };
153
- if (typeof raw.content === "string" && !file.sensitive) {
154
- file.content = maskSecrets(raw.content.slice(0, MAX_FILE_CHARS)).text;
503
+ // Files past the size limit are listed as too large rather than half checked.
504
+ if (typeof raw.content === "string" && raw.content.length > MAX_FILE_CHARS) file.tooLarge = true;
505
+ else if (typeof raw.content === "string" && !file.sensitive && !file.listed && !file.linked) {
506
+ file.content = maskSecrets(raw.content).text;
155
507
  file.lines = file.content.split(/\r?\n/);
156
508
  }
157
- const control = controlFor(path);
509
+ const control = controlFor(path) ?? (file.role ? { tools: ["Claude Code"], kind: file.role === "claude-hooks" ? "Plugin hooks" : "Plugin MCP servers" } : null);
158
510
  file.tools = control ? control.tools : file.loose ? ["Any agent started there"] : [];
159
511
  file.kind = control ? control.kind : file.loose ? "Loose file" : null;
160
512
  files.push(file);
161
513
  }
514
+ // Files that settings name as instructions, such as Gemini CLI's
515
+ // context.fileName, are instructions for that agent whatever their name.
516
+ const named = namedInstructions(files.filter((f) => f.content && NAMING_SETTINGS.some((re) => re.test(f.path))));
517
+ for (const f of files) {
518
+ if ((f.kind && !f.loose) || f.sensitive || f.listed || f.linked || !f.content) continue;
519
+ const hit = named.find((n) => n.test(f.path));
520
+ if (!hit) continue;
521
+ f.kind = "Instructions";
522
+ f.tools = [hit.tool];
523
+ f.loose = false;
524
+ f.named = true;
525
+ }
162
526
  const shape = input.shape && typeof input.shape === "object" ? input.shape : {};
527
+ const topLevel = Array.isArray(shape.topLevel) ? shape.topLevel.filter((s) => typeof s === "string").slice(0, 200) : [];
163
528
  return {
164
529
  root: typeof input.root === "string" ? input.root.slice(0, 120) : null,
165
530
  files,
166
531
  shape: {
167
532
  entries: toInt(shape.entries),
168
- topLevel: Array.isArray(shape.topLevel) ? shape.topLevel.filter((s) => typeof s === "string").slice(0, 200) : [],
533
+ topLevel,
169
534
  rootGit: shape.rootGit === true,
170
535
  gitRepos: toInt(shape.gitRepos),
171
536
  truncated: shape.truncated === true,
172
537
  },
538
+ // git's own ignore lists, read by the command: .git/info/exclude and
539
+ // the global list in ~/.config/git/ignore. Text only, never shown.
540
+ ignoreLists: (Array.isArray(input.ignoreLists) ? input.ignoreLists : [])
541
+ .filter((l) => typeof l?.content === "string")
542
+ .slice(0, 4)
543
+ .map((l) => l.content.slice(0, 64 * 1024)),
173
544
  maskedInBrowser: toInt(input.masked?.count),
545
+ // Found by the command on this computer: agent installs, editor
546
+ // extensions and files attacks leave. Each is checked against what
547
+ // known.js expects, so nothing else can get through.
548
+ installs: installsFrom(input.installs),
549
+ locked: lockedFrom(input.locked),
550
+ extensions: extensionsFrom(input.extensions),
551
+ traces: new Set((Array.isArray(input.traces) ? input.traces : []).filter((p) => typeof p === "string" && TRACE_PATHS.has(p))),
552
+ packages: [],
553
+ homeLike: topLevel.filter((n) => HOME_MARKERS.has(n)).length >= 3,
554
+ // The command was run in the home folder, so it checked the agent
555
+ // settings there, not a project. Where the agents themselves were
556
+ // started is in their own settings.
557
+ ranInHome: input.scanned?.projectSkipped === true,
558
+ // Glob matching work allowed for the whole check.
559
+ ignoreBudget: { left: 8_000_000 },
174
560
  findings: [],
175
561
  seen: new Set(),
176
562
  mcpServers: [],
177
563
  claudeDeny: [],
178
564
  claudeSettingsFiles: [],
565
+ // Project files whose settings run commands on their own: the first one each.
566
+ autorun: new Map(),
567
+ named,
179
568
  };
180
569
  }
181
570
 
182
571
  function cleanPath(p) {
183
572
  const unix = p.replace(/\\/g, "/");
184
573
  const parts = unix.split("/").filter((s) => s && s !== ".");
185
- if (!parts.length || parts.includes("..") || parts.join("/").length > 400) return null;
574
+ // As long as a path can be. Shorter would let a deep folder hide a file.
575
+ if (!parts.length || parts.includes("..") || parts.join("/").length > 4096) return null;
186
576
  // Keep the leading slash of system files such as /etc/claude-code/managed-settings.json.
187
577
  return (unix.startsWith("/") ? "/" : "") + parts.join("/");
188
578
  }
189
579
 
190
- const toInt = (n) => (Number.isFinite(Number(n)) ? Math.max(0, Math.floor(Number(n))) : 0);
580
+ // Strings and numbers from a JSON list, as text. Anything else is dropped.
581
+ const scalars = (x) => (Array.isArray(x) ? x.filter((v) => typeof v === "string" || typeof v === "number").map(String) : []);
582
+ // A value from a settings file as text, or "" when it isn't a string, number or boolean.
583
+ const asText = (v) => (typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : "");
584
+ // Only numbers and number strings count: Number() on an object can call its
585
+ // own conversion code or throw.
586
+ const toInt = (n) => {
587
+ const x = typeof n === "number" || typeof n === "string" ? Number(n) : NaN;
588
+ return Number.isFinite(x) ? Math.max(0, Math.floor(x)) : 0;
589
+ };
191
590
  const arr = (x) => (Array.isArray(x) ? x.filter((s) => typeof s === "string") : []);
192
591
  const isObj = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
193
592
  const clip = (s, n = 180) => {
@@ -196,9 +595,9 @@ const clip = (s, n = 180) => {
196
595
  };
197
596
 
198
597
  function isInstructionFile(f) {
199
- if (f.loose) return true;
598
+ if (f.loose || f.named) return true;
200
599
  if (!f.kind) return false;
201
- return /\.(md|mdc|txt)$/i.test(f.path) || /(^|\/)\.(cursorrules|windsurfrules|clinerules)$/i.test(f.path) || /(^|\/)\.clinerules\//i.test(f.path);
600
+ 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);
202
601
  }
203
602
 
204
603
  // The line that names a folder as a key. Quoted first, so "~" doesn't match
@@ -213,20 +612,78 @@ function lineOf(file, test) {
213
612
  return idx >= 0 ? idx + 1 : 0;
214
613
  }
215
614
 
216
- 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;
615
+ // The first line at or after `from` that matches, else the first anywhere.
616
+ // Two servers can use the same package or key; each finding should point at
617
+ // its own server's lines.
618
+ function lineAfter(file, test, from) {
619
+ if (!file.lines || !from) return lineOf(file, test);
620
+ const idx = file.lines.findIndex((line, i) => i >= from - 1 && (typeof test === "string" ? line.includes(test) : test.test(line)));
621
+ return idx >= 0 ? idx + 1 : lineOf(file, test);
622
+ }
623
+
624
+ // The warning has to reach the match: a sentence end, a semicolon or a word
625
+ // like "instead" or "then" starts something new. A dot inside a name, as in
626
+ // paste.ee, doesn't.
627
+ 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;
628
+
629
+ // True when the words just before `index`, on the same line, warn against it.
630
+ function negated(text, index) {
631
+ return NEGATED.test(sameLineBefore(text, index, 60));
632
+ }
633
+
634
+ // Up to `max` characters before `index`, back to the start of its line. Only
635
+ // that much is looked at, so many matches on one long line stay fast.
636
+ function sameLineBefore(text, index, max) {
637
+ const before = text.slice(Math.max(0, index - max), index);
638
+ return before.slice(before.lastIndexOf("\n") + 1);
639
+ }
217
640
 
218
- function firstMatch(text, re, affirmative) {
641
+ function firstMatch(text, re, affirmative, reject) {
219
642
  const global = new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g");
220
643
  for (const m of text.matchAll(global)) {
221
- if (affirmative) {
222
- const lineStart = text.lastIndexOf("\n", m.index) + 1;
223
- if (NEGATED.test(text.slice(Math.max(lineStart, m.index - 60), m.index))) continue;
224
- }
644
+ if (affirmative && negated(text, m.index)) continue;
645
+ if (reject && reject(m)) continue;
225
646
  return m;
226
647
  }
227
648
  return null;
228
649
  }
229
650
 
651
+ // True when a match is quoted as an example rather than said: it follows
652
+ // "e.g." or "such as", or sits inside quotes.
653
+ function quotedExample(text, m, quotes) {
654
+ const before = text.slice(Math.max(0, m.index - 24), m.index);
655
+ if (/(?:e\.g\.|i\.e\.|for example|such as|like)[,:]?\s*["'“‘(`]?\s*$/i.test(before)) return true;
656
+ const open = before.match(/(\S)\s*$/)?.[1];
657
+ if (!open || !quotes.includes(open)) return false;
658
+ const close = { "“": "”", "‘": "’" }[open] ?? open;
659
+ const after = text.slice(m.index + m[0].length, m.index + m[0].length + 40);
660
+ const end = after.indexOf(close);
661
+ if (end < 0 || end > 30 || after.slice(0, end).includes("\n")) return false;
662
+ // Quotes alone don't make an example: the sentence has to say it's one.
663
+ return RX_EXAMPLE_CONTEXT.test(sameLineBefore(text, m.index, 120));
664
+ }
665
+ const RX_EXAMPLE_CONTEXT =
666
+ /\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;
667
+
668
+ // True when a match sits in a code block that the text just before it
669
+ // introduces as an example, as in "An injection looks like this:".
670
+ function fencedExample(text, index, fence) {
671
+ const block = fence(index);
672
+ return block !== null && RX_EXAMPLE_CONTEXT.test(text.slice(Math.max(0, block[0] - 160), block[0]));
673
+ }
674
+
675
+ // The first run of 300 or more base64 characters, skipping images embedded
676
+ // as data: URLs.
677
+ function longBase64(text) {
678
+ RX_BASE64_RUN.lastIndex = 0;
679
+ for (let m = RX_BASE64_RUN.exec(text); m; m = RX_BASE64_RUN.exec(text)) {
680
+ if (m[0].length < 300) continue;
681
+ if (/data:image\/[\w.+-]+;base64,$/i.test(text.slice(Math.max(0, m.index - 40), m.index))) continue;
682
+ return { index: m.index, length: m[0].length };
683
+ }
684
+ return null;
685
+ }
686
+
230
687
  function lineAt(text, index) {
231
688
  let n = 1;
232
689
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
@@ -237,16 +694,21 @@ function evidenceLine(file, line) {
237
694
  return line && file.lines ? clip(file.lines[line - 1] ?? "") : undefined;
238
695
  }
239
696
 
240
- function add(ctx, id, { file, line = 0, evidence, vars = {}, tool } = {}) {
697
+ function add(ctx, id, opts = {}) {
698
+ const { file, line = 0, vars = {} } = opts;
699
+ const key = [id, file?.path ?? null, line, ...["server", "key", "rule", "place", "ext", "pkg", "known", "name", "skill", "campaign", "path"].map((k) => vars[k] ?? "")].join("|");
700
+ if (ctx.seen.has(key)) return;
701
+ ctx.seen.add(key);
702
+ ctx.findings.push(makeFinding(id, opts));
703
+ }
704
+
705
+ function makeFinding(id, { file, line = 0, evidence, vars = {}, tool } = {}) {
241
706
  const rule = RULES[id];
242
707
  if (!rule) throw new Error(`Unknown rule ${id}`);
243
708
  const filePath = file?.path ?? null;
244
- const key = `${id}|${filePath}|${line}|${vars.server ?? ""}|${vars.key ?? ""}|${vars.rule ?? ""}|${vars.place ?? ""}`;
245
- if (ctx.seen.has(key)) return;
246
- ctx.seen.add(key);
247
709
  const values = Object.fromEntries(Object.entries({ file: filePath ?? "", ...vars }).map(([k, v]) => [k, String(v ?? "")]));
248
710
  const fill = (text) => fillTemplate(text, values);
249
- ctx.findings.push({
711
+ return {
250
712
  id,
251
713
  severity: rule.severity,
252
714
  category: rule.category,
@@ -258,67 +720,177 @@ function add(ctx, id, { file, line = 0, evidence, vars = {}, tool } = {}) {
258
720
  line: line || null,
259
721
  evidence: evidence ? describeMasks(clip(evidence, 220)) : null,
260
722
  vars: values,
261
- });
723
+ };
262
724
  }
263
725
 
264
726
  function fillTemplate(text, values) {
265
- return text.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? "");
727
+ return text.replace(/\{(\w+)\}/g, (_, k) => {
728
+ const v = values[k] ?? "";
729
+ if (FROM_FILES.has(k)) return fileValue(v, k);
730
+ // "where" is a fixed phrase that can quote a name, as in The “deploy” script.
731
+ if (k === "where") return v.replace(/“([^”]*)”/g, (_, name) => `“${fileValue(name, "server")}”`);
732
+ return v;
733
+ });
266
734
  }
267
735
 
268
- // Parts of a finding that come from the user's own files: quoted text, paths,
269
- // commands and the names people choose for servers, packages, variables and
270
- // files. They never leave the computer. Shared reports show "[hidden]".
271
- const PRIVATE_VARS = new Set(["cmd", "decoded", "phrase", "host", "ref", "path", "dir", "command", "rule", "files", "list", "key", "server", "pkg", "lookup", "root"]);
272
-
273
- // "where" is a fixed phrase that can quote a name, as in The “deploy” script.
274
- const hideNames = (text) => String(text).replace(/“[^”]*”/g, "“[hidden]”");
275
-
276
- export function publicFinding(f) {
277
- const rule = RULES[f.id];
278
- const values = { ...(f.vars ?? {}) };
279
- for (const k of PRIVATE_VARS) values[k] = "[hidden]";
280
- if (typeof values.where === "string") values.where = hideNames(values.where);
281
- const fill = (text, fallback) => (rule ? fillTemplate(text, values) : fallback);
282
- return {
283
- id: f.id,
284
- severity: f.severity,
285
- category: f.category,
286
- tool: f.tool,
287
- title: fill(rule?.title ?? "", f.title),
288
- why: fill(rule?.why ?? "", f.why),
289
- fix: fill(rule?.fix ?? "", f.fix),
290
- file: f.file,
291
- line: f.line,
292
- };
736
+ // Text from the user's files inside one of misconfig's own sentences: names,
737
+ // paths, commands and quoted phrases. It's kept to one line, without double
738
+ // quotes or direction marks, and cut to size, so a name in a hostile file
739
+ // can't close misconfig's quotes or carry a sentence of its own.
740
+ const FROM_FILES = new Set(["cmd", "decoded", "phrase", "host", "ref", "path", "dir", "command", "rule", "files", "list", "key", "server", "pkg", "skill"]);
741
+ const FILE_VALUE_MAX = { key: 80, server: 40, skill: 40, pkg: 80, host: 100, folder: 80 };
742
+ function fileValue(value, k) {
743
+ let text = String(value)
744
+ .replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, " ")
745
+ .replace(/["“”„‟]/g, "'")
746
+ .replace(/\s+/g, " ")
747
+ .trim();
748
+ // Variable and header names have no spaces, so a space ends the name.
749
+ if (k === "key") text = text.split(" ")[0];
750
+ const max = FILE_VALUE_MAX[k] ?? 120;
751
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
293
752
  }
294
753
 
295
- export function headlineFor(counts, top, hasControlFiles) {
296
- const lower = (t) => t.charAt(0).toLowerCase() + t.slice(1);
754
+ // The worst finding in its own words, then how many more like it. Titles
755
+ // start with names such as Codex or ~/.zshrc, so they're never lowercased.
756
+ function headlineFor(counts, top, hasControlFiles) {
297
757
  const minor = counts.medium + counts.low;
298
758
  if (!hasControlFiles && !top) return "No agent setup files found here.";
299
- if (counts.critical === 1) return top.title;
300
- if (counts.critical) return `${counts.critical} critical issues, starting with: ${lower(top.title)}`;
301
- if (counts.high) return `${counts.high} high-risk issue${counts.high === 1 ? "" : "s"}, starting with: ${lower(top.title)}`;
759
+ const lead = (n, level) => (n > 1 ? `${top.title}, and ${n - 1} more ${level} issue${n === 2 ? "" : "s"}.` : `${top.title}.`);
760
+ if (counts.critical) return lead(counts.critical, "critical");
761
+ if (counts.high) return lead(counts.high, "high-risk");
302
762
  if (minor) return `No critical issues. ${minor} thing${minor === 1 ? "" : "s"} worth tightening.`;
303
763
  return "No issues found in these agent files.";
304
764
  }
305
765
 
306
- // --- Claude Code ---------------------------------------------------------------
766
+ // --- Claude Code -------------------------------------------------------------
307
767
 
308
768
  function parsed(file) {
309
- if (file.parsed === undefined) file.parsed = /\.toml$/i.test(file.path) ? parseTOML(file.content) : parseJSONC(file.content) ?? null;
769
+ 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;
310
770
  return file.parsed;
311
771
  }
312
772
 
773
+ // Environment variables that make the programs an agent runs load other
774
+ // code as they start: a Node module, a shared library, a shell script, a
775
+ // Java agent, a .NET hook, or a command git runs. Values that only tune a
776
+ // program, such as NODE_OPTIONS=--max-old-space-size=4096, don't count.
777
+ const JAVA_AGENT = (v) => /-(?:javaagent|agentpath|agentlib)[:=]/i.test(v);
778
+ const CODE_LOADING_ENV = {
779
+ NODE_OPTIONS: (v) => /(?:^|\s)(?:-r|--require|--import|--loader|--experimental-loader)(?:[\s=]|$)/.test(v),
780
+ LD_PRELOAD: () => true,
781
+ LD_AUDIT: () => true,
782
+ DYLD_INSERT_LIBRARIES: () => true,
783
+ BASH_ENV: () => true,
784
+ ZDOTDIR: () => true,
785
+ PERL5OPT: (v) => /-[MmIdx]/.test(v),
786
+ RUBYOPT: (v) => /(?:^|\s)-(?:r|I)/.test(v),
787
+ JAVA_TOOL_OPTIONS: JAVA_AGENT,
788
+ _JAVA_OPTIONS: JAVA_AGENT,
789
+ JDK_JAVA_OPTIONS: JAVA_AGENT,
790
+ DOTNET_STARTUP_HOOKS: () => true,
791
+ // Plain ssh with options is how deploy keys are chosen; anything else runs a program.
792
+ GIT_SSH_COMMAND: (v) => !/^\s*ssh(?:\.exe)?(?:\s+-[A-Za-z](?:\s+[^\s;&|`$()<>]+)?)*\s*$/.test(v),
793
+ GIT_SSH: () => true,
794
+ GIT_EXTERNAL_DIFF: () => true,
795
+ GIT_CONFIG_PARAMETERS: (v) => /core\.(?:fsmonitor|hookspath|sshcommand|pager|editor|askpass)|alias\./i.test(v),
796
+ CLAUDE_CODE_SHELL_PREFIX: () => true,
797
+ // A folder named relative to wherever a command runs, or an empty entry,
798
+ // which means the current folder: a project's own programs then stand in
799
+ // for git, npm and the rest.
800
+ PATH: (v) => {
801
+ const windows = v.includes(";");
802
+ return v.length > 0 && v.split(windows ? ";" : ":").some((p) => (p.trim() ? !/^(?:\/|~|[A-Za-z]:[\\/]|\$|%)/.test(p.trim()) : !windows));
803
+ },
804
+ };
805
+ // The variable that loads code, or null.
806
+ function codeLoadingVariable(key, value) {
807
+ if (typeof key !== "string" || (typeof value !== "string" && typeof value !== "number")) return null;
808
+ const v = String(value);
809
+ if (Object.hasOwn(CODE_LOADING_ENV, key)) return CODE_LOADING_ENV[key](v) ? key : null;
810
+ // git reads GIT_CONFIG_KEY_0=core.fsmonitor with GIT_CONFIG_VALUE_0.
811
+ if (/^GIT_CONFIG_KEY_\d{1,3}$/.test(key) && /^(?:core\.(?:fsmonitor|hookspath|sshcommand|pager|editor|askpass)|alias\.)/i.test(v)) return key;
812
+ return null;
813
+ }
814
+
815
+ // Where an agent sends its requests. A base address, a proxy or a telemetry
816
+ // collector set by a project hands that host the prompts, the code and often
817
+ // the API key once the folder is trusted. In your own settings it's usually
818
+ // a company gateway, so there it's only noted.
819
+ const ENDPOINT_VARIABLES = new Set([
820
+ "ANTHROPIC_BASE_URL", "ANTHROPIC_BEDROCK_BASE_URL", "ANTHROPIC_VERTEX_BASE_URL", "ANTHROPIC_FOUNDRY_BASE_URL",
821
+ "OPENAI_BASE_URL", "OPENAI_API_BASE", "GOOGLE_GEMINI_BASE_URL", "GEMINI_BASE_URL",
822
+ "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
823
+ "HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY",
824
+ ]);
825
+ const CA_VARIABLES = new Set(["NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"]);
826
+ // The services' own addresses, and cloud providers that host them.
827
+ const OFFICIAL_ENDPOINT = /(?:^|\.)(?:anthropic\.com|claude\.ai|openai\.com|googleapis\.com|amazonaws\.com|azure\.com|azure\.net|windows\.net)$/i;
828
+ function endpointHost(value) {
829
+ if (typeof value !== "string" || !value.trim() || value.length > 2000) return null;
830
+ let url;
831
+ try {
832
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(value.trim()) ? value.trim() : `http://${value.trim()}`);
833
+ } catch {
834
+ return null;
835
+ }
836
+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
837
+ return !host || isLocalHost(host) || isLocalHost(`[${host}]`) || OFFICIAL_ENDPOINT.test(host) ? null : host;
838
+ }
839
+ // { variable, host } when an environment variable points the agent elsewhere.
840
+ function endpointVariable(key, value) {
841
+ const name = typeof key === "string" ? key.toUpperCase() : "";
842
+ if (!ENDPOINT_VARIABLES.has(name)) return null;
843
+ const host = endpointHost(typeof value === "number" ? String(value) : value);
844
+ return host ? { variable: name, host } : null;
845
+ }
846
+ const tlsOff = (key, value) => typeof key === "string" && key.toUpperCase() === "NODE_TLS_REJECT_UNAUTHORIZED" && String(value).trim() === "0";
847
+ // A file in the project folder, as opposed to the settings on the computer.
848
+ const inProject = (ctx, f) => !ctx.homeLike && !/^(~|\/|[A-Za-z]:)/.test(f.path);
849
+ // Environment variables that send requests elsewhere or weaken TLS, from any
850
+ // setting that sets them for the agent.
851
+ function checkEnvironment(ctx, f, where, key, value, line) {
852
+ const at = { file: f, line, evidence: evidenceLine(f, line) };
853
+ const endpoint = endpointVariable(key, value);
854
+ if (endpoint) add(ctx, inProject(ctx, f) ? "AGENT-ENDPOINT" : "AGENT-ENDPOINT-USER", { ...at, vars: { where, ...endpoint } });
855
+ if (tlsOff(key, value)) add(ctx, "ENV-TLS-OFF", { ...at, vars: { where, variable: "NODE_TLS_REJECT_UNAUTHORIZED" } });
856
+ const ca = typeof key === "string" ? key.toUpperCase() : "";
857
+ if (CA_VARIABLES.has(ca) && inProject(ctx, f) && String(value).trim()) add(ctx, "ENV-CA-PROJECT", { ...at, vars: { where, variable: ca } });
858
+ }
859
+ function checkEndpointSetting(ctx, f, where, setting, value, line) {
860
+ const host = endpointHost(value);
861
+ if (host) add(ctx, inProject(ctx, f) ? "AGENT-ENDPOINT" : "AGENT-ENDPOINT-USER", { file: f, line, evidence: evidenceLine(f, line), vars: { where, variable: setting, host } });
862
+ }
863
+
864
+ // Settings that make Claude Code run a command, and the ones it ignores in a
865
+ // project's own settings files.
866
+ const CLAUDE_COMMAND_KEYS = ["apiKeyHelper", "awsAuthRefresh", "awsCredentialExport", "gcpAuthRefresh", "otelHeadersHelper", "statusLine", "subagentStatusLine", "fileSuggestion", "processWrapper", "policyHelper", "sshHostCommands"];
867
+ const CLAUDE_USER_ONLY_KEYS = new Set(["processWrapper", "policyHelper", "sshHostCommands"]);
868
+
869
+ // A project's own .claude/settings.json or settings.local.json, as opposed to
870
+ // the user's ~/.claude/settings.json or an administrator's managed settings.
871
+ function isProjectSettings(ctx, f) {
872
+ return !ctx.homeLike && !/^(~|\/|[A-Za-z]:)/.test(f.path) && !/(^|\/)managed-settings/i.test(f.path);
873
+ }
874
+
875
+ // The commands in a setting's value: a string, { command } or { path }, or a list of those.
876
+ function commandsIn(value, depth = 0) {
877
+ if (typeof value === "string") return [value];
878
+ if (Array.isArray(value) && depth < 4) return value.flatMap((v) => commandsIn(v, depth + 1));
879
+ if (isObj(value)) return [value.command, value.path].filter((c) => typeof c === "string");
880
+ return [];
881
+ }
882
+
313
883
  function checkClaudeSettings(ctx, f) {
314
884
  const json = parsed(f);
315
885
  if (!isObj(json)) return;
316
886
  ctx.claudeSettingsFiles.push(f);
317
887
  const p = isObj(json.permissions) ? json.permissions : {};
888
+ const shared = isProjectSettings(ctx, f);
318
889
 
319
890
  if (p.defaultMode === "bypassPermissions") {
891
+ // Claude Code 2.1.257 and later ignore this in project settings.
320
892
  const line = lineOf(f, /bypassPermissions/);
321
- add(ctx, "CC-BYPASS", { file: f, line, evidence: evidenceLine(f, line) });
893
+ add(ctx, shared ? "CC-BYPASS-PROJECT" : "CC-BYPASS", { file: f, line, evidence: evidenceLine(f, line) });
322
894
  } else if (p.defaultMode === "acceptEdits") {
323
895
  const line = lineOf(f, /acceptEdits/);
324
896
  add(ctx, "CC-ACCEPT-EDITS", { file: f, line, evidence: evidenceLine(f, line) });
@@ -357,23 +929,62 @@ function checkClaudeSettings(ctx, f) {
357
929
  const line = lineOf(f, `"${key}"`);
358
930
  add(ctx, "CC-ENV-SECRET", { file: f, line, evidence: `${key} = ${redact(value)}`, vars: { key } });
359
931
  }
932
+ const variable = codeLoadingVariable(key, value);
933
+ if (variable) {
934
+ const line = lineOf(f, `"${key}"`);
935
+ add(ctx, "ENV-CODE-LOAD", { file: f, line, evidence: evidenceLine(f, line), vars: { where: "Claude Code's env setting", variable } });
936
+ }
937
+ checkEnvironment(ctx, f, "Claude Code's env setting", key, value, lineOf(f, `"${key}"`));
360
938
  }
361
939
  }
940
+ // Claude Code keeps each person's approvals in settings.local.json. In the
941
+ // shared settings, a project approves its own servers for everyone.
942
+ if (shared && !/settings\.local\.json$/i.test(f.path) && arr(json.enabledMcpjsonServers).length) {
943
+ const line = lineOf(f, /enabledMcpjsonServers/);
944
+ add(ctx, "CC-MCP-PROJECT-APPROVED", { file: f, line, evidence: evidenceLine(f, line) });
945
+ }
362
946
 
363
- if (isObj(json.hooks)) {
364
- for (const [event, entries] of Object.entries(json.hooks)) {
365
- for (const entry of Array.isArray(entries) ? entries : []) {
366
- const hooks = Array.isArray(entry?.hooks) ? entry.hooks : [entry];
367
- for (const h of hooks) {
368
- if (typeof h?.command === "string") checkCommand(ctx, h.command, f, `A Claude Code ${event} hook`);
369
- }
947
+ for (const key of CLAUDE_COMMAND_KEYS) {
948
+ if (shared && CLAUDE_USER_ONLY_KEYS.has(key)) continue;
949
+ for (const command of commandsIn(json[key])) checkCommand(ctx, command, f, `Claude Code's ${key} setting`);
950
+ }
951
+ checkClaudeHooks(ctx, f, json.hooks);
952
+ }
953
+
954
+ // Hooks in Claude Code settings and in plugins' hooks/hooks.json. Command
955
+ // hooks run on this computer; http hooks post what Claude is doing to a URL.
956
+ function checkClaudeHooks(ctx, f, hooks) {
957
+ if (!isObj(hooks)) return;
958
+ for (const [event, entries] of Object.entries(hooks)) {
959
+ const where = Object.hasOwn(HOOK_EVENTS, event) ? `A Claude Code ${event} hook` : "A Claude Code hook";
960
+ for (const entry of Array.isArray(entries) ? entries : []) {
961
+ for (const h of Array.isArray(entry?.hooks) ? entry.hooks : [entry]) {
962
+ if (typeof h?.command === "string") checkCommand(ctx, h.command, f, where);
963
+ if (h?.type === "http" && typeof h.url === "string") checkHookUrl(ctx, h.url, f, where);
370
964
  }
371
965
  }
372
966
  }
373
967
  }
374
968
 
969
+ function checkHookUrl(ctx, url, f, where) {
970
+ let host;
971
+ try {
972
+ host = new URL(url).hostname;
973
+ } catch {
974
+ return;
975
+ }
976
+ if (isLocalHost(host)) return;
977
+ const line = lineOf(f, url.slice(0, 60)) || lineOf(f, /"url"/);
978
+ add(ctx, "HOOK-HTTP", { file: f, line, evidence: evidenceLine(f, line), vars: { where, host } });
979
+ }
980
+
981
+ const isLocalHost = (host) => /^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?|0\.0\.0\.0|host\.docker\.internal)$/i.test(host);
982
+
375
983
  function checkClaudeUserConfig(ctx, f) {
376
- if (isMasked(f.content)) add(ctx, "CC-USER-SECRET", { file: f, line: lineOf(f, /«masked:/) });
984
+ // ~/.claude.json is where Claude Code keeps its account data. A copy in a
985
+ // project folder is the problem.
986
+ const inProject = !/^(~|\/|[A-Za-z]:)/.test(f.path) && !ctx.homeLike;
987
+ if (inProject && isMasked(f.content)) add(ctx, "CC-USER-SECRET", { file: f, line: lineOf(f, /«masked:/) });
377
988
  const json = parsed(f);
378
989
  if (!isObj(json)) return;
379
990
  if (isObj(json.projects)) {
@@ -392,7 +1003,7 @@ function checkClaudeUserConfig(ctx, f) {
392
1003
  }
393
1004
  }
394
1005
 
395
- // --- Codex ---------------------------------------------------------------------
1006
+ // --- Codex -------------------------------------------------------------------
396
1007
 
397
1008
  function checkCodex(ctx, f) {
398
1009
  const toml = parsed(f);
@@ -417,6 +1028,36 @@ function checkCodex(ctx, f) {
417
1028
  }
418
1029
  const notify = arr(toml.notify).join(" ");
419
1030
  if (notify) checkCommand(ctx, notify, f, "Codex's notify command");
1031
+ if (isObj(toml.hooks)) checkJsonHooks(ctx, f, "A Codex hook", toml.hooks);
1032
+ for (const provider of isObj(toml.model_providers) ? Object.values(toml.model_providers) : []) {
1033
+ const auth = provider?.auth;
1034
+ const command = isObj(auth) && typeof auth.command === "string" ? [auth.command, ...arr(auth.args)].join(" ") : "";
1035
+ if (command) checkCommand(ctx, command, f, "Codex's model provider login command");
1036
+ }
1037
+ for (const server of isObj(toml.mcp_servers) ? Object.values(toml.mcp_servers) : []) {
1038
+ for (const command of commandsIn(server?.http_headers_helper)) checkCommand(ctx, command, f, "Codex's MCP header command");
1039
+ }
1040
+ const set = toml.shell_environment_policy?.set;
1041
+ if (isObj(set)) {
1042
+ for (const [key, value] of Object.entries(set)) {
1043
+ const variable = codeLoadingVariable(key, value);
1044
+ if (variable) {
1045
+ const line = lineOf(f, key);
1046
+ add(ctx, "ENV-CODE-LOAD", { file: f, line, evidence: evidenceLine(f, line), vars: { where: "Codex's shell_environment_policy", variable } });
1047
+ }
1048
+ // It sets the commands Codex runs, not Codex itself, so only TLS counts here.
1049
+ if (tlsOff(key, value)) {
1050
+ const line = lineOf(f, key);
1051
+ add(ctx, "ENV-TLS-OFF", { file: f, line, evidence: evidenceLine(f, line), vars: { where: "Codex's shell_environment_policy", variable: "NODE_TLS_REJECT_UNAUTHORIZED" } });
1052
+ }
1053
+ }
1054
+ }
1055
+ for (const provider of isObj(toml.model_providers) ? Object.values(toml.model_providers).slice(0, 20) : []) {
1056
+ 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/));
1057
+ }
1058
+ for (const key of ["openai_base_url", "chatgpt_base_url"]) {
1059
+ if (typeof toml[key] === "string") checkEndpointSetting(ctx, f, "Codex's model_providers setting", "base_url", toml[key], lineOf(f, key));
1060
+ }
420
1061
  if (isObj(toml.projects)) {
421
1062
  for (const [dir, settings] of Object.entries(toml.projects)) {
422
1063
  const place = riskyPlace(dir);
@@ -426,65 +1067,96 @@ function checkCodex(ctx, f) {
426
1067
  }
427
1068
 
428
1069
  // Folders an agent should never be started in. Accepts absolute and ~ paths.
1070
+ const RISK_HOME = "It can read everything there, including SSH keys, cloud credentials and your other projects.";
1071
+ const RISK_DOWNLOADS = "Files saved there from websites, chats and email become context the agent reads and may act on.";
1072
+ const RISK_DRIVE = "It can read and change anything on that drive.";
1073
+
429
1074
  export function riskyPlace(dir) {
430
- const d = String(dir).replace(/\\/g, "/").replace(/\/+$/, "");
1075
+ const d = trimWord(String(dir).replace(/\\/g, "/").replace(/\/{2,}/g, "/"), "", "/");
431
1076
  const last = d.split("/").pop();
432
- if (/^(~|\/Users\/[^/]+|\/home\/[^/]+|\/root|[A-Za-z]:\/Users\/[^/]+)$/i.test(d)) {
433
- return { name: "your home folder", risk: "It can read everything there, including SSH keys, cloud credentials and your other projects." };
434
- }
435
- if (/^(Downloads|Desktop)$/i.test(last)) {
436
- return { name: `your ${last} folder`, risk: "Files saved there from websites, chats and email become context the agent reads and may act on." };
437
- }
438
- if (d === "" || /^[A-Za-z]:$/.test(d)) return { name: "the root of a drive", risk: "It can read and change anything on that drive." };
1077
+ if (/^(~|\/Users\/[^/]+|\/home\/[^/]+|\/root|[A-Za-z]:\/Users\/[^/]+)$/i.test(d)) return { name: "your home folder", risk: RISK_HOME };
1078
+ if (/^(Downloads|Desktop)$/i.test(last)) return { name: `your ${folderName(last)} folder`, risk: RISK_DOWNLOADS };
1079
+ if (d === "" || /^[A-Za-z]:$/.test(d)) return { name: "the root of a drive", risk: RISK_DRIVE };
439
1080
  return null;
440
1081
  }
441
1082
 
442
1083
  function checkShellProfile(ctx, f) {
443
1084
  for (const [i, line] of f.lines.entries()) {
444
1085
  if (/^\s*#/.test(line)) continue;
445
- const flag = line.match(RX_DANGER_FLAGS);
446
- if (!flag) continue;
447
- const agent = line.match(/\b(claude|codex|gemini|qwen|opencode|cursor-agent|amp)\b/i)?.[1]?.toLowerCase();
448
- const names = { claude: "Claude Code", codex: "Codex", gemini: "Gemini CLI", qwen: "Qwen Code", opencode: "OpenCode", "cursor-agent": "Cursor", amp: "Amp" };
449
- 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) } });
1086
+ const trace = SHELL_TRACES.find((t) => t.line.test(line));
1087
+ if (trace) add(ctx, "ATTACK-SHELL-LINE", { file: f, line: i + 1, evidence: line, vars: { campaign: trace.campaign, what: trace.what, advice: trace.fix } });
1088
+ const hit = findDangerFlag(line);
1089
+ 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) } });
450
1090
  }
451
1091
  }
452
1092
 
453
- // --- Gemini, VS Code, OpenCode, Zed, Aider -------------------------------------
1093
+ // --- Gemini, VS Code, OpenCode, Zed, Aider -----------------------------------
454
1094
 
455
1095
  function checkGemini(ctx, f) {
456
1096
  const json = parsed(f);
457
1097
  if (!isObj(json)) return;
458
1098
  let yolo = false;
459
1099
  let autoAccept = false;
1100
+ let autoEdit = false;
460
1101
  walk(json, (key, value) => {
461
1102
  if (/^yolo$/i.test(key) && value === true) yolo = true;
462
- if (/approvalMode$/i.test(key) && /^yolo$/i.test(String(value))) yolo = true;
1103
+ if (/approvalMode$/i.test(key) && /^yolo$/i.test(asText(value))) yolo = true;
1104
+ if (/approvalMode$/i.test(key) && /^auto_edit$/i.test(asText(value))) autoEdit = true;
463
1105
  if (key === "autoAccept" && value === true) autoAccept = true;
464
1106
  });
1107
+ // Commands Gemini CLI runs itself: to find and call project tools, and hooks.
1108
+ const at = (...keys) => keys.reduce((o, k) => (isObj(o) ? o[k] : undefined), json);
1109
+ for (const [value, where] of [
1110
+ [at("tools", "discoveryCommand"), "Gemini CLI's tool discovery command"],
1111
+ [at("toolDiscoveryCommand"), "Gemini CLI's tool discovery command"],
1112
+ [at("tools", "callCommand"), "Gemini CLI's tool call command"],
1113
+ [at("toolCallCommand"), "Gemini CLI's tool call command"],
1114
+ ]) {
1115
+ for (const command of commandsIn(value)) checkCommand(ctx, command, f, where);
1116
+ }
1117
+ if (isObj(json.hooks)) checkJsonHooks(ctx, f, "A Gemini CLI hook", json.hooks);
1118
+ // Gemini CLI ignores YOLO mode in settings, so asking for it there doesn't
1119
+ // hide the settings it does apply.
465
1120
  if (yolo) {
466
1121
  const line = lineOf(f, /yolo/i);
467
1122
  add(ctx, "GM-YOLO", { file: f, line, evidence: evidenceLine(f, line) });
468
- } else if (autoAccept) {
1123
+ }
1124
+ if (autoAccept) {
469
1125
  const line = lineOf(f, /autoAccept/);
470
1126
  add(ctx, "GM-AUTO-ACCEPT", { file: f, line, evidence: evidenceLine(f, line) });
471
1127
  }
1128
+ if (autoEdit) {
1129
+ const line = lineOf(f, /auto_edit/);
1130
+ add(ctx, "GM-AUTO-EDIT", { file: f, line, evidence: evidenceLine(f, line) });
1131
+ }
472
1132
  }
473
1133
 
1134
+ const VS_CODE_AUTO_APPROVE = ["chat.tools.autoApprove", "chat.tools.global.autoApprove", "chat.permissions.default"];
1135
+ const ALWAYS_ALLOW_KEYS = ["alwaysAllow", "autoApprove", "auto_approve", "trust"];
1136
+
474
1137
  function checkVSCode(ctx, f) {
475
1138
  const json = parsed(f);
476
1139
  if (!isObj(json)) return;
477
- for (const key of ["chat.tools.autoApprove", "chat.tools.global.autoApprove"]) {
478
- if (json[key] === true) {
479
- const line = lineOf(f, key);
480
- add(ctx, "VS-AUTO-APPROVE", { file: f, line, evidence: evidenceLine(f, line), vars: { key } });
481
- }
1140
+ const at = (key) => {
1141
+ const line = lineOf(f, key);
1142
+ return { file: f, line, evidence: evidenceLine(f, line) };
1143
+ };
1144
+ for (const key of VS_CODE_AUTO_APPROVE) {
1145
+ if (json[key] === true || json[key] === "autoApprove") add(ctx, "VS-AUTO-APPROVE", { ...at(key), vars: { setting: key } });
482
1146
  }
1147
+ if (json["github.copilot.chat.claudeAgent.allowDangerouslySkipPermissions"] === true) add(ctx, "VS-CLAUDE-SKIP", at("allowDangerouslySkipPermissions"));
1148
+ if (json["chat.tools.terminal.ignoreDefaultAutoApproveRules"] === true) add(ctx, "VS-NO-DEFAULT-RULES", at("ignoreDefaultAutoApproveRules"));
1149
+ // VS Code asks before an agent edits its own settings. Approving those
1150
+ // edits lets an agent turn on its own auto-approval.
1151
+ // The last pattern that matches a file decides, as in VS Code.
1152
+ const edits = json["chat.tools.edits.autoApprove"];
1153
+ const approves = (p) => Object.entries(edits).filter(([glob]) => globMatch(glob.replace(/^\.\//, ""), p)).pop()?.[1] === true;
1154
+ if (isObj(edits) && [".vscode/settings.json", ".vscode/mcp.json"].some(approves)) add(ctx, "VS-EDITS-AUTO", at("chat.tools.edits.autoApprove"));
483
1155
  const terminal = json["chat.tools.terminal.autoApprove"] ?? json["github.copilot.chat.agent.terminal.allowList"];
484
1156
  if (isObj(terminal)) {
485
1157
  for (const [pattern, allowed] of Object.entries(terminal)) {
486
1158
  const on = allowed === true || (isObj(allowed) && allowed.approve === true);
487
- 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))) {
1159
+ 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))) {
488
1160
  const line = lineOf(f, JSON.stringify(pattern)) || lineOf(f, pattern);
489
1161
  add(ctx, "VS-TERMINAL-AUTO", { file: f, line, evidence: evidenceLine(f, line), vars: { rule: pattern } });
490
1162
  }
@@ -492,9 +1164,19 @@ function checkVSCode(ctx, f) {
492
1164
  }
493
1165
  }
494
1166
 
1167
+ // A terminal rule written to match every command: *, .*, /.*/, /^.*$/ or /.+/.
1168
+ function matchesEverything(pattern) {
1169
+ const body = pattern.startsWith("/") && pattern.lastIndexOf("/") > 0 ? pattern.slice(1, pattern.lastIndexOf("/")) : pattern;
1170
+ return ["", "*", ".*", ".+", "[\\s\\S]*", "[\\s\\S]+"].includes(trimWord(body, "^", "$"));
1171
+ }
1172
+
495
1173
  function checkOpenCode(ctx, f) {
496
1174
  const json = parsed(f);
497
1175
  if (!isObj(json)) return;
1176
+ for (const provider of isObj(json.provider) ? Object.values(json.provider).slice(0, 20) : []) {
1177
+ const url = provider?.options?.baseURL;
1178
+ if (typeof url === "string") checkEndpointSetting(ctx, f, "OpenCode's provider setting", "baseURL", url, lineOf(f, url.slice(0, 60)) || lineOf(f, /baseURL/));
1179
+ }
498
1180
  if (json.share === "auto") {
499
1181
  const line = lineOf(f, /"share"/);
500
1182
  add(ctx, "OC-AUTO-SHARE", { file: f, line, evidence: evidenceLine(f, line) });
@@ -516,58 +1198,423 @@ function checkOpenCode(ctx, f) {
516
1198
  function checkZed(ctx, f) {
517
1199
  const json = parsed(f);
518
1200
  if (!isObj(json)) return;
519
- if (json.agent?.always_allow_tool_actions === true || json.assistant?.always_allow_tool_actions === true) {
520
- const line = lineOf(f, /always_allow_tool_actions/);
1201
+ if (json.agent?.always_allow_tool_actions === true || json.assistant?.always_allow_tool_actions === true || json.agent?.tool_permissions?.default === "allow") {
1202
+ const line = lineOf(f, /always_allow_tool_actions|"default"\s*:\s*"allow"/);
521
1203
  add(ctx, "ZED-ALWAYS-ALLOW", { file: f, line, evidence: evidenceLine(f, line) });
522
1204
  }
1205
+ if (json.session?.trust_all_worktrees === true) {
1206
+ const line = lineOf(f, /trust_all_worktrees/);
1207
+ add(ctx, "ZED-TRUST-ALL", { file: f, line, evidence: evidenceLine(f, line) });
1208
+ }
1209
+ }
1210
+
1211
+ // --- Trusted folders, hooks and settings of other agents ---------------------
1212
+
1213
+ // Gemini CLI: { "/path": "TRUST_FOLDER" | "TRUST_PARENT" | "DO_NOT_TRUST" }.
1214
+ function geminiTrusted(json) {
1215
+ if (!isObj(json)) return [];
1216
+ const parent = (d) => trimWord(d, "", "/\\").replace(/[\\/][^\\/]*$/, "") || "/";
1217
+ return Object.entries(json).flatMap(([dir, level]) => (level === "TRUST_FOLDER" ? [[dir, dir]] : level === "TRUST_PARENT" ? [[parent(dir), dir]] : []));
1218
+ }
1219
+
1220
+ // GitHub Copilot CLI: a list of trusted folders in ~/.copilot/config.json.
1221
+ function copilotTrusted(json) {
1222
+ return arr(json?.trusted_folders ?? json?.trustedFolders).map((dir) => [dir, dir]);
1223
+ }
1224
+
1225
+ // Folders the settings on this computer say agents have been started in or
1226
+ // trust. The command also checks the loose files in the risky ones.
1227
+ export function agentFolders(path, content) {
1228
+ const json = /\.toml$/i.test(path) ? parseTOML(content) : parseJSONC(content);
1229
+ if (!isObj(json)) return [];
1230
+ if (/(^|\/)\.claude\.json$/i.test(path)) return isObj(json.projects) ? Object.keys(json.projects) : [];
1231
+ if (/(^|\/)\.codex\/config\.toml$/i.test(path)) return isObj(json.projects) ? Object.entries(json.projects).filter(([, s]) => s?.trust_level === "trusted").map(([d]) => d) : [];
1232
+ if (/(^|\/)\.gemini\/trustedFolders\.json$/i.test(path)) return geminiTrusted(json).map(([d]) => d);
1233
+ if (/(^|\/)\.copilot\/config\.json$/i.test(path)) return copilotTrusted(json).map(([d]) => d);
1234
+ return [];
1235
+ }
1236
+
1237
+ // [folder trusted, folder as written in the file] pairs.
1238
+ function checkTrustedFolders(ctx, f, tool, trusted) {
1239
+ for (const [dir, written] of trusted) {
1240
+ const place = riskyPlace(dir);
1241
+ if (place) add(ctx, "WS-TRUSTED-DIR", { file: f, line: keyLine(f, written), tool, vars: { tool, place: place.name, risk: place.risk, dir } });
1242
+ }
1243
+ }
1244
+
1245
+ // Every command in a hooks file, such as .github/hooks/*.json or Cursor's
1246
+ // hooks.json, or in `value` when hooks sit inside other settings. Hooks name
1247
+ // their command "command", "bash" or "powershell".
1248
+ function checkJsonHooks(ctx, f, where, value = parsed(f)) {
1249
+ const visit = (v, key, depth) => {
1250
+ if (depth > 8) return;
1251
+ if (typeof v === "string" && ["command", "bash", "powershell"].includes(key)) checkCommand(ctx, v, f, where);
1252
+ else if (Array.isArray(v)) {
1253
+ // A command written as a list of arguments.
1254
+ if (key === "command" && v.length && v.every((x) => typeof x === "string")) checkCommand(ctx, v.join(" "), f, where);
1255
+ else for (const x of v) visit(x, key, depth + 1);
1256
+ } else if (isObj(v)) for (const [k, x] of Object.entries(v)) visit(x, k, depth + 1);
1257
+ };
1258
+ visit(value, "", 0);
1259
+ }
1260
+
1261
+ // Cursor's cloud agents run install on every build, start on every boot and
1262
+ // each terminal's command, in a virtual machine with the repo's secrets.
1263
+ function checkCursorEnvironment(ctx, f) {
1264
+ const json = parsed(f);
1265
+ if (!isObj(json)) return;
1266
+ const where = "Cursor's cloud agent setup";
1267
+ for (const key of ["install", "start"]) for (const command of commandsIn(json[key])) checkCommand(ctx, command, f, where);
1268
+ 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);
1269
+ }
1270
+
1271
+ // Codex rules that let a command run outside the sandbox without asking:
1272
+ // prefix_rule(pattern = ["git", "push"], decision = "allow"). Only programs
1273
+ // that run other code, change or delete files broadly, or reach the network
1274
+ // are reported.
1275
+ 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;
1276
+ // The words a rule's pattern matches at one place: a word, or a list of
1277
+ // alternatives. A program is matched by its name, so /bin/bash and bash.exe
1278
+ // count as bash.
1279
+ const ruleWords = (pattern, i) => (Array.isArray(pattern[i]) ? pattern[i] : [pattern[i]]).filter((w) => typeof w === "string").map((w) => w.trim());
1280
+ // True when rule a matches every command rule b matches: a is no longer than
1281
+ // b, and at each place a allows every word b does.
1282
+ const ruleCovers = (a, b) => a.length <= b.length && a.every((_, i) => ruleWords(b, i).every((w) => ruleWords(a, i).includes(w)));
1283
+ // git is only risky when every git command is allowed, or one that pushes,
1284
+ // changes settings or brings in code from elsewhere.
1285
+ const RISKY_GIT = /^(?:push|config|submodule|clone|fetch|pull|remote|-c|filter-branch|filter-repo)$/i;
1286
+
1287
+ function checkCodexRules(ctx, f) {
1288
+ const all = parseCodexRules(f.content);
1289
+ // A rule that may allow something, built in a way this check can't follow.
1290
+ const hidden = all.find((r) => r.unread && r.decision !== "prompt" && r.decision !== "forbidden");
1291
+ if (hidden) {
1292
+ const line = lineAt(f.content, hidden.index);
1293
+ add(ctx, "CX-RULES-UNREAD", { file: f, line, evidence: evidenceLine(f, line) });
1294
+ }
1295
+ const rules = all.filter((r) => !r.unread && r.pattern?.length && r.pattern.every((w) => w !== null && (!Array.isArray(w) || w.length)));
1296
+ const allowing = [];
1297
+ for (const rule of rules) {
1298
+ if (rule.decision !== "allow") continue;
1299
+ // When rules overlap, Codex applies the strictest one.
1300
+ if (rules.some((r) => (r.decision === "prompt" || r.decision === "forbidden") && ruleCovers(r.pattern, rule.pattern))) continue;
1301
+ 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))));
1302
+ if (!program) continue;
1303
+ // The command as the rule allows it, naming the risky choice where it
1304
+ // gives several, as in git push.
1305
+ 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] ?? "";
1306
+ allowing.push({ line: lineAt(f.content, rule.index), start: [program, pick(1)].filter(Boolean).join(" ") });
1307
+ }
1308
+ // One finding for the file: a Codex user can have dozens of these rules,
1309
+ // one for each command they approved. The patterns are named by program
1310
+ // and first word, such as powershell -Command; --explain lists each rule.
1311
+ if (allowing.length) {
1312
+ const starts = [...new Set(allowing.map((a) => clip(a.start, 40)))];
1313
+ const { line } = allowing[0];
1314
+ add(ctx, "CX-RULE-ALLOW", {
1315
+ file: f,
1316
+ line,
1317
+ evidence: evidenceLine(f, line),
1318
+ vars: { commands: allowing.length === 1 ? "a command" : `${allowing.length} commands`, list: listNames(starts, 4) },
1319
+ });
1320
+ }
1321
+ }
1322
+
1323
+ // Kiro and Amazon Q agent files: hooks, and tools the agent uses without
1324
+ // asking. Kiro's shell tool is "shell", also known by its Amazon Q names.
1325
+ // allowedTools entries can use * and ? as wildcards. Commands allowed in
1326
+ // toolsSettings are regular expressions that must match the whole command,
1327
+ // and the newer permissions rules match commands by prefix.
1328
+ const SHELL_TOOLS = ["shell", "execute_bash", "execute_cmd"];
1329
+ function wildcardMatch(glob, text) {
1330
+ let g = 0;
1331
+ let t = 0;
1332
+ let star = -1;
1333
+ let mark = 0;
1334
+ while (t < text.length) {
1335
+ if (g < glob.length && (glob[g] === "?" || glob[g] === text[t])) {
1336
+ g++;
1337
+ t++;
1338
+ } else if (g < glob.length && glob[g] === "*") {
1339
+ star = g++;
1340
+ mark = t;
1341
+ } else if (star >= 0) {
1342
+ g = star + 1;
1343
+ t = ++mark;
1344
+ } else return false;
1345
+ }
1346
+ while (glob[g] === "*") g++;
1347
+ return g === glob.length;
1348
+ }
1349
+ // A command pattern that lets through any command, or any use of a program
1350
+ // that can run anything: ".*", "curl .*", "bash*".
1351
+ const MATCH_ALL = /^\^?(?:\.\*|\.\+|\(\.\*\)|\[\\s\\S\]\*)\??\$?$/;
1352
+ function openCommand(pattern, regex) {
1353
+ const text = pattern.trim();
1354
+ if (!text || text === "*" || text === "**" || (regex && MATCH_ALL.test(text))) return true;
1355
+ const word = programName(/^\^?([^\s*.\\(]+)/.exec(text)?.[1] ?? "");
1356
+ const rest = text.slice(text.indexOf(word) + word.length);
1357
+ const open = regex ? /^(?:\s|\\s|\[ \])*(?:\.\*|\.\+|\(\.\*\))/.test(rest) || rest === "" : /^\s*\*/.test(rest) || rest.trim() === "";
1358
+ return RISKY_PROGRAM.test(word) && open;
1359
+ }
1360
+ function checkAgentFile(ctx, f, where) {
1361
+ checkJsonHooks(ctx, f, where);
1362
+ const json = parsed(f);
1363
+ if (!isObj(json)) return;
1364
+ const found = [];
1365
+ for (const tool of arr(json.allowedTools).slice(0, 200)) {
1366
+ const t = tool.trim();
1367
+ if (t === "*" || t === "@builtin" || SHELL_TOOLS.some((name) => wildcardMatch(t, name) || wildcardMatch(t, `@builtin/${name}`))) found.push({ rule: t, setting: "allowedTools" });
1368
+ }
1369
+ for (const name of SHELL_TOOLS) {
1370
+ const pattern = arr(json.toolsSettings?.[name]?.allowedCommands).slice(0, 200).find((c) => openCommand(c, true));
1371
+ if (pattern !== undefined) found.push({ rule: pattern.trim(), setting: "toolsSettings" });
1372
+ }
1373
+ for (const rule of Array.isArray(json.permissions?.rules) ? json.permissions.rules.slice(0, 200) : []) {
1374
+ if (!isObj(rule) || rule.capability !== "shell" || rule.effect !== "allow") continue;
1375
+ // A rule with no commands to match matches every one.
1376
+ const match = arr(rule.match);
1377
+ const open = match.length === 0 ? "*" : match.find((m) => openCommand(m, false));
1378
+ if (open !== undefined) found.push({ rule: open.trim(), setting: "permissions" });
1379
+ }
1380
+ if (!found.length) return;
1381
+ const line = lineOf(f, new RegExp(`"${found[0].setting}"`));
1382
+ add(ctx, "AGENT-ALLOW-SHELL", { file: f, line, evidence: evidenceLine(f, line), vars: found[0] });
1383
+ }
1384
+
1385
+ function checkCursorCli(ctx, f) {
1386
+ const json = parsed(f);
1387
+ for (const rule of arr(json?.permissions?.allow)) {
1388
+ if (/^Shell(\((\*|\*\*|\*:\*)?\))?$/i.test(rule.trim())) {
1389
+ const line = lineOf(f, rule);
1390
+ add(ctx, "CU-ALLOW-ALL-SHELL", { file: f, line, evidence: evidenceLine(f, line), vars: { rule } });
1391
+ }
1392
+ }
1393
+ }
1394
+
1395
+ function checkCursorSandbox(ctx, f) {
1396
+ if (parsed(f)?.type === "insecure_none") {
1397
+ const line = lineOf(f, /insecure_none/);
1398
+ add(ctx, "CU-NO-SANDBOX", { file: f, line, evidence: evidenceLine(f, line) });
1399
+ }
1400
+ }
1401
+
1402
+ // Cline keeps its approval settings in ~/.cline/data/globalState.json.
1403
+ function checkCline(ctx, f) {
1404
+ const json = parsed(f);
1405
+ if (!isObj(json)) return;
1406
+ if (json.yoloModeToggled === true) {
1407
+ const line = lineOf(f, /yoloModeToggled/);
1408
+ add(ctx, "CL-YOLO", { file: f, line, evidence: evidenceLine(f, line) });
1409
+ } else if (json.autoApprovalSettings?.enabled !== false && json.autoApprovalSettings?.actions?.executeAllCommands === true) {
1410
+ const line = lineOf(f, /executeAllCommands/);
1411
+ add(ctx, "CL-AUTO-COMMANDS", { file: f, line, evidence: evidenceLine(f, line) });
1412
+ }
1413
+ }
1414
+
1415
+ function checkGrok(ctx, f) {
1416
+ const toml = parsed(f);
1417
+ for (const command of commandsIn(toml?.ui?.status_line?.command)) checkCommand(ctx, command, f, "Grok's status line command");
1418
+ const mode = toml?.ui?.permission_mode ?? toml?.permission_mode;
1419
+ if (mode === "always-approve" || mode === "yolo") {
1420
+ const line = lineOf(f, /permission_mode/);
1421
+ add(ctx, "GROK-ALWAYS-APPROVE", { file: f, line, evidence: evidenceLine(f, line), vars: { mode } });
1422
+ }
1423
+ }
1424
+
1425
+ function checkAmp(ctx, f) {
1426
+ if (parsed(f)?.["amp.dangerouslyAllowAll"] === true) {
1427
+ const line = lineOf(f, /dangerouslyAllowAll/);
1428
+ add(ctx, "AMP-ALLOW-ALL", { file: f, line, evidence: evidenceLine(f, line) });
1429
+ }
1430
+ }
1431
+
1432
+ // YAML, read line by line: GOOSE_MODE sits at the top level.
1433
+ function checkGoose(ctx, f) {
1434
+ const line = lineOf(f, /^GOOSE_MODE\s*:\s*["']?auto["']?\s*(#.*)?$/);
1435
+ if (line) add(ctx, "GOOSE-AUTO", { file: f, line, evidence: evidenceLine(f, line) });
523
1436
  }
524
1437
 
1438
+ // Continue's data destinations send session events to a URL.
1439
+ function checkContinue(ctx, f) {
1440
+ for (const [i, text] of f.lines.entries()) {
1441
+ const api = text.match(/^\s*(?:-\s*)?["']?apiBase["']?\s*:\s*["']?([^\s"',#]+)/);
1442
+ if (api) checkEndpointSetting(ctx, f, "Continue's model settings", "apiBase", api[1], i + 1);
1443
+ const m = text.match(/^\s*(?:-\s*)?destination\s*:\s*["']?(https?:\/\/[^\s"'#]+)/i);
1444
+ if (!m) continue;
1445
+ let host;
1446
+ try {
1447
+ host = new URL(m[1]).hostname;
1448
+ } catch {
1449
+ continue;
1450
+ }
1451
+ if (!isLocalHost(host)) add(ctx, "CONT-DATA", { file: f, line: i + 1, evidence: text, vars: { host } });
1452
+ }
1453
+ }
1454
+
1455
+ // YAML, read line by line. lint-cmd runs after every change Aider makes
1456
+ // (auto-lint is on by default), test-cmd after changes when auto-test is on,
1457
+ // and the notification command when Aider is waiting.
1458
+ const AIDER_COMMANDS = { "lint-cmd": "Aider's lint command", "test-cmd": "Aider's test command", "notifications-command": "Aider's notification command" };
1459
+ const unquote = (v) => v.trim().replace(/^(["'])(.*)\1$/, "$2");
525
1460
  function checkAider(ctx, f) {
1461
+ const yaml = parsed(f);
1462
+ if (!isObj(yaml)) return checkAiderLines(ctx, f);
1463
+ // The line a key is on, for keys written plain or quoted.
1464
+ const keyAt = (key) => lineOf(f, new RegExp(`^[ \\t]*(?:-[ \\t]+)?["']?${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["']?[ \\t]*:`, "m")) || lineOf(f, key);
1465
+ const valueAt = (key, value) => (typeof value === "string" && value.trim() && lineOf(f, value.trim().split("\n")[0].slice(0, 60))) || keyAt(key);
1466
+ if (yaml["yes-always"] === true) {
1467
+ const line = keyAt("yes-always");
1468
+ add(ctx, "AIDER-YES", { file: f, line, evidence: evidenceLine(f, line) });
1469
+ }
1470
+ for (const key of [...Object.keys(AIDER_COMMANDS), "set-env", "openai-api-base"]) {
1471
+ const raw = yaml[key];
1472
+ // One value, a list of them, or "- python: flake8" items read as mappings.
1473
+ 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);
1474
+ for (const value of values) aiderValue(ctx, f, key, value, valueAt(key, value));
1475
+ }
1476
+ }
1477
+ // Aider's settings read line by line, for a file the YAML reader can't read.
1478
+ function checkAiderLines(ctx, f) {
526
1479
  const line = lineOf(f, /^\s*yes-always\s*:\s*true\b/i);
527
1480
  if (line) add(ctx, "AIDER-YES", { file: f, line, evidence: evidenceLine(f, line) });
1481
+ let key = null;
1482
+ for (const [i, text] of f.lines.entries()) {
1483
+ const top = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(text);
1484
+ if (top) {
1485
+ key = top[1].toLowerCase();
1486
+ const value = unquote(top[2].replace(/\s+#.*$/, ""));
1487
+ if (value) aiderValue(ctx, f, key, value, i + 1);
1488
+ continue;
1489
+ }
1490
+ // A list under the key: lint-cmd as "- python: flake8 --select", set-env as "- NAME=value".
1491
+ const item = /^\s+-\s+(.*)$/.exec(text);
1492
+ if (item && key) aiderValue(ctx, f, key, unquote(item[1]), i + 1);
1493
+ }
1494
+ }
1495
+ function aiderValue(ctx, f, key, value, line) {
1496
+ if (key === "openai-api-base") checkEndpointSetting(ctx, f, "Aider's openai-api-base setting", "openai-api-base", value, line);
1497
+ if (Object.hasOwn(AIDER_COMMANDS, key)) {
1498
+ const command = key === "lint-cmd" ? value.replace(/^[\w+#.-]{1,30}:\s+/, "") : value;
1499
+ if (command && !command.startsWith("[")) checkCommand(ctx, command, f, AIDER_COMMANDS[key], { line });
1500
+ } else if (key === "set-env") {
1501
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(value);
1502
+ const variable = m && codeLoadingVariable(m[1], unquote(m[2]));
1503
+ if (variable) add(ctx, "ENV-CODE-LOAD", { file: f, line, evidence: evidenceLine(f, line), vars: { where: "Aider's set-env setting", variable } });
1504
+ if (m) checkEnvironment(ctx, f, "Aider's set-env setting", m[1], unquote(m[2]), line);
1505
+ }
528
1506
  }
529
1507
 
530
1508
  function checkPackageJson(ctx, f) {
531
1509
  const json = parsed(f);
532
1510
  if (!isObj(json?.scripts)) return;
533
1511
  for (const [name, script] of Object.entries(json.scripts)) {
534
- const m = typeof script === "string" && script.match(RX_DANGER_FLAGS);
535
- if (m) {
1512
+ const hit = typeof script === "string" && findDangerFlag(script);
1513
+ if (hit) {
536
1514
  const line = lineOf(f, `"${name}"`);
537
- 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` } });
1515
+ 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` } });
538
1516
  }
539
1517
  }
540
1518
  }
541
1519
 
542
- // --- Commands run by hooks -----------------------------------------------------
1520
+ // --- Commands run by hooks ---------------------------------------------------
543
1521
 
544
- function checkCommand(ctx, command, f, where) {
545
- const line = lineOf(f, command.split("\n")[0].slice(0, 60)) || lineOf(f, /"command"/);
1522
+ function checkCommand(ctx, command, f, where, { autorun = true, line: near = 0 } = {}) {
1523
+ const line = lineOf(f, command.split("\n")[0].slice(0, 60)) || near || lineOf(f, /"command"/);
546
1524
  const cmd = clip(command, 140);
547
1525
  const vars = { where, cmd };
548
- if (RX_REMOTE_EXEC.test(command)) add(ctx, "HOOK-REMOTE-EXEC", { file: f, line, evidence: command, vars });
549
- else if (RX_NET_SEND.test(command)) add(ctx, "HOOK-NETWORK", { file: f, line, evidence: command, vars });
550
- if (RX_DESTRUCTIVE.test(command)) add(ctx, "HOOK-DESTRUCTIVE", { file: f, line, evidence: command, vars });
551
- if (RX_OUTSIDE_SCRIPT.test(command)) add(ctx, "HOOK-OUTSIDE", { file: f, line, evidence: command, vars });
552
- const flag = command.match(RX_DANGER_FLAGS);
553
- if (flag) add(ctx, "FLAG-SCRIPT", { file: f, line, evidence: command, vars: { flag: flag[0].trim(), where } });
1526
+ const remote = RX_REMOTE_EXEC.test(command);
1527
+ const sends = !remote && sendsData(command);
1528
+ if (remote) add(ctx, "HOOK-REMOTE-EXEC", { file: f, line, evidence: command, vars });
1529
+ else if (sends) add(ctx, "HOOK-NETWORK", { file: f, line, evidence: command, vars });
1530
+ const destructive = isDestructive(command);
1531
+ if (destructive) add(ctx, "HOOK-DESTRUCTIVE", { file: f, line, evidence: command, vars });
1532
+ const outside = runsOutsideScript(command);
1533
+ if (outside) add(ctx, "HOOK-OUTSIDE", { file: f, line, evidence: command, vars });
1534
+ const hit = findDangerFlag(command);
1535
+ if (hit) add(ctx, "FLAG-SCRIPT", { file: f, line, evidence: command, tool: hit.agent, vars: { flag: hit.flag, where } });
1536
+ // Anything else a project's settings run on their own is still the
1537
+ // project's code running on this computer, reported once per file.
1538
+ if (autorun && !remote && !sends && !destructive && !outside && !hit && inProject(ctx, f) && !harmlessCommand(command)) {
1539
+ if (!ctx.autorun.has(f)) ctx.autorun.set(f, { line, evidence: command, vars });
1540
+ }
1541
+ }
1542
+
1543
+ // Commands that only print, wait or make a sound, such as a notification.
1544
+ const HARMLESS_PROGRAMS = new Set(["echo", "printf", "true", "false", ":", "date", "pwd", "exit", "sleep", "notify-send", "terminal-notifier", "say", "afplay", "paplay", "aplay", "tput", "clear"]);
1545
+ function harmlessCommand(command) {
1546
+ if (/\$\(|`|<\(|>\(/.test(command)) return false;
1547
+ const segments = commandSegments(shellWords(command));
1548
+ return (
1549
+ segments.length > 0 &&
1550
+ segments.every((segment) => {
1551
+ let i = 0;
1552
+ while (i < segment.length - 1 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(segment[i])) i++;
1553
+ return HARMLESS_PROGRAMS.has(segment[i].split(/[\\/]/).pop().toLowerCase()) && !segment.slice(i + 1).some((w) => /^[<>]|^\d?>/.test(w));
1554
+ })
1555
+ );
1556
+ }
1557
+
1558
+ // A settings file that has the agent read instructions from outside the
1559
+ // project, or from a web page.
1560
+ function checkNamed(ctx) {
1561
+ for (const n of ctx.named) {
1562
+ const f = ctx.files.find((x) => x.path === n.from);
1563
+ if (!f || (!n.outside && !n.web)) continue;
1564
+ const line = lineOf(f, n.name.slice(0, 60));
1565
+ if (n.web) {
1566
+ let host = "";
1567
+ try {
1568
+ host = new URL(n.name).hostname;
1569
+ } catch {}
1570
+ if (host) add(ctx, "TXT-REMOTE-INSTRUCTIONS", { file: f, line, evidence: evidenceLine(f, line), vars: { host } });
1571
+ } else add(ctx, "TXT-IMPORT-OUTSIDE", { file: f, line, evidence: evidenceLine(f, line), vars: { ref: clip(n.name, 80) } });
1572
+ }
1573
+ }
1574
+
1575
+ function checkAutorun(ctx) {
1576
+ for (const [f, found] of ctx.autorun) add(ctx, "PROJECT-AUTORUN", { file: f, ...found });
1577
+ }
1578
+
1579
+ // VS Code tasks, which every editor built on VS Code runs. A task with
1580
+ // runOn: folderOpen runs when the folder opens: in Cursor without asking,
1581
+ // since Workspace Trust is off there by default.
1582
+ function checkVsCodeTasks(ctx, f) {
1583
+ const json = parsed(f);
1584
+ const tasks = Array.isArray(json?.tasks) ? json.tasks.slice(0, 200) : [];
1585
+ for (const task of tasks) {
1586
+ if (!isObj(task) || task.runOptions?.runOn !== "folderOpen") continue;
1587
+ const commands = [task, task.windows, task.osx, task.linux]
1588
+ .filter(isObj)
1589
+ .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())
1590
+ .filter(Boolean);
1591
+ const label = typeof task.label === "string" ? task.label : "";
1592
+ // The "folderOpen" line nearest the task's label, so the evidence is the
1593
+ // setting itself.
1594
+ const labelLine = label ? lineOf(f, `"${label.slice(0, 60)}"`) : 0;
1595
+ const opens = (f.lines ?? []).flatMap((l, i) => (/"folderOpen"/.test(l) ? [i + 1] : []));
1596
+ const line = opens.length ? opens.reduce((a, b) => (labelLine && Math.abs(b - labelLine) < Math.abs(a - labelLine) ? b : a)) : labelLine || lineOf(f, /folderOpen/);
1597
+ const command = commands[0] ?? label;
1598
+ add(ctx, "TASK-FOLDER-OPEN", { file: f, line, evidence: evidenceLine(f, line), vars: { cmd: clip(command || "a task", 140) } });
1599
+ for (const c of new Set(commands)) checkCommand(ctx, c, f, "A task that runs when the folder opens", { autorun: false });
1600
+ }
554
1601
  }
555
1602
 
556
1603
  function checkHookScript(ctx, f) {
557
- const where = `The hook script ${f.path}`;
1604
+ const where = "This hook script";
558
1605
  for (const [i, line] of f.lines.entries()) {
559
1606
  if (!line.trim() || /^\s*(#|\/\/|REM\b)/i.test(line)) continue;
560
1607
  const vars = { where, cmd: clip(line, 140) };
561
1608
  const opts = { file: f, line: i + 1, evidence: line, vars };
562
1609
  if (RX_REMOTE_EXEC.test(line)) add(ctx, "HOOK-REMOTE-EXEC", opts);
563
- else if (RX_NET_SEND.test(line)) add(ctx, "HOOK-NETWORK", opts);
564
- if (RX_DESTRUCTIVE.test(line)) add(ctx, "HOOK-DESTRUCTIVE", opts);
565
- const flag = line.match(RX_DANGER_FLAGS);
566
- if (flag) add(ctx, "FLAG-SCRIPT", { ...opts, vars: { flag: flag[0].trim(), where } });
1610
+ else if (sendsData(line)) add(ctx, "HOOK-NETWORK", opts);
1611
+ if (isDestructive(line)) add(ctx, "HOOK-DESTRUCTIVE", opts);
1612
+ const hit = findDangerFlag(line);
1613
+ if (hit) add(ctx, "FLAG-SCRIPT", { ...opts, tool: hit.agent, vars: { flag: hit.flag, where } });
567
1614
  }
568
1615
  }
569
1616
 
570
- // --- Instruction files -----------------------------------------------------------
1617
+ // --- Instruction files -------------------------------------------------------
571
1618
 
572
1619
  function checkInstructionText(ctx, f) {
573
1620
  const text = f.content;
@@ -576,80 +1623,111 @@ function checkInstructionText(ctx, f) {
576
1623
  return { file: f, line, evidence: evidenceLine(f, line) };
577
1624
  };
578
1625
 
579
- const tags = [...text.matchAll(/[\u{E0000}-\u{E007F}]/gu)];
1626
+ const tags = hiddenTags(text);
580
1627
  if (tags.length) {
581
- const decoded = tags
582
- .map((m) => String.fromCharCode(m[0].codePointAt(0) - 0xe0000))
583
- .join("")
584
- .replace(/[^\x20-\x7e]/g, "");
585
- add(ctx, "TXT-TAGS", { ...at(tags[0].index), evidence: null, vars: { count: tags.length, decoded: clip(maskSecrets(decoded).text, 140) } });
1628
+ const decoded = tags.map((t) => t.decoded).join("");
1629
+ const count = tags.reduce((n, t) => n + t.length, 0);
1630
+ add(ctx, "TXT-TAGS", { ...at(tags[0].index), evidence: null, vars: { count, decoded: clip(maskSecrets(decoded).text, 140) } });
586
1631
  }
587
- const bidi = text.search(/[‪-‮⁦-⁩]/);
1632
+ const bidi = text.search(/[\u202a-\u202e\u2066-\u2069]/);
588
1633
  if (bidi >= 0) add(ctx, "TXT-BIDI", { ...at(bidi), evidence: null });
589
- const zeroWidth = [...text.slice(1).matchAll(/[​-‍⁠᠎]/g)];
590
- if (zeroWidth.length >= 3) add(ctx, "TXT-ZERO-WIDTH", { ...at(zeroWidth[0].index + 1), evidence: null, vars: { count: zeroWidth.length } });
1634
+ const zeroWidth = hiddenZeroWidth(text);
1635
+ if (zeroWidth.length >= 3) add(ctx, "TXT-ZERO-WIDTH", { ...at(zeroWidth[0]), evidence: null, vars: { count: zeroWidth.length } });
591
1636
 
592
- for (const m of text.matchAll(/<!--([\s\S]*?)-->/g)) {
593
- const inner = m[1].trim();
1637
+ for (const c of hiddenComments(text)) {
1638
+ const inner = c.inner.trim();
594
1639
  if (inner && !RX_BENIGN_COMMENT.test(inner) && RX_INJECT_WORDS.test(inner)) {
595
- add(ctx, "TXT-HIDDEN-COMMENT", { ...at(m.index), evidence: inner });
1640
+ add(ctx, "TXT-HIDDEN-COMMENT", { ...at(c.index), evidence: inner });
596
1641
  break;
597
1642
  }
598
1643
  }
599
1644
 
600
1645
  // Rules marked `affirmative` ignore lines that warn against the thing,
601
1646
  // such as "Never read .env files" or "Do not disable the sandbox".
602
- const textRule = (id, re, varsFrom, { affirmative = false } = {}) => {
603
- const m = firstMatch(text, re, affirmative);
1647
+ const textRule = (id, re, varsFrom, { affirmative = false, reject } = {}) => {
1648
+ const m = firstMatch(text, re, affirmative, reject);
604
1649
  if (m) add(ctx, id, { ...at(m.index + (m[0].length - m[0].trimStart().length)), vars: varsFrom ? varsFrom(m) : {} });
605
1650
  };
606
1651
  textRule("TXT-REMOTE-EXEC", RX_REMOTE_EXEC, null, { affirmative: true });
607
1652
  textRule("TXT-EXFIL", RX_EXFIL_HOST, (m) => ({ host: m[1] }));
608
- textRule("TXT-OVERRIDE", RX_OVERRIDE, (m) => ({ phrase: clip(m[0], 80) }), { affirmative: true });
609
- textRule("TXT-SECRET-ACCESS", RX_SECRET_ACCESS, (m) => ({ phrase: clip(m[0], 80) }), { affirmative: true });
610
- textRule("TXT-BLOB", RX_BLOB, (m) => ({ length: m[0].length.toLocaleString("en-US") }));
611
- textRule("TXT-IMPORT-OUTSIDE", RX_IMPORT_OUTSIDE, (m) => ({ ref: "@" + clip(m[1], 80) }));
612
- textRule("FLAG-DOCS", RX_DANGER_FLAGS, (m) => ({ flag: m[0].trim() }), { affirmative: true });
1653
+ textRule("TXT-PASTE-SITE", RX_PASTE_SITE, (m) => ({ host: m[1].toLowerCase() }), { affirmative: true });
1654
+ // A paste site already has its own finding.
1655
+ 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]}`) });
1656
+ textRule("TXT-ARCHIVE-PASSWORD", RX_ARCHIVE_PASSWORD, null, { affirmative: true, reject: (m) => !givesArchivePassword(text, m) });
1657
+ textRule("TXT-QUARANTINE", RX_QUARANTINE, null, { affirmative: true });
1658
+ // Defensive instructions quote injections as examples, as in: if a page
1659
+ // says "ignore previous instructions", don't follow it.
1660
+ let fence = null;
1661
+ textRule("TXT-OVERRIDE", RX_OVERRIDE, (m) => ({ phrase: clip(m[0], 80) }), {
1662
+ affirmative: true,
1663
+ reject: (m) => quotedExample(text, m, "\"'“‘`") || fencedExample(text, m.index, (fence ??= fenceAt(text))),
1664
+ });
1665
+ // Setting up a project ("copy .env.example to .env", "add .env to
1666
+ // .gitignore") isn't handing secrets to the agent.
1667
+ textRule("TXT-SECRET-ACCESS", RX_SECRET_ACCESS, (m) => ({ phrase: clip(m[0], 80) }), {
1668
+ affirmative: true,
1669
+ reject: (m) =>
1670
+ quotedExample(text, m, "\"'“‘") ||
1671
+ /\.env\.(?:example|sample|template|dist|defaults)\b|gitignore/i.test(text.slice(m.index, m.index + m[0].length + 40)) ||
1672
+ // "Settings are read from .env" says what a program does, not what the agent should.
1673
+ /\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)),
1674
+ });
1675
+ const blob = longBase64(text);
1676
+ if (blob) add(ctx, "TXT-BLOB", { ...at(blob.index), vars: { length: blob.length.toLocaleString("en-US") } });
1677
+ // Only files that import can pull a file in, and never from inside code.
1678
+ if (CAN_IMPORT.test(f.path)) {
1679
+ textRule("TXT-IMPORT-OUTSIDE", RX_IMPORT_OUTSIDE, (m) => ({ ref: "@" + clip(m[1], 80) }), {
1680
+ reject: (m) => (fence ??= fenceAt(text))(m.index) !== null || inCodeSpan(text, m.index),
1681
+ });
1682
+ }
1683
+ const flag = findDangerFlag(text, (index) => negated(text, index));
1684
+ if (flag) add(ctx, "FLAG-DOCS", { ...at(flag.index), tool: flag.agent, vars: { flag: flag.flag } });
613
1685
 
614
- if (text.length > 60_000 && !f.loose) add(ctx, "TXT-HUGE", { file: f, vars: { size: `${Math.round(text.length / 1024)} KB` } });
1686
+ // A file read only in part is reported as that instead.
1687
+ if (text.length > 60_000 && !f.loose && !f.partial) add(ctx, "TXT-HUGE", { file: f, vars: { size: `${Math.round(text.length / 1024)} KB` } });
615
1688
  }
616
1689
 
617
- // --- MCP servers -------------------------------------------------------------------
618
-
619
- function collectMcpServers(ctx) {
620
- for (const f of ctx.files) {
621
- if (!f.content) continue;
622
- const p = f.path;
623
- let groups = [];
624
- if (/(^|\/)\.codex\/config\.toml$/i.test(p)) groups = [parsed(f)?.mcp_servers];
625
- else if (/\.jsonc?$/i.test(p)) {
626
- const json = parsed(f);
627
- if (!isObj(json)) continue;
628
- if (/(^|\/)\.vscode\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
629
- else if (/(^|\/)opencode\.jsonc?$/i.test(p)) groups = [json.mcp];
630
- else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(p)) groups = [json.context_servers];
631
- else if (/\/User\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
632
- else if (/\/User\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
633
- else if (/(^|\/)\.claude\.json$/i.test(p)) groups = [json.mcpServers, ...(isObj(json.projects) ? Object.values(json.projects).map((x) => x?.mcpServers) : [])];
634
- else if (/(^|\/)\.vscode\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
635
- else groups = [json.mcpServers];
636
- }
637
- for (const group of groups) {
638
- if (!isObj(group)) continue;
639
- for (const [name, def] of Object.entries(group)) ctx.mcpServers.push(normalizeServer(name, def, f));
640
- }
1690
+ // --- MCP servers -------------------------------------------------------------
1691
+
1692
+ // The MCP servers a file defines, wherever its agent keeps them.
1693
+ function collectMcpServers(ctx, f) {
1694
+ const p = f.path;
1695
+ let groups = [];
1696
+ if (/(^|\/)(\.codex\/([^/]+\.)?config|\.grok\/config)\.toml$/i.test(p)) groups = [parsed(f)?.mcp_servers];
1697
+ // Continue lists servers with a name each; Goose calls them extensions.
1698
+ else if (/(^|\/)\.continue\/(config|mcpServers\/[^/]+)\.ya?ml$/i.test(p)) {
1699
+ const list = parsed(f)?.mcpServers;
1700
+ 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];
1701
+ } else if (/(^|\/)goose\/config\.ya?ml$/i.test(p)) groups = [parsed(f)?.extensions];
1702
+ else if (/\.jsonc?$/i.test(p)) {
1703
+ const json = parsed(f);
1704
+ if (!isObj(json)) return;
1705
+ if (/(^|\/)(\.vscode|\.github)\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
1706
+ else if (/(^|\/)(\.amp|\.config\/amp)\/settings\.json$/i.test(p)) groups = [json["amp.mcpServers"]];
1707
+ else if (/(^|\/)opencode\.jsonc?$/i.test(p)) groups = [json.mcp];
1708
+ else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(p)) groups = [json.context_servers];
1709
+ else if (/\/User\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
1710
+ else if (/\/User\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
1711
+ else if (/(^|\/)\.claude\.json$/i.test(p)) groups = [json.mcpServers, ...(isObj(json.projects) ? Object.values(json.projects).map((x) => x?.mcpServers) : [])];
1712
+ else if (/(^|\/)\.vscode\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
1713
+ else if (f.role === "mcp-servers") groups = [json.mcpServers ?? json];
1714
+ else groups = [json.mcpServers];
1715
+ }
1716
+ for (const group of groups) {
1717
+ if (!isObj(group)) continue;
1718
+ for (const [name, def] of Object.entries(group)) ctx.mcpServers.push(normalizeServer(name, def, f));
641
1719
  }
642
1720
  }
643
1721
 
644
1722
  function normalizeServer(name, def, file) {
645
1723
  const d = isObj(def) ? def : {};
646
- let command = d.command;
647
- let args = Array.isArray(d.args) ? d.args.map(String) : [];
1724
+ let command = d.command ?? d.cmd;
1725
+ let args = scalars(d.args);
648
1726
  if (Array.isArray(command)) {
649
- args = [...command.slice(1).map(String), ...args];
1727
+ args = [...scalars(command.slice(1)), ...args];
650
1728
  command = command[0];
651
1729
  } else if (isObj(command)) {
652
- args = Array.isArray(command.args) ? command.args.map(String) : args;
1730
+ args = Array.isArray(command.args) ? scalars(command.args) : args;
653
1731
  command = command.path ?? command.command;
654
1732
  }
655
1733
  const url = [d.url, d.serverUrl, d.httpUrl].find((u) => typeof u === "string") ?? null;
@@ -658,23 +1736,30 @@ function normalizeServer(name, def, file) {
658
1736
  file,
659
1737
  command: typeof command === "string" ? command : null,
660
1738
  args,
661
- env: isObj(d.env) ? d.env : isObj(d.environment) ? d.environment : {},
1739
+ env: isObj(d.env) ? d.env : isObj(d.environment) ? d.environment : isObj(d.envs) ? d.envs : {},
662
1740
  headers: isObj(d.headers) ? d.headers : isObj(d.http_headers) ? d.http_headers : {},
663
1741
  extra: d,
664
1742
  url,
665
1743
  alwaysAllow: d.alwaysAllow ?? d.autoApprove ?? d.auto_approve ?? (d.trust === true ? true : undefined),
666
- alwaysAllowKey: ["alwaysAllow", "autoApprove", "auto_approve", "trust"].find((k) => d[k] !== undefined) ?? null,
1744
+ alwaysAllowKey: ALWAYS_ALLOW_KEYS.find((k) => d[k] !== undefined) ?? null,
667
1745
  disabled: d.disabled === true || d.enabled === false,
668
1746
  };
669
1747
  }
670
1748
 
671
1749
  const REFERENCE = /^\$\{[^}]+\}$|^\$[A-Za-z_][A-Za-z0-9_]*$|^\{env:[^}]+\}$|^%[A-Za-z_][A-Za-z0-9_]*%$|\$\{(?:env|input):/i;
672
1750
 
1751
+ // References such as ${GITHUB_TOKEN}, {env:KEY} or %API_KEY%, anywhere in a value.
1752
+ const REFERENCES = /\$\{[^}]{0,200}\}|\{env:[^}]{0,200}\}|%[A-Za-z_][A-Za-z0-9_]{0,100}%|\$[A-Za-z_][A-Za-z0-9_]*/g;
1753
+
673
1754
  function isSecretValue(key, value) {
674
1755
  if (typeof value !== "string" || REFERENCE.test(value.trim()) || isPathLike(value)) return false;
675
1756
  if (isMasked(value)) return true;
676
- if (/^(true|false|\d+|https?:\/\/[^@]*)$/i.test(value)) return false;
677
- return /(token|secret|key|password|passwd|auth|credential|bearer|cookie|session)/i.test(key) ? looksLikeSecret(value) || value.length >= 20 : looksLikeToken(value) && value.length >= 24;
1757
+ // What's left once references and an auth scheme are taken out, so
1758
+ // "Bearer ${GITHUB_TOKEN}" counts as a reference too.
1759
+ const rest = value.replace(REFERENCES, "").replace(/^\s*(?:Bearer|Basic|Token|Bot)\b\s*/i, "").trim();
1760
+ if (rest.length < 8 || /^(true|false|\d+|https?:\/\/[^@]*)$/i.test(rest)) return false;
1761
+ if (/(token|secret|key|password|passwd|auth|credential|bearer|cookie|session)/i.test(key)) return looksLikeSecret(rest) || (rest.length >= 20 && !/\s/.test(rest));
1762
+ return looksLikeToken(rest) && rest.length >= 24;
678
1763
  }
679
1764
 
680
1765
  function redact(value) {
@@ -686,21 +1771,27 @@ function checkMcpServer(ctx, s) {
686
1771
  const tool = f.tools[0] ?? null;
687
1772
  const nameLine = lineOf(f, `"${s.name}"`) || lineOf(f, s.name);
688
1773
  const base = (line = nameLine) => ({ file: f, line, tool, evidence: evidenceLine(f, line) });
1774
+ const near = (test) => lineAfter(f, test, nameLine);
689
1775
 
690
1776
  for (const [key, value] of [...Object.entries(s.env), ...Object.entries(s.headers)]) {
691
1777
  if (isSecretValue(key, value)) {
692
- const line = lineOf(f, `"${key}"`) || lineOf(f, key) || nameLine;
1778
+ const line = near(`"${key}"`) || near(key) || nameLine;
693
1779
  add(ctx, "MCP-SECRET", { ...base(line), evidence: `${key} = ${redact(value)}`, vars: { server: s.name, key } });
694
1780
  }
695
1781
  }
1782
+ for (const [key, value] of Object.entries(s.env)) {
1783
+ const variable = codeLoadingVariable(key, value);
1784
+ if (variable) add(ctx, "MCP-ENV-CODE-LOAD", { ...base(near(`"${key}"`) || near(key) || nameLine), vars: { server: s.name, variable } });
1785
+ 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" } });
1786
+ }
696
1787
  for (const key of ["bearer_token", "bearerToken", "apiKey", "api_key", "token"]) {
697
1788
  const value = s.extra[key];
698
1789
  if (typeof value === "string" && isSecretValue(key, value)) {
699
- add(ctx, "MCP-SECRET", { ...base(lineOf(f, key) || nameLine), evidence: `${key} = ${redact(value)}`, vars: { server: s.name, key } });
1790
+ add(ctx, "MCP-SECRET", { ...base(near(key) || nameLine), evidence: `${key} = ${redact(value)}`, vars: { server: s.name, key } });
700
1791
  }
701
1792
  }
702
1793
  const secretArg = s.args.find((a) => isMasked(a) || (looksLikeToken(a) && a.length >= 24 && !a.includes("/")));
703
- 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" } });
1794
+ if (secretArg) add(ctx, "MCP-SECRET", { ...base(near(secretArg.slice(0, 20)) || nameLine), evidence: `args contain ${redact(secretArg)}`, vars: { server: s.name, key: "args" } });
704
1795
 
705
1796
  if (s.url) {
706
1797
  let u = null;
@@ -708,95 +1799,249 @@ function checkMcpServer(ctx, s) {
708
1799
  u = new URL(s.url);
709
1800
  } catch {}
710
1801
  if (u) {
711
- const local = /^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?|0\.0\.0\.0|host\.docker\.internal)$/i.test(u.hostname);
712
- if (u.protocol === "http:" && !local) add(ctx, "MCP-HTTP", { ...base(lineOf(f, s.url) || nameLine), vars: { server: s.name, host: u.hostname } });
1802
+ if (u.protocol === "http:" && !isLocalHost(u.hostname)) add(ctx, "MCP-HTTP", { ...base(near(s.url) || nameLine), vars: { server: s.name, host: u.hostname } });
713
1803
  if ([...u.searchParams.keys()].some((k) => /token|key|secret|auth|sig|password/i.test(k)) || u.password || isMasked(s.url)) {
714
- add(ctx, "MCP-URL-TOKEN", { ...base(lineOf(f, u.hostname) || nameLine), vars: { server: s.name } });
1804
+ add(ctx, "MCP-URL-TOKEN", { ...base(near(u.hostname) || nameLine), vars: { server: s.name } });
715
1805
  }
716
1806
  }
717
1807
  }
718
1808
 
719
1809
  const pkg = packageSpec(s.command, s.args);
720
- if (pkg && !pkg.pinned) {
1810
+ const flagged = checkMcpPackage(ctx, s, base, near);
1811
+ if (pkg && !pkg.pinned && !flagged) {
721
1812
  add(ctx, "MCP-UNPINNED", {
722
- ...base(lineOf(f, pkg.spec) || nameLine),
1813
+ ...base(near(pkg.spec) || nameLine),
723
1814
  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` },
724
1815
  });
725
1816
  }
726
1817
 
727
1818
  if (/(^|[\\/])(docker|podman)(\.exe)?$/i.test(s.command ?? "")) {
728
- const flag = dockerRisk(s.args);
729
- if (flag) add(ctx, "MCP-DOCKER", { ...base(lineOf(f, flag.split(" ")[0]) || nameLine), vars: { server: s.name, flag } });
1819
+ const risk = dockerRisk(s.args);
1820
+ if (risk) add(ctx, "MCP-DOCKER", { ...base(near(risk.arg) || nameLine), vars: { server: s.name, flag: risk.flag } });
1821
+ }
1822
+
1823
+ // What the command runs, whatever launches it: a download piped into a
1824
+ // shell, or, in a project's own settings, a file from the project.
1825
+ if (typeof s.command === "string" && s.command) {
1826
+ const line = [s.command, ...s.args].join(" ");
1827
+ 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) } });
1828
+ else if (!pkg && inProject(ctx, f)) {
1829
+ const local = localCode(s.command, s.args);
1830
+ if (local) add(ctx, "MCP-LOCAL-CODE", { ...base(near(local.slice(0, 60)) || nameLine), vars: { server: s.name, path: clip(local, 120) } });
1831
+ }
730
1832
  }
731
1833
 
732
1834
  const broad = s.args.find((a) => isBroadPath(a));
733
1835
  if (broad && !/(^|[\\/])(docker|podman)(\.exe)?$/i.test(s.command ?? "")) {
734
- add(ctx, "MCP-FS-BROAD", { ...base(lineOf(f, `"${broad}"`) || nameLine), vars: { server: s.name, path: broad } });
1836
+ add(ctx, "MCP-FS-BROAD", { ...base(near(`"${broad}"`) || nameLine), vars: { server: s.name, path: broad } });
735
1837
  }
736
1838
 
737
1839
  if (SHELL_SERVER.test(s.name) || (pkg && SHELL_SERVER.test(pkg.name))) add(ctx, "MCP-SHELL", { ...base(), vars: { server: s.name } });
738
1840
 
739
1841
  if (s.alwaysAllow === true || (Array.isArray(s.alwaysAllow) && s.alwaysAllow.length)) {
740
1842
  const count = s.alwaysAllow === true ? "every tool" : `${s.alwaysAllow.length} tool${s.alwaysAllow.length === 1 ? "" : "s"}`;
741
- add(ctx, "MCP-ALWAYS-ALLOW", { ...base(lineOf(f, s.alwaysAllowKey) || nameLine), vars: { server: s.name, key: s.alwaysAllowKey, count } });
1843
+ add(ctx, "MCP-ALWAYS-ALLOW", { ...base(near(s.alwaysAllowKey) || nameLine), vars: { server: s.name, setting: s.alwaysAllowKey, count } });
742
1844
  }
743
1845
  }
744
1846
 
1847
+ // The project file an MCP server's command runs, or the code a shell is given
1848
+ // inline: ./server.js, node tools/server.js, python3 -m pkg isn't one.
1849
+ 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;
1850
+ 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));
1851
+ function localCode(command, args) {
1852
+ const name = command.split(/[\\/]/).pop().replace(/\.(?:exe|cmd|bat)$/i, "");
1853
+ if (relativeFile(command) && !RUNS_FILES.test(name)) return command;
1854
+ // uv run server.py runs a file from the project too.
1855
+ if (/^uv$/i.test(name) && args[0] === "run") return args.slice(1).find((a) => relativeFile(a)) ?? null;
1856
+ if (!RUNS_FILES.test(name)) return null;
1857
+ const inline = args.findIndex((a) => /^(?:-c|\/c|\/k|-Command|-e|--eval)$/i.test(a));
1858
+ if (inline >= 0 && typeof args[inline + 1] === "string") return args[inline + 1];
1859
+ return args.find((a) => relativeFile(a)) ?? null;
1860
+ }
1861
+
1862
+ // Launcher options that name the package, and options that take a value, so
1863
+ // the value isn't read as the package (npx --registry URL pkg, uvx --python
1864
+ // 3.12 pkg). For uvx, -p is the Python version.
1865
+ const LAUNCHER_OPTIONS = {
1866
+ node: { pkg: ["-p", "--package"], valued: ["--registry", "--cache", "--prefix", "--userconfig", "-c", "--call", "--node-options", "-w", "--workspace"] },
1867
+ python: {
1868
+ pkg: ["--from", "--spec"],
1869
+ 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"],
1870
+ },
1871
+ };
1872
+
745
1873
  export function packageSpec(command, args) {
746
- if (!command) return null;
1874
+ const raw = launcherSpec(command, args);
1875
+ return raw ? judgeSpec(raw.spec, raw.python) : null;
1876
+ }
1877
+
1878
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish", "ash"]);
1879
+
1880
+ // A command line split into words the way a shell would, for simple quoting:
1881
+ // "a b" and 'a b' are one word. Kept short, since it runs on untrusted text.
1882
+ function shellWords(text) {
1883
+ const words = [];
1884
+ let word = null;
1885
+ let quote = null;
1886
+ for (const ch of String(text).slice(0, 2000)) {
1887
+ if (quote) {
1888
+ if (ch === quote) quote = null;
1889
+ else word += ch;
1890
+ } else if (ch === '"' || ch === "'") {
1891
+ quote = ch;
1892
+ word ??= "";
1893
+ } else if (/\s/.test(ch)) {
1894
+ if (word !== null) words.push(word);
1895
+ word = null;
1896
+ } else if (";|&".includes(ch)) {
1897
+ if (word !== null) words.push(word);
1898
+ words.push(ch);
1899
+ word = null;
1900
+ } else word = (word ?? "") + ch;
1901
+ }
1902
+ if (word !== null) words.push(word);
1903
+ return words;
1904
+ }
1905
+
1906
+ // The separate commands in a list of words: a; b && c | d.
1907
+ function commandSegments(words) {
1908
+ const segments = [[]];
1909
+ for (const w of words) {
1910
+ if (w === ";" || w === "|" || w === "&") segments.push([]);
1911
+ else segments.at(-1).push(w);
1912
+ }
1913
+ return segments.filter((s) => s.length).slice(0, 10);
1914
+ }
1915
+
1916
+ // The argument a launcher such as npx or uvx runs, as { spec, python }. A
1917
+ // launcher can sit inside a wrapper: cmd /c, a shell's -c string,
1918
+ // PowerShell's -Command, env, npm exec, bun x or deno's npm: names.
1919
+ function launcherSpec(command, args, depth = 0) {
1920
+ if (typeof command !== "string" || !command || depth > 3) return null;
747
1921
  const base = command.split(/[\\/]/).pop().replace(/\.(cmd|exe|bat)$/i, "").toLowerCase();
748
- let rest = [...args];
749
- if (base === "cmd" && /^\/c$/i.test(rest[0] ?? "")) return packageSpec(rest[1], rest.slice(2));
1922
+ let rest = args.filter((a) => typeof a === "string").slice(0, 60);
1923
+ const inner = (words) => {
1924
+ for (const segment of commandSegments(words)) {
1925
+ // Past FOO=1 and exec, command, nohup or time in front of the command.
1926
+ let i = 0;
1927
+ while (i < segment.length - 1 && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(segment[i]) || /^(?:exec|command|nohup|time|builtin)$/.test(segment[i]))) i++;
1928
+ const found = launcherSpec(segment[i], segment.slice(i + 1), depth + 1);
1929
+ if (found) return found;
1930
+ }
1931
+ return null;
1932
+ };
1933
+ if (base === "cmd") {
1934
+ const c = rest.findIndex((a) => /^\/[ck]$/i.test(a));
1935
+ return c < 0 ? null : inner(rest.slice(c + 1).flatMap(shellWords));
1936
+ }
1937
+ if (SHELLS.has(base)) {
1938
+ const c = rest.findIndex((a) => /^-[a-z]*c[a-z]*$/i.test(a));
1939
+ return c < 0 || typeof rest[c + 1] !== "string" ? null : inner(shellWords(rest[c + 1]));
1940
+ }
1941
+ if (base === "pwsh" || base === "powershell") {
1942
+ const c = rest.findIndex((a) => /^-(?:c|command)$/i.test(a));
1943
+ return c < 0 ? null : inner(rest.slice(c + 1).flatMap(shellWords));
1944
+ }
1945
+ if (base === "env") {
1946
+ let i = 0;
1947
+ while (i < rest.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(rest[i]) || rest[i].startsWith("-"))) {
1948
+ if (/^(?:-S|--split-string)$/.test(rest[i])) return inner(shellWords(rest[i + 1] ?? ""));
1949
+ i += /^(?:-u|--unset|-C|--chdir)$/.test(rest[i]) ? 2 : 1;
1950
+ }
1951
+ return inner(rest.slice(i));
1952
+ }
1953
+ if (base === "deno") {
1954
+ const spec = rest.find((a) => /^npm:/i.test(a));
1955
+ return spec ? { spec: spec.slice(4), python: false } : null;
1956
+ }
1957
+ if ((base === "npm" && (rest[0] === "exec" || rest[0] === "x")) || (base === "bun" && rest[0] === "x")) return launcherSpec("npx", rest.slice(1), depth + 1);
750
1958
  if (base === "pnpm" || base === "yarn") {
751
1959
  if (rest[0] !== "dlx") return null;
752
1960
  rest = rest.slice(1);
753
1961
  } else if (base === "pipx") {
754
1962
  if (rest[0] !== "run") return null;
755
1963
  rest = rest.slice(1);
1964
+ } else if (base === "uv") {
1965
+ if (rest[0] !== "tool" || rest[1] !== "run") return null;
1966
+ rest = rest.slice(2);
756
1967
  } else if (!["npx", "bunx", "pnpx", "uvx"].includes(base)) return null;
757
1968
 
758
- const python = base === "uvx" || base === "pipx";
1969
+ const python = ["uvx", "pipx", "uv"].includes(base);
1970
+ const { pkg, valued } = LAUNCHER_OPTIONS[python ? "python" : "node"];
759
1971
  for (let i = 0; i < rest.length; i++) {
760
1972
  const a = rest[i];
761
- if (["-p", "--package", "--from", "--spec"].includes(a)) return judgeSpec(rest[i + 1], python);
762
- const eq = a.match(/^--(?:package|from|spec)=(.+)$/);
763
- if (eq) return judgeSpec(eq[1], python);
764
- if (a.startsWith("-")) continue;
765
- return judgeSpec(a, python);
1973
+ const eq = a.startsWith("--") ? a.indexOf("=") : -1;
1974
+ const name = eq > 0 ? a.slice(0, eq) : a;
1975
+ if (pkg.includes(name)) {
1976
+ const spec = eq > 0 ? a.slice(eq + 1) : rest[i + 1];
1977
+ return spec ? { spec, python } : null;
1978
+ }
1979
+ if (a.startsWith("-")) {
1980
+ if (eq < 0 && valued.includes(name)) i++;
1981
+ continue;
1982
+ }
1983
+ return { spec: a, python };
766
1984
  }
767
1985
  return null;
768
1986
  }
769
1987
 
1988
+ // Package names as the registries allow them. The name goes into the fix a
1989
+ // report gives, such as "npm view NAME version", so anything else, such as
1990
+ // "x; curl ... | bash" in a hostile project's args, isn't treated as a package.
1991
+ const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._~-]{0,100}\/)?[a-z0-9][a-z0-9._~-]{0,213}$/i;
1992
+ const PYTHON_NAME = /^[a-z0-9](?:[a-z0-9._-]{0,200}[a-z0-9])?$/i;
1993
+
770
1994
  function judgeSpec(spec, python) {
771
1995
  if (!spec) return null;
1996
+ // Local paths and URLs, such as ./server or git+https://..., aren't from a registry.
1997
+ if (/^(\.|\/|~|%|\$|[a-z][a-z0-9+.-]*:)/i.test(spec) || spec.includes("\\")) return null;
772
1998
  if (python) {
773
- const name = spec.split(/[=@<>~!\[]/)[0];
774
- return { name, spec, pinned: /==\s*\d|@\s*\d/.test(spec), python: true };
1999
+ const name = spec.split(/[=@<>~!\[]/)[0].trim();
2000
+ if (!PYTHON_NAME.test(name)) return null;
2001
+ const exact = spec.match(/(?:==|@)\s*(\d+(?:\.\d+){1,3})\s*$/);
2002
+ return { name, spec, pinned: /==\s*\d|@\s*\d/.test(spec), python: true, version: exact ? exact[1] : "" };
775
2003
  }
776
- if (/^(\.|\/|[a-z]+:|~)/i.test(spec)) return null; // local path or URL
777
2004
  const at = spec.lastIndexOf("@");
778
2005
  const name = at > 0 ? spec.slice(0, at) : spec;
2006
+ if (!NPM_NAME.test(name)) return null;
779
2007
  const version = at > 0 ? spec.slice(at + 1) : "";
780
- return { name, spec, pinned: /^\d+\.\d+\.\d+([-+][\w.]+)?$/.test(version) };
2008
+ const pinned = /^\d+\.\d+\.\d+([-+][\w.]+)?$/.test(version);
2009
+ return { name, spec, pinned, version: pinned ? version : "" };
781
2010
  }
782
2011
 
2012
+ // The Docker option that gives a container control of the host, as
2013
+ // { flag, arg }. `flag` is a fixed description such as "--network=host" or
2014
+ // "-v ~", so the folder names in the real option never reach a report.
783
2015
  function dockerRisk(args) {
784
2016
  for (let i = 0; i < args.length; i++) {
785
2017
  const a = args[i];
786
2018
  const next = args[i + 1] ?? "";
787
- if (/^--privileged$/i.test(a)) return a;
788
- if (/^--(pid|network|net|ipc|uts)=host$/i.test(a)) return a;
789
- if (/^--(pid|network|net|ipc|uts)$/i.test(a) && next === "host") return `${a} host`;
790
- if (/^--cap-add=(ALL|SYS_ADMIN)$/i.test(a)) return a;
791
- if (a === "--cap-add" && /^(ALL|SYS_ADMIN)$/i.test(next)) return `${a} ${next}`;
2019
+ if (/^--privileged$/i.test(a)) return { flag: "--privileged", arg: a };
2020
+ let m = a.match(/^--(pid|network|net|ipc|uts)=host$/i) ?? (next === "host" ? a.match(/^--(pid|network|net|ipc|uts)$/i) : null);
2021
+ if (m) return { flag: `--${m[1].toLowerCase() === "net" ? "network" : m[1].toLowerCase()}=host`, arg: a };
2022
+ m = a.match(/^--cap-add=(ALL|SYS_ADMIN)$/i) ?? (a === "--cap-add" ? next.match(/^(ALL|SYS_ADMIN)$/i) : null);
2023
+ if (m) return { flag: `--cap-add=${m[1].toUpperCase()}`, arg: a };
792
2024
  const volume = a === "-v" || a === "--volume" ? next : a.startsWith("--volume=") ? a.slice(9) : null;
793
2025
  const mount = a === "--mount" ? next : a.startsWith("--mount=") ? a.slice(8) : null;
794
2026
  const source = volume ? mountSource(volume) : mount ? (mount.match(/(?:^|,)(?:source|src)=([^,]+)/)?.[1] ?? "") : null;
795
- if (source && (isBroadPath(source) || /docker\.sock|docker_engine/i.test(source))) return `${a === "--mount" || a.startsWith("--mount") ? "--mount" : "-v"} ${volume ?? mount}`;
2027
+ const label = source ? hostPathLabel(source) : null;
2028
+ if (label) return { flag: `${mount !== null ? "--mount" : "-v"} ${label}`, arg: a };
796
2029
  }
797
2030
  return null;
798
2031
  }
799
2032
 
2033
+ // "/", "~", "/etc", "C:\" or the Docker socket, for a mount source that
2034
+ // exposes the host. Null for anything narrower.
2035
+ function hostPathLabel(source) {
2036
+ if (/docker\.sock|docker_engine/i.test(source)) return "/var/run/docker.sock";
2037
+ if (!isBroadPath(source)) return null;
2038
+ const v = trimWord(String(source).trim().replace(/\\/g, "/"), "", "/");
2039
+ if (v === "") return "/";
2040
+ if (/^[A-Za-z]:$/.test(v)) return `${v.toUpperCase()}\\`;
2041
+ const system = v.match(/^\/(root|etc|var|opt|usr)$/i);
2042
+ return system ? `/${system[1].toLowerCase()}` : "~";
2043
+ }
2044
+
800
2045
  function mountSource(volume) {
801
2046
  const win = volume.match(/^([A-Za-z]:[\\/][^:]*)/);
802
2047
  return win ? win[1] : volume.split(":")[0];
@@ -805,7 +2050,7 @@ function mountSource(volume) {
805
2050
  export function isBroadPath(value) {
806
2051
  const raw = String(value).trim();
807
2052
  if (raw === "/" || raw === "\\") return true;
808
- const v = raw.replace(/\\/g, "/").replace(/\/+$/, "");
2053
+ const v = trimWord(raw.replace(/\\/g, "/"), "", "/");
809
2054
  return (
810
2055
  /^(~|\$HOME|\$\{HOME\}|%USERPROFILE%|%HOMEPATH%|\$env:USERPROFILE|[A-Za-z]:)$/i.test(v) ||
811
2056
  /^\/(Users|home)(\/[^/]+)?$/i.test(v) ||
@@ -814,20 +2059,31 @@ export function isBroadPath(value) {
814
2059
  );
815
2060
  }
816
2061
 
817
- // --- Workspace -------------------------------------------------------------------
2062
+ // Folder names the checks write the usual way, such as Downloads.
2063
+ const FOLDER_NAMES = { downloads: "Downloads", download: "Downloads", desktop: "Desktop", temp: "Temp", tmp: "tmp" };
2064
+ const folderName = (name) => FOLDER_NAMES[String(name).toLowerCase()] ?? String(name);
2065
+
2066
+ // A folder agents read their settings from, such as .claude or .cursor/rules.
2067
+ const agentFolder = (p) => typeof p === "string" && TOOL_ROOT.test(p.split("/")[0]) && p.split("/").length <= 4;
2068
+
2069
+ // --- Workspace ---------------------------------------------------------------
818
2070
 
819
2071
  function checkWorkspace(ctx) {
820
2072
  const root = ctx.root ?? "";
821
- const markers = HOME_MARKERS.filter((m) => ctx.shape.topLevel.includes(m));
822
- const homeLike = markers.length >= 3;
2073
+ const markers = [...HOME_MARKERS].filter((m) => ctx.shape.topLevel.includes(m));
2074
+ const homeLike = ctx.homeLike;
823
2075
  const downloadsLike = DOWNLOADS_LIKE.test(root);
824
2076
 
825
- if (homeLike) add(ctx, "WS-HOME", { vars: { markers: listNames(markers.filter((m) => m.startsWith(".") || m === "AppData").concat(markers).slice(0, 3)) } });
826
- if (downloadsLike) add(ctx, "WS-DOWNLOADS", { vars: { root } });
2077
+ // The command in a home folder with --project-only checks the folder
2078
+ // someone opens agents in. Run in the home folder as a
2079
+ // whole, the command only says where it ran, and the agents' own settings
2080
+ // say whether they were started there.
2081
+ if (homeLike && !ctx.ranInHome) add(ctx, "WS-HOME", { vars: { markers: listNames(markers.filter((m) => m.startsWith(".") || m === "AppData").concat(markers).slice(0, 3)) } });
2082
+ if (downloadsLike) add(ctx, "WS-DOWNLOADS", { vars: { root: folderName(root) } });
827
2083
 
828
2084
  if (downloadsLike) {
829
2085
  const steering = ctx.files.filter((f) => f.content && (f.kind || f.loose) && isInstructionFile(f) && (!f.loose || steers(ctx, f)));
830
- if (steering.length) add(ctx, "WS-POISON-RISK", { vars: { files: listNames(steering.map((f) => f.path), 3), place: `your ${root} folder` } });
2086
+ if (steering.length) add(ctx, "WS-POISON-RISK", { vars: { files: listNames(steering.map((f) => f.path), 3), place: `your ${folderName(root)} folder` } });
831
2087
  }
832
2088
 
833
2089
  const looseByDir = new Map();
@@ -845,12 +2101,12 @@ function checkWorkspace(ctx) {
845
2101
 
846
2102
  if (ctx.shape.gitRepos >= 3) add(ctx, "WS-MULTI-REPO", { vars: { count: ctx.shape.gitRepos } });
847
2103
 
848
- const sensitive = ctx.files.filter((f) => f.sensitive && !EXAMPLE_ENV.test(f.path));
2104
+ const sensitive = ctx.files.filter((f) => f.sensitive && !EXAMPLE_ENV.test(f.path) && !isCertificate(f.path) && !USUALLY_HARMLESS.test(f.path));
849
2105
  const keys = sensitive.filter((f) => KEY_FILE.test(f.path));
850
2106
  const others = sensitive.filter((f) => !KEY_FILE.test(f.path));
851
2107
  if (keys.length) add(ctx, "WS-KEYS", { vars: { files: listNames(keys.map((f) => f.path), 4) } });
852
2108
  if (others.length) {
853
- const denied = (f) => ctx.claudeDeny.some((d) => denyCovers(d, f.path));
2109
+ const denied = (f) => ctx.claudeDeny.some((d) => denyCovers(d, f.path, ctx.ignoreBudget));
854
2110
  const exposed = others.filter((f) => !denied(f));
855
2111
  if (ctx.claudeSettingsFiles.length && exposed.length) {
856
2112
  add(ctx, "CC-NO-SECRET-DENY", { file: ctx.claudeSettingsFiles[0], vars: { files: listNames(exposed.map((f) => f.path), 4) } });
@@ -861,32 +2117,58 @@ function checkWorkspace(ctx) {
861
2117
 
862
2118
  const gitignore = ctx.files.find((f) => f.path === ".gitignore" && f.content);
863
2119
  if (ctx.shape.rootGit) {
864
- const envFiles = others.filter((f) => /(^|\/)\.env(\.|$)/i.test(f.path));
865
- if (envFiles.length && !(gitignore && /^\s*\/?(\*\*\/)?(\.env\b|\.env\*|\*\.env)/m.test(gitignore.content))) {
866
- add(ctx, "WS-ENV-COMMITTED", { file: gitignore ?? null, vars: { files: listNames(envFiles.map((f) => f.path), 3) } });
867
- }
868
- const local = ctx.files.filter((f) => /(^|\/)(\.claude\/settings\.local\.json|claude\.local\.md)$/i.test(f.path));
869
- const ignored = (f) => gitignore && (gitignore.content.includes(f.path) || gitignore.content.includes(f.path.split("/").pop()));
870
- const exposedLocal = local.filter((f) => !ignored(f));
871
- if (exposedLocal.length) add(ctx, "WS-LOCAL-SETTINGS", { file: gitignore ?? null, vars: { files: listNames(exposedLocal.map((f) => f.path), 3) } });
2120
+ const rules = gitIgnoreRules(ctx);
2121
+ const exposed = (list) => list.filter((f) => !isIgnored(rules, f.path, ctx.ignoreBudget));
2122
+ const envFiles = exposed(others.filter((f) => /(^|\/)\.env(\.|$)/i.test(f.path)));
2123
+ if (envFiles.length) add(ctx, "WS-ENV-COMMITTED", { file: gitignore ?? null, vars: { files: listNames(envFiles.map((f) => f.path), 3) } });
2124
+ const local = exposed(ctx.files.filter((f) => /(^|\/)(\.claude\/settings\.local\.json|claude\.local\.md)$/i.test(f.path)));
2125
+ if (local.length) add(ctx, "WS-LOCAL-SETTINGS", { file: gitignore ?? null, vars: { files: listNames(local.map((f) => f.path), 3) } });
872
2126
  }
873
2127
 
874
- const tooLarge = ctx.files.filter((f) => f.tooLarge);
875
- if (tooLarge.length) add(ctx, "WS-TOO-LARGE", { vars: { count: tooLarge.length } });
2128
+ for (const f of ctx.files.filter((x) => x.tooLarge && x.kind).slice(0, 5)) add(ctx, "WS-TOO-LARGE", { file: f });
2129
+ for (const f of ctx.files.filter((x) => x.partial && !x.tooLarge && x.kind).slice(0, 5)) add(ctx, "WS-PARTLY-CHECKED", { file: f });
2130
+ 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 });
2131
+ 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 });
2132
+ }
2133
+
2134
+ // Ignore rules for the project, lowest precedence first: git's global list,
2135
+ // .git/info/exclude, then .gitignore files from the top folder down.
2136
+ function gitIgnoreRules(ctx) {
2137
+ const rules = ctx.ignoreLists.flatMap((text) => ignoreRules(text, ""));
2138
+ const files = ctx.files
2139
+ .filter((f) => f.content && /(^|\/)\.gitignore$/.test(f.path) && !/^(~|\/|[A-Za-z]:)/.test(f.path))
2140
+ .sort((a, b) => a.path.split("/").length - b.path.split("/").length);
2141
+ for (const f of files) rules.push(...ignoreRules(f.content, f.path.includes("/") ? f.path.slice(0, f.path.lastIndexOf("/")) : ""));
2142
+ return rules;
876
2143
  }
877
2144
 
878
- function denyCovers(rule, path) {
879
- const m = rule.match(/^Read\((.+)\)$/i);
2145
+ // Whether a Read(...) deny rule in Claude Code settings covers a project file.
2146
+ // The patterns follow .gitignore syntax: "//" starts an absolute path, "~/"
2147
+ // the home folder, "/" and "./" the project, and a bare name matches at any
2148
+ // depth. A rule outside the project covers it only through **, as in ~/**/.env.
2149
+ const denyCache = new Map();
2150
+ function denyCovers(rule, path, budget) {
2151
+ const m = /^Read\((.+)\)$/i.exec(rule.trim());
880
2152
  if (!m) return false;
881
- const pattern = m[1].trim().replace(/^\.\//, "");
882
- if (pattern === "**" || pattern === "./**") return true;
883
- const name = path.split("/").pop();
884
- const toRegex = (glob) => new RegExp("^" + glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\/?/g, "§").replace(/\*/g, "[^/]*").replace(/§/g, ".*") + "$", "i");
885
- try {
886
- return toRegex(pattern).test(path) || toRegex(pattern).test(name);
887
- } catch {
888
- return false;
2153
+ let pattern = m[1].trim();
2154
+ if (/^(?:\/\/|~\/)/.test(pattern)) {
2155
+ pattern = pattern.replace(/^(?:\/\/|~\/)/, "");
2156
+ if (!pattern.startsWith("**")) return false;
889
2157
  }
2158
+ pattern = pattern.replace(/^\.\//, "/");
2159
+ if (!denyCache.has(pattern)) {
2160
+ if (denyCache.size > 500) denyCache.clear();
2161
+ denyCache.set(pattern, ignoreRules(pattern));
2162
+ }
2163
+ return isIgnored(denyCache.get(pattern), path, budget);
2164
+ }
2165
+
2166
+ // A plugin's plugin.json that sets no hooks or MCP servers only names the
2167
+ // plugin. The plugin's skills, commands and agents are listed on their own.
2168
+ function emptyManifest(ctx, f) {
2169
+ if (!/(^|\/)\.claude-plugin\/plugin\.json$/i.test(f.path) || !f.content) return false;
2170
+ const json = parsed(f);
2171
+ return isObj(json) && json.hooks == null && json.mcpServers == null && !ctx.findings.some((x) => x.file === f.path);
890
2172
  }
891
2173
 
892
2174
  // A loose file counts as steering an agent only when it reads like orders to
@@ -914,24 +2196,486 @@ function walk(obj, visit, depth = 0) {
914
2196
  }
915
2197
  }
916
2198
 
917
- // --- Sprawl ------------------------------------------------------------------------
2199
+ // --- Sprawl ------------------------------------------------------------------
918
2200
 
2201
+ // Instruction files at the top of the project that different agents read
2202
+ // first, counting a rules folder once. A short file that only points to
2203
+ // another, such as a CLAUDE.md that says "@AGENTS.md", and an exact copy or
2204
+ // link of another file, don't count.
919
2205
  function checkSprawl(ctx) {
920
- 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));
921
- const tools = new Set(steering.flatMap((f) => f.tools));
922
- if (steering.length >= 4 && tools.size >= 3) {
923
- add(ctx, "SPRAWL", { vars: { count: steering.length, list: listNames(steering.map((f) => f.path), 4) } });
2206
+ const entries = new Map();
2207
+ const seen = new Set();
2208
+ for (const f of ctx.files) {
2209
+ if (!f.content || !f.kind || f.loose || !isInstructionFile(f) || /^(~|\/|[A-Za-z]:)/.test(f.path)) continue;
2210
+ const key = entryPoint(f.path);
2211
+ if (!key || seen.has(f.content) || pointsElsewhere(f.content)) continue;
2212
+ seen.add(f.content);
2213
+ if (!entries.has(key)) entries.set(key, new Set());
2214
+ for (const t of f.tools) entries.get(key).add(t);
924
2215
  }
2216
+ const tools = new Set([...entries.values()].flatMap((t) => [...t]));
2217
+ if (entries.size >= 3 && tools.size >= 3) add(ctx, "SPRAWL", { vars: { count: entries.size, list: listNames([...entries.keys()], 4) } });
2218
+ }
2219
+
2220
+ function entryPoint(path) {
2221
+ if (!path.includes("/")) return path;
2222
+ if (/^\.github\/copilot-instructions\.md$/i.test(path)) return path;
2223
+ if (/^\.roo\/rules[^/]*\//i.test(path)) return ".roo/rules/";
2224
+ const folder = path.match(/^(\.clinerules|\.cursor\/rules|\.windsurf\/rules|\.kiro\/steering|\.amazonq\/rules|\.github\/instructions|\.claude\/rules|\.continue\/rules|\.junie)\//i);
2225
+ return folder ? `${folder[1]}/` : null;
2226
+ }
2227
+
2228
+ const pointsElsewhere = (text) => {
2229
+ const t = text.trim();
2230
+ return t.length < 300 && /(^|\s)@\S+\.md\b|\b(?:AGENTS|CLAUDE|GEMINI|README)\.md\b/i.test(t);
2231
+ };
2232
+
2233
+ // --- Installed code ----------------------------------------------------------
2234
+ //
2235
+ // MCP packages, editor extensions, agent installs, skills and files attacks
2236
+ // leave behind, checked against known.js with no network requests. With
2237
+ // --lookup, the command adds OSV.dev's answers afterwards (applyLookup).
2238
+
2239
+ const TRACE_PATHS = new Set(TRACES.flatMap((t) => t.paths));
2240
+ const EDITORS = new Set(["VS Code", "VS Code Insiders", "VSCodium", "Cursor", "Windsurf", "Kiro"]);
2241
+ const EXT_ID = /^[a-z0-9][a-z0-9-]{0,99}\.[a-z0-9][a-z0-9._-]{0,99}$/i;
2242
+ // How an agent was installed, in words.
2243
+ 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" };
2244
+ const INSTALL_VIA = new Set(Object.keys(INSTALLED_BY));
2245
+ const PLATFORMS = new Set(["mac", "windows", "linux"]);
2246
+ const cleanVersion = (v) => (typeof v === "string" && VERSION_RE.test(v) ? v.replace(/^v/, "") : "");
2247
+
2248
+ function installsFrom(list) {
2249
+ return (Array.isArray(list) ? list : [])
2250
+ .slice(0, 200)
2251
+ .filter((i) => isObj(i) && typeof i.package === "string" && (Object.hasOwn(AGENT_PACKAGES, i.package) || knownPackage("npm", i.package)))
2252
+ .filter((i) => cleanVersion(i.version) && INSTALL_VIA.has(i.via) && typeof i.path === "string" && cleanPath(i.path))
2253
+ .map((i) => ({ package: i.package, version: cleanVersion(i.version), via: i.via, path: cleanPath(i.path), platform: PLATFORMS.has(i.platform) ? i.platform : null }));
925
2254
  }
926
2255
 
927
- // --- Score -------------------------------------------------------------------------
2256
+ // Versions pinned in the project's lockfile, by name and version. Only known
2257
+ // lockfile names and packages known.js lists get through.
2258
+ export const LOCKFILES = new Set(["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock"]);
2259
+ function lockedFrom(list) {
2260
+ return (Array.isArray(list) ? list : [])
2261
+ .slice(0, 500)
2262
+ .filter((l) => isObj(l) && LOCKFILES.has(l.file) && typeof l.package === "string" && knownPackage("npm", l.package) && cleanVersion(l.version))
2263
+ .map((l) => ({ file: l.file, package: l.package, version: cleanVersion(l.version) }));
2264
+ }
2265
+
2266
+ function extensionsFrom(list) {
2267
+ return (Array.isArray(list) ? list : [])
2268
+ .slice(0, 12)
2269
+ .filter((g) => isObj(g) && EDITORS.has(g.editor) && typeof g.dir === "string" && cleanPath(g.dir))
2270
+ .map((g) => ({
2271
+ editor: g.editor,
2272
+ dir: cleanPath(g.dir),
2273
+ items: (Array.isArray(g.items) ? g.items : [])
2274
+ .slice(0, 3000)
2275
+ .filter((x) => isObj(x) && typeof x.id === "string" && EXT_ID.test(x.id))
2276
+ .map((x) => ({
2277
+ id: x.id.toLowerCase(),
2278
+ // The ID with the capitals its publisher gave it, which OSV.dev
2279
+ // needs to find the extension. Only the same ID is accepted.
2280
+ published: typeof x.published === "string" && EXT_ID.test(x.published) && x.published.toLowerCase() === x.id.toLowerCase() ? x.published : null,
2281
+ version: cleanVersion(x.version),
2282
+ source: x.source === "vsix" || x.source === "gallery" ? x.source : null,
2283
+ })),
2284
+ }));
2285
+ }
2286
+ // Where each editor installs extensions from, as OSV.dev names it.
2287
+ const OPEN_VSX = "VSCode:https://open-vsx.org";
2288
+ const extensionRegistry = (editor) => (OPEN_VSX_EDITORS.includes(editor) ? OPEN_VSX : "VSCode");
2289
+
2290
+ // The name known.js lists a package under: Python names are compared the way
2291
+ // PyPI compares them.
2292
+ const knownName = (ecosystem, name) => (ecosystem === "PyPI" ? String(name).toLowerCase().replace(/[-_.]+/g, "-") : String(name));
2293
+ const knownPackage = (ecosystem, name) => {
2294
+ const key = `${ecosystem}:${knownName(ecosystem, name)}`;
2295
+ return Object.hasOwn(KNOWN_PACKAGES, key) ? KNOWN_PACKAGES[key] : null;
2296
+ };
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;
2348
+ }
2349
+ return null;
2350
+ }
2351
+
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: extensionRegistry(group.editor), name: x.published ?? x.id, version: x.version || null, where: `Installed as a ${group.editor} extension`, file: group.dir, via: "extension" });
2423
+ const known = extensionListing(x.id, group.editor);
2424
+ // A bad build one marketplace served doesn't apply to a copy installed from a file.
2425
+ if (known && (!known.editors || 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, rather
2555
+ // 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
+ function safeSummary(text) {
2594
+ return String(text ?? "")
2595
+ .replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, " ")
2596
+ .replace(/\b(?:[a-z][a-z0-9+.-]*:\/\/|www\.)\S*/gi, "a link")
2597
+ .replace(/[|`$]/g, " ")
2598
+ .replace(/\s+/g, " ")
2599
+ .trim();
2600
+ }
2601
+ export function applyLookup(result, hits) {
2602
+ if (!isObj(result) || !Array.isArray(result.findings)) return result;
2603
+ const packages = Array.isArray(result.packages) ? result.packages.filter(isObj) : [];
2604
+ // Names as the bundled list's findings write them: extension IDs in
2605
+ // lowercase, Python names the way PyPI compares them.
2606
+ const loose = (name) => String(name).toLowerCase().replace(/[-_.]+/g, "-");
2607
+ const flagged = new Set(result.findings.filter((f) => MALWARE_RULES.has(f.id)).map((f) => `${loose(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(`${loose(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
+ // Without a pinned version, a listing that names only some versions,
2632
+ // often of a real package whose account was taken over, says those
2633
+ // versions were malware, not the package.
2634
+ const some = !pkg.version && use.malicious.allVersions !== true;
2635
+ extra.push(makeFinding(some ? "LOOKUP-MALICIOUS-VERSION" : "LOOKUP-MALICIOUS", { file, vars: { ...common, ref: use.malicious.ref } }));
2636
+ continue;
2637
+ }
2638
+ const vulns = [...use.vulns.values()];
2639
+ if (!vulns.length) continue;
2640
+ const rank = (h) => LOOKUP_RANK[h.severity] ?? 1;
2641
+ vulns.sort((a, b) => rank(a) - rank(b));
2642
+ const worst = vulns[0];
2643
+ const one = vulns.length === 1;
2644
+ // The newest fixed version fixes every one that has a fix.
2645
+ const fixes = vulns.map((h) => cleanVersion(h.fixed));
2646
+ const newest = fixes.filter(Boolean).reduce((top, v) => (!top || compareVersions(v, top) > 0 ? v : top), "");
2647
+ const unknown = vulns.some((h) => h.detailed === false);
2648
+ const advice = unknown ? LOOKUP_UNKNOWN : !newest ? LOOKUP_NO_FIX : `Update to ${newest} or later${fixes.every(Boolean) ? "" : LOOKUP_SOME_FIXED}`;
2649
+ const summary = safeSummary(typeof worst.summary === "string" ? worst.summary : "");
2650
+ extra.push(
2651
+ makeFinding(LOOKUP_RULES[rank(worst)], {
2652
+ file,
2653
+ vars: {
2654
+ ...common,
2655
+ vulns: one ? "a published vulnerability" : `${vulns.length} published vulnerabilities`,
2656
+ lead: one ? "The issue" : "The most serious",
2657
+ 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",
2658
+ ref: worst.ref,
2659
+ advice,
2660
+ },
2661
+ }),
2662
+ );
2663
+ }
2664
+ if (!extra.length) return result;
2665
+ const findings = [...result.findings, ...extra].sort(bySeverity);
2666
+ const controlMap = (result.controlMap ?? []).map((f) => ({ ...f, findings: findings.filter((x) => x.file === f.path).length }));
2667
+ const { counts, score, grade } = scoreFindings(findings, controlMap.length > 0);
2668
+ return { ...result, findings, controlMap, counts, score, grade, headline: headlineFor(counts, findings[0], controlMap.length > 0), lookedUp: true };
2669
+ }
2670
+
2671
+ // --- Score -------------------------------------------------------------------
928
2672
 
929
2673
  const bySeverity = (a, b) =>
930
2674
  SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity) || a.category.localeCompare(b.category) || (a.file ?? "").localeCompare(b.file ?? "");
931
2675
 
932
- // Score, grade and counts from a list of findings. Shared by the local check
933
- // and by the Worker when it publishes a shared report.
934
- export function scoreFindings(findings, hasControlFiles) {
2676
+ // Score, grade and counts from a list of findings, for a check and again
2677
+ // after a lookup.
2678
+ function scoreFindings(findings, hasControlFiles) {
935
2679
  const counts = Object.fromEntries(SEVERITIES.map((s) => [s, findings.filter((f) => f.severity === s).length]));
936
2680
  // Repeats of the same rule count less, so one noisy pattern can't zero the score.
937
2681
  const byRule = new Map();
@@ -939,21 +2683,58 @@ export function scoreFindings(findings, hasControlFiles) {
939
2683
  let penalty = 0;
940
2684
  for (const [id, n] of byRule) penalty += WEIGHT[RULES[id].severity] * Math.min(2, 1 + 0.25 * (n - 1));
941
2685
  const score = Math.max(0, Math.min(100, Math.round(100 - penalty)));
942
- let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 65 ? "C" : score >= 50 ? "D" : "F";
2686
+ let grade = GRADES.find(([, min]) => score >= min)?.[0] ?? "F";
943
2687
  if (counts.critical && "ABC".includes(grade)) grade = "D";
944
2688
  if (!hasControlFiles && !findings.length) grade = "–";
945
2689
  return { counts, score: grade === "–" ? null : score, grade };
946
2690
  }
947
2691
 
2692
+ // What each rule's findings take off the score, most first: the order to fix
2693
+ // things in. The points are the same ones scoreFindings counts.
2694
+ export function pointsOff(findings) {
2695
+ const byRule = new Map();
2696
+ for (const f of findings) {
2697
+ if (!Object.hasOwn(RULES, f.id)) continue;
2698
+ const entry = byRule.get(f.id) ?? { id: f.id, severity: RULES[f.id].severity, findings: [] };
2699
+ entry.findings.push(f);
2700
+ byRule.set(f.id, entry);
2701
+ }
2702
+ const rules = [...byRule.values()].map((r) => ({ ...r, points: WEIGHT[r.severity] * Math.min(2, 1 + 0.25 * (r.findings.length - 1)) }));
2703
+ rules.sort((a, b) => b.points - a.points || SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity));
2704
+ return { rules: rules.filter((r) => r.points > 0), total: rules.reduce((sum, r) => sum + r.points, 0) };
2705
+ }
2706
+
948
2707
  function agentsIn(controlMap) {
949
- // Agents with their own config files. AGENTS.md alone doesn't mean an agent is in use.
950
- const specific = controlMap.filter((f) => !/(^|\/)agents(\.override)?\.md$/i.test(f.path));
2708
+ // Agents with files of their own. A file several agents read, such as
2709
+ // AGENTS.md or .mcp.json, doesn't show that each of them is in use.
2710
+ const specific = controlMap.filter((f) => f.tools.length === 1);
951
2711
  return [...new Set((specific.length ? specific : controlMap).flatMap((f) => f.tools))].filter((t) => t !== "Any agent started there" && t !== "Your shell");
952
2712
  }
953
2713
 
2714
+ function explainSafely(f, ctx) {
2715
+ try {
2716
+ 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) });
2717
+ } catch {
2718
+ return { scope: scopeOf(f), summary: "Couldn't be summarized.", details: [] };
2719
+ }
2720
+ }
2721
+
954
2722
  function summarize(ctx) {
955
2723
  const findings = ctx.findings.sort(bySeverity);
956
- const controlFiles = ctx.files.filter((f) => f.kind && (!f.loose || steers(ctx, f)) && (f.kind !== "Shell profile" || !f.content || agentLines(f).length));
2724
+ // Plugin code is listed by name, never read, but it controls the agent
2725
+ // that loads it, so it's in the map.
2726
+ const controlFiles = ctx.files.filter(
2727
+ (f) =>
2728
+ f.kind &&
2729
+ (!f.listed || f.kind === "Plugin code") &&
2730
+ (!f.loose || steers(ctx, f)) &&
2731
+ (f.kind !== "Shell profile" || !f.content || agentLines(f).length) &&
2732
+ !emptyManifest(ctx, f),
2733
+ );
2734
+ // Each agent's files together, agents in the order they were first found.
2735
+ const firstSeen = new Map();
2736
+ for (const f of controlFiles) if (!firstSeen.has(f.tools.join())) firstSeen.set(f.tools.join(), firstSeen.size);
2737
+ controlFiles.sort((a, b) => firstSeen.get(a.tools.join()) - firstSeen.get(b.tools.join()));
957
2738
  const { counts, score, grade } = scoreFindings(findings, controlFiles.length > 0);
958
2739
  const toolNames = agentsIn(controlFiles);
959
2740
  const headline = headlineFor(counts, findings[0], controlFiles.length > 0);
@@ -969,8 +2750,8 @@ function summarize(ctx) {
969
2750
  findings,
970
2751
  categories: CATEGORIES,
971
2752
  tools: toolNames,
972
- // What each file tells its agents, worked out here and shown only here:
973
- // the share payload keeps just the path.
2753
+ // What each file tells its agents, worked out here, for --explain and
2754
+ // the page --open saves.
974
2755
  controlMap: controlFiles.map((f) => ({
975
2756
  path: f.path,
976
2757
  kind: f.kind,
@@ -978,91 +2759,42 @@ function summarize(ctx) {
978
2759
  size: f.size,
979
2760
  lines: f.lines ? f.lines.length : null,
980
2761
  findings: findings.filter((x) => x.file === f.path).length,
981
- ...explainFile(f, { json: f.content && /\.(jsonc?|toml)$/i.test(f.path) ? parsed(f) : null, servers: ctx.mcpServers.filter((s) => s.file === f) }),
2762
+ ...(f.listed ? { listed: true } : {}),
2763
+ ...explainSafely(f, ctx),
982
2764
  })),
983
2765
  stats: {
984
- filesChecked: ctx.files.filter((f) => f.content).length,
2766
+ // Agent files read and checked. Files read only for a check, such as
2767
+ // .gitignore, and plugin code, which is listed, aren't counted.
2768
+ filesChecked: controlFiles.filter((f) => f.content).length,
985
2769
  secretFilesListed: ctx.files.filter((f) => f.sensitive).length,
986
2770
  maskedInBrowser: ctx.maskedInBrowser,
987
2771
  mcpServers: ctx.mcpServers.length,
988
2772
  entriesScanned: ctx.shape.entries,
989
2773
  truncated: ctx.shape.truncated,
2774
+ agentInstalls: ctx.installs.filter((i) => Object.hasOwn(AGENT_PACKAGES, i.package)).length,
2775
+ extensions: ctx.extensions.reduce((n, g) => n + g.items.length, 0),
990
2776
  },
2777
+ // What's installed, for --explain, --open and --lookup.
2778
+ installed: {
2779
+ 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 })),
2780
+ editors: ctx.extensions.map((g) => ({
2781
+ editor: g.editor,
2782
+ dir: g.dir,
2783
+ count: g.items.length,
2784
+ agents: g.items.filter((x) => Object.hasOwn(AGENT_EXTENSIONS, x.id)).map((x) => ({ name: AGENT_EXTENSIONS[x.id], id: x.id, version: x.version })),
2785
+ })),
2786
+ },
2787
+ packages: ctx.packages.slice(0, 2000),
991
2788
  };
992
2789
  }
993
2790
 
994
- // --- Sharing -------------------------------------------------------------------------
995
-
996
- // What leaves the computer when someone chooses to share: rule IDs, file names,
997
- // line numbers and the non-private details. No file contents, no evidence lines,
998
- // nothing that quotes a file or reveals a local path.
999
- export function toShareable(result) {
1000
- return {
1001
- version: result.version,
1002
- findings: result.findings.map((f) => ({
1003
- id: f.id,
1004
- file: f.file,
1005
- line: f.line,
1006
- // The file name travels once, as file; the report rebuilds the rest.
1007
- vars: Object.fromEntries(
1008
- Object.entries(f.vars ?? {})
1009
- .filter(([k]) => k !== "file" && !PRIVATE_VARS.has(k))
1010
- .map(([k, v]) => [k, k === "where" ? hideNames(v) : v]),
1011
- ),
1012
- })),
1013
- controlMap: result.controlMap.map((f) => f.path),
1014
- stats: { filesChecked: result.stats.filesChecked, mcpServers: result.stats.mcpServers },
1015
- };
1016
- }
1017
-
1018
- // Rebuilds a public report from a shareable payload. Every title and sentence
1019
- // comes from the rule catalog, so a shared page can only say what a real check
1020
- // would say. Unknown rules and oversized values are dropped.
1021
- export function publicReportFrom(payload) {
1022
- if (!isObj(payload) || !Array.isArray(payload.findings) || !Array.isArray(payload.controlMap)) return null;
1023
- const safe = (v, n = 120) => String(v ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, n);
1024
- // Shared reports cover a project, so only paths inside one are kept.
1025
- const projectPath = (p) => {
1026
- const clean = cleanPath(String(p));
1027
- return clean && !/^(\/|~|[A-Za-z]:)/.test(clean) ? clean : null;
1028
- };
1029
- const paths = [...new Set(payload.controlMap.slice(0, 300).map(projectPath).filter(Boolean))];
1030
- const findings = payload.findings
1031
- .slice(0, 400)
1032
- .filter((f) => isObj(f) && RULES[f.id] && (f.file == null || projectPath(f.file)))
1033
- .map((f) => {
1034
- const rule = RULES[f.id];
1035
- const allowed = new Set([...`${rule.title} ${rule.why} ${rule.fix}`.matchAll(/\{(\w+)\}/g)].map((m) => m[1]));
1036
- const vars = {};
1037
- for (const [k, v] of Object.entries(isObj(f.vars) ? f.vars : {})) if (allowed.has(k) && !PRIVATE_VARS.has(k)) vars[k] = safe(k === "where" ? hideNames(v) : v);
1038
- const file = typeof f.file === "string" ? projectPath(f.file) : null;
1039
- vars.file = file ?? "";
1040
- const control = file ? controlFor(file) : null;
1041
- return publicFinding({
1042
- id: f.id,
1043
- severity: rule.severity,
1044
- category: rule.category,
1045
- tool: rule.tool ?? control?.tools?.[0] ?? (typeof vars.tool === "string" && vars.tool) ?? null,
1046
- file,
1047
- line: Number.isInteger(f.line) && f.line > 0 && f.line < 1e7 ? f.line : null,
1048
- vars,
1049
- });
1050
- })
1051
- .sort(bySeverity);
1052
- const controlMap = paths
1053
- .map((path) => ({ path, ...(controlFor(path) ?? { tools: ["Any agent started there"], kind: "Loose file" }) }))
1054
- .map((f) => ({ ...f, findings: findings.filter((x) => x.file === f.path).length }));
1055
- const { counts, score, grade } = scoreFindings(findings, controlMap.length > 0);
1056
- const stats = isObj(payload.stats) ? payload.stats : {};
1057
- return {
1058
- version: safe(payload.version, 20),
1059
- score,
1060
- grade,
1061
- headline: headlineFor(counts, findings[0], controlMap.length > 0),
1062
- counts,
1063
- tools: agentsIn(controlMap),
1064
- stats: { filesChecked: toInt(stats.filesChecked), mcpServers: toInt(stats.mcpServers) },
1065
- findings,
1066
- controlMap,
1067
- };
2791
+ // --- Today's list ------------------------------------------------------------------
2792
+ //
2793
+ // Adds the malware misconfig.ai lists since this release (addKnownMalware in
2794
+ // known.js). Call it before a check; calling it again with a newer list
2795
+ // replaces what the last one added. Returns when the list was made and how
2796
+ // many entries it holds, or null when it isn't a list.
2797
+ export function useKnownMalware(feed) {
2798
+ const added = addKnownMalware(feed);
2799
+ return added ? { updated: added.updated, packages: added.packages.length, extensions: added.extensions.length } : null;
1068
2800
  }