@misconfig/cli 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1055 @@
1
+ // misconfig.ai rule engine. Runs only in the Worker, never in the browser.
2
+
3
+ import { maskSecrets, looksLikeSecret, looksLikeToken, isMasked, isPathLike, describeMasks } from "./mask.js";
4
+ import { parseJSONC, parseTOML } from "./parse.js";
5
+ import { RULES, CATEGORIES } from "./catalog.js";
6
+
7
+ export const RULESET_VERSION = "2026.11.2";
8
+
9
+ const WEIGHT = { critical: 30, high: 15, medium: 6, low: 2, info: 0 };
10
+ const SEVERITIES = ["critical", "high", "medium", "low", "info"];
11
+ const MAX_FILE_CHARS = 450_000;
12
+
13
+ // Which agents read which files. Used for the control map and attribution.
14
+ const CONTROL = [
15
+ [/(^|\/)claude(\.local)?\.md$/i, ["Claude Code"], "Instructions"],
16
+ [/(^|\/)\.codex\/agents(\.override)?\.md$/i, ["Codex"], "Instructions"],
17
+ [/(^|\/)\.config\/opencode\/agents\.md$/i, ["OpenCode"], "Instructions"],
18
+ [/(^|\/)agents(\.override)?\.md$/i, ["Codex", "OpenCode", "Cursor", "GitHub Copilot", "Zed"], "Instructions"],
19
+ [/(^|\/)gemini\.md$/i, ["Gemini CLI"], "Instructions"],
20
+ [/(^|\/)\.claude\/settings(\.local)?\.json$/i, ["Claude Code"], "Permissions & hooks"],
21
+ [/(^|\/)managed-settings\.json$/i, ["Claude Code"], "Admin policy"],
22
+ [/(^|\/)claude_desktop_config\.json$/i, ["Claude Desktop"], "MCP servers"],
23
+ [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User\/settings\.json$/i, (p) => [editorTool(p)], "Editor settings"],
24
+ [/(^|\/)(Code|Code - Insiders|VSCodium|Cursor)\/User\/mcp\.json$/i, (p) => [editorTool(p)], "MCP servers"],
25
+ [/(^|\/)saoudrizwan\.claude-dev\/settings\/cline_mcp_settings\.json$/i, ["Cline"], "MCP servers"],
26
+ [/(^|\/)rooveterinaryinc\.roo-cline\/settings\/mcp_settings\.json$/i, ["Roo Code"], "MCP servers"],
27
+ [/(^|\/)\.codeium\/windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
28
+ [/(^|\/)(\.bashrc|\.zshrc|\.bash_profile|\.profile|\.zprofile|config\.fish|[^/]*profile\.ps1)$/i, ["Your shell"], "Shell profile"],
29
+ [/(^|\/)\.claude\/hooks\//i, ["Claude Code"], "Hook script"],
30
+ [/(^|\/)\.claude\/(commands|agents|skills|output-styles)\//i, ["Claude Code"], "Commands & agents"],
31
+ [/(^|\/)\.mcp\.json$/i, ["Claude Code"], "MCP servers"],
32
+ [/(^|\/)\.claude\.json$/i, ["Claude Code"], "User config"],
33
+ [/(^|\/)\.codex\/config\.toml$/i, ["Codex"], "Permissions & MCP"],
34
+ [/(^|\/)\.codex\/.+\.md$/i, ["Codex"], "Prompts"],
35
+ [/(^|\/)\.cursor\/mcp\.json$/i, ["Cursor"], "MCP servers"],
36
+ [/(^|\/)\.cursor\/.+\.mdc?$/i, ["Cursor"], "Rules"],
37
+ [/(^|\/)\.cursorrules$/i, ["Cursor"], "Rules (legacy)"],
38
+ [/(^|\/)\.github\/copilot-instructions\.md$/i, ["GitHub Copilot"], "Instructions"],
39
+ [/(^|\/)\.github\/(instructions|prompts|chatmodes|agents)\//i, ["GitHub Copilot"], "Instructions & prompts"],
40
+ [/(^|\/)\.vscode\/mcp\.json$/i, ["GitHub Copilot"], "MCP servers"],
41
+ [/(^|\/)\.vscode\/settings\.json$/i, ["GitHub Copilot"], "Editor settings"],
42
+ [/(^|\/)\.gemini\/settings\.json$/i, ["Gemini CLI"], "Settings & MCP"],
43
+ [/(^|\/)\.gemini\/.+\.md$/i, ["Gemini CLI"], "Instructions"],
44
+ [/(^|\/)opencode\.jsonc?$/i, ["OpenCode"], "Settings & MCP"],
45
+ [/(^|\/)\.opencode\//i, ["OpenCode"], "Agents & commands"],
46
+ [/(^|\/)\.grok\/settings\.json$/i, ["Grok CLI"], "Settings & MCP"],
47
+ [/(^|\/)(\.grok\/.+|grok)\.md$/i, ["Grok CLI"], "Instructions"],
48
+ [/(^|\/)(\.windsurfrules|\.windsurf\/rules\/.+)$/i, ["Windsurf"], "Rules"],
49
+ [/(^|\/)\.windsurf\/mcp_config\.json$/i, ["Windsurf"], "MCP servers"],
50
+ [/(^|\/)\.clinerules/i, ["Cline"], "Rules"],
51
+ [/(^|\/)(\.roomodes|\.roo\/.+)$/i, ["Roo Code"], "Rules & modes"],
52
+ [/(^|\/)\.kiro\/steering\//i, ["Kiro"], "Steering"],
53
+ [/(^|\/)\.kiro\/settings\/mcp\.json$/i, ["Kiro"], "MCP servers"],
54
+ [/(^|\/)\.amazonq\/rules\//i, ["Amazon Q"], "Rules"],
55
+ [/(^|\/)\.?amazonq\/mcp\.json$/i, ["Amazon Q"], "MCP servers"],
56
+ [/(^|\/)\.continue\//i, ["Continue"], "Config & rules"],
57
+ [/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i, ["Zed"], "Agent settings"],
58
+ [/(^|\/)\.junie\/guidelines\.md$/i, ["Junie"], "Guidelines"],
59
+ [/(^|\/)\.aider\.conf\.ya?ml$/i, ["Aider"], "Settings"],
60
+ ];
61
+
62
+ function editorTool(path) {
63
+ if (/(^|\/)Cursor\/User\//i.test(path)) return "Cursor";
64
+ if (/(^|\/)Windsurf\/User\//i.test(path)) return "Windsurf";
65
+ return "GitHub Copilot";
66
+ }
67
+
68
+ // Which agents read a file, and what it controls. Null for files no agent reads.
69
+ export function controlFor(path) {
70
+ const hit = CONTROL.find(([re]) => re.test(path));
71
+ if (!hit) return null;
72
+ return { tools: typeof hit[1] === "function" ? hit[1](path) : hit[1], kind: hit[2] };
73
+ }
74
+
75
+ const HOME_MARKERS = [".ssh", "AppData", "Library", "NTUSER.DAT", ".bashrc", ".zshrc", ".profile", "Downloads", "Documents", "Desktop", ".config", ".local", "Pictures", "Music", "Videos"];
76
+ const DOWNLOADS_LIKE = /^(downloads?|desktop|temp|tmp)$/i;
77
+ const KEY_FILE = /\.(pem|key|p12|pfx|jks|keystore|ppk)$|(^|\/)id_(rsa|dsa|ecdsa|ed25519)$|\.aws\/credentials$|service[-_]?account[^/]*\.json$|(^|\/)credentials\.json$|\.git-credentials$|\.codex\/auth\.json$|\.claude\/\.credentials\.json$|\.grok\/user-settings\.json$|\.kube\/config$|\.docker\/config\.json$/i;
78
+ const EXAMPLE_ENV = /\.env\.(example|sample|template|dist|defaults)$/i;
79
+
80
+ // --- Text patterns -----------------------------------------------------------
81
+
82
+ const RX_REMOTE_EXEC =
83
+ /\b(?:curl|wget)\b[^\n|;&]{0,300}\|\s*(?:sudo\s+)?(?:ba|z|da|k|fi)?sh\b|\b(?:iwr|irm|Invoke-WebRequest|Invoke-RestMethod)\b[^\n|]{0,300}\|\s*(?:iex|Invoke-Expression)\b|\b(?:iex|Invoke-Expression)\b[^\n]{0,20}(?:Net\.WebClient|DownloadString|iwr|irm|Invoke-WebRequest|Invoke-RestMethod)|\bbase64\s+(?:-d|--decode)\b[^\n|]{0,120}\|\s*(?:ba)?sh\b|\b(?:bash|sh|zsh)\s+<\(\s*(?:curl|wget)\b|\bpowershell(?:\.exe)?\b[^\n]{0,60}\s-(?:e|enc|encodedcommand)\s+[A-Za-z0-9+/=]{20,}/i;
84
+ const RX_NET_SEND =
85
+ /\bcurl\b[^\n]{0,200}\s(?:-d|--data(?:-binary|-raw|-urlencode)?|-F|--form|-T|--upload-file|-X\s*(?:POST|PUT))\b|\bwget\b[^\n]{0,200}--post-(?:data|file)\b|\b(?:Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[^\n]{0,200}-(?:Method\s+(?:Post|Put)|Body|InFile)\b|\b(?:nc|ncat|netcat)\s+[^\n]{0,80}\b\d{2,5}\b|\bscp\s+\S+\s+\S+@|\brsync\b[^\n]{0,100}\s[\w.-]+@[\w.-]+:/i;
86
+ const RX_DESTRUCTIVE =
87
+ /\brm\s+-[a-z]*(?:rf|fr)\b|\bRemove-Item\b[^\n]{0,80}-Recurse[^\n]{0,40}-Force|\bdel\s+\/[sq]\b|\brmdir\s+\/s\b|\bgit\s+push\b[^\n]*\s--force\b|\bgit\s+reset\s+--hard\b|\bgit\s+clean\s+-[a-z]*f|\bmkfs\b|\bdd\s+if=/i;
88
+ const RX_OUTSIDE_SCRIPT =
89
+ /(?:^|[\s"'=])((?:\/tmp|\/var\/tmp|~\/Downloads|\$HOME\/Downloads|%TEMP%|%TMP%|\$env:TEMP|[A-Za-z]:[\\/]Users[\\/][^\\/\s"']+[\\/](?:Downloads|AppData[\\/]Local[\\/]Temp))[\\/][^\s"']+)/i;
90
+ const RX_EXFIL_HOST =
91
+ /\b(webhook\.site|requestbin\.(?:com|net)|[a-z0-9-]+\.pipedream\.net|[a-z0-9-]+\.ngrok(?:-free)?\.(?:app|io|dev)|interact\.sh|[a-z0-9-]+\.oast\.(?:fun|live|me|online|pro|site)|burpcollaborator\.net|canarytokens\.(?:com|org)|discord(?:app)?\.com\/api\/webhooks|hooks\.slack\.com\/services|pastebin\.com|transfer\.sh|0x0\.st|requestcatcher\.com|beeceptor\.com|hookbin\.com|ptsv[23]\.com|postb\.in)\b/i;
92
+ const RX_OVERRIDE =
93
+ /\b(?:ignore|disregard|forget|override)\b[^.\n]{0,40}\b(?:previous|prior|above|earlier|system|safety|your|developer)\b[^.\n]{0,20}\b(?:instructions?|rules|prompts?|guidelines|guardrails)\b|\bdo not (?:tell|inform|alert|notify|show|mention (?:this|it) to) the user\b|\bwithout (?:asking|telling|notifying|confirmation|consent|permission)\b|\bnever ask (?:the user )?(?:for )?(?:permission|confirmation|approval)\b|\b(?:always|automatically) (?:approve|accept|allow)\b|\b(?:disable|turn off|bypass|skip)\b[^.\n]{0,20}\b(?:sandbox|approvals?|permissions?|confirmations?|safety checks?|guardrails)\b/gi;
94
+ const RX_SECRET_ACCESS =
95
+ /\b(?:cat|read|print|output|copy|send|upload|post|include|paste|exfiltrat\w*|grab|collect|dump)\b[^\n]{0,60}(?:~\/\.ssh|\bid_rsa\b|\bid_ed25519\b|\.aws\/credentials|\.env\b|\.npmrc|\.git-credentials|auth\.json|\.credentials\.json|keychain|browser (?:cookies|passwords))/ig;
96
+ const RX_INJECT_WORDS =
97
+ /\b(?:ignore|disregard|override|secretly|silently|quietly|without (?:asking|telling)|do not (?:tell|mention|reveal|ask)|exfiltrat\w*|curl|wget|upload|send (?:it|this|the|them|all|everything)|token|api key|password|ssh|credentials?|base64|you are now|new instructions)\b/i;
98
+ const RX_BENIGN_COMMENT = /^\s*(?:markdownlint|prettier|toc|end ?toc|eslint|cspell|vale|begin|end|lint|todo|fixme|note)\b/i;
99
+ const RX_DANGER_FLAGS =
100
+ /--dangerously-skip-permissions|--allow-dangerously-skip-permissions|--dangerously-bypass-approvals-and-sandbox|--permission-mode[= ]+["']?bypassPermissions|--approval-mode[= ]+["']?yolo|\b(?:codex|gemini|qwen)\b[^\n]{0,80}\s--yolo\b|\bgemini\b[^\n]{0,80}\s-y\b/i;
101
+ const RX_IMPORT_OUTSIDE = /(?:^|\s)@((?:~\/|\.\.\/|[A-Za-z]:[\\/]|\/(?:Users|home|etc|tmp|var|opt|root|mnt)\/)[^\s)\]]+)/g;
102
+ const RX_BLOB = /[A-Za-z0-9+/]{300,}={0,2}/;
103
+ 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;
104
+ const SHELL_SERVER = /(?:^|[-_/@.])(?:shell|terminal|exec|executor|commands?|cmd|desktop-commander|ssh|powershell|bash|zsh|run-command)(?:[-_.]|$)/i;
105
+
106
+ // --- Entry point -------------------------------------------------------------
107
+
108
+ export function analyze(input) {
109
+ const ctx = buildContext(input ?? {});
110
+ collectMcpServers(ctx);
111
+ for (const f of ctx.files) {
112
+ if (!f.content) continue;
113
+ if (/(^|\/)(\.claude\/settings(\.local)?|managed-settings)\.json$/i.test(f.path)) checkClaudeSettings(ctx, f);
114
+ else if (/(^|\/)\.claude\.json$/i.test(f.path)) checkClaudeUserConfig(ctx, f);
115
+ else if (/(^|\/)\.codex\/config\.toml$/i.test(f.path)) checkCodex(ctx, f);
116
+ else if (/(^|\/)\.gemini\/settings\.json$/i.test(f.path)) checkGemini(ctx, f);
117
+ else if (/(^|\/)(\.vscode|(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User)\/settings\.json$/i.test(f.path)) checkVSCode(ctx, f);
118
+ else if (/(^|\/)opencode\.jsonc?$/i.test(f.path)) checkOpenCode(ctx, f);
119
+ else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(f.path)) checkZed(ctx, f);
120
+ else if (f.kind === "Shell profile") checkShellProfile(ctx, f);
121
+ else if (/(^|\/)\.aider\.conf\.ya?ml$/i.test(f.path)) checkAider(ctx, f);
122
+ else if (/^package\.json$/i.test(f.path)) checkPackageJson(ctx, f);
123
+
124
+ if (/(^|\/)\.claude\/hooks\//i.test(f.path)) checkHookScript(ctx, f);
125
+ else if (isInstructionFile(f)) checkInstructionText(ctx, f);
126
+ }
127
+ for (const server of ctx.mcpServers) checkMcpServer(ctx, server);
128
+ const enabled = ctx.mcpServers.filter((s) => !s.disabled).length;
129
+ if (enabled > 12) add(ctx, "MCP-MANY", { vars: { count: enabled } });
130
+ checkWorkspace(ctx);
131
+ checkSprawl(ctx);
132
+ return summarize(ctx);
133
+ }
134
+
135
+ // --- Context -----------------------------------------------------------------
136
+
137
+ function buildContext(input) {
138
+ const files = [];
139
+ const seenPaths = new Set();
140
+ for (const raw of Array.isArray(input.files) ? input.files : []) {
141
+ if (!raw || typeof raw.path !== "string") continue;
142
+ const path = cleanPath(raw.path);
143
+ if (!path || seenPaths.has(path)) continue;
144
+ seenPaths.add(path);
145
+ const file = {
146
+ path,
147
+ size: toInt(raw.size),
148
+ sensitive: raw.sensitive === true,
149
+ tooLarge: raw.tooLarge === true,
150
+ loose: raw.loose === true,
151
+ };
152
+ if (typeof raw.content === "string" && !file.sensitive) {
153
+ file.content = maskSecrets(raw.content.slice(0, MAX_FILE_CHARS)).text;
154
+ file.lines = file.content.split(/\r?\n/);
155
+ }
156
+ const control = controlFor(path);
157
+ file.tools = control ? control.tools : file.loose ? ["Any agent started there"] : [];
158
+ file.kind = control ? control.kind : file.loose ? "Loose file" : null;
159
+ files.push(file);
160
+ }
161
+ const shape = input.shape && typeof input.shape === "object" ? input.shape : {};
162
+ return {
163
+ root: typeof input.root === "string" ? input.root.slice(0, 120) : null,
164
+ files,
165
+ shape: {
166
+ entries: toInt(shape.entries),
167
+ topLevel: Array.isArray(shape.topLevel) ? shape.topLevel.filter((s) => typeof s === "string").slice(0, 200) : [],
168
+ rootGit: shape.rootGit === true,
169
+ gitRepos: toInt(shape.gitRepos),
170
+ truncated: shape.truncated === true,
171
+ },
172
+ maskedInBrowser: toInt(input.masked?.count),
173
+ findings: [],
174
+ seen: new Set(),
175
+ mcpServers: [],
176
+ claudeDeny: [],
177
+ claudeSettingsFiles: [],
178
+ };
179
+ }
180
+
181
+ function cleanPath(p) {
182
+ const unix = p.replace(/\\/g, "/");
183
+ const parts = unix.split("/").filter((s) => s && s !== ".");
184
+ if (!parts.length || parts.includes("..") || parts.join("/").length > 400) return null;
185
+ // Keep the leading slash of system files such as /etc/claude-code/managed-settings.json.
186
+ return (unix.startsWith("/") ? "/" : "") + parts.join("/");
187
+ }
188
+
189
+ const toInt = (n) => (Number.isFinite(Number(n)) ? Math.max(0, Math.floor(Number(n))) : 0);
190
+ const arr = (x) => (Array.isArray(x) ? x.filter((s) => typeof s === "string") : []);
191
+ const isObj = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
192
+ const clip = (s, n = 180) => {
193
+ const t = String(s).replace(/\s+/g, " ").trim();
194
+ return t.length > n ? t.slice(0, n - 1) + "…" : t;
195
+ };
196
+
197
+ function isInstructionFile(f) {
198
+ if (f.loose) return true;
199
+ if (!f.kind) return false;
200
+ return /\.(md|mdc|txt)$/i.test(f.path) || /(^|\/)\.(cursorrules|windsurfrules|clinerules)$/i.test(f.path) || /(^|\/)\.clinerules\//i.test(f.path);
201
+ }
202
+
203
+ // The line that names a folder as a key. Quoted first, so "~" doesn't match
204
+ // the line for "~/Downloads".
205
+ function keyLine(file, key) {
206
+ return lineOf(file, JSON.stringify(key)) || lineOf(file, `'${key}'`) || lineOf(file, key);
207
+ }
208
+
209
+ function lineOf(file, test) {
210
+ if (!file.lines) return 0;
211
+ const idx = file.lines.findIndex((line) => (typeof test === "string" ? line.includes(test) : test.test(line)));
212
+ return idx >= 0 ? idx + 1 : 0;
213
+ }
214
+
215
+ const NEGATED = /\b(?:never|don['’]t|do not|does not|must not|mustn['’]t|should not|shouldn['’]t|avoid|refuse to|forbidden|prohibited|no need to)\b[^.!?\n]{0,30}$/i;
216
+
217
+ function firstMatch(text, re, affirmative) {
218
+ const global = new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g");
219
+ for (const m of text.matchAll(global)) {
220
+ if (affirmative) {
221
+ const lineStart = text.lastIndexOf("\n", m.index) + 1;
222
+ if (NEGATED.test(text.slice(Math.max(lineStart, m.index - 60), m.index))) continue;
223
+ }
224
+ return m;
225
+ }
226
+ return null;
227
+ }
228
+
229
+ function lineAt(text, index) {
230
+ let n = 1;
231
+ for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
232
+ return n;
233
+ }
234
+
235
+ function evidenceLine(file, line) {
236
+ return line && file.lines ? clip(file.lines[line - 1] ?? "") : undefined;
237
+ }
238
+
239
+ function add(ctx, id, { file, line = 0, evidence, vars = {}, tool } = {}) {
240
+ const rule = RULES[id];
241
+ if (!rule) throw new Error(`Unknown rule ${id}`);
242
+ const filePath = file?.path ?? null;
243
+ const key = `${id}|${filePath}|${line}|${vars.server ?? ""}|${vars.key ?? ""}|${vars.rule ?? ""}|${vars.place ?? ""}`;
244
+ if (ctx.seen.has(key)) return;
245
+ ctx.seen.add(key);
246
+ const values = Object.fromEntries(Object.entries({ file: filePath ?? "", ...vars }).map(([k, v]) => [k, String(v ?? "")]));
247
+ const fill = (text) => fillTemplate(text, values);
248
+ ctx.findings.push({
249
+ id,
250
+ severity: rule.severity,
251
+ category: rule.category,
252
+ tool: tool ?? rule.tool ?? (file?.tools?.length ? file.tools[0] : null),
253
+ title: fill(rule.title),
254
+ why: fill(rule.why),
255
+ fix: fill(rule.fix),
256
+ file: filePath,
257
+ line: line || null,
258
+ evidence: evidence ? describeMasks(clip(evidence, 220)) : null,
259
+ vars: values,
260
+ });
261
+ }
262
+
263
+ function fillTemplate(text, values) {
264
+ return text.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? "");
265
+ }
266
+
267
+ // Parts of a finding that quote file contents or reveal local paths. Shared
268
+ // reports replace them, so a public link shows the issue without the details.
269
+ const PRIVATE_VARS = new Set(["cmd", "decoded", "phrase", "host", "ref", "path", "dir", "command"]);
270
+
271
+ export function publicFinding(f) {
272
+ const rule = RULES[f.id];
273
+ const values = { ...(f.vars ?? {}) };
274
+ for (const k of PRIVATE_VARS) values[k] = "[redacted]";
275
+ const fill = (text, fallback) => (rule ? fillTemplate(text, values) : fallback);
276
+ return {
277
+ id: f.id,
278
+ severity: f.severity,
279
+ category: f.category,
280
+ tool: f.tool,
281
+ title: fill(rule?.title ?? "", f.title),
282
+ why: fill(rule?.why ?? "", f.why),
283
+ fix: fill(rule?.fix ?? "", f.fix),
284
+ file: f.file,
285
+ line: f.line,
286
+ };
287
+ }
288
+
289
+ export function headlineFor(counts, top, hasControlFiles) {
290
+ const lower = (t) => t.charAt(0).toLowerCase() + t.slice(1);
291
+ const minor = counts.medium + counts.low;
292
+ if (!hasControlFiles && !top) return "No agent setup files found here.";
293
+ if (counts.critical === 1) return top.title;
294
+ if (counts.critical) return `${counts.critical} critical issues, starting with: ${lower(top.title)}`;
295
+ if (counts.high) return `${counts.high} high-risk issue${counts.high === 1 ? "" : "s"}, starting with: ${lower(top.title)}`;
296
+ if (minor) return `No critical issues. ${minor} thing${minor === 1 ? "" : "s"} worth tightening.`;
297
+ return "No issues found in these agent files.";
298
+ }
299
+
300
+ // --- Claude Code ---------------------------------------------------------------
301
+
302
+ function parsed(file) {
303
+ if (file.parsed === undefined) file.parsed = /\.toml$/i.test(file.path) ? parseTOML(file.content) : parseJSONC(file.content) ?? null;
304
+ return file.parsed;
305
+ }
306
+
307
+ function checkClaudeSettings(ctx, f) {
308
+ const json = parsed(f);
309
+ if (!isObj(json)) return;
310
+ ctx.claudeSettingsFiles.push(f);
311
+ const p = isObj(json.permissions) ? json.permissions : {};
312
+
313
+ if (p.defaultMode === "bypassPermissions") {
314
+ const line = lineOf(f, /bypassPermissions/);
315
+ add(ctx, "CC-BYPASS", { file: f, line, evidence: evidenceLine(f, line) });
316
+ } else if (p.defaultMode === "acceptEdits") {
317
+ const line = lineOf(f, /acceptEdits/);
318
+ add(ctx, "CC-ACCEPT-EDITS", { file: f, line, evidence: evidenceLine(f, line) });
319
+ }
320
+
321
+ for (const rule of arr(p.allow)) {
322
+ const r = rule.trim();
323
+ const line = lineOf(f, r);
324
+ const hit = (id) => add(ctx, id, { file: f, line, evidence: evidenceLine(f, line), vars: { rule: r } });
325
+ if (/^Bash(\((\*|\*:\*|:\*|\*\*)?\))?$/i.test(r)) hit("CC-ALLOW-ALL-BASH");
326
+ else if (/^Bash\(\s*(sudo|su|doas|rm|bash|sh|zsh|fish|pwsh|powershell|cmd|python3?|node|deno|bun|npx|perl|ruby|php|eval|exec|iex|Invoke-Expression|chmod|chown|dd|docker|kubectl|env|xargs|find)\b/i.test(r)) hit("CC-ALLOW-RISKY-BASH");
327
+ else if (/^Bash\(\s*(curl|wget|ssh|scp|sftp|rsync|nc|ncat|netcat|ftp|telnet|Invoke-WebRequest|iwr|irm|git push|gh)\b/i.test(r)) hit("CC-ALLOW-NET-BASH");
328
+ else if (/^(Edit|Write|MultiEdit|NotebookEdit)\(\s*(\/\/|~\/|~$|\/\*\*|[A-Za-z]:)/i.test(r)) hit("CC-ALLOW-WRITE-ANYWHERE");
329
+ else if (/^Read\(\s*(\/\/|~\/|~$|[A-Za-z]:)/i.test(r)) hit("CC-ALLOW-READ-ANYWHERE");
330
+ else if (/^WebFetch(\(\s*(domain:\*|\*)?\s*\))?$/i.test(r)) hit("CC-ALLOW-WEBFETCH");
331
+ else if (/^mcp__[^_]+(__\*)?$/i.test(r)) hit("CC-ALLOW-MCP-ALL");
332
+ }
333
+
334
+ ctx.claudeDeny.push(...arr(p.deny));
335
+
336
+ for (const dir of arr(p.additionalDirectories)) {
337
+ if (isBroadPath(dir) || /^\.\.(\/\.\.)*\/?$/.test(dir.trim())) {
338
+ const line = lineOf(f, dir);
339
+ add(ctx, "CC-EXTRA-DIRS", { file: f, line, evidence: evidenceLine(f, line), vars: { dir } });
340
+ }
341
+ }
342
+
343
+ if (json.enableAllProjectMcpServers === true) {
344
+ const line = lineOf(f, /enableAllProjectMcpServers/);
345
+ add(ctx, "CC-MCP-AUTO-APPROVE", { file: f, line, evidence: evidenceLine(f, line) });
346
+ }
347
+
348
+ if (isObj(json.env)) {
349
+ for (const [key, value] of Object.entries(json.env)) {
350
+ if (typeof value === "string" && isSecretValue(key, value)) {
351
+ const line = lineOf(f, `"${key}"`);
352
+ add(ctx, "CC-ENV-SECRET", { file: f, line, evidence: `${key} = ${redact(value)}`, vars: { key } });
353
+ }
354
+ }
355
+ }
356
+
357
+ if (isObj(json.hooks)) {
358
+ for (const [event, entries] of Object.entries(json.hooks)) {
359
+ for (const entry of Array.isArray(entries) ? entries : []) {
360
+ const hooks = Array.isArray(entry?.hooks) ? entry.hooks : [entry];
361
+ for (const h of hooks) {
362
+ if (typeof h?.command === "string") checkCommand(ctx, h.command, f, `A Claude Code ${event} hook`);
363
+ }
364
+ }
365
+ }
366
+ }
367
+ }
368
+
369
+ function checkClaudeUserConfig(ctx, f) {
370
+ if (isMasked(f.content)) add(ctx, "CC-USER-SECRET", { file: f, line: lineOf(f, /«masked:/) });
371
+ const json = parsed(f);
372
+ if (!isObj(json)) return;
373
+ if (isObj(json.projects)) {
374
+ for (const dir of Object.keys(json.projects)) {
375
+ const place = riskyPlace(dir);
376
+ if (place) add(ctx, "WS-OPENED-IN", { file: f, line: keyLine(f, dir), tool: "Claude Code", vars: { tool: "Claude Code", place: place.name, risk: place.risk, dir } });
377
+ }
378
+ for (const project of Object.values(json.projects)) {
379
+ for (const rule of arr(project?.allowedTools)) {
380
+ if (/^Bash(\((\*|\*:\*|:\*)?\))?$/i.test(rule.trim())) {
381
+ const line = lineOf(f, rule);
382
+ add(ctx, "CC-ALLOW-ALL-BASH", { file: f, line, evidence: evidenceLine(f, line), vars: { rule } });
383
+ }
384
+ }
385
+ }
386
+ }
387
+ }
388
+
389
+ // --- Codex ---------------------------------------------------------------------
390
+
391
+ function checkCodex(ctx, f) {
392
+ const toml = parsed(f);
393
+ if (!isObj(toml)) return;
394
+ const scopes = [["", toml]];
395
+ if (isObj(toml.profiles)) for (const [name, prof] of Object.entries(toml.profiles)) if (isObj(prof)) scopes.push([` in profile “${name}”`, prof]);
396
+
397
+ for (const [where, scope] of scopes) {
398
+ const approval = scope.approval_policy;
399
+ const sandbox = scope.sandbox_mode;
400
+ const line = lineOf(f, sandbox === "danger-full-access" ? /danger-full-access/ : /approval_policy/);
401
+ if (approval === "never" && sandbox === "danger-full-access") add(ctx, "CX-YOLO", { file: f, line, evidence: evidenceLine(f, line), vars: { where } });
402
+ else if (sandbox === "danger-full-access") add(ctx, "CX-FULL-ACCESS", { file: f, line, evidence: evidenceLine(f, line), vars: { where } });
403
+ else if (approval === "never" && sandbox !== "read-only") {
404
+ const l = lineOf(f, /approval_policy\s*=\s*["']never/);
405
+ add(ctx, "CX-NEVER-ASK", { file: f, line: l, evidence: evidenceLine(f, l), vars: { where } });
406
+ }
407
+ }
408
+ if (toml.sandbox_workspace_write?.network_access === true) {
409
+ const line = lineOf(f, /network_access\s*=\s*true/);
410
+ add(ctx, "CX-NETWORK", { file: f, line, evidence: evidenceLine(f, line) });
411
+ }
412
+ const notify = arr(toml.notify).join(" ");
413
+ if (notify) checkCommand(ctx, notify, f, "Codex's notify command");
414
+ if (isObj(toml.projects)) {
415
+ for (const [dir, settings] of Object.entries(toml.projects)) {
416
+ const place = riskyPlace(dir);
417
+ if (place && settings?.trust_level === "trusted") add(ctx, "CX-TRUSTED-DIR", { file: f, line: keyLine(f, dir), vars: { place: place.name, risk: place.risk, dir } });
418
+ }
419
+ }
420
+ }
421
+
422
+ // Folders an agent should never be started in. Accepts absolute and ~ paths.
423
+ export function riskyPlace(dir) {
424
+ const d = String(dir).replace(/\\/g, "/").replace(/\/+$/, "");
425
+ const last = d.split("/").pop();
426
+ if (/^(~|\/Users\/[^/]+|\/home\/[^/]+|\/root|[A-Za-z]:\/Users\/[^/]+)$/i.test(d)) {
427
+ return { name: "your home folder", risk: "It can read everything there, including SSH keys, cloud credentials and your other projects." };
428
+ }
429
+ if (/^(Downloads|Desktop)$/i.test(last)) {
430
+ return { name: `your ${last} folder`, risk: "Files saved there from websites, chats and email become context the agent reads and may act on." };
431
+ }
432
+ if (d === "" || /^[A-Za-z]:$/.test(d)) return { name: "the root of a drive", risk: "It can read and change anything on that drive." };
433
+ return null;
434
+ }
435
+
436
+ function checkShellProfile(ctx, f) {
437
+ for (const [i, line] of f.lines.entries()) {
438
+ if (/^\s*#/.test(line)) continue;
439
+ const flag = line.match(RX_DANGER_FLAGS);
440
+ if (!flag) continue;
441
+ const agent = line.match(/\b(claude|codex|gemini|qwen|opencode|cursor-agent|amp)\b/i)?.[1]?.toLowerCase();
442
+ const names = { claude: "Claude Code", codex: "Codex", gemini: "Gemini CLI", qwen: "Qwen Code", opencode: "OpenCode", "cursor-agent": "Cursor", amp: "Amp" };
443
+ add(ctx, "FLAG-ALIAS", { file: f, line: i + 1, evidence: line, tool: names[agent] ?? null, vars: { agent: names[agent] ?? "an agent", flag: flag[0].trim(), cmd: clip(line, 120) } });
444
+ }
445
+ }
446
+
447
+ // --- Gemini, VS Code, OpenCode, Zed, Aider -------------------------------------
448
+
449
+ function checkGemini(ctx, f) {
450
+ const json = parsed(f);
451
+ if (!isObj(json)) return;
452
+ let yolo = false;
453
+ let autoAccept = false;
454
+ walk(json, (key, value) => {
455
+ if (/^yolo$/i.test(key) && value === true) yolo = true;
456
+ if (/approvalMode$/i.test(key) && /^yolo$/i.test(String(value))) yolo = true;
457
+ if (key === "autoAccept" && value === true) autoAccept = true;
458
+ });
459
+ if (yolo) {
460
+ const line = lineOf(f, /yolo/i);
461
+ add(ctx, "GM-YOLO", { file: f, line, evidence: evidenceLine(f, line) });
462
+ } else if (autoAccept) {
463
+ const line = lineOf(f, /autoAccept/);
464
+ add(ctx, "GM-AUTO-ACCEPT", { file: f, line, evidence: evidenceLine(f, line) });
465
+ }
466
+ }
467
+
468
+ function checkVSCode(ctx, f) {
469
+ const json = parsed(f);
470
+ if (!isObj(json)) return;
471
+ for (const key of ["chat.tools.autoApprove", "chat.tools.global.autoApprove"]) {
472
+ if (json[key] === true) {
473
+ const line = lineOf(f, key);
474
+ add(ctx, "VS-AUTO-APPROVE", { file: f, line, evidence: evidenceLine(f, line), vars: { key } });
475
+ }
476
+ }
477
+ const terminal = json["chat.tools.terminal.autoApprove"] ?? json["github.copilot.chat.agent.terminal.allowList"];
478
+ if (isObj(terminal)) {
479
+ for (const [pattern, allowed] of Object.entries(terminal)) {
480
+ const on = allowed === true || (isObj(allowed) && allowed.approve === true);
481
+ if (on && (/^\/\.\*\/|^\*$|^\.\*$/.test(pattern) || /\b(rm|curl|wget|sudo|bash|sh|pwsh|powershell|iex|python|node|npx|ssh|scp|git push)\b/i.test(pattern))) {
482
+ const line = lineOf(f, JSON.stringify(pattern)) || lineOf(f, pattern);
483
+ add(ctx, "VS-TERMINAL-AUTO", { file: f, line, evidence: evidenceLine(f, line), vars: { rule: pattern } });
484
+ }
485
+ }
486
+ }
487
+ }
488
+
489
+ function checkOpenCode(ctx, f) {
490
+ const json = parsed(f);
491
+ if (!isObj(json)) return;
492
+ if (json.share === "auto") {
493
+ const line = lineOf(f, /"share"/);
494
+ add(ctx, "OC-AUTO-SHARE", { file: f, line, evidence: evidenceLine(f, line) });
495
+ }
496
+ const bashAllows = (perm) => perm?.bash === "allow" || (isObj(perm?.bash) && perm.bash["*"] === "allow");
497
+ if (bashAllows(json.permission)) {
498
+ const line = lineOf(f, /"bash"/);
499
+ add(ctx, "OC-BASH-ALLOW", { file: f, line, evidence: evidenceLine(f, line), vars: { where: "" } });
500
+ }
501
+ if (isObj(json.agent)) {
502
+ for (const [name, agent] of Object.entries(json.agent)) {
503
+ if (bashAllows(agent?.permission)) {
504
+ add(ctx, "OC-BASH-ALLOW", { file: f, line: lineOf(f, `"${name}"`), vars: { where: ` for the “${name}” agent`, rule: name } });
505
+ }
506
+ }
507
+ }
508
+ }
509
+
510
+ function checkZed(ctx, f) {
511
+ const json = parsed(f);
512
+ if (!isObj(json)) return;
513
+ if (json.agent?.always_allow_tool_actions === true || json.assistant?.always_allow_tool_actions === true) {
514
+ const line = lineOf(f, /always_allow_tool_actions/);
515
+ add(ctx, "ZED-ALWAYS-ALLOW", { file: f, line, evidence: evidenceLine(f, line) });
516
+ }
517
+ }
518
+
519
+ function checkAider(ctx, f) {
520
+ const line = lineOf(f, /^\s*yes-always\s*:\s*true\b/i);
521
+ if (line) add(ctx, "AIDER-YES", { file: f, line, evidence: evidenceLine(f, line) });
522
+ }
523
+
524
+ function checkPackageJson(ctx, f) {
525
+ const json = parsed(f);
526
+ if (!isObj(json?.scripts)) return;
527
+ for (const [name, script] of Object.entries(json.scripts)) {
528
+ const m = typeof script === "string" && script.match(RX_DANGER_FLAGS);
529
+ if (m) {
530
+ const line = lineOf(f, `"${name}"`);
531
+ add(ctx, "FLAG-SCRIPT", { file: f, line, evidence: evidenceLine(f, line), vars: { flag: m[0].trim(), rule: name, where: `The “${name}” script in package.json` } });
532
+ }
533
+ }
534
+ }
535
+
536
+ // --- Commands run by hooks -----------------------------------------------------
537
+
538
+ function checkCommand(ctx, command, f, where) {
539
+ const line = lineOf(f, command.split("\n")[0].slice(0, 60)) || lineOf(f, /"command"/);
540
+ const cmd = clip(command, 140);
541
+ const vars = { where, cmd };
542
+ if (RX_REMOTE_EXEC.test(command)) add(ctx, "HOOK-REMOTE-EXEC", { file: f, line, evidence: command, vars });
543
+ else if (RX_NET_SEND.test(command)) add(ctx, "HOOK-NETWORK", { file: f, line, evidence: command, vars });
544
+ if (RX_DESTRUCTIVE.test(command)) add(ctx, "HOOK-DESTRUCTIVE", { file: f, line, evidence: command, vars });
545
+ if (RX_OUTSIDE_SCRIPT.test(command)) add(ctx, "HOOK-OUTSIDE", { file: f, line, evidence: command, vars });
546
+ const flag = command.match(RX_DANGER_FLAGS);
547
+ if (flag) add(ctx, "FLAG-SCRIPT", { file: f, line, evidence: command, vars: { flag: flag[0].trim(), where } });
548
+ }
549
+
550
+ function checkHookScript(ctx, f) {
551
+ const where = `The hook script ${f.path}`;
552
+ for (const [i, line] of f.lines.entries()) {
553
+ if (!line.trim() || /^\s*(#|\/\/|REM\b)/i.test(line)) continue;
554
+ const vars = { where, cmd: clip(line, 140) };
555
+ const opts = { file: f, line: i + 1, evidence: line, vars };
556
+ if (RX_REMOTE_EXEC.test(line)) add(ctx, "HOOK-REMOTE-EXEC", opts);
557
+ else if (RX_NET_SEND.test(line)) add(ctx, "HOOK-NETWORK", opts);
558
+ if (RX_DESTRUCTIVE.test(line)) add(ctx, "HOOK-DESTRUCTIVE", opts);
559
+ const flag = line.match(RX_DANGER_FLAGS);
560
+ if (flag) add(ctx, "FLAG-SCRIPT", { ...opts, vars: { flag: flag[0].trim(), where } });
561
+ }
562
+ }
563
+
564
+ // --- Instruction files -----------------------------------------------------------
565
+
566
+ function checkInstructionText(ctx, f) {
567
+ const text = f.content;
568
+ const at = (index) => {
569
+ const line = lineAt(text, index);
570
+ return { file: f, line, evidence: evidenceLine(f, line) };
571
+ };
572
+
573
+ const tags = [...text.matchAll(/[\u{E0000}-\u{E007F}]/gu)];
574
+ if (tags.length) {
575
+ const decoded = tags
576
+ .map((m) => String.fromCharCode(m[0].codePointAt(0) - 0xe0000))
577
+ .join("")
578
+ .replace(/[^\x20-\x7e]/g, "");
579
+ add(ctx, "TXT-TAGS", { ...at(tags[0].index), evidence: null, vars: { count: tags.length, decoded: clip(maskSecrets(decoded).text, 140) } });
580
+ }
581
+ const bidi = text.search(/[‪-‮⁦-⁩]/);
582
+ if (bidi >= 0) add(ctx, "TXT-BIDI", { ...at(bidi), evidence: null });
583
+ const zeroWidth = [...text.slice(1).matchAll(/[​-‍⁠᠎]/g)];
584
+ if (zeroWidth.length >= 3) add(ctx, "TXT-ZERO-WIDTH", { ...at(zeroWidth[0].index + 1), evidence: null, vars: { count: zeroWidth.length } });
585
+
586
+ for (const m of text.matchAll(/<!--([\s\S]*?)-->/g)) {
587
+ const inner = m[1].trim();
588
+ if (inner && !RX_BENIGN_COMMENT.test(inner) && RX_INJECT_WORDS.test(inner)) {
589
+ add(ctx, "TXT-HIDDEN-COMMENT", { ...at(m.index), evidence: inner });
590
+ break;
591
+ }
592
+ }
593
+
594
+ // Rules marked `affirmative` ignore lines that warn against the thing,
595
+ // such as "Never read .env files" or "Do not disable the sandbox".
596
+ const textRule = (id, re, varsFrom, { affirmative = false } = {}) => {
597
+ const m = firstMatch(text, re, affirmative);
598
+ if (m) add(ctx, id, { ...at(m.index + (m[0].length - m[0].trimStart().length)), vars: varsFrom ? varsFrom(m) : {} });
599
+ };
600
+ textRule("TXT-REMOTE-EXEC", RX_REMOTE_EXEC, null, { affirmative: true });
601
+ textRule("TXT-EXFIL", RX_EXFIL_HOST, (m) => ({ host: m[1] }));
602
+ textRule("TXT-OVERRIDE", RX_OVERRIDE, (m) => ({ phrase: clip(m[0], 80) }), { affirmative: true });
603
+ textRule("TXT-SECRET-ACCESS", RX_SECRET_ACCESS, (m) => ({ phrase: clip(m[0], 80) }), { affirmative: true });
604
+ textRule("TXT-BLOB", RX_BLOB, (m) => ({ length: m[0].length.toLocaleString("en-US") }));
605
+ textRule("TXT-IMPORT-OUTSIDE", RX_IMPORT_OUTSIDE, (m) => ({ ref: "@" + clip(m[1], 80) }));
606
+ textRule("FLAG-DOCS", RX_DANGER_FLAGS, (m) => ({ flag: m[0].trim() }), { affirmative: true });
607
+
608
+ if (text.length > 60_000 && !f.loose) add(ctx, "TXT-HUGE", { file: f, vars: { size: `${Math.round(text.length / 1024)} KB` } });
609
+ }
610
+
611
+ // --- MCP servers -------------------------------------------------------------------
612
+
613
+ function collectMcpServers(ctx) {
614
+ for (const f of ctx.files) {
615
+ if (!f.content) continue;
616
+ const p = f.path;
617
+ let groups = [];
618
+ if (/(^|\/)\.codex\/config\.toml$/i.test(p)) groups = [parsed(f)?.mcp_servers];
619
+ else if (/\.jsonc?$/i.test(p)) {
620
+ const json = parsed(f);
621
+ if (!isObj(json)) continue;
622
+ if (/(^|\/)\.vscode\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
623
+ else if (/(^|\/)opencode\.jsonc?$/i.test(p)) groups = [json.mcp];
624
+ else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(p)) groups = [json.context_servers];
625
+ else if (/\/User\/mcp\.json$/i.test(p)) groups = [json.servers, json.mcpServers];
626
+ else if (/\/User\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
627
+ else if (/(^|\/)\.claude\.json$/i.test(p)) groups = [json.mcpServers, ...(isObj(json.projects) ? Object.values(json.projects).map((x) => x?.mcpServers) : [])];
628
+ else if (/(^|\/)\.vscode\/settings\.json$/i.test(p)) groups = [json.mcp?.servers];
629
+ else groups = [json.mcpServers];
630
+ }
631
+ for (const group of groups) {
632
+ if (!isObj(group)) continue;
633
+ for (const [name, def] of Object.entries(group)) ctx.mcpServers.push(normalizeServer(name, def, f));
634
+ }
635
+ }
636
+ }
637
+
638
+ function normalizeServer(name, def, file) {
639
+ const d = isObj(def) ? def : {};
640
+ let command = d.command;
641
+ let args = Array.isArray(d.args) ? d.args.map(String) : [];
642
+ if (Array.isArray(command)) {
643
+ args = [...command.slice(1).map(String), ...args];
644
+ command = command[0];
645
+ } else if (isObj(command)) {
646
+ args = Array.isArray(command.args) ? command.args.map(String) : args;
647
+ command = command.path ?? command.command;
648
+ }
649
+ const url = [d.url, d.serverUrl, d.httpUrl].find((u) => typeof u === "string") ?? null;
650
+ return {
651
+ name,
652
+ file,
653
+ command: typeof command === "string" ? command : null,
654
+ args,
655
+ env: isObj(d.env) ? d.env : isObj(d.environment) ? d.environment : {},
656
+ headers: isObj(d.headers) ? d.headers : isObj(d.http_headers) ? d.http_headers : {},
657
+ extra: d,
658
+ url,
659
+ alwaysAllow: d.alwaysAllow ?? d.autoApprove ?? d.auto_approve ?? (d.trust === true ? true : undefined),
660
+ alwaysAllowKey: ["alwaysAllow", "autoApprove", "auto_approve", "trust"].find((k) => d[k] !== undefined) ?? null,
661
+ disabled: d.disabled === true || d.enabled === false,
662
+ };
663
+ }
664
+
665
+ const REFERENCE = /^\$\{[^}]+\}$|^\$[A-Za-z_][A-Za-z0-9_]*$|^\{env:[^}]+\}$|^%[A-Za-z_][A-Za-z0-9_]*%$|\$\{(?:env|input):/i;
666
+
667
+ function isSecretValue(key, value) {
668
+ if (typeof value !== "string" || REFERENCE.test(value.trim()) || isPathLike(value)) return false;
669
+ if (isMasked(value)) return true;
670
+ if (/^(true|false|\d+|https?:\/\/[^@]*)$/i.test(value)) return false;
671
+ return /(token|secret|key|password|passwd|auth|credential|bearer|cookie|session)/i.test(key) ? looksLikeSecret(value) || value.length >= 20 : looksLikeToken(value) && value.length >= 24;
672
+ }
673
+
674
+ function redact(value) {
675
+ return isMasked(value) ? value : `•••• (${value.length} chars)`;
676
+ }
677
+
678
+ function checkMcpServer(ctx, s) {
679
+ const f = s.file;
680
+ const tool = f.tools[0] ?? null;
681
+ const nameLine = lineOf(f, `"${s.name}"`) || lineOf(f, s.name);
682
+ const base = (line = nameLine) => ({ file: f, line, tool, evidence: evidenceLine(f, line) });
683
+
684
+ for (const [key, value] of [...Object.entries(s.env), ...Object.entries(s.headers)]) {
685
+ if (isSecretValue(key, value)) {
686
+ const line = lineOf(f, `"${key}"`) || lineOf(f, key) || nameLine;
687
+ add(ctx, "MCP-SECRET", { ...base(line), evidence: `${key} = ${redact(value)}`, vars: { server: s.name, key } });
688
+ }
689
+ }
690
+ for (const key of ["bearer_token", "bearerToken", "apiKey", "api_key", "token"]) {
691
+ const value = s.extra[key];
692
+ if (typeof value === "string" && isSecretValue(key, value)) {
693
+ add(ctx, "MCP-SECRET", { ...base(lineOf(f, key) || nameLine), evidence: `${key} = ${redact(value)}`, vars: { server: s.name, key } });
694
+ }
695
+ }
696
+ const secretArg = s.args.find((a) => isMasked(a) || (looksLikeToken(a) && a.length >= 24 && !a.includes("/")));
697
+ if (secretArg) add(ctx, "MCP-SECRET", { ...base(lineOf(f, secretArg.slice(0, 20)) || nameLine), evidence: `args contain ${redact(secretArg)}`, vars: { server: s.name, key: "args" } });
698
+
699
+ if (s.url) {
700
+ let u = null;
701
+ try {
702
+ u = new URL(s.url);
703
+ } catch {}
704
+ if (u) {
705
+ const local = /^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?|0\.0\.0\.0|host\.docker\.internal)$/i.test(u.hostname);
706
+ if (u.protocol === "http:" && !local) add(ctx, "MCP-HTTP", { ...base(lineOf(f, s.url) || nameLine), vars: { server: s.name, host: u.hostname } });
707
+ if ([...u.searchParams.keys()].some((k) => /token|key|secret|auth|sig|password/i.test(k)) || u.password || isMasked(s.url)) {
708
+ add(ctx, "MCP-URL-TOKEN", { ...base(lineOf(f, u.hostname) || nameLine), vars: { server: s.name } });
709
+ }
710
+ }
711
+ }
712
+
713
+ const pkg = packageSpec(s.command, s.args);
714
+ if (pkg && !pkg.pinned) {
715
+ add(ctx, "MCP-UNPINNED", {
716
+ ...base(lineOf(f, pkg.spec) || nameLine),
717
+ vars: { server: s.name, command: clip([s.command, ...s.args].join(" "), 90), pkg: pkg.name },
718
+ });
719
+ }
720
+
721
+ if (/(^|[\\/])(docker|podman)(\.exe)?$/i.test(s.command ?? "")) {
722
+ const flag = dockerRisk(s.args);
723
+ if (flag) add(ctx, "MCP-DOCKER", { ...base(lineOf(f, flag.split(" ")[0]) || nameLine), vars: { server: s.name, flag } });
724
+ }
725
+
726
+ const broad = s.args.find((a) => isBroadPath(a));
727
+ if (broad && !/(^|[\\/])(docker|podman)(\.exe)?$/i.test(s.command ?? "")) {
728
+ add(ctx, "MCP-FS-BROAD", { ...base(lineOf(f, `"${broad}"`) || nameLine), vars: { server: s.name, path: broad } });
729
+ }
730
+
731
+ if (SHELL_SERVER.test(s.name) || (pkg && SHELL_SERVER.test(pkg.name))) add(ctx, "MCP-SHELL", { ...base(), vars: { server: s.name } });
732
+
733
+ if (s.alwaysAllow === true || (Array.isArray(s.alwaysAllow) && s.alwaysAllow.length)) {
734
+ const count = s.alwaysAllow === true ? "every tool" : `${s.alwaysAllow.length} tool${s.alwaysAllow.length === 1 ? "" : "s"}`;
735
+ add(ctx, "MCP-ALWAYS-ALLOW", { ...base(lineOf(f, s.alwaysAllowKey) || nameLine), vars: { server: s.name, key: s.alwaysAllowKey, count } });
736
+ }
737
+ }
738
+
739
+ export function packageSpec(command, args) {
740
+ if (!command) return null;
741
+ const base = command.split(/[\\/]/).pop().replace(/\.(cmd|exe|bat)$/i, "").toLowerCase();
742
+ let rest = [...args];
743
+ if (base === "cmd" && /^\/c$/i.test(rest[0] ?? "")) return packageSpec(rest[1], rest.slice(2));
744
+ if (base === "pnpm" || base === "yarn") {
745
+ if (rest[0] !== "dlx") return null;
746
+ rest = rest.slice(1);
747
+ } else if (base === "pipx") {
748
+ if (rest[0] !== "run") return null;
749
+ rest = rest.slice(1);
750
+ } else if (!["npx", "bunx", "pnpx", "uvx"].includes(base)) return null;
751
+
752
+ const python = base === "uvx" || base === "pipx";
753
+ for (let i = 0; i < rest.length; i++) {
754
+ const a = rest[i];
755
+ if (["-p", "--package", "--from", "--spec"].includes(a)) return judgeSpec(rest[i + 1], python);
756
+ const eq = a.match(/^--(?:package|from|spec)=(.+)$/);
757
+ if (eq) return judgeSpec(eq[1], python);
758
+ if (a.startsWith("-")) continue;
759
+ return judgeSpec(a, python);
760
+ }
761
+ return null;
762
+ }
763
+
764
+ function judgeSpec(spec, python) {
765
+ if (!spec) return null;
766
+ if (python) {
767
+ const name = spec.split(/[=@<>~!\[]/)[0];
768
+ return { name, spec, pinned: /==\s*\d|@\s*\d/.test(spec) };
769
+ }
770
+ if (/^(\.|\/|[a-z]+:|~)/i.test(spec)) return null; // local path or URL
771
+ const at = spec.lastIndexOf("@");
772
+ const name = at > 0 ? spec.slice(0, at) : spec;
773
+ const version = at > 0 ? spec.slice(at + 1) : "";
774
+ return { name, spec, pinned: /^\d+\.\d+\.\d+([-+][\w.]+)?$/.test(version) };
775
+ }
776
+
777
+ function dockerRisk(args) {
778
+ for (let i = 0; i < args.length; i++) {
779
+ const a = args[i];
780
+ const next = args[i + 1] ?? "";
781
+ if (/^--privileged$/i.test(a)) return a;
782
+ if (/^--(pid|network|net|ipc|uts)=host$/i.test(a)) return a;
783
+ if (/^--(pid|network|net|ipc|uts)$/i.test(a) && next === "host") return `${a} host`;
784
+ if (/^--cap-add=(ALL|SYS_ADMIN)$/i.test(a)) return a;
785
+ if (a === "--cap-add" && /^(ALL|SYS_ADMIN)$/i.test(next)) return `${a} ${next}`;
786
+ const volume = a === "-v" || a === "--volume" ? next : a.startsWith("--volume=") ? a.slice(9) : null;
787
+ const mount = a === "--mount" ? next : a.startsWith("--mount=") ? a.slice(8) : null;
788
+ const source = volume ? mountSource(volume) : mount ? (mount.match(/(?:^|,)(?:source|src)=([^,]+)/)?.[1] ?? "") : null;
789
+ if (source && (isBroadPath(source) || /docker\.sock|docker_engine/i.test(source))) return `${a === "--mount" || a.startsWith("--mount") ? "--mount" : "-v"} ${volume ?? mount}`;
790
+ }
791
+ return null;
792
+ }
793
+
794
+ function mountSource(volume) {
795
+ const win = volume.match(/^([A-Za-z]:[\\/][^:]*)/);
796
+ return win ? win[1] : volume.split(":")[0];
797
+ }
798
+
799
+ export function isBroadPath(value) {
800
+ const raw = String(value).trim();
801
+ if (raw === "/" || raw === "\\") return true;
802
+ const v = raw.replace(/\\/g, "/").replace(/\/+$/, "");
803
+ return (
804
+ /^(~|\$HOME|\$\{HOME\}|%USERPROFILE%|%HOMEPATH%|\$env:USERPROFILE|[A-Za-z]:)$/i.test(v) ||
805
+ /^\/(Users|home)(\/[^/]+)?$/i.test(v) ||
806
+ /^[A-Za-z]:\/Users(\/[^/]+)?$/i.test(v) ||
807
+ /^\/(root|etc|var|opt|usr)?$/i.test(v)
808
+ );
809
+ }
810
+
811
+ // --- Workspace -------------------------------------------------------------------
812
+
813
+ function checkWorkspace(ctx) {
814
+ const root = ctx.root ?? "";
815
+ const markers = HOME_MARKERS.filter((m) => ctx.shape.topLevel.includes(m));
816
+ const homeLike = markers.length >= 3;
817
+ const downloadsLike = DOWNLOADS_LIKE.test(root);
818
+
819
+ if (homeLike) add(ctx, "WS-HOME", { vars: { markers: listNames(markers.filter((m) => m.startsWith(".") || m === "AppData").concat(markers).slice(0, 3)) } });
820
+ if (downloadsLike) add(ctx, "WS-DOWNLOADS", { vars: { root } });
821
+
822
+ if (downloadsLike) {
823
+ const steering = ctx.files.filter((f) => f.content && (f.kind || f.loose) && isInstructionFile(f) && (!f.loose || steers(ctx, f)));
824
+ if (steering.length) add(ctx, "WS-POISON-RISK", { vars: { files: listNames(steering.map((f) => f.path), 3), place: `your ${root} folder` } });
825
+ }
826
+
827
+ const looseByDir = new Map();
828
+ for (const f of ctx.files) {
829
+ if (!f.loose || !f.content || !f.path.includes("/")) continue;
830
+ const dir = f.path.slice(0, f.path.lastIndexOf("/"));
831
+ if (!looseByDir.has(dir)) looseByDir.set(dir, []);
832
+ looseByDir.get(dir).push(f);
833
+ }
834
+ for (const [dir, list] of looseByDir) {
835
+ if (!riskyPlace(dir)) continue;
836
+ const steering = list.filter((f) => steers(ctx, f));
837
+ if (steering.length) add(ctx, "WS-POISON-RISK", { vars: { files: listNames(steering.map((f) => f.path.split("/").pop()), 3), place: riskyPlace(dir).name } });
838
+ }
839
+
840
+ if (ctx.shape.gitRepos >= 3) add(ctx, "WS-MULTI-REPO", { vars: { count: ctx.shape.gitRepos } });
841
+
842
+ const sensitive = ctx.files.filter((f) => f.sensitive && !EXAMPLE_ENV.test(f.path));
843
+ const keys = sensitive.filter((f) => KEY_FILE.test(f.path));
844
+ const others = sensitive.filter((f) => !KEY_FILE.test(f.path));
845
+ if (keys.length) add(ctx, "WS-KEYS", { vars: { files: listNames(keys.map((f) => f.path), 4) } });
846
+ if (others.length) {
847
+ const denied = (f) => ctx.claudeDeny.some((d) => denyCovers(d, f.path));
848
+ const exposed = others.filter((f) => !denied(f));
849
+ if (ctx.claudeSettingsFiles.length && exposed.length) {
850
+ add(ctx, "CC-NO-SECRET-DENY", { file: ctx.claudeSettingsFiles[0], vars: { files: listNames(exposed.map((f) => f.path), 4) } });
851
+ } else if (!ctx.claudeSettingsFiles.length) {
852
+ add(ctx, "WS-SECRETS", { vars: { files: listNames(others.map((f) => f.path), 4) } });
853
+ }
854
+ }
855
+
856
+ const gitignore = ctx.files.find((f) => f.path === ".gitignore" && f.content);
857
+ if (ctx.shape.rootGit) {
858
+ const envFiles = others.filter((f) => /(^|\/)\.env(\.|$)/i.test(f.path));
859
+ if (envFiles.length && !(gitignore && /^\s*\/?(\*\*\/)?(\.env\b|\.env\*|\*\.env)/m.test(gitignore.content))) {
860
+ add(ctx, "WS-ENV-COMMITTED", { file: gitignore ?? null, vars: { files: listNames(envFiles.map((f) => f.path), 3) } });
861
+ }
862
+ const local = ctx.files.filter((f) => /(^|\/)(\.claude\/settings\.local\.json|claude\.local\.md)$/i.test(f.path));
863
+ const ignored = (f) => gitignore && (gitignore.content.includes(f.path) || gitignore.content.includes(f.path.split("/").pop()));
864
+ const exposedLocal = local.filter((f) => !ignored(f));
865
+ if (exposedLocal.length) add(ctx, "WS-LOCAL-SETTINGS", { file: gitignore ?? null, vars: { files: listNames(exposedLocal.map((f) => f.path), 3) } });
866
+ }
867
+
868
+ const tooLarge = ctx.files.filter((f) => f.tooLarge);
869
+ if (tooLarge.length) add(ctx, "WS-TOO-LARGE", { vars: { count: tooLarge.length } });
870
+ }
871
+
872
+ function denyCovers(rule, path) {
873
+ const m = rule.match(/^Read\((.+)\)$/i);
874
+ if (!m) return false;
875
+ const pattern = m[1].trim().replace(/^\.\//, "");
876
+ if (pattern === "**" || pattern === "./**") return true;
877
+ const name = path.split("/").pop();
878
+ const toRegex = (glob) => new RegExp("^" + glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\/?/g, "§").replace(/\*/g, "[^/]*").replace(/§/g, ".*") + "$", "i");
879
+ try {
880
+ return toRegex(pattern).test(path) || toRegex(pattern).test(name);
881
+ } catch {
882
+ return false;
883
+ }
884
+ }
885
+
886
+ // A loose file counts as steering an agent only when it reads like orders to
887
+ // one, or carries an injection pattern. Size and encoded blobs don't count:
888
+ // page dumps and logs are full of both.
889
+ const STEERING_RULES = new Set(["TXT-TAGS", "TXT-BIDI", "TXT-ZERO-WIDTH", "TXT-HIDDEN-COMMENT", "TXT-REMOTE-EXEC", "TXT-EXFIL", "TXT-OVERRIDE", "TXT-SECRET-ACCESS", "FLAG-DOCS"]);
890
+ function steers(ctx, f) {
891
+ return Boolean(f.content) && (RX_DIRECTIVE.test(f.content) || ctx.findings.some((x) => x.file === f.path && STEERING_RULES.has(x.id)));
892
+ }
893
+
894
+ function listNames(names, max = 4) {
895
+ const unique = [...new Set(names)];
896
+ const shown = unique.slice(0, max);
897
+ const rest = unique.length - shown.length;
898
+ if (!shown.length) return "";
899
+ const text = shown.length === 1 ? shown[0] : `${shown.slice(0, -1).join(", ")} and ${shown[shown.length - 1]}`;
900
+ return rest > 0 ? `${shown.join(", ")} and ${rest} more` : text;
901
+ }
902
+
903
+ function walk(obj, visit, depth = 0) {
904
+ if (!isObj(obj) || depth > 6) return;
905
+ for (const [k, v] of Object.entries(obj)) {
906
+ visit(k, v);
907
+ if (isObj(v)) walk(v, visit, depth + 1);
908
+ }
909
+ }
910
+
911
+ // --- Sprawl ------------------------------------------------------------------------
912
+
913
+ function checkSprawl(ctx) {
914
+ const steering = ctx.files.filter((f) => f.content && f.kind && !f.loose && isInstructionFile(f) && !/(^|\/)\.(claude|github|codex|opencode)\/(commands|prompts|agents|chatmodes|skills|output-styles)\//i.test(f.path));
915
+ const tools = new Set(steering.flatMap((f) => f.tools));
916
+ if (steering.length >= 4 && tools.size >= 3) {
917
+ add(ctx, "SPRAWL", { vars: { count: steering.length, list: listNames(steering.map((f) => f.path), 4) } });
918
+ }
919
+ }
920
+
921
+ // --- Score -------------------------------------------------------------------------
922
+
923
+ const bySeverity = (a, b) =>
924
+ SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity) || a.category.localeCompare(b.category) || (a.file ?? "").localeCompare(b.file ?? "");
925
+
926
+ // Score, grade and counts from a list of findings. Shared by the local check
927
+ // and by the Worker when it publishes a shared report.
928
+ export function scoreFindings(findings, hasControlFiles) {
929
+ const counts = Object.fromEntries(SEVERITIES.map((s) => [s, findings.filter((f) => f.severity === s).length]));
930
+ // Repeats of the same rule count less, so one noisy pattern can't zero the score.
931
+ const byRule = new Map();
932
+ for (const f of findings) byRule.set(f.id, (byRule.get(f.id) ?? 0) + 1);
933
+ let penalty = 0;
934
+ for (const [id, n] of byRule) penalty += WEIGHT[RULES[id].severity] * Math.min(2, 1 + 0.25 * (n - 1));
935
+ const score = Math.max(0, Math.min(100, Math.round(100 - penalty)));
936
+ let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 65 ? "C" : score >= 50 ? "D" : "F";
937
+ if (counts.critical && "ABC".includes(grade)) grade = "D";
938
+ if (!hasControlFiles && !findings.length) grade = "–";
939
+ return { counts, score: grade === "–" ? null : score, grade };
940
+ }
941
+
942
+ function agentsIn(controlMap) {
943
+ // Agents with their own config files. AGENTS.md alone doesn't mean an agent is in use.
944
+ const specific = controlMap.filter((f) => !/(^|\/)agents(\.override)?\.md$/i.test(f.path));
945
+ return [...new Set((specific.length ? specific : controlMap).flatMap((f) => f.tools))].filter((t) => t !== "Any agent started there" && t !== "Your shell");
946
+ }
947
+
948
+ function summarize(ctx) {
949
+ const findings = ctx.findings.sort(bySeverity);
950
+ const controlFiles = ctx.files.filter((f) => f.kind && (!f.loose || steers(ctx, f)));
951
+ const { counts, score, grade } = scoreFindings(findings, controlFiles.length > 0);
952
+ const toolNames = agentsIn(controlFiles);
953
+ const headline = headlineFor(counts, findings[0], controlFiles.length > 0);
954
+
955
+ return {
956
+ version: RULESET_VERSION,
957
+ checkedAt: Date.now(),
958
+ root: ctx.root,
959
+ score,
960
+ grade,
961
+ headline,
962
+ counts,
963
+ findings,
964
+ categories: CATEGORIES,
965
+ tools: toolNames,
966
+ controlMap: controlFiles.map((f) => ({
967
+ path: f.path,
968
+ kind: f.kind,
969
+ tools: f.tools,
970
+ size: f.size,
971
+ lines: f.lines ? f.lines.length : null,
972
+ findings: findings.filter((x) => x.file === f.path).length,
973
+ })),
974
+ stats: {
975
+ filesChecked: ctx.files.filter((f) => f.content).length,
976
+ secretFilesListed: ctx.files.filter((f) => f.sensitive).length,
977
+ maskedInBrowser: ctx.maskedInBrowser,
978
+ mcpServers: ctx.mcpServers.length,
979
+ entriesScanned: ctx.shape.entries,
980
+ truncated: ctx.shape.truncated,
981
+ },
982
+ };
983
+ }
984
+
985
+ // --- Sharing -------------------------------------------------------------------------
986
+
987
+ // What leaves the computer when someone chooses to share: rule IDs, file names,
988
+ // line numbers and the non-private details. No file contents, no evidence lines,
989
+ // nothing that quotes a file or reveals a local path.
990
+ export function toShareable(result) {
991
+ return {
992
+ version: result.version,
993
+ findings: result.findings.map((f) => ({
994
+ id: f.id,
995
+ file: f.file,
996
+ line: f.line,
997
+ // The file name travels once, as file; the report rebuilds the rest.
998
+ vars: Object.fromEntries(Object.entries(f.vars ?? {}).filter(([k]) => k !== "file" && !PRIVATE_VARS.has(k))),
999
+ })),
1000
+ controlMap: result.controlMap.map((f) => f.path),
1001
+ stats: { filesChecked: result.stats.filesChecked, mcpServers: result.stats.mcpServers },
1002
+ };
1003
+ }
1004
+
1005
+ // Rebuilds a public report from a shareable payload. Every title and sentence
1006
+ // comes from the rule catalog, so a shared page can only say what a real check
1007
+ // would say. Unknown rules and oversized values are dropped.
1008
+ export function publicReportFrom(payload) {
1009
+ if (!isObj(payload) || !Array.isArray(payload.findings) || !Array.isArray(payload.controlMap)) return null;
1010
+ const safe = (v, n = 120) => String(v ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, n);
1011
+ // Shared reports cover a project, so only paths inside one are kept.
1012
+ const projectPath = (p) => {
1013
+ const clean = cleanPath(String(p));
1014
+ return clean && !/^(\/|~|[A-Za-z]:)/.test(clean) ? clean : null;
1015
+ };
1016
+ const paths = [...new Set(payload.controlMap.slice(0, 300).map(projectPath).filter(Boolean))];
1017
+ const findings = payload.findings
1018
+ .slice(0, 400)
1019
+ .filter((f) => isObj(f) && RULES[f.id] && (f.file == null || projectPath(f.file)))
1020
+ .map((f) => {
1021
+ const rule = RULES[f.id];
1022
+ const allowed = new Set([...`${rule.title} ${rule.why} ${rule.fix}`.matchAll(/\{(\w+)\}/g)].map((m) => m[1]));
1023
+ const vars = {};
1024
+ for (const [k, v] of Object.entries(isObj(f.vars) ? f.vars : {})) if (allowed.has(k) && !PRIVATE_VARS.has(k)) vars[k] = safe(v);
1025
+ const file = typeof f.file === "string" ? projectPath(f.file) : null;
1026
+ vars.file = file ?? "";
1027
+ const control = file ? controlFor(file) : null;
1028
+ return publicFinding({
1029
+ id: f.id,
1030
+ severity: rule.severity,
1031
+ category: rule.category,
1032
+ tool: rule.tool ?? control?.tools?.[0] ?? (typeof vars.tool === "string" && vars.tool) ?? null,
1033
+ file,
1034
+ line: Number.isInteger(f.line) && f.line > 0 && f.line < 1e7 ? f.line : null,
1035
+ vars,
1036
+ });
1037
+ })
1038
+ .sort(bySeverity);
1039
+ const controlMap = paths
1040
+ .map((path) => ({ path, ...(controlFor(path) ?? { tools: ["Any agent started there"], kind: "Loose file" }) }))
1041
+ .map((f) => ({ ...f, findings: findings.filter((x) => x.file === f.path).length }));
1042
+ const { counts, score, grade } = scoreFindings(findings, controlMap.length > 0);
1043
+ const stats = isObj(payload.stats) ? payload.stats : {};
1044
+ return {
1045
+ version: safe(payload.version, 20),
1046
+ score,
1047
+ grade,
1048
+ headline: headlineFor(counts, findings[0], controlMap.length > 0),
1049
+ counts,
1050
+ tools: agentsIn(controlMap),
1051
+ stats: { filesChecked: toInt(stats.filesChecked), mcpServers: toInt(stats.mcpServers) },
1052
+ findings,
1053
+ controlMap,
1054
+ };
1055
+ }