@yagyeshvyas/vibeguard 1.3.0 → 1.11.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.
Files changed (167) hide show
  1. package/.vibeguard-mcp.example.json +51 -0
  2. package/CHANGELOG.md +604 -216
  3. package/MCP-FIREWALL.md +296 -0
  4. package/README.md +355 -31
  5. package/bin/cli.js +355 -27
  6. package/bin/cmd-agent-monitor.js +45 -0
  7. package/bin/cmd-agent-risk.js +64 -0
  8. package/bin/cmd-gif.js +62 -0
  9. package/bin/cmd-git-scan.js +74 -0
  10. package/bin/cmd-llm-proxy.js +164 -0
  11. package/bin/cmd-mcp-firewall.js +191 -0
  12. package/bin/cmd-pentest.js +103 -0
  13. package/bin/cmd-platform.js +137 -0
  14. package/bin/cmd-pr-scan.js +135 -0
  15. package/bin/cmd-sbom-diff.js +38 -0
  16. package/bin/cmd-skill-scan.js +35 -0
  17. package/docs/AISVS.md +25 -0
  18. package/docs/ARCHITECTURE.md +81 -0
  19. package/docs/INSTALLATION.md +139 -0
  20. package/docs/WINDOWS.md +74 -0
  21. package/docs/security-policy.strict.example.json +134 -0
  22. package/docs/security-policy.strict.example.pub.pem +3 -0
  23. package/package.json +45 -7
  24. package/src/.vibeguard/cache/file-hashes.json +60 -0
  25. package/src/.vibeguard/latest-snapshot.json +36 -0
  26. package/src/.vibeguard/mcp-pins.json +1 -0
  27. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +428 -0
  28. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +344 -0
  29. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +279 -0
  30. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +297 -0
  31. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +151 -0
  32. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +299 -0
  33. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +65 -0
  34. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +2051 -0
  35. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +168 -0
  36. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +362 -0
  37. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +150 -0
  38. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +1611 -0
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +164 -0
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +292 -0
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +144 -0
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +220 -0
  43. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +428 -0
  44. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +344 -0
  45. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +297 -0
  46. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +299 -0
  47. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +37 -0
  48. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +2055 -0
  49. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +168 -0
  50. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +362 -0
  51. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +220 -0
  52. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +428 -0
  53. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +344 -0
  54. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +279 -0
  55. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +297 -0
  56. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +151 -0
  57. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +299 -0
  58. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +65 -0
  59. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +2055 -0
  60. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +168 -0
  61. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +362 -0
  62. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +150 -0
  63. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +1611 -0
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +164 -0
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +292 -0
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +144 -0
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +220 -0
  68. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +428 -0
  69. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +344 -0
  70. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +279 -0
  71. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +297 -0
  72. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +151 -0
  73. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +299 -0
  74. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +65 -0
  75. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +2054 -0
  76. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +168 -0
  77. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +362 -0
  78. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +150 -0
  79. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +1611 -0
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +164 -0
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +292 -0
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +144 -0
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +220 -0
  84. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +428 -0
  85. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +344 -0
  86. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +297 -0
  87. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +299 -0
  88. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +37 -0
  89. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +2055 -0
  90. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +168 -0
  91. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +362 -0
  92. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +220 -0
  93. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +428 -0
  94. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +344 -0
  95. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +297 -0
  96. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +33 -0
  97. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +2055 -0
  98. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +1611 -0
  99. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +292 -0
  100. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +220 -0
  101. package/src/.vibeguard-baseline.json +5226 -0
  102. package/src/action-guard.js +84 -6
  103. package/src/agent-monitor.js +262 -0
  104. package/src/agent-policy.js +642 -0
  105. package/src/agent-risk.js +271 -0
  106. package/src/agentic.js +1513 -0
  107. package/src/ast.js +165 -7
  108. package/src/audit-trail.js +212 -67
  109. package/src/auto.js +427 -427
  110. package/src/autofix.js +11 -4
  111. package/src/bundles.js +198 -0
  112. package/src/daemon.js +343 -343
  113. package/src/dashboard.js +278 -278
  114. package/src/engine.js +3 -0
  115. package/src/entropy.js +187 -0
  116. package/src/firewall.js +19 -3
  117. package/src/gif.js +134 -0
  118. package/src/gitscan.js +282 -0
  119. package/src/hook.js +151 -151
  120. package/src/injection-decode.js +136 -0
  121. package/src/install.js +298 -280
  122. package/src/integrity.js +16 -1
  123. package/src/integrity.json +43 -13
  124. package/src/interceptor.js +12 -9
  125. package/src/llm-proxy.js +986 -0
  126. package/src/mcp-audit.js +61 -5
  127. package/src/mcp-firewall.js +971 -0
  128. package/src/mcp-server.js +2500 -2047
  129. package/src/obfuscation.js +315 -0
  130. package/src/owasp-agentic.js +314 -0
  131. package/src/pentest.js +589 -0
  132. package/src/pii.js +4 -0
  133. package/src/platform/aisvs.js +38 -0
  134. package/src/platform/approval.js +187 -0
  135. package/src/platform/canonical.js +73 -0
  136. package/src/platform/contracts.js +158 -0
  137. package/src/platform/delegation.js +73 -0
  138. package/src/platform/http-gateway.js +177 -0
  139. package/src/platform/identity.js +253 -0
  140. package/src/platform/jwt.js +86 -0
  141. package/src/platform/mcp-http-bridge.js +199 -0
  142. package/src/platform/memory-guard.js +64 -0
  143. package/src/platform/os-sandbox.js +144 -0
  144. package/src/platform/policy.js +332 -0
  145. package/src/platform/sandbox-manager.js +92 -0
  146. package/src/platform/signed-audit.js +357 -0
  147. package/src/platform/ssrf.js +129 -0
  148. package/src/plugin.js +182 -168
  149. package/src/pre-deploy.js +170 -55
  150. package/src/privacy-audit.js +272 -272
  151. package/src/repl.js +150 -150
  152. package/src/report.js +7 -1
  153. package/src/routes.js +1210 -0
  154. package/src/rules-2026.js +1407 -0
  155. package/src/rules-pack.js +3068 -3019
  156. package/src/rules.js +376 -60
  157. package/src/sandbox.js +200 -10
  158. package/src/sbom.js +193 -164
  159. package/src/scanner.js +189 -33
  160. package/src/shell-guard.js +11 -0
  161. package/src/skill-scan.js +477 -0
  162. package/src/slopsquat.js +144 -144
  163. package/src/surface.js +408 -0
  164. package/src/taint-ast.js +204 -37
  165. package/src/taint.js +15 -3
  166. package/src/tokenlean.js +579 -0
  167. package/src/trace.js +220 -220
package/src/agentic.js ADDED
@@ -0,0 +1,1513 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/agentic.js — OWASP Agentic AI (ASI01–ASI10) + MCP security posture.
5
+ *
6
+ * This is a config-and-code posture pass layered on top of the line scanner and
7
+ * mcp-audit.js. It looks for agent-specific composition problems that a single
8
+ * regex line rule cannot see: how a tool is described, what its schema invites,
9
+ * what its handler does with that invitation, and how an agent loop, memory, or
10
+ * prompt is wired. Everything is static and offline.
11
+ *
12
+ * API: analyzeAgentic({ root, files }) -> findings[]
13
+ * files: [{ rel, content, lines }] for every scanned project file.
14
+ *
15
+ * Findings use the same shape as src/rules.js makeFinding():
16
+ * { ruleId, severity, confidence, title, message, fix, file, line, column, snippet }
17
+ *
18
+ * Rule IDs are all prefixed `agent2026.` so this pack can be enabled, graded,
19
+ * or ignored independently of ai.* and mcp.* rules.
20
+ */
21
+
22
+ const path = require('path');
23
+
24
+ const SKIP_DIRS = new Set([
25
+ 'node_modules', '.git', '.vibeguard', 'dist', 'build', '.next', 'out',
26
+ 'coverage', '.cache', 'vendor', '.venv', 'venv', '__pycache__',
27
+ ]);
28
+
29
+ const LOCKFILES = new Set([
30
+ 'package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml',
31
+ 'bun.lockb', 'composer.lock', 'poetry.lock', 'Pipfile.lock', 'Gemfile.lock',
32
+ 'Cargo.lock', 'uv.lock', 'go.sum', 'mix.lock',
33
+ ]);
34
+
35
+ const SEV_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
36
+ const MAX_BLOCK = 12000;
37
+ const MAX_FINDINGS = 500;
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // File classification / normalization
41
+ // ---------------------------------------------------------------------------
42
+
43
+ function normRel(rel) {
44
+ return String(rel || '').replace(/\\/g, '/').replace(/^\.\//, '');
45
+ }
46
+
47
+ function baseOf(rel) {
48
+ return path.posix.basename(normRel(rel));
49
+ }
50
+
51
+ function isSkipped(rel) {
52
+ const parts = normRel(rel).split('/');
53
+ for (const p of parts) if (SKIP_DIRS.has(p)) return true;
54
+ return LOCKFILES.has(baseOf(rel));
55
+ }
56
+
57
+ function isMcpConfigFile(rel, content) {
58
+ const base = baseOf(rel);
59
+ const r = normRel(rel);
60
+ if (base === '.cursorrules') return /^\s*[{[]/.test(content || '');
61
+ if (base === '.mcp.json' || base === 'mcp.json' || base === 'claude_desktop_config.json') return true;
62
+ if (base.endsWith('.mcp.json')) return true;
63
+ if (r.endsWith('.cursor/mcp.json') || r.endsWith('.vscode/mcp.json')) return true;
64
+ if (r.endsWith('.claude/settings.json')) return true;
65
+ return false;
66
+ }
67
+
68
+ function isPromptConfigFile(rel) {
69
+ const base = baseOf(rel);
70
+ const r = normRel(rel);
71
+ if (base === 'CLAUDE.md' || base === 'AGENTS.md' || base === '.cursorrules') return true;
72
+ if (r === '.github/copilot-instructions.md' || r.endsWith('/.github/copilot-instructions.md')) return true;
73
+ return false;
74
+ }
75
+
76
+ function isCodeFile(rel) {
77
+ return /\.(?:js|jsx|ts|tsx|mjs|cjs|py|rb|go|java|cs|rs|php)$/i.test(rel);
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Text helpers
82
+ // ---------------------------------------------------------------------------
83
+
84
+ // Replace comments and string interiors with spaces while preserving length and
85
+ // newlines. Indexes into the masked copy still address the original text, so a
86
+ // sink found in real (non-string) code can be read from the raw source.
87
+ function maskNonCode(text) {
88
+ const out = text.split('');
89
+ let state = null;
90
+
91
+ for (let i = 0; i < text.length; i++) {
92
+ const c = text[i];
93
+ const n = text[i + 1];
94
+
95
+ if (state === 'line') {
96
+ if (c === '\n') state = null;
97
+ else out[i] = ' ';
98
+ continue;
99
+ }
100
+ if (state === 'block') {
101
+ if (c === '*' && n === '/') {
102
+ out[i] = ' ';
103
+ out[i + 1] = ' ';
104
+ i++;
105
+ state = null;
106
+ } else if (c !== '\n') {
107
+ out[i] = ' ';
108
+ }
109
+ continue;
110
+ }
111
+ if (state) { // inside a quoted string; keep the delimiters for key parsing
112
+ if (c === '\\') {
113
+ out[i] = ' ';
114
+ if (i + 1 < text.length) {
115
+ if (text[i + 1] !== '\n') out[i + 1] = ' ';
116
+ i++;
117
+ }
118
+ continue;
119
+ }
120
+ if (c === state) {
121
+ state = null;
122
+ continue;
123
+ }
124
+ if (c !== '\n') out[i] = ' ';
125
+ continue;
126
+ }
127
+
128
+ if (c === '/' && n === '/') {
129
+ out[i] = ' ';
130
+ out[i + 1] = ' ';
131
+ i++;
132
+ state = 'line';
133
+ } else if (c === '/' && n === '*') {
134
+ out[i] = ' ';
135
+ out[i + 1] = ' ';
136
+ i++;
137
+ state = 'block';
138
+ } else if (c === '"' || c === "'" || c === '`') {
139
+ state = c;
140
+ }
141
+ }
142
+ return out.join('');
143
+ }
144
+
145
+ function lineOf(text, idx) {
146
+ let line = 1;
147
+ const end = Math.min(idx, text.length);
148
+ for (let i = 0; i < end; i++) if (text[i] === '\n') line++;
149
+ return line;
150
+ }
151
+
152
+ function snippetAt(lines, line) {
153
+ return String(lines[line - 1] || '').trim().slice(0, 220);
154
+ }
155
+
156
+ function sanitizeSnippet(s) {
157
+ return String(s || '')
158
+ .replace(/[\u200B-\u200F\u202A-\u202E\u2060-\u2069\uFEFF]/g, (ch) => {
159
+ return '<U+' + ch.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0') + '>';
160
+ })
161
+ .slice(0, 240);
162
+ }
163
+
164
+ function escapeRe(s) {
165
+ return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
166
+ }
167
+
168
+ function findLineOfKey(lines, key) {
169
+ const re = new RegExp('["\\\']?' + escapeRe(key) + '["\\\']?\\s*:');
170
+ for (let i = 0; i < lines.length; i++) if (re.test(lines[i])) return { line: i + 1, column: lines[i].search(re) + 1 };
171
+ return { line: 1, column: 1 };
172
+ }
173
+
174
+ function lineOfPattern(lines, re) {
175
+ for (let i = 0; i < lines.length; i++) if (re.test(lines[i])) return i + 1;
176
+ return 1;
177
+ }
178
+
179
+ // Decode the escapes an LLM-facing description commonly carries, without eval.
180
+ function decodeEscapes(s) {
181
+ return String(s)
182
+ .replace(/\\u\{([0-9a-f]+)\}/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
183
+ .replace(/\\u([0-9a-f]{4})/gi, (_, h) => String.fromCharCode(parseInt(h, 16)))
184
+ .replace(/\\x([0-9a-f]{2})/gi, (_, h) => String.fromCharCode(parseInt(h, 16)))
185
+ .replace(/\\n/g, '\n')
186
+ .replace(/\\r/g, '\r')
187
+ .replace(/\\t/g, '\t');
188
+ }
189
+
190
+ // ---------------------------------------------------------------------------
191
+ // Secrets
192
+ // ---------------------------------------------------------------------------
193
+
194
+ const SECRET_PATTERNS = [
195
+ { re: /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}\b/, type: 'API key' },
196
+ { re: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/, type: 'GitHub token' },
197
+ { re: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/, type: 'GitHub token' },
198
+ { re: /\bAKIA[0-9A-Z]{16}\b/, type: 'AWS access key' },
199
+ { re: /\bglpat-[A-Za-z0-9_-]{20,}\b/, type: 'GitLab token' },
200
+ { re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/, type: 'Slack token' },
201
+ { re: /\b(?:sk|rk)_live_[A-Za-z0-9]{20,}\b/, type: 'Stripe key' },
202
+ { re: /-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/, type: 'private key' },
203
+ ];
204
+
205
+ function isPlaceholderSecret(value) {
206
+ const v = String(value || '');
207
+ if (v.length < 12) return true;
208
+ return /\$\{|process\.env|os\.environ|import\.meta|<[^>]+>|your[_-]|example|placeholder|dummy|redacted|changeme|x{6,}|\*{3,}/i.test(v);
209
+ }
210
+
211
+ function findSecret(value) {
212
+ const v = String(value || '');
213
+ if (!v || isPlaceholderSecret(v)) return null;
214
+ for (const p of SECRET_PATTERNS) {
215
+ const m = p.re.exec(v);
216
+ if (m) return { type: p.type, value: m[0], masked: maskSecret(m[0]) };
217
+ }
218
+ return null;
219
+ }
220
+
221
+ function maskSecret(value) {
222
+ if (/PRIVATE KEY/.test(value)) return '[private key redacted]';
223
+ if (value.length <= 8) return '[redacted]';
224
+ return value.slice(0, 6) + '…' + value.slice(-2);
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // Stable comparison for cross-file server definitions
229
+ // ---------------------------------------------------------------------------
230
+
231
+ function stableValue(v) {
232
+ if (Array.isArray(v)) return '[' + v.map(stableValue).join(',') + ']';
233
+ if (v && typeof v === 'object') {
234
+ return '{' + Object.keys(v).sort().map((k) => JSON.stringify(k) + ':' + stableValue(v[k])).join(',') + '}';
235
+ }
236
+ return JSON.stringify(v);
237
+ }
238
+
239
+ // ---------------------------------------------------------------------------
240
+ // Object / tool block helpers
241
+ // ---------------------------------------------------------------------------
242
+
243
+ function findObjectBlocks(text) {
244
+ const blocks = [];
245
+ const stack = [];
246
+ let state = null;
247
+
248
+ for (let i = 0; i < text.length; i++) {
249
+ const c = text[i];
250
+ const n = text[i + 1];
251
+
252
+ if (state === 'line') {
253
+ if (c === '\n') state = null;
254
+ continue;
255
+ }
256
+ if (state === 'block') {
257
+ if (c === '*' && n === '/') { state = null; i++; }
258
+ continue;
259
+ }
260
+ if (state) {
261
+ if (c === '\\') { i++; continue; }
262
+ if (c === state) state = null;
263
+ continue;
264
+ }
265
+ if (c === '/' && n === '/') { state = 'line'; i++; continue; }
266
+ if (c === '/' && n === '*') { state = 'block'; i++; continue; }
267
+ if (c === '"' || c === "'" || c === '`') { state = c; continue; }
268
+ if (c === '{') {
269
+ stack.push(i);
270
+ } else if (c === '}' && stack.length) {
271
+ const start = stack.pop();
272
+ if (i - start <= MAX_BLOCK) blocks.push({ start, end: i });
273
+ }
274
+ }
275
+ return blocks;
276
+ }
277
+
278
+ function smallestBlockAt(blocks, idx) {
279
+ let best = null;
280
+ for (const b of blocks) {
281
+ if (b.start < idx && b.end > idx && (!best || (b.end - b.start) < (best.end - best.start))) best = b;
282
+ }
283
+ return best;
284
+ }
285
+
286
+ // Match `{`/`[`/`(` at openIdx to its closing character, aware of strings.
287
+ function matchBracket(text, openIdx) {
288
+ const open = text[openIdx];
289
+ const close = open === '{' ? '}' : open === '[' ? ']' : ')';
290
+ let depth = 0;
291
+ let state = null;
292
+
293
+ for (let i = openIdx; i < text.length; i++) {
294
+ const c = text[i];
295
+ const n = text[i + 1];
296
+ if (state === 'line') { if (c === '\n') state = null; continue; }
297
+ if (state === 'block') { if (c === '*' && n === '/') { state = null; i++; } continue; }
298
+ if (state) {
299
+ if (c === '\\') { i++; continue; }
300
+ if (c === state) state = null;
301
+ continue;
302
+ }
303
+ if (c === '/' && n === '/') { state = 'line'; i++; continue; }
304
+ if (c === '/' && n === '*') { state = 'block'; i++; continue; }
305
+ if (c === '"' || c === "'" || c === '`') { state = c; continue; }
306
+ if (c === open) depth++;
307
+ else if (c === close) {
308
+ depth--;
309
+ if (depth === 0) return i;
310
+ }
311
+ }
312
+ return text.length - 1;
313
+ }
314
+
315
+ function extractStringAt(text, idx) {
316
+ let i = idx;
317
+ while (i < text.length && /\s/.test(text[i])) i++;
318
+ const q = text[i];
319
+ if (q !== '"' && q !== "'" && q !== '`') return null;
320
+ let out = '';
321
+ i++;
322
+ for (; i < text.length && out.length < 12000; i++) {
323
+ const c = text[i];
324
+ if (c === '\\') {
325
+ out += c;
326
+ if (i + 1 < text.length) out += text[++i];
327
+ continue;
328
+ }
329
+ if (c === q) return { value: decodeEscapes(out), raw: out, start: idx, end: i + 1 };
330
+ out += c;
331
+ }
332
+ return { value: decodeEscapes(out), raw: out, start: idx, end: i, unterminated: true };
333
+ }
334
+
335
+ function valueAfterKey(text, key) {
336
+ const re = new RegExp('(?:^|[{,\\s])["\\\']?' + escapeRe(key) + '["\\\']?\\s*:\\s*', 'i');
337
+ const m = re.exec(text);
338
+ if (!m) return null;
339
+ let i = m.index + m[0].length;
340
+ while (i < text.length && /\s/.test(text[i])) i++;
341
+ if (text[i] === '{' || text[i] === '[' || text[i] === '(') {
342
+ return text.slice(i, matchBracket(text, i) + 1);
343
+ }
344
+ if (text[i] === '"' || text[i] === "'" || text[i] === '`') {
345
+ const s = extractStringAt(text, i);
346
+ return s ? s.value : null;
347
+ }
348
+ return null;
349
+ }
350
+
351
+ function fieldIndex(text, key) {
352
+ const re = new RegExp('(?:^|[{,\\s])["\\\']?' + escapeRe(key) + '["\\\']?\\s*:', 'i');
353
+ const m = re.exec(text);
354
+ return m ? m.index : -1;
355
+ }
356
+
357
+ // ---------------------------------------------------------------------------
358
+ // Finding collector
359
+ // ---------------------------------------------------------------------------
360
+
361
+ function makeCollector() {
362
+ const findings = [];
363
+ const seen = new Set();
364
+ const add = (f) => {
365
+ if (!f || !f.ruleId || !f.severity || !f.title || !f.message || !f.fix || !f.file) return;
366
+ const key = `${f.ruleId}|${f.file}|${f.line || 1}`;
367
+ if (seen.has(key)) return;
368
+ seen.add(key);
369
+ findings.push({
370
+ ruleId: f.ruleId,
371
+ severity: f.severity,
372
+ confidence: f.confidence || 'medium',
373
+ title: f.title,
374
+ message: f.message,
375
+ fix: f.fix,
376
+ file: normRel(f.file),
377
+ line: Math.max(1, Number(f.line) || 1),
378
+ column: Math.max(1, Number(f.column) || 1),
379
+ snippet: sanitizeSnippet(f.snippet || ''),
380
+ });
381
+ };
382
+ return { findings, add };
383
+ }
384
+
385
+ // ---------------------------------------------------------------------------
386
+ // MCP server configs
387
+ // ---------------------------------------------------------------------------
388
+
389
+ function exactVersion(pkg) {
390
+ if (!pkg) return false;
391
+ let v = null;
392
+ if (pkg.startsWith('@')) {
393
+ const slash = pkg.indexOf('/');
394
+ if (slash < 0) return false;
395
+ const at = pkg.indexOf('@', slash + 1);
396
+ if (at < 0) return false;
397
+ v = pkg.slice(at + 1);
398
+ } else if (pkg.includes('==')) {
399
+ v = pkg.slice(pkg.indexOf('==') + 2);
400
+ } else if (pkg.includes('@')) {
401
+ v = pkg.slice(pkg.lastIndexOf('@') + 1);
402
+ } else {
403
+ return false;
404
+ }
405
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(v);
406
+ }
407
+
408
+ function packageArg(args) {
409
+ for (let i = 0; i < args.length; i++) {
410
+ const a = String(args[i]);
411
+ if (a === '-p' || a === '--package' || a === '--from') {
412
+ if (i + 1 < args.length) return String(args[i + 1]);
413
+ continue;
414
+ }
415
+ if (a.startsWith('-')) continue;
416
+ if (a === 'dlx' || a === 'exec') continue;
417
+ return a;
418
+ }
419
+ return null;
420
+ }
421
+
422
+ function isLocalHost(hostname) {
423
+ const h = String(hostname || '').toLowerCase();
424
+ return h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]' ||
425
+ h === '0.0.0.0' || h.endsWith('.localhost');
426
+ }
427
+
428
+ function parseHttpUrl(value) {
429
+ if (!value) return null;
430
+ try {
431
+ const u = new URL(String(value));
432
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
433
+ return u;
434
+ } catch {
435
+ return null;
436
+ }
437
+ }
438
+
439
+ function hasAuthHeader(cfg, content) {
440
+ const headers = cfg && cfg.headers && typeof cfg.headers === 'object' ? cfg.headers : {};
441
+ for (const [k, v] of Object.entries(headers)) {
442
+ if (/^(?:authorization|proxy-authorization|x-api-key|api-key|apikey|token|x-auth-token)$/i.test(k) && v) return true;
443
+ }
444
+ if (cfg && (cfg.bearerToken || cfg.token || cfg.apiKey)) return true;
445
+ if (cfg && cfg.auth && typeof cfg.auth === 'object' && Object.keys(cfg.auth).length) return true;
446
+ // smithery.yaml: headers are YAML, not a parsed object.
447
+ if (content && /^\s*(?:authorization|api[_-]?key|x-api-key|token)\s*:/im.test(content)) return true;
448
+ return false;
449
+ }
450
+
451
+ const APPROVE_KEYS = /^(?:autoapprove|auto_approve|alwaysallow|always_allow|autoapprovetools|alwaysallowtools|allowedtools|autoapproveall|allowalltools)$/i;
452
+ const DANGEROUS_TOOL_RE = /(?:^|[_\-.:])(?:\*|all|shell|bash|sh|exec|execute|command|terminal|run|process|spawn|write|edit|delete|remove|rm|create|move|copy|drop|truncate|fetch|http|curl|wget|network|browser|web|url|post|upload|download|request|sql|query|database|db|deploy|transfer|install|package)(?:$|[_\-.:])/i;
453
+
454
+ function dangerousAutoApproved(value) {
455
+ if (value === true) return ['all tools'];
456
+ if (value === false || value == null) return [];
457
+ if (typeof value === 'string') value = [value];
458
+ if (!Array.isArray(value)) return [];
459
+ const hits = [];
460
+ for (const v of value) {
461
+ const s = String(v || '').trim();
462
+ if (!s) continue;
463
+ if (s === '*' || /^all$/i.test(s) || DANGEROUS_TOOL_RE.test(s)) hits.push(s);
464
+ }
465
+ return hits;
466
+ }
467
+
468
+ function analyzeMcpServer(server, lines, add, state) {
469
+ const { name, cfg, rel } = server;
470
+ const line = server.line || 1;
471
+ const snippet = snippetAt(lines, line);
472
+ const commandRaw = typeof cfg.command === 'string' ? cfg.command : '';
473
+ const argv = commandRaw.trim() ? commandRaw.trim().split(/\s+/) : [];
474
+ const command = argv[0] || '';
475
+ const args = Array.isArray(cfg.args) ? cfg.args.map(String) : (argv.length > 1 ? argv.slice(1) : []);
476
+ const env = cfg.env && typeof cfg.env === 'object' ? cfg.env : {};
477
+ const cmdLine = [commandRaw, ...args].join(' ').trim();
478
+
479
+ // 1. Unpinned auto-install (rug-pull surface).
480
+ const cmdBase = path.posix.basename(command);
481
+ if (/^(?:npx|bunx|pnpm|yarn)$/i.test(cmdBase)) {
482
+ const pkg = packageArg(args);
483
+ if (pkg && args.some((a) => /^(?:-y|--yes)$/i.test(a)) && !exactVersion(pkg)) {
484
+ add({
485
+ ruleId: 'agent2026.mcp-unpinned-install', severity: 'medium', confidence: 'high',
486
+ title: 'MCP server auto-installs an unpinned package',
487
+ message: `Server "${name}" runs "${cmdLine}", which downloads "${pkg}" with no exact version. The package's code can change between agent sessions (rug-pull).`,
488
+ fix: `Pin the package to an exact version (e.g. "${pkg}@1.2.3") or vendor the server, and avoid -y auto-install in .mcp.json.`,
489
+ file: rel, line, column: server.column || 1, snippet,
490
+ });
491
+ }
492
+ } else if (/^(?:uvx|uv)$/i.test(cmdBase)) {
493
+ const pkg = packageArg(args);
494
+ if (pkg && !exactVersion(pkg)) {
495
+ add({
496
+ ruleId: 'agent2026.mcp-unpinned-install', severity: 'medium', confidence: 'high',
497
+ title: 'MCP server auto-installs an unpinned package',
498
+ message: `Server "${name}" runs "${cmdLine}", which resolves "${pkg}" at launch with no exact version. A new release can silently change the tools the agent trusts.`,
499
+ fix: `Pin the package with an exact version (e.g. "uvx ${pkg.split('==')[0]}==1.2.3") or vendor the server.`,
500
+ file: rel, line, column: server.column || 1, snippet,
501
+ });
502
+ }
503
+ }
504
+
505
+ // 2. Remote transport without authentication / not disabled.
506
+ const urlText = String(cfg.url || cfg.serverUrl || cfg.httpUrl ||
507
+ (cfg.transport && cfg.transport.url) || '');
508
+ let remoteUrl = parseHttpUrl(urlText);
509
+ if (!remoteUrl && /(?:^|\s)--(?:url|sse-url|server-url)\b/i.test(cmdLine)) {
510
+ const m = cmdLine.match(/https?:\/\/[^\s'"]+/i);
511
+ if (m) remoteUrl = parseHttpUrl(m[0]);
512
+ }
513
+ if (remoteUrl && !isLocalHost(remoteUrl.hostname)) {
514
+ const authed = hasAuthHeader(cfg, server.content);
515
+ const remoteLine = cfg.url ? findLineOfKey(lines, 'url').line : line;
516
+ if (!authed) {
517
+ add({
518
+ ruleId: 'agent2026.mcp-remote-no-auth', severity: 'medium', confidence: 'high',
519
+ title: 'Remote MCP server has no authentication header',
520
+ message: `Server "${name}" connects to ${remoteUrl.protocol}//${remoteUrl.host} over a network transport with no Authorization/API-key header. Anyone who can reach that URL can call the agent's tools.`,
521
+ fix: `Require an auth header (e.g. "headers": { "Authorization": "Bearer <token>" }) for the remote server, or use a local stdio server.`,
522
+ file: rel, line: remoteLine, column: 1, snippet: snippetAt(lines, remoteLine),
523
+ });
524
+ }
525
+ if (cfg.disabled !== true && cfg.enabled !== false) {
526
+ add({
527
+ ruleId: 'agent2026.mcp-remote-not-disabled', severity: 'low', confidence: 'medium',
528
+ title: 'Remote MCP server is enabled by default',
529
+ message: `Server "${name}" is a remote endpoint and has no "disabled": true guard, so every agent session connects to it automatically.`,
530
+ fix: `Set "disabled": true in the shared config and enable the remote server explicitly only when needed.`,
531
+ file: rel, line: remoteLine, column: 1, snippet: snippetAt(lines, remoteLine),
532
+ });
533
+ }
534
+ state.remoteServers.push({ name, rel, line: remoteLine, url: remoteUrl.href, auth: authed });
535
+ }
536
+
537
+ // 3. Secrets committed in env / args.
538
+ const secretStrings = [];
539
+ for (const [k, v] of Object.entries(env)) {
540
+ if (typeof v !== 'string') continue;
541
+ secretStrings.push({ key: k, value: v, line: findLineOfKey(lines, k).line, env: true });
542
+ }
543
+ if (commandRaw) secretStrings.push({ key: 'command', value: cmdLine, line, env: false });
544
+ const reportedSecrets = new Set();
545
+ for (const s of secretStrings) {
546
+ const hit = findSecret(s.value);
547
+ if (!hit) continue;
548
+ if (reportedSecrets.has(hit.masked)) continue;
549
+ reportedSecrets.add(hit.masked);
550
+ const rawLine = snippetAt(lines, s.line);
551
+ add({
552
+ ruleId: 'agent2026.mcp-secret-in-env', severity: 'critical', confidence: 'high',
553
+ title: 'Secret committed in MCP server config',
554
+ message: `Server "${name}" contains a hardcoded ${hit.type} in ${s.env ? `env var ${s.key}` : 'its command/args'}. The credential is committed to the repo and is readable by every process and agent on this machine.`,
555
+ fix: `Remove the literal from ${rel}, reference a local environment variable or the VibeGuard vault instead, and rotate the exposed ${hit.type}.`,
556
+ file: rel, line: s.line, column: 1,
557
+ snippet: rawLine.includes(hit.value) ? rawLine.replace(hit.value, hit.masked) : `${s.key}: ${hit.masked}`,
558
+ });
559
+ state.secretRefs.push({ name, rel, line: s.line, key: s.key });
560
+ }
561
+
562
+ // 4. Shell wrapper / inline code execution in the server command.
563
+ const shellBase = path.posix.basename(command);
564
+ const shellWrapper = /^(?:sh|bash|zsh|dash|fish|ksh|cmd|cmd\.exe|powershell|powershell\.exe|pwsh|pwsh\.exe)$/i.test(shellBase) ||
565
+ /(?:^|\s)(?:sh|bash|zsh|cmd|powershell|pwsh)\s+(?:-c|\/c)\b/i.test(cmdLine) ||
566
+ /(?:&&|\|\||;|\$\(|`|\|\s*(?:sh|bash|zsh)\b)/.test(commandRaw);
567
+ const inlineEval = /^(?:node|deno|bun|python\d*|perl|ruby)$/i.test(shellBase) &&
568
+ args.some((a) => /^(?:-e|--eval|-c)$/i.test(a));
569
+ if (shellWrapper || inlineEval) {
570
+ add({
571
+ ruleId: 'agent2026.mcp-shell-command', severity: 'medium', confidence: 'high',
572
+ title: 'MCP server is launched through a shell wrapper',
573
+ message: `Server "${name}" is started with "${cmdLine}". Shell metacharacters or an inline -e/-c payload turn the MCP config into arbitrary code execution on every agent launch.`,
574
+ fix: `Launch a pinned executable directly (command + args array) and remove shell operators, bash -c, cmd /c, and -e/-c inline code from the config.`,
575
+ file: rel, line, column: 1, snippet,
576
+ });
577
+ }
578
+
579
+ // 5. Auto-approving dangerous tools removes the human confirmation step.
580
+ for (const [k, v] of Object.entries(cfg)) {
581
+ if (!APPROVE_KEYS.test(k)) continue;
582
+ const hits = dangerousAutoApproved(v);
583
+ if (!hits.length) continue;
584
+ add({
585
+ ruleId: 'agent2026.mcp-auto-approve-dangerous', severity: 'high', confidence: 'high',
586
+ title: 'MCP config auto-approves destructive tools',
587
+ message: `Server "${name}" sets ${k} to ${JSON.stringify(v)}, so the agent can run ${hits.slice(0, 4).join(', ')} without asking the user. A poisoned tool call becomes unattended shell/write/network access.`,
588
+ fix: `Remove ${k} for shell, write, and network tools; require explicit user confirmation per call, and keep auto-approval to read-only tools only.`,
589
+ file: rel, line: findLineOfKey(lines, k).line, column: 1,
590
+ snippet: snippetAt(lines, findLineOfKey(lines, k).line),
591
+ });
592
+ }
593
+
594
+ state.servers.push(server);
595
+ }
596
+
597
+ function mcpEntriesFromJson(json) {
598
+ const maps = [];
599
+ if (json && typeof json === 'object') {
600
+ if (json.mcpServers && typeof json.mcpServers === 'object') maps.push(json.mcpServers);
601
+ if (json.servers && typeof json.servers === 'object') maps.push(json.servers);
602
+ if (json.mcp && typeof json.mcp === 'object' && json.mcp.servers && typeof json.mcp.servers === 'object') {
603
+ maps.push(json.mcp.servers);
604
+ }
605
+ }
606
+ const out = [];
607
+ for (const map of maps) {
608
+ for (const [name, cfg] of Object.entries(map)) {
609
+ if (cfg && typeof cfg === 'object' && !Array.isArray(cfg)) out.push({ name, cfg });
610
+ }
611
+ }
612
+ return out;
613
+ }
614
+
615
+ function analyzeMcpJson(rel, content, lines, add, state) {
616
+ let json;
617
+ try { json = JSON.parse(content); } catch { return; }
618
+ for (const { name, cfg } of mcpEntriesFromJson(json)) {
619
+ const loc = findLineOfKey(lines, name);
620
+ analyzeMcpServer({ name, cfg, rel, line: loc.line, column: loc.column, content }, lines, add, state);
621
+ }
622
+ }
623
+
624
+ function analyzeSmitheryYaml(rel, content, lines, add, state) {
625
+ const nameM = content.match(/^\s*name\s*:\s*["']?([\w.-]+)["']?/m);
626
+ const cmdM = content.match(/^\s*command\s*:\s*(.+?)\s*$/m);
627
+ if (!cmdM && !/\bargs\s*:/.test(content)) return;
628
+
629
+ const command = cmdM ? cmdM[1].replace(/^["']|["']$/g, '').trim() : '';
630
+ let args = [];
631
+ const inline = content.match(/^\s*args\s*:\s*\[([^\]]*)\]/m);
632
+ if (inline) {
633
+ args = inline[1].split(',').map((s) => s.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
634
+ } else {
635
+ const idx = lines.findIndex((l) => /^\s*args\s*:\s*$/.test(l));
636
+ if (idx >= 0) {
637
+ for (let j = idx + 1; j < lines.length; j++) {
638
+ const m = lines[j].match(/^\s*-\s*(.+?)\s*$/);
639
+ if (!m) break;
640
+ args.push(m[1].replace(/^["']|["']$/g, ''));
641
+ }
642
+ }
643
+ }
644
+
645
+ const cfg = { command, args };
646
+ const urlM = content.match(/^\s*url\s*:\s*["']?(https?:\/\/[^\s"']+)/m);
647
+ if (urlM) cfg.url = urlM[1];
648
+
649
+ const envIdx = lines.findIndex((l) => /^\s*env\s*:\s*$/.test(l));
650
+ if (envIdx >= 0) {
651
+ const env = {};
652
+ for (let j = envIdx + 1; j < lines.length; j++) {
653
+ const m = lines[j].match(/^\s+([A-Za-z_][\w]*)\s*:\s*(.+?)\s*$/);
654
+ if (!m) break;
655
+ env[m[1]] = m[2].replace(/^["']|["']$/g, '');
656
+ }
657
+ if (Object.keys(env).length) cfg.env = env;
658
+ }
659
+ const disabledM = content.match(/^\s*disabled\s*:\s*(true|false)\s*$/m);
660
+ if (disabledM) cfg.disabled = disabledM[1] === 'true';
661
+
662
+ const name = nameM ? nameM[1] : (baseOf(rel).replace(/\.ya?ml$/i, '') || 'smithery');
663
+ const line = cmdM ? lineOfPattern(lines, /^\s*command\s*:/) : 1;
664
+ analyzeMcpServer({ name, cfg, rel, line, column: 1, content }, lines, add, state);
665
+ }
666
+
667
+ // ---------------------------------------------------------------------------
668
+ // Tool descriptions and tool objects
669
+ // ---------------------------------------------------------------------------
670
+
671
+ const STRONG_POISON = [
672
+ { re: /ignore\s+(?:all\s+)?(?:the\s+)?(?:previous|prior|above|earlier)\s+(?:instructions?|prompts?|rules?)/i, label: 'ignore-previous-instructions' },
673
+ { re: /disregard\s+(?:all\s+)?(?:the\s+)?(?:previous|prior|above|earlier|system)/i, label: 'disregard-instructions' },
674
+ { re: /forget\s+(?:all\s+)?(?:the\s+)?(?:previous|prior|above)/i, label: 'forget-instructions' },
675
+ { re: /(?:do\s+not|don'?t)\s+(?:tell|mention|inform|alert|reveal|disclose)/i, label: 'hide-from-user' },
676
+ { re: /regardless\s+of\s+(?:what|any|the|your|instructions?|safety|content|rules?)/i, label: 'ignore-policy' },
677
+ { re: /always\s+(?:call|use|invoke|run|execute|include|send|post|return)/i, label: 'always-do' },
678
+ { re: /before\s+(?:answering|responding|calling|replying)/i, label: 'pre-answer-hook' },
679
+ { re: /system\s+prompt/i, label: 'system-prompt-reference' },
680
+ { re: /secretly/i, label: 'concealment' },
681
+ { re: /\bexfiltrat(?:e|es|ed|ing)\b/i, label: 'exfiltration' },
682
+ { re: /new\s+instructions?\s*:/i, label: 'injected-instructions' },
683
+ { re: /never\s+refuse/i, label: 'never-refuse' },
684
+ { re: /bypass\s+(?:safety|policy|guard|filter|restrictions?|approval)/i, label: 'safety-bypass' },
685
+ { re: /you\s+are\s+now\s+(?:a|an|the|in)\b/i, label: 'role-override' },
686
+ ];
687
+
688
+ const WEAK_POISON = [
689
+ { re: /\byou\s+must\b/i, label: 'directive-you-must' },
690
+ { re: /\bmust\s+not\s+(?:tell|mention|reveal|disclose)\b/i, label: 'directive-must-not' },
691
+ { re: /\bdo\s+not\s+(?:stop|ask|check)\b/i, label: 'directive-no-stop' },
692
+ ];
693
+
694
+ // Assembled from fragments so this detector does not match its own source when
695
+ // the repo is self-scanned.
696
+ const SANDBOX_FLAG_RE = new RegExp([
697
+ 'dangerously' + '_skip_permissions',
698
+ 'dangerously' + 'SkipPermissions',
699
+ '--dangerously' + '-skip-permissions',
700
+ 'bypass' + 'Permissions',
701
+ "permissionMode\\s*:\\s*[\"']bypass" + "Permissions[\"']",
702
+ 'auto' + 'ApproveAll',
703
+ 'allow' + 'AllTools',
704
+ 'dangerously' + 'AllowAll',
705
+ ].join('|'));
706
+
707
+ const ZERO_WIDTH_RE = /[\u200B-\u200D\u2060\uFEFF\u180E]/g;
708
+ const BIDI_RE = /[\u202A-\u202E\u2066-\u2069]/g;
709
+
710
+ function analyzeToolDescription(desc, tool, rel, lines, line, add) {
711
+ if (!desc) return;
712
+ const text = desc;
713
+ const rawLine = snippetAt(lines, line);
714
+
715
+ // Hidden Unicode / bidi control characters — used to smuggle instructions.
716
+ const zwMatches = text.match(ZERO_WIDTH_RE) || [];
717
+ const bidiMatches = text.match(BIDI_RE) || [];
718
+ if (zwMatches.length > 4 || bidiMatches.length > 0) {
719
+ add({
720
+ ruleId: 'agent2026.tool-description-hidden-unicode', severity: 'high', confidence: 'high',
721
+ title: 'Tool description carries hidden Unicode',
722
+ message: `Tool "${tool}" has ${zwMatches.length} zero-width character(s) and ${bidiMatches.length} bidi override(s) in its description. Hidden text can redirect the model while the visible description looks benign.`,
723
+ fix: 'Strip zero-width and bidi control characters from all tool descriptions, and fail CI if they reappear in tool metadata.',
724
+ file: rel, line, column: 1, snippet: rawLine,
725
+ });
726
+ }
727
+
728
+ // Base64 blobs in a description are concealment, not documentation.
729
+ const b64 = text.match(/\b[A-Za-z0-9+/]{80,}={0,2}\b/);
730
+ if (b64 && !/https?:\/\//i.test(text)) {
731
+ let printable = 0;
732
+ try {
733
+ const dec = Buffer.from(b64[0], 'base64').toString('utf8');
734
+ if (dec.length) {
735
+ const chars = dec.slice(0, 400);
736
+ for (const ch of chars) if (/[\x20-\x7E\n\r\t]/.test(ch)) printable++;
737
+ printable = printable / chars.length;
738
+ }
739
+ } catch { printable = 0; }
740
+ if (printable > 0.85) {
741
+ add({
742
+ ruleId: 'agent2026.tool-description-encoded', severity: 'medium', confidence: 'medium',
743
+ title: 'Tool description contains a base64 payload',
744
+ message: `Tool "${tool}" embeds a ${b64[0].length}-character base64 blob in its description. Encoded content in tool metadata is a common way to hide injected instructions.`,
745
+ fix: 'Remove encoded content from tool descriptions; descriptions should be short factual prose a reviewer can read.',
746
+ file: rel, line, column: 1, snippet: rawLine,
747
+ });
748
+ }
749
+ }
750
+
751
+ // Description telling the model to send data to a host.
752
+ const urlM = text.match(/https?:\/\/[^\s'"`)]+/i);
753
+ if (urlM) {
754
+ const parsed = parseHttpUrl(urlM[0]);
755
+ const send = /\b(?:send|post|pass|forward|upload|transmit|include|attach|append|share|leak)\b/i.test(text);
756
+ const data = /\b(?:conversation|history|messages?|context|secrets?|tokens?|keys?|credentials?|environment|env|files?|contents?|data|prompt)\b/i.test(text);
757
+ if (parsed && !isLocalHost(parsed.hostname) && send && data) {
758
+ add({
759
+ ruleId: 'agent2026.tool-description-exfil-instruction', severity: 'high', confidence: 'medium',
760
+ title: 'Tool description instructs data exfiltration',
761
+ message: `Tool "${tool}" tells the model to send conversation/secrets data to ${parsed.host}. A tool description is executable instruction to an LLM, so this is an exfiltration directive.`,
762
+ fix: 'Remove the URL and any send/post directive from the tool description; if the tool needs to call a host, allowlist it in code and require user confirmation.',
763
+ file: rel, line, column: 1, snippet: rawLine,
764
+ });
765
+ }
766
+ }
767
+
768
+ // Instruction overrides. Strong signals are high; a lone weak directive is low.
769
+ const strong = [];
770
+ for (const p of STRONG_POISON) if (p.re.test(text)) strong.push(p.label);
771
+ if (strong.length) {
772
+ add({
773
+ ruleId: 'agent2026.tool-description-poisoning', severity: 'high', confidence: 'high',
774
+ title: 'Tool description contains instruction-override text',
775
+ message: `Tool "${tool}" describes itself with ${strong.slice(0, 3).join(', ')}. The model reads this as an instruction, not documentation, so the tool can hijack the agent's behaviour.`,
776
+ fix: 'Rewrite the tool description as factual capability text ("Lists files in a directory") and remove every instruction, policy, or user-directed sentence.',
777
+ file: rel, line, column: 1, snippet: rawLine,
778
+ });
779
+ } else {
780
+ const weak = [];
781
+ for (const p of WEAK_POISON) if (p.re.test(text)) weak.push(p.label);
782
+ if (weak.length) {
783
+ add({
784
+ ruleId: 'agent2026.tool-description-weak-directive', severity: 'low', confidence: 'low',
785
+ title: 'Tool description reads as a directive',
786
+ message: `Tool "${tool}" uses directive language (${weak.join(', ')}). It is not proof of poisoning, but tool descriptions should describe the tool, not command the model.`,
787
+ fix: 'Rephrase the description as a factual summary of what the tool does and returns.',
788
+ file: rel, line, column: 1, snippet: rawLine,
789
+ });
790
+ }
791
+ }
792
+ }
793
+
794
+ const DESTRUCTIVE_NAME_RE = /^(?:delete|drop|exec|execute|shell|run_command|run_shell|run_command_line|shell_exec|deploy|transfer|destroy|wipe|remove|truncate|kill|format|write_file|write|install|publish)[_\-.]?/i;
795
+ const CONFIRM_RE = /\b(?:confirm|confirmed|confirmation|dryRun|dry_run|askForConfirmation|requiresConfirmation|requireConfirmation|humanApproval)\b/i;
796
+
797
+ function toolHandlerName(name) {
798
+ const pascal = String(name).split(/[_\-.]+/).filter(Boolean)
799
+ .map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
800
+ return 'handle' + pascal;
801
+ }
802
+
803
+ function findFunctionBody(text, name) {
804
+ if (!name) return null;
805
+ const escaped = escapeRe(name);
806
+ const patterns = [
807
+ new RegExp('(?:async\\s+)?function\\s+' + escaped + '\\s*\\([^)]*\\)\\s*\\{'),
808
+ new RegExp('(?:const|let|var)\\s+' + escaped + '\\s*=\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>\\s*\\{'),
809
+ new RegExp(escaped + '\\s*:\\s*(?:async\\s*)?(?:function\\s*)?\\([^)]*\\)\\s*\\{'),
810
+ ];
811
+ for (const re of patterns) {
812
+ const m = re.exec(text);
813
+ if (!m) continue;
814
+ const open = text.indexOf('{', m.index + m[0].length - 1);
815
+ if (open < 0) continue;
816
+ const end = matchBracket(text, open);
817
+ return { start: open, end, body: text.slice(open, end + 1) };
818
+ }
819
+ return null;
820
+ }
821
+
822
+ function schemaParamNames(schema) {
823
+ const names = [];
824
+ if (!schema) return names;
825
+ const re = /["']?(?:command|cmd|sql|query|url|path|script)["']?\s*:\s*\{/gi;
826
+ let m;
827
+ while ((m = re.exec(schema))) {
828
+ const n = m[0].replace(/["']/g, '').replace(/\s*:\s*\{$/, '').trim();
829
+ if (!names.includes(n)) names.push(n);
830
+ }
831
+ return names;
832
+ }
833
+
834
+ function analyzeToolBlock(tool, content, rel, lines, add) {
835
+ const blockText = content.slice(tool.block.start, tool.block.end + 1);
836
+ const line = tool.line;
837
+
838
+ const descIdx = fieldIndex(blockText, 'description');
839
+ const schemaIdx = Math.max(
840
+ fieldIndex(blockText, 'inputSchema'),
841
+ fieldIndex(blockText, 'input_schema'),
842
+ fieldIndex(blockText, 'parameters')
843
+ );
844
+ let desc = null;
845
+ if (descIdx >= 0 && (schemaIdx < 0 || descIdx < schemaIdx)) {
846
+ const s = extractStringAt(blockText, blockText.indexOf(':', descIdx) + 1);
847
+ if (s && s.value) desc = s.value;
848
+ }
849
+ const schemaKey = fieldIndex(blockText, 'inputSchema') >= 0 ? 'inputSchema'
850
+ : fieldIndex(blockText, 'input_schema') >= 0 ? 'input_schema'
851
+ : fieldIndex(blockText, 'parameters') >= 0 ? 'parameters' : null;
852
+ const schema = schemaKey ? valueAfterKey(blockText, schemaKey) : null;
853
+
854
+ if (desc) analyzeToolDescription(desc, tool.name, rel, lines, line, add);
855
+
856
+ // Destructive capability without a confirmation parameter.
857
+ if (DESTRUCTIVE_NAME_RE.test(tool.name) && !CONFIRM_RE.test(schema || '') && !CONFIRM_RE.test(tool.registrationHandler || '')) {
858
+ add({
859
+ ruleId: 'agent2026.tool-destructive-no-confirm', severity: 'high', confidence: 'high',
860
+ title: 'Destructive tool has no confirmation parameter',
861
+ message: `Tool "${tool.name}" is named as a destructive action (delete/drop/exec/deploy/transfer/write) but its schema and description expose no confirm/dryRun switch. The model can invoke it unattended.`,
862
+ fix: 'Add a required "confirm": true or "dryRun" parameter, and require an explicit human approval before the destructive branch runs.',
863
+ file: rel, line, column: 1, snippet: snippetAt(lines, line),
864
+ });
865
+ }
866
+
867
+ // Filesystem tool rooted at the whole disk.
868
+ if (/(?:file|filesystem|fs\b|directory|read|write|list)/i.test(tool.name) && schema) {
869
+ const directRoot = /["']?(?:root|rootDir|baseDir|allowedRoot|allowedRoots|filesystemRoot)["']?\s*:\s*["'](?:\.|\/|~|[A-Za-z]:[\\/]{1,2})["']/i.test(schema);
870
+ const defaultRoot = /["']?(?:root|rootDir|baseDir|allowedRoot|allowedRoots|filesystemRoot)["']?\s*:\s*\{[^}]{0,400}?["']?\bdefault["']?\s*:\s*["'](?:\.|\/|~|[A-Za-z]:[\\/]{1,2})["']/i.test(schema);
871
+ if (directRoot || defaultRoot) {
872
+ add({
873
+ ruleId: 'agent2026.filesystem-broad-root', severity: 'high', confidence: 'medium',
874
+ title: 'Filesystem tool is rooted at the whole disk',
875
+ message: `Tool "${tool.name}" exposes a filesystem root of ".", "/", "~", or a drive root. A prompt-injected path can read or write any file the agent process can reach.`,
876
+ fix: 'Root the filesystem tool at one project directory, resolve every requested path against it, and reject paths that escape that base.',
877
+ file: rel, line, column: 1, snippet: snippetAt(lines, line),
878
+ });
879
+ }
880
+ }
881
+
882
+ // Raw command/sql/url/path/script input that reaches a dangerous sink.
883
+ const params = schemaParamNames(schema);
884
+ if (params.length) {
885
+ let body = null;
886
+ if (tool.inlineHandler) body = tool.inlineHandler;
887
+ else if (tool.registrationHandler) body = tool.registrationHandler;
888
+ else {
889
+ const h = findFunctionBody(content, toolHandlerName(tool.name));
890
+ if (h) body = h.body;
891
+ }
892
+ if (body) {
893
+ const argRef = params.map(escapeRe).join('|');
894
+ const sinkRe = new RegExp(
895
+ '\\b(?:exec|execSync|spawn|spawnSync|execFile|execFileSync|query|raw|fetch|axios(?:\\.[a-z]+)?|requests\\.(?:get|post)|https?\\.request|eval)\\s*\\([^)]{0,300}' +
896
+ '(?:args|input|params|arguments|ctx|request)\\s*(?:\\.|\\[\\s*["\\\']?)\\s*(?:' + argRef + ')\\b', 'i'
897
+ );
898
+ if (sinkRe.test(body)) {
899
+ add({
900
+ ruleId: 'agent2026.tool-input-to-sink', severity: 'high', confidence: 'high',
901
+ title: 'Tool input is interpolated into a dangerous sink',
902
+ message: `Tool "${tool.name}" accepts raw ${params.join('/')} input and its handler passes that value into a shell/query/fetch sink. A prompt-injected argument becomes command, SQL, SSRF, or path traversal.`,
903
+ fix: 'Validate the argument against an allowlist/enum, parameterize queries, and never interpolate tool input into exec, fetch, or raw SQL.',
904
+ file: rel, line, column: 1, snippet: snippetAt(lines, line),
905
+ });
906
+ }
907
+ }
908
+ }
909
+
910
+ // readOnlyHint: true while the visible handler writes.
911
+ if (/["']?readOnlyHint["']?\s*:\s*true\b/i.test(blockText)) {
912
+ let body = tool.inlineHandler || tool.registrationHandler || null;
913
+ if (!body) {
914
+ const h = findFunctionBody(content, toolHandlerName(tool.name));
915
+ if (h) body = h.body;
916
+ }
917
+ if (body && /\b(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream|unlink|unlinkSync|rmSync|rmdir|mkdir|rename|truncate)\s*\(|\.(?:insert|update|delete|drop|upsert)\s*\(|(?:exec|execSync|spawn)\s*\(/i.test(body)) {
918
+ add({
919
+ ruleId: 'agent2026.tool-readonly-lie', severity: 'high', confidence: 'high',
920
+ title: 'Tool claims read-only but writes',
921
+ message: `Tool "${tool.name}" declares readOnlyHint: true, but its handler in this file performs a write/exec operation. Agents and reviewers will trust the hint and skip approval.`,
922
+ fix: 'Remove readOnlyHint from any tool that writes, executes, or mutates state; set readOnlyHint only on handlers that exclusively read.',
923
+ file: rel, line, column: 1, snippet: snippetAt(lines, line),
924
+ });
925
+ }
926
+ }
927
+ }
928
+
929
+ function isToolScanFile(rel, content) {
930
+ if (isSkipped(rel)) return false;
931
+ if (content.length > 1024 * 1024) return false;
932
+ if (/\.json$/i.test(rel)) {
933
+ const b = baseOf(rel);
934
+ if (b === 'package.json' || b === 'tsconfig.json' || b === 'jsconfig.json' || b === 'composer.json') return false;
935
+ return /["'](?:inputSchema|input_schema|parameters|type)["']\s*:/.test(content) && /["']name["']\s*:/.test(content);
936
+ }
937
+ return /\.(?:js|jsx|ts|tsx|mjs|cjs|py)$/i.test(rel);
938
+ }
939
+
940
+ function analyzeTools(rel, content, lines, masked, blocks, add, state) {
941
+ if (!isToolScanFile(rel, content)) return;
942
+ const seen = new Set();
943
+
944
+ const nameRe = /["']?name["']?\s*:\s*/g;
945
+ let m;
946
+ while ((m = nameRe.exec(content))) {
947
+ if (masked[m.index] === ' ' || masked[m.index] === '\n') continue;
948
+ const block = smallestBlockAt(blocks, m.index);
949
+ if (!block || seen.has(block.start)) continue;
950
+ const blockText = content.slice(block.start, block.end + 1);
951
+ if (!/["']?(?:inputSchema|input_schema|parameters)["']?\s*:/.test(blockText)) continue;
952
+ const nameInfo = extractStringAt(content, m.index + m[0].length);
953
+ if (!nameInfo || !nameInfo.value) continue;
954
+ const name = nameInfo.value.trim();
955
+ if (!/^[A-Za-z_$][\w$.:-]{0,120}$/.test(name)) continue;
956
+ seen.add(block.start);
957
+ const tool = { name, block, line: lineOf(content, m.index) };
958
+ state.toolDefs.push({ name, rel, line: tool.line });
959
+ analyzeToolBlock(tool, content, rel, lines, add);
960
+ }
961
+
962
+ // server.tool('name', { description, inputSchema, annotations }, handler)
963
+ const regRe = /\b(?:server|mcp|app|tool)\s*\.\s*(?:tool|registerTool|register_tool)\s*\(\s*(["'`])([\w.:-]+)\1\s*,\s*/g;
964
+ while ((m = regRe.exec(content))) {
965
+ if (masked[m.index] === ' ' || masked[m.index] === '\n') continue; // inside a string/comment
966
+ const name = m[2];
967
+ const argStart = m.index + m[0].length;
968
+ if (content[argStart] !== '{') continue;
969
+ const end = matchBracket(content, argStart);
970
+ const block = { start: argStart, end };
971
+ if (seen.has(block.start)) continue;
972
+ seen.add(block.start);
973
+ const blockText = content.slice(block.start, block.end + 1);
974
+ if (!/["']?(?:description|inputSchema|input_schema|parameters)["']?\s*:/.test(blockText)) continue;
975
+ // Handler is the argument after the metadata object.
976
+ let after = block.end + 1;
977
+ while (after < content.length && /[\s,]/.test(content[after])) after++;
978
+ let handlerBody = null;
979
+ if (content[after] === '(' || /^(?:async\s*)?(?:function\b|\()/.test(content.slice(after, after + 20))) {
980
+ const openParen = content.indexOf('(', after);
981
+ const bodyOpen = content.indexOf('{', openParen >= 0 ? openParen : after);
982
+ if (bodyOpen >= 0 && (openParen < 0 || bodyOpen < matchBracket(content, openParen))) {
983
+ handlerBody = content.slice(bodyOpen, matchBracket(content, bodyOpen) + 1);
984
+ }
985
+ } else {
986
+ const id = content.slice(after).match(/^[A-Za-z_$][\w$]*/);
987
+ if (id) {
988
+ const h = findFunctionBody(content, id[0]);
989
+ if (h) handlerBody = h.body;
990
+ }
991
+ }
992
+ const tool = { name, block, line: lineOf(content, m.index), registrationHandler: handlerBody };
993
+ state.toolDefs.push({ name, rel, line: tool.line });
994
+ analyzeToolBlock(tool, content, rel, lines, add);
995
+ }
996
+ }
997
+
998
+ // ---------------------------------------------------------------------------
999
+ // Agent runtime code
1000
+ // ---------------------------------------------------------------------------
1001
+
1002
+ const LLM_CALL_RE = new RegExp(
1003
+ '(?:' +
1004
+ '\\b(?:openai|anthropic|claude|gemini|mistral|groq|ollama|llm|client|model|agent)\\s*\\.\\s*' +
1005
+ '(?:chat\\s*\\.\\s*completions|chatCompletion|ChatCompletion|completions|responses|messages|generateContent|generate_content)\\s*\\.?\\s*(?:create|stream|generate)?\\s*\\(' +
1006
+ '|\\b(?:generateText|streamText|generateObject|streamObject|generateContent|invokeLLM|callLLM|runAgent)\\s*\\(' +
1007
+ '|\\bllm\\s*\\(' +
1008
+ ')', 'i'
1009
+ );
1010
+
1011
+ const USER_INPUT_RE = /\b(?:userInput|user_input|req\.(?:body|query|params|headers)|request\.(?:body|query|params)|message\.content|userMessage|inputText|promptText)\b/;
1012
+
1013
+ function systemMessageBlocks(content, blocks) {
1014
+ const candidates = [];
1015
+ for (const b of blocks) {
1016
+ const body = content.slice(b.start, b.end + 1);
1017
+ if (body.length > 4000) continue;
1018
+ if (/\brole["']?\s*:\s*["']system["']/i.test(body) && /\bcontent["']?\s*:/i.test(body)) candidates.push({ b, body });
1019
+ }
1020
+ // A message array's outer object also contains the role string; keep only the
1021
+ // innermost message objects so a neighbouring user message cannot taint the
1022
+ // analysis of the system message.
1023
+ return candidates.filter(({ b }) => !candidates.some((o) => o.b.start > b.start && o.b.end < b.end));
1024
+ }
1025
+
1026
+ const TOOL_RESULT_RE = /\b(?:toolResult|tool_result|toolOutput|tool_output|observation|functionResult|function_result|tool\.result|result\.content)\b/i;
1027
+
1028
+ // Read the first fetch/axios argument, resolving a simple `const url = '...'`
1029
+ // alias. Returns a parsed URL only when the host is statically knowable.
1030
+ function resolveRequestUrl(content, args, beforeIdx) {
1031
+ const first = String(args || '').replace(/^\(/, '').trim();
1032
+ const lit = /^["'`](https?:\/\/[^"'`\s]+)["'`]/.exec(first);
1033
+ if (lit) return parseHttpUrl(lit[1]);
1034
+ const id = /^([A-Za-z_$][\w$]*)/.exec(first);
1035
+ if (!id) return null;
1036
+ const re = new RegExp('(?:const|let|var)\\s+' + escapeRe(id[1]) + '\\s*=\\s*["\\\'](https?:\\/\\/[^"\\\']+)["\\\']');
1037
+ const m = re.exec(content.slice(0, beforeIdx));
1038
+ return m ? parseHttpUrl(m[1]) : null;
1039
+ }
1040
+
1041
+ function analyzeAgentCode(rel, content, lines, masked, blocks, add) {
1042
+ if (!isCodeFile(rel)) return;
1043
+ if (content.length > 1024 * 1024) return;
1044
+ const maskedLines = masked.split('\n');
1045
+ const lineStarts = [0];
1046
+ for (let i = 0; i < content.length; i++) if (content[i] === '\n') lineStarts.push(i + 1);
1047
+ const hasLLM = LLM_CALL_RE.test(masked);
1048
+
1049
+ // Sandbox / permission bypass is a config fact; check it even without an LLM
1050
+ // call in the same file (the call often lives in another module).
1051
+ for (let i = 0; i < lines.length; i++) {
1052
+ const raw = lines[i];
1053
+ const t = raw.trim();
1054
+ if (!t || t.startsWith('//') || t.startsWith('#') || t.startsWith('*') || t.startsWith('/*')) continue;
1055
+ if (/^re\s*:\s*\//i.test(t) || /\bre\s*:\s*\//.test(t)) continue; // rule database, not live config
1056
+ if (SANDBOX_FLAG_RE.test(raw)) {
1057
+ add({
1058
+ ruleId: 'agent2026.sandbox-bypass', severity: 'high', confidence: 'high',
1059
+ title: 'Agent sandbox / permission gate is disabled',
1060
+ message: 'A flag or permission mode disables the agent sandbox gate, so a prompt-injected action executes without a human confirmation step.',
1061
+ fix: 'Remove the bypass flag, keep the sandbox and permission prompts enabled, and allowlist only the specific tools/paths the agent needs.',
1062
+ file: rel, line: i + 1, column: 1, snippet: snippetAt(lines, i + 1),
1063
+ });
1064
+ break;
1065
+ }
1066
+ }
1067
+
1068
+ // Memory written directly from user input with no provenance label.
1069
+ for (let i = 0; i < lines.length; i++) {
1070
+ const code = maskedLines[i] || '';
1071
+ if (!/\b(?:memory|agentMemory|longTermMemory|memoryStore|conversationHistory|chatHistory)\b/i.test(code)) continue;
1072
+ if (!/\b(?:push|unshift|set|add|save|append|write)\s*\(/i.test(code)) continue;
1073
+ if (!USER_INPUT_RE.test(code)) continue;
1074
+ add({
1075
+ ruleId: 'agent2026.memory-user-input', severity: 'medium', confidence: 'medium',
1076
+ title: 'Agent memory is written from raw user input',
1077
+ message: 'User input is written into agent memory without provenance or sanitisation. A prompt injection in today\'s message becomes a trusted memory in tomorrow\'s system context.',
1078
+ fix: 'Store user content with a provenance tag, validate it, and never promote raw user text to trusted long-term memory; require review for persisted facts.',
1079
+ file: rel, line: i + 1, column: 1, snippet: snippetAt(lines, i + 1),
1080
+ });
1081
+ }
1082
+
1083
+ // Raw user content upserted into a vector store / RAG index.
1084
+ for (let i = 0; i < lines.length; i++) {
1085
+ const window = maskedLines.slice(Math.max(0, i - 2), Math.min(maskedLines.length, i + 3)).join('\n');
1086
+ if (!/\b(?:vector|vectorStore|embedding|pinecone|chroma|weaviate|qdrant|faiss|milvus|rag|knowledgeBase|index)\b/i.test(window)) continue;
1087
+ if (!/\.(?:upsert|addDocuments|add|insert|index)\s*\(/i.test(maskedLines[i] || '')) continue;
1088
+ const after = maskedLines.slice(i, Math.min(maskedLines.length, i + 4)).join('\n');
1089
+ if (!USER_INPUT_RE.test(after)) continue;
1090
+ add({
1091
+ ruleId: 'agent2026.vector-store-poisoning', severity: 'medium', confidence: 'medium',
1092
+ title: 'Raw user content is upserted into a vector store',
1093
+ message: 'Request/user content is written straight into a vector store or RAG index. An attacker can plant text that is later retrieved as trusted knowledge (memory poisoning).',
1094
+ fix: 'Moderate and provenance-tag user content before indexing, isolate untrusted collections, and keep a trusted/untrusted boundary at retrieval time.',
1095
+ file: rel, line: i + 1, column: 1, snippet: snippetAt(lines, i + 1),
1096
+ });
1097
+ }
1098
+
1099
+ // Conversation history posted to an external host.
1100
+ for (let i = 0; i < lines.length; i++) {
1101
+ const code = maskedLines[i] || '';
1102
+ const cm = /\b(?:fetch|axios\.(?:post|put)|sendBeacon|https?\.request)\s*\(/i.exec(code);
1103
+ if (!cm) continue;
1104
+ const callIdx = lineStarts[i] + cm.index + cm[0].lastIndexOf('(');
1105
+ const end = matchBracket(content, callIdx);
1106
+ const args = content.slice(callIdx, end + 1);
1107
+ if (!/JSON\.stringify\s*\(\s*(?:history|messages|conversation|conversationHistory|chatHistory|transcript|context)\b/i.test(args) &&
1108
+ !/\b(?:body|data|json)\s*(?::|=)\s*(?:history|messages|conversation|conversationHistory|chatHistory|transcript)\b/i.test(args)) continue;
1109
+ const parsed = resolveRequestUrl(content, args, callIdx);
1110
+ if (!parsed || isLocalHost(parsed.hostname)) continue;
1111
+ add({
1112
+ ruleId: 'agent2026.history-exfil', severity: 'critical', confidence: 'high',
1113
+ title: 'Conversation history is posted to an external host',
1114
+ message: `The agent serializes conversation history into a request body sent to ${parsed.host}. A single injected instruction can turn this into full transcript exfiltration, including secrets the user pasted.`,
1115
+ fix: 'Remove history from outbound request bodies; if remote logging is required, allowlist the host, redact secrets/PII, and require explicit opt-in.',
1116
+ file: rel, line: i + 1, column: 1, snippet: snippetAt(lines, i + 1),
1117
+ });
1118
+ }
1119
+
1120
+ // Tool list loaded from a remote registry instead of a local allowlist.
1121
+ for (let i = 0; i < lines.length; i++) {
1122
+ const code = maskedLines[i] || '';
1123
+ if (!/\btools\s*:\s*(?:await\s+)?(?:fetch|axios|loadRemote|remoteTools|getRemote|registry|toolRegistry)\b/i.test(code) &&
1124
+ !/\b(?:const|let|var)\s+tools\s*=\s*(?:await\s+)?(?:fetch|loadRemote|getRemote|registry|toolRegistry)\b/i.test(code)) continue;
1125
+ add({
1126
+ ruleId: 'agent2026.tools-from-remote', severity: 'medium', confidence: 'medium',
1127
+ title: 'Tool allowlist is loaded from a remote registry',
1128
+ message: 'The agent builds its tools list from a remote source. Whoever controls that registry can add shell/write tools the developer never reviewed.',
1129
+ fix: 'Use a local, reviewed tool allowlist and pin each tool definition; fetch remote tools only behind a signed/approved manifest.',
1130
+ file: rel, line: i + 1, column: 1, snippet: snippetAt(lines, i + 1),
1131
+ });
1132
+ }
1133
+
1134
+ if (!hasLLM) return;
1135
+
1136
+ // Agent loop with no iteration cap.
1137
+ for (let i = 0; i < lines.length; i++) {
1138
+ const codeLine = maskedLines[i] || '';
1139
+ if (!/^\s*(?:while\s*\(\s*(?:true|1)\s*\)|for\s*\(\s*;\s*;\s*\)|do\s*\{)/.test(codeLine)) continue;
1140
+ const window = maskedLines.slice(i, Math.min(maskedLines.length, i + 60)).join('\n');
1141
+ if (!LLM_CALL_RE.test(window) && !/\bagent\s*\.\s*(?:step|run|invoke|execute)\s*\(/i.test(window)) continue;
1142
+ if (/\b(?:maxSteps|maxIterations|max_iterations|maxTurns|max_loops|maxLoops|iterationLimit|stepLimit)\b/i.test(window)) continue;
1143
+ if (/\b(?:step|iteration|iterations|count|turn|tries)\s*(?:[<>]=?|===?)\s*\d+/i.test(window)) continue;
1144
+ add({
1145
+ ruleId: 'agent2026.agent-loop-no-cap', severity: 'medium', confidence: 'medium',
1146
+ title: 'Agent loop has no iteration cap',
1147
+ message: 'An unbounded while(true)/for(;;) loop drives an LLM call locally with no maxSteps/maxIterations counter and no visible cap. A model that never returns a stop condition burns tokens and hangs the process.',
1148
+ fix: 'Add a finite maxSteps/maxIterations counter (or a deadline) and break the loop when it is reached; log the cap hit.',
1149
+ file: rel, line: i + 1, column: 1, snippet: snippetAt(lines, i + 1),
1150
+ });
1151
+ }
1152
+
1153
+ // Self-recursive agent function with no visible base case.
1154
+ const fnRe = /(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{/g;
1155
+ let fm;
1156
+ while ((fm = fnRe.exec(masked))) {
1157
+ const name = fm[1];
1158
+ const open = masked.indexOf('{', fm.index + fm[0].length - 1);
1159
+ if (open < 0) continue;
1160
+ const end = matchBracket(masked, open);
1161
+ if (end <= open) continue;
1162
+ const body = masked.slice(open, end + 1);
1163
+ if (!LLM_CALL_RE.test(body)) continue;
1164
+ const callRe = new RegExp('\\b' + escapeRe(name) + '\\s*\\(', 'g');
1165
+ callRe.lastIndex = 1;
1166
+ const call = callRe.exec(body);
1167
+ if (!call) continue;
1168
+ const before = body.slice(0, call.index);
1169
+ if (/\bif\s*\([^)]*\)[^{]*\{?[^}]*\breturn\b/i.test(before) || /\b(?:baseCase|maxDepth|depth\s*[<>]=?|if\s*\([^)]*\b(?:depth|count|tries)\b)/i.test(before)) continue;
1170
+ add({
1171
+ ruleId: 'agent2026.recursive-agent-no-base', severity: 'medium', confidence: 'medium',
1172
+ title: 'Recursive agent function has no visible base case',
1173
+ message: `Function "${name}" calls itself after an LLM step with no base-case return before the recursive call. A model that keeps producing another step recurses until the stack or budget dies.`,
1174
+ fix: 'Add an explicit base case (depth/attempt cap and a terminal return) before the recursive call, and default to a bounded loop instead.',
1175
+ file: rel, line: lineOf(content, open), column: 1, snippet: snippetAt(lines, lineOf(content, open)),
1176
+ });
1177
+ }
1178
+
1179
+ // Streaming LLM call without a max_tokens bound.
1180
+ const streamCallRe = /\b(?:openai|anthropic|client|ai|model)\s*\.\s*(?:chat\s*\.\s*completions|completions|responses|messages)\s*\.\s*(?:create|stream)\s*\(|\b(?:streamText|streamObject)\s*\(/gi;
1181
+ let sm;
1182
+ while ((sm = streamCallRe.exec(masked))) {
1183
+ const openParen = masked.indexOf('(', sm.index + sm[0].length - 1);
1184
+ if (openParen < 0) continue;
1185
+ const closeParen = matchBracket(masked, openParen);
1186
+ const argsRaw = content.slice(openParen, closeParen + 1);
1187
+ const isStream = /\bstream\s*[=:]\s*true\b/i.test(argsRaw) || /\.stream\s*\(/i.test(sm[0]) || /^\s*stream(?:Text|Object)\s*\(/i.test(sm[0]);
1188
+ if (!isStream) continue;
1189
+ if (/\b(?:max_tokens|maxTokens|max_output_tokens|maxOutputTokens)\b/.test(argsRaw)) continue;
1190
+ add({
1191
+ ruleId: 'agent2026.streaming-no-max-tokens', severity: 'medium', confidence: 'medium',
1192
+ title: 'Streaming LLM call has no max_tokens limit',
1193
+ message: 'A streaming LLM call sets stream: true but passes no max_tokens/maxTokens bound. A runaway generation streams until the provider or process cuts it off.',
1194
+ fix: 'Set max_tokens (or max_output_tokens) on every streaming call, and enforce a per-session token budget.',
1195
+ file: rel, line: lineOf(content, sm.index), column: 1, snippet: snippetAt(lines, lineOf(content, sm.index)),
1196
+ });
1197
+ }
1198
+
1199
+ const sysBlocks = systemMessageBlocks(content, blocks);
1200
+
1201
+ // User input concatenated into a system-role message.
1202
+ for (const { b, body } of sysBlocks) {
1203
+ if (!USER_INPUT_RE.test(body)) continue;
1204
+ const contentIdx = body.search(/\bcontent["']?\s*:/i);
1205
+ if (contentIdx < 0) continue;
1206
+ const valueRaw = body.slice(contentIdx, contentIdx + 400);
1207
+ const directUser = /\bcontent["']?\s*:\s*(?:userInput|user_input|req\.(?:body|query|params)|request\.(?:body|query|params)|userMessage|promptText)\b/i.test(valueRaw);
1208
+ if (!(directUser || /\$\{[^}]*\}/.test(valueRaw) || /\+\s*[A-Za-z_$]/.test(valueRaw) || /["']\s*\+/.test(valueRaw))) continue;
1209
+ if (TOOL_RESULT_RE.test(valueRaw)) continue;
1210
+ add({
1211
+ ruleId: 'agent2026.system-prompt-user-input', severity: 'high', confidence: 'high',
1212
+ title: 'User input is interpolated into the system prompt',
1213
+ message: 'A system-role message is built from request/user input. The user can rewrite the agent\'s highest-priority instructions (direct prompt injection).',
1214
+ fix: 'Keep the system prompt static; put user content in a user message, and validate/label it before sending it to the model.',
1215
+ file: rel, line: lineOf(content, b.start), column: 1, snippet: snippetAt(lines, lineOf(content, b.start)),
1216
+ });
1217
+ break;
1218
+ }
1219
+
1220
+ // Shorthand `system:` / `system =` prompt property (some SDKs use it instead
1221
+ // of a role message) built from user input.
1222
+ for (let i = 0; i < lines.length; i++) {
1223
+ const code = maskedLines[i] || '';
1224
+ const sm = /\bsystem["']?\s*[:=]/i.exec(code);
1225
+ if (!sm) continue;
1226
+ const raw = lines[i];
1227
+ if (!USER_INPUT_RE.test(raw)) continue;
1228
+ const valuePart = raw.slice(sm.index);
1229
+ const direct = /\bsystem["']?\s*[:=]\s*(?:userInput|user_input|req\.(?:body|query|params)|request\.(?:body|query|params)|userMessage|promptText)\b/i.test(valuePart);
1230
+ if (!(direct || /\$\{[^}]*\}/.test(valuePart) || /\+\s*[A-Za-z_$]/.test(valuePart) || /["']\s*\+/.test(valuePart))) continue;
1231
+ add({
1232
+ ruleId: 'agent2026.system-prompt-user-input', severity: 'high', confidence: 'high',
1233
+ title: 'User input is interpolated into the system prompt',
1234
+ message: 'A shorthand system prompt is built from request/user input. The user controls the agent\'s highest-priority instruction.',
1235
+ fix: 'Keep the system prompt static and pass user content in a user message instead.',
1236
+ file: rel, line: i + 1, column: 1, snippet: snippetAt(lines, i + 1),
1237
+ });
1238
+ break;
1239
+ }
1240
+
1241
+ // Tool result promoted into the system role.
1242
+ for (const { b, body } of sysBlocks) {
1243
+ if (!TOOL_RESULT_RE.test(body)) continue;
1244
+ add({
1245
+ ruleId: 'agent2026.tool-result-to-system', severity: 'high', confidence: 'medium',
1246
+ title: 'Tool result is inserted into the system prompt',
1247
+ message: 'A tool result is placed in a system-role message. Tool output is attacker-influenced data; in the system prompt it becomes an instruction the model will follow.',
1248
+ fix: 'Return tool output in a tool/assistant message (or a clearly delimited user message), never in the system role; validate and label it as untrusted data.',
1249
+ file: rel, line: lineOf(content, b.start), column: 1, snippet: snippetAt(lines, lineOf(content, b.start)),
1250
+ });
1251
+ break;
1252
+ }
1253
+
1254
+ // Secrets interpolated into the agent's system prompt.
1255
+ for (const { b, body } of sysBlocks) {
1256
+ if (!/process\.env\s*(?:\.|\[)\s*["']?[A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)[A-Za-z0-9_]*["']?\s*\]?/i.test(body)) continue;
1257
+ add({
1258
+ ruleId: 'agent2026.secret-in-agent-prompt', severity: 'high', confidence: 'high',
1259
+ title: 'Secret is interpolated into the agent prompt',
1260
+ message: 'The system prompt interpolates a process.env secret (API key/token/password). Every model provider, log, and prompt dump now receives the credential.',
1261
+ fix: 'Never put secrets in prompts; pass credentials only through the provider SDK/HTTP auth header and keep them out of message content.',
1262
+ file: rel, line: lineOf(content, b.start), column: 1, snippet: snippetAt(lines, lineOf(content, b.start)),
1263
+ });
1264
+ break;
1265
+ }
1266
+
1267
+ // JSX sink for LLM output that the existing innerHTML rule does not cover.
1268
+ for (let i = 0; i < lines.length; i++) {
1269
+ const window = lines.slice(i, Math.min(lines.length, i + 4)).join(' ');
1270
+ if (!/dangerouslySetInnerHTML\s*=\s*\{\{\s*__html\s*:/i.test(window)) continue;
1271
+ if (!/\b(?:completion|llmOutput|llm_output|aiResponse|ai_response|response\.choices|message\.content|choices\[0\]|modelOutput)\b/i.test(window)) continue;
1272
+ add({
1273
+ ruleId: 'agent2026.llm-output-dom', severity: 'high', confidence: 'medium',
1274
+ title: 'LLM output is rendered as raw HTML',
1275
+ message: 'dangerouslySetInnerHTML receives LLM output. Prompt injection becomes stored XSS with the user\'s session.',
1276
+ fix: 'Render model output as text (React children/textContent) or sanitize it with DOMPurify before setting __html.',
1277
+ file: rel, line: i + 1, column: 1, snippet: snippetAt(lines, i + 1),
1278
+ });
1279
+ }
1280
+
1281
+ // Code interpreter fed with LLM output.
1282
+ const execRe = /\b(?:eval|exec|execSync|Function|runInSandbox)\s*\(\s*(?:await\s+)?(?:\w+\s*\.\s*)*(?:completion|response|llmOutput|llm_output|llm|aiResponse|ai_response|modelOutput|message\.content|choices\[0\])/gi;
1283
+ let em;
1284
+ while ((em = execRe.exec(masked))) {
1285
+ add({
1286
+ ruleId: 'agent2026.llm-output-exec', severity: 'high', confidence: 'high',
1287
+ title: 'LLM output is executed as code',
1288
+ message: 'Model output is passed directly to eval/exec/Function (a code interpreter). A prompt-injected response becomes remote code execution.',
1289
+ fix: 'Never execute model output; parse structured data, and if a code interpreter is required, run generated code in a hardened sandbox with no secrets, network, or host filesystem.',
1290
+ file: rel, line: lineOf(content, em.index), column: 1, snippet: snippetAt(lines, lineOf(content, em.index)),
1291
+ });
1292
+ }
1293
+ }
1294
+
1295
+ // ---------------------------------------------------------------------------
1296
+ // Prompt / instruction files
1297
+ // ---------------------------------------------------------------------------
1298
+
1299
+ const PROMPT_POISON_RE = /(?:ignore\s+(?:all\s+)?(?:the\s+)?(?:previous|prior|above)\s+instructions?|never\s+refuse|(?:do\s+not|don'?t)\s+tell\s+the\s+user|disregard\s+(?:all\s+)?(?:previous|prior|system)|do\s+anything\s+now|\bDAN\s+mode\b)/i;
1300
+
1301
+ function isNegated(line, idx) {
1302
+ const before = line.slice(Math.max(0, idx - 60), idx);
1303
+ return /\b(?:never|don'?t|do\s+not|must\s+not|avoid|without|not)\b/i.test(before);
1304
+ }
1305
+
1306
+ function analyzePromptFile(rel, content, lines, add, state) {
1307
+ const isMcpCfg = isMcpConfigFile(rel, content);
1308
+
1309
+ // A secret pasted into an instruction file is committed and model-readable.
1310
+ if (!isMcpCfg) {
1311
+ const hit = findSecret(content);
1312
+ if (hit) {
1313
+ const line = lineOf(content, content.indexOf(hit.value));
1314
+ const rawLine = snippetAt(lines, line);
1315
+ add({
1316
+ ruleId: 'agent2026.prompt-file-secret', severity: 'critical', confidence: 'high',
1317
+ title: 'Secret committed in an agent instruction file',
1318
+ message: `This instruction file contains a hardcoded ${hit.type}. Every AI tool that reads CLAUDE.md/AGENTS.md/copilot instructions now has the credential in context, and it is in git.`,
1319
+ fix: `Remove the ${hit.type} from ${rel}, move it to a local environment variable or the vault, and rotate it.`,
1320
+ file: rel, line, column: 1,
1321
+ snippet: rawLine.includes(hit.value) ? rawLine.replace(hit.value, hit.masked) : '[secret redacted]',
1322
+ });
1323
+ state.secretRefs.push({ name: 'prompt-file', rel, line, key: 'instruction-file' });
1324
+ }
1325
+ }
1326
+
1327
+ const poison = PROMPT_POISON_RE.exec(content);
1328
+ if (poison) {
1329
+ add({
1330
+ ruleId: 'agent2026.prompt-instruction-poisoning', severity: 'medium', confidence: 'high',
1331
+ title: 'Agent instruction file contains overrides',
1332
+ message: `The instruction file contains "${poison[0]}". A committed rule that disables refusal or hides behaviour from the user overrides the model's safety instructions for every session.`,
1333
+ fix: 'Remove the instruction-override language; state task rules positively and keep refusal/safety behaviour intact.',
1334
+ file: rel, line: lineOf(content, poison.index), column: 1,
1335
+ snippet: snippetAt(lines, lineOf(content, poison.index)),
1336
+ });
1337
+ }
1338
+
1339
+ // Instructions that read credentials and send them somewhere.
1340
+ let readAt = -1;
1341
+ for (let i = 0; i < lines.length; i++) {
1342
+ const line = lines[i];
1343
+ const cred = /(?:\.env\b|\.ssh\b|id_rsa\b|credentials?\b|secrets?\b|api[_-]?keys?\b|tokens?\b|private\s+key)/i.exec(line);
1344
+ if (!cred) continue;
1345
+ const verb = /\b(?:read|open|load|cat|access|copy|print|dump|gather|collect)\b/gi;
1346
+ let vm;
1347
+ let ok = false;
1348
+ while ((vm = verb.exec(line))) {
1349
+ if (Math.abs(vm.index - cred.index) < 50 && !isNegated(line, vm.index)) { ok = true; break; }
1350
+ }
1351
+ if (ok) { readAt = i; break; }
1352
+ }
1353
+ if (readAt >= 0) {
1354
+ let sendAt = -1;
1355
+ for (let i = 0; i < lines.length; i++) {
1356
+ const line = lines[i];
1357
+ const send = /\b(?:send|post|upload|curl|wget|exfiltrate|forward|transmit|webhook)\b/i.exec(line);
1358
+ const url = /https?:\/\/[^\s'"`)]+/i.exec(line);
1359
+ const hit = send || url;
1360
+ if (!hit) continue;
1361
+ let external = true;
1362
+ if (url) {
1363
+ const u = parseHttpUrl(url[0]);
1364
+ external = !!u && !isLocalHost(u.hostname);
1365
+ }
1366
+ if (external && !isNegated(line, hit.index)) { sendAt = i; break; }
1367
+ }
1368
+ if (sendAt >= 0) {
1369
+ add({
1370
+ ruleId: 'agent2026.prompt-exfil-instruction', severity: 'high', confidence: 'medium',
1371
+ title: 'Agent instructions tell the model to exfiltrate credentials',
1372
+ message: `The instruction file tells the agent to read credentials (${lines[readAt].trim()}) and send them somewhere (${lines[sendAt].trim()}). The model will treat this as authorised behaviour and leak secrets.`,
1373
+ fix: 'Delete the credential-reading and send instruction; if the agent needs a credential, inject a scoped secret in code, never through prompt text.',
1374
+ file: rel, line: readAt + 1, column: 1, snippet: snippetAt(lines, readAt + 1),
1375
+ });
1376
+ }
1377
+ }
1378
+ }
1379
+
1380
+ // ---------------------------------------------------------------------------
1381
+ // Cross-file posture
1382
+ // ---------------------------------------------------------------------------
1383
+
1384
+ function analyzeCrossFile(state, add) {
1385
+ // Same server name in multiple config files — cross-file shadowing / drift.
1386
+ const byName = new Map();
1387
+ for (const s of state.servers) {
1388
+ if (!byName.has(s.name)) byName.set(s.name, []);
1389
+ byName.get(s.name).push(s);
1390
+ }
1391
+ for (const [name, entries] of byName) {
1392
+ if (entries.length < 2) continue;
1393
+ const distinctRel = new Set(entries.map((e) => e.rel));
1394
+ if (distinctRel.size < 2) continue;
1395
+ const first = entries[0];
1396
+ const firstDef = stableValue(first.cfg);
1397
+ for (let i = 1; i < entries.length; i++) {
1398
+ const e = entries[i];
1399
+ if (e.rel === first.rel) continue;
1400
+ const differs = stableValue(e.cfg) !== firstDef;
1401
+ add({
1402
+ ruleId: 'agent2026.mcp-server-shadowing', severity: differs ? 'medium' : 'low', confidence: 'high',
1403
+ title: 'MCP server name is defined in multiple configs',
1404
+ message: `Server "${name}" is defined in both ${first.rel} and ${e.rel}${differs ? ' with different commands/URLs/env' : ' with identical settings'}. Agents may load either definition, so a change in one config silently changes what the other agent trusts (rug-pull proxy).`,
1405
+ fix: `Keep one canonical definition for "${name}" in a single shared config, remove the duplicate, and review the diff before trusting the server in either file.`,
1406
+ file: e.rel, line: e.line, column: e.column || 1, snippet: snippetAt(state.lines[e.rel] || [], e.line),
1407
+ });
1408
+ }
1409
+ }
1410
+
1411
+ // Remote server + committed local secrets: a compromised remote tool can read
1412
+ // local env and send it out.
1413
+ if (state.remoteServers.length && state.secretRefs.length) {
1414
+ for (const r of state.remoteServers.slice(0, 3)) {
1415
+ const sec = state.secretRefs.find((s) => s.rel !== r.rel) || state.secretRefs[0];
1416
+ add({
1417
+ ruleId: 'agent2026.mcp-remote-local-secrets', severity: 'high', confidence: 'medium',
1418
+ title: 'Remote MCP endpoint coexists with committed secrets',
1419
+ message: `Remote MCP server "${r.name}" (${r.url}) is configured in this project, and committed MCP/prompt secrets are also present (e.g. ${sec.rel}:${sec.line}). A malicious tool behind the remote endpoint can read the local secret store and exfiltrate it.`,
1420
+ fix: 'Remove secrets from committed config, use local secret injection/vault, and require authenticated, allowlisted remote MCP endpoints.',
1421
+ file: r.rel, line: r.line, column: 1, snippet: snippetAt(state.lines[r.rel] || [], r.line),
1422
+ });
1423
+ }
1424
+ }
1425
+
1426
+ // An MCP server plus a locally mounted shell tool gives the agent both a
1427
+ // trusted tool plane and unrestricted command execution.
1428
+ const shellTool = state.toolDefs.find((t) => /^(?:shell|bash|exec|execute|exec_command|run_command|run_shell|terminal|powershell|shell_exec|exec_shell)$/i.test(t.name));
1429
+ if (state.servers.length && shellTool) {
1430
+ const server = state.servers[0];
1431
+ add({
1432
+ ruleId: 'agent2026.mcp-with-shell-tool', severity: 'medium', confidence: 'medium',
1433
+ title: 'MCP tools and a shell tool are mounted together',
1434
+ message: `The project configures MCP server "${server.name}" and also defines a shell/exec tool ("${shellTool.name}"). A poisoned MCP tool can call the shell tool, turning a tool-plane compromise into host command execution.`,
1435
+ fix: 'Do not expose a shell/exec tool to an agent that also trusts MCP servers; replace the shell tool with narrow allowlisted operations and require confirmation.',
1436
+ file: shellTool.rel, line: shellTool.line, column: 1, snippet: snippetAt(state.lines[shellTool.rel] || [], shellTool.line),
1437
+ });
1438
+ }
1439
+ }
1440
+
1441
+ // ---------------------------------------------------------------------------
1442
+ // Public API
1443
+ // ---------------------------------------------------------------------------
1444
+
1445
+ function analyzeAgentic(input) {
1446
+ const { findings, add } = makeCollector();
1447
+ if (!input || !Array.isArray(input.files)) return findings;
1448
+ const root = input.root ? path.resolve(input.root) : process.cwd();
1449
+
1450
+ const files = [];
1451
+ for (const f of input.files) {
1452
+ if (!f || typeof f.content !== 'string') continue;
1453
+ let rel = normRel(f.rel);
1454
+ if (path.isAbsolute(String(f.rel || ''))) rel = normRel(path.relative(root, f.rel));
1455
+ if (!rel || rel === '.' || isSkipped(rel)) continue;
1456
+ if (f.content.indexOf('\u0000') !== -1) continue;
1457
+ const lines = Array.isArray(f.lines) ? f.lines : f.content.split(/\r?\n/);
1458
+ files.push({ rel, content: f.content, lines });
1459
+ }
1460
+ files.sort((a, b) => a.rel.localeCompare(b.rel));
1461
+
1462
+ const state = {
1463
+ servers: [], remoteServers: [], secretRefs: [], toolDefs: [], lines: {},
1464
+ };
1465
+
1466
+ for (const f of files) {
1467
+ state.lines[f.rel] = f.lines;
1468
+ if (isMcpConfigFile(f.rel, f.content)) {
1469
+ if (/\.[cm]?json$/i.test(f.rel) || /^\s*[{[]/.test(f.content)) {
1470
+ analyzeMcpJson(f.rel, f.content, f.lines, add, state);
1471
+ }
1472
+ if (/\bcommand\s*:|\bargs\s*:/.test(f.content) && /\.ya?ml$/i.test(f.rel)) {
1473
+ analyzeSmitheryYaml(f.rel, f.content, f.lines, add, state);
1474
+ }
1475
+ } else if (/^(?:smithery\.ya?ml)$/i.test(baseOf(f.rel))) {
1476
+ analyzeSmitheryYaml(f.rel, f.content, f.lines, add, state);
1477
+ }
1478
+
1479
+ if (isPromptConfigFile(f.rel)) {
1480
+ analyzePromptFile(f.rel, f.content, f.lines, add, state);
1481
+ }
1482
+
1483
+ let masked = null;
1484
+ let blocks = null;
1485
+ if (isToolScanFile(f.rel, f.content)) {
1486
+ masked = maskNonCode(f.content);
1487
+ blocks = findObjectBlocks(f.content);
1488
+ analyzeTools(f.rel, f.content, f.lines, masked, blocks, add, state);
1489
+ }
1490
+ if (isCodeFile(f.rel) || /\.(?:jsx|tsx|vue|svelte)$/i.test(f.rel)) {
1491
+ if (!masked) {
1492
+ masked = maskNonCode(f.content);
1493
+ blocks = findObjectBlocks(f.content);
1494
+ }
1495
+ analyzeAgentCode(f.rel, f.content, f.lines, masked, blocks, add);
1496
+ }
1497
+ }
1498
+
1499
+ analyzeCrossFile(state, add);
1500
+
1501
+ const out = findings
1502
+ .filter((f) => f.file && f.fix && f.message)
1503
+ .sort((a, b) => {
1504
+ const s = (SEV_ORDER[a.severity] ?? 9) - (SEV_ORDER[b.severity] ?? 9);
1505
+ if (s) return s;
1506
+ return a.file.localeCompare(b.file) || a.line - b.line;
1507
+ })
1508
+ .slice(0, MAX_FINDINGS);
1509
+
1510
+ return out;
1511
+ }
1512
+
1513
+ module.exports = { analyzeAgentic };