@yagyeshvyas/vibeguard 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/daemon.js ADDED
@@ -0,0 +1,342 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/daemon.js — VibeGuard background daemon.
5
+ *
6
+ * Runs as a persistent process. Watches the working directory for file changes,
7
+ * auto-scans modified files in real-time, and blocks dangerous writes before
8
+ * they hit disk.
9
+ *
10
+ * The daemon provides three protections simultaneously:
11
+ * 1. File watcher: scans every file write (using fs.watch) in real-time
12
+ * 2. Process spawner guard: wraps child_process to intercept spawned commands
13
+ * 3. HTTP interceptor: wraps outbound requests from the daemon process
14
+ *
15
+ * Usage:
16
+ * vibeguard auto-start [dir] Start daemon in background
17
+ * vibeguard auto-stop [dir] Stop daemon
18
+ * vibeguard auto-status [dir] Check if daemon is running
19
+ *
20
+ * The daemon writes a PID file to .vibeguard-daemon.json and logs to
21
+ * .vibeguard-daemon.log in the working directory.
22
+ *
23
+ * 100% local. Zero network. Zero dependencies.
24
+ */
25
+
26
+ const fs = require('fs');
27
+ const path = require('path');
28
+ const os = require('os');
29
+ const { spawn, execSync } = require('child_process');
30
+
31
+ const DAEMON_FILE = '.vibeguard-daemon.json';
32
+ const DAEMON_LOG = '.vibeguard-daemon.log';
33
+ const PID_CHECK_INTERVAL = 5000; // check if process alive every 5s
34
+
35
+ // ─── Daemon process ────────────────────────────────────────────────────────
36
+
37
+ function runDaemon(rootDir, opts) {
38
+ opts = opts || {};
39
+ const logPath = path.join(rootDir, DAEMON_LOG);
40
+ const logStream = fs.createWriteStream(logPath, { flags: 'a' });
41
+
42
+ function log(msg) {
43
+ const ts = new Date().toISOString();
44
+ const line = `[${ts}] ${msg}\n`;
45
+ logStream.write(line);
46
+ if (opts.verbose) process.stderr.write(`[VibeGuard Daemon] ${msg}\n`);
47
+ }
48
+
49
+ log('daemon started');
50
+ log(`watching: ${rootDir}`);
51
+
52
+ // Write PID file
53
+ const pidData = {
54
+ pid: process.pid,
55
+ root: rootDir,
56
+ startedAt: new Date().toISOString(),
57
+ findings: 0,
58
+ blocked: 0,
59
+ watched: 0,
60
+ };
61
+ fs.writeFileSync(path.join(rootDir, DAEMON_FILE), JSON.stringify(pidData, null, 2));
62
+
63
+ // Activate interceptor (wraps exec, fetch, fs, http in THIS process)
64
+ try {
65
+ require('./interceptor').activate({ throwOnBlock: false, logBlocked: true });
66
+ log('interceptor activated');
67
+ } catch (e) {
68
+ log(`interceptor failed: ${e.message}`);
69
+ }
70
+
71
+ // Activate guard (wraps execSync, spawn)
72
+ try {
73
+ require('./guard');
74
+ log('guard activated');
75
+ } catch (e) {
76
+ log(`guard failed: ${e.message}`);
77
+ }
78
+
79
+ // File watcher — scan files on change
80
+ let scanQueue = [];
81
+ let scanTimer = null;
82
+ const { scanFileContent } = require('./scanner');
83
+
84
+ function scheduleScan(filePath) {
85
+ // Only scan code files
86
+ const ext = path.extname(filePath).toLowerCase();
87
+ const codeExts = new Set(['.js', '.ts', '.jsx', '.tsx', '.py', '.go', '.rb', '.java', '.kt', '.swift', '.cs', '.rs', '.php', '.sql', '.sh', '.yml', '.yaml', '.json', '.env']);
88
+ if (!codeExts.has(ext) && !filePath.endsWith('.env') && !filePath.includes('.env')) return;
89
+
90
+ scanQueue.push(filePath);
91
+ if (scanTimer) clearTimeout(scanTimer);
92
+ scanTimer = setTimeout(() => {
93
+ const files = [...new Set(scanQueue)];
94
+ scanQueue = [];
95
+ for (const f of files) {
96
+ try {
97
+ const content = fs.readFileSync(f, 'utf8');
98
+ const relPath = path.relative(rootDir, f);
99
+ const findings = scanFileContent(f, relPath, content, null);
100
+ const critical = findings.filter((x) => x.severity === 'critical');
101
+
102
+ if (critical.length > 0) {
103
+ pidData.findings += findings.length;
104
+ for (const finding of critical) {
105
+ pidData.blocked++;
106
+ log(`BLOCKED [critical] ${finding.ruleId}: ${finding.file}:${finding.line} — ${finding.message}`);
107
+ const color = '\x1b[31m';
108
+ process.stderr.write(`${color}[VibeGuard] BLOCKED [critical] ${finding.ruleId}: ${finding.file}:${finding.line}\x1b[0m\n`);
109
+ process.stderr.write(`${color} ${finding.message}\x1b[0m\n`);
110
+ process.stderr.write(`${color} Fix: ${finding.fix || 'Review this finding.'}\x1b[0m\n\n`);
111
+ }
112
+
113
+ // Auto-revert: restore from git if file is tracked, otherwise warn
114
+ if (critical.length > 0 && !opts.noRevert) {
115
+ try {
116
+ const { execSync } = require('child_process');
117
+ const gitResult = execSync(`git show HEAD:"${relPath}" 2>NUL`, {
118
+ cwd: rootDir,
119
+ encoding: 'utf8',
120
+ stdio: 'pipe',
121
+ timeout: 2000,
122
+ });
123
+ if (gitResult) {
124
+ fs.writeFileSync(f, gitResult);
125
+ process.stderr.write(`\x1b[31m[VibeGuard] REVERTED: ${relPath} restored from git HEAD\x1b[0m\n\n`);
126
+ }
127
+ } catch {
128
+ // Not in git — can't revert, just warn
129
+ process.stderr.write(`\x1b[33m[VibeGuard] WARNING: ${relPath} has critical findings but is not in git — cannot auto-revert\x1b[0m\n\n`);
130
+ }
131
+ }
132
+ } else if (findings.length > 0) {
133
+ // High/medium findings — alert but don't revert
134
+ const high = findings.filter((x) => x.severity === 'high');
135
+ if (high.length > 0) {
136
+ pidData.findings += findings.length;
137
+ for (const finding of high) {
138
+ log(`ALERT [high] ${finding.ruleId}: ${finding.file}:${finding.line} — ${finding.message}`);
139
+ process.stderr.write(`\x1b[33m[VibeGuard] ALERT [high] ${finding.ruleId}: ${finding.file}:${finding.line}\x1b[0m\n`);
140
+ process.stderr.write(`\x1b[33m ${finding.message}\x1b[0m\n\n`);
141
+ }
142
+ }
143
+ }
144
+ // Update PID file
145
+ fs.writeFileSync(path.join(rootDir, DAEMON_FILE), JSON.stringify(pidData, null, 2));
146
+ } catch (e) {
147
+ // File might be deleted or locked — skip
148
+ }
149
+ }
150
+ }, 300); // debounce 300ms
151
+ }
152
+
153
+ // Watch the directory tree
154
+ let watcher;
155
+ try {
156
+ watcher = fs.watch(rootDir, { recursive: true }, (eventType, filename) => {
157
+ if (!filename) return;
158
+ const fullPath = path.join(rootDir, filename);
159
+ if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
160
+ pidData.watched++;
161
+ scheduleScan(fullPath);
162
+ }
163
+ });
164
+ log('file watcher active');
165
+ } catch (e) {
166
+ log(`file watcher failed: ${e.message} — trying manual polling`);
167
+ // Fallback: poll every 2 seconds
168
+ const knownFiles = new Map();
169
+ setInterval(() => {
170
+ function walkDir(dir) {
171
+ try {
172
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
173
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
174
+ const fullPath = path.join(dir, entry.name);
175
+ if (entry.isFile()) {
176
+ try {
177
+ const mtime = fs.statSync(fullPath).mtimeMs;
178
+ const prev = knownFiles.get(fullPath);
179
+ if (!prev || prev !== mtime) {
180
+ knownFiles.set(fullPath, mtime);
181
+ if (prev) scheduleScan(fullPath); // only scan changed files
182
+ }
183
+ } catch {}
184
+ } else if (entry.isDirectory()) {
185
+ walkDir(fullPath);
186
+ }
187
+ }
188
+ } catch {}
189
+ }
190
+ walkDir(rootDir);
191
+ }, 2000);
192
+ log('polling fallback active (2s interval)');
193
+ }
194
+
195
+ // Keep process alive
196
+ process.on('SIGTERM', () => {
197
+ log('daemon stopping (SIGTERM)');
198
+ if (watcher) watcher.close();
199
+ try { fs.unlinkSync(path.join(rootDir, DAEMON_FILE)); } catch {}
200
+ process.exit(0);
201
+ });
202
+
203
+ process.on('SIGINT', () => {
204
+ log('daemon stopping (SIGINT)');
205
+ if (watcher) watcher.close();
206
+ try { fs.unlinkSync(path.join(rootDir, DAEMON_FILE)); } catch {}
207
+ process.exit(0);
208
+ });
209
+
210
+ // Heartbeat — update PID file every 30s to prove we're alive
211
+ setInterval(() => {
212
+ pidData.heartbeat = new Date().toISOString();
213
+ try {
214
+ fs.writeFileSync(path.join(rootDir, DAEMON_FILE), JSON.stringify(pidData, null, 2));
215
+ } catch {}
216
+ }, 30000);
217
+ }
218
+
219
+ // ─── Daemon management ────────────────────────────────────────────────────
220
+
221
+ function startDaemon(rootDir, opts) {
222
+ opts = opts || {};
223
+ const pidFile = path.join(rootDir, DAEMON_FILE);
224
+
225
+ // Check if already running
226
+ if (isDaemonRunning(rootDir)) {
227
+ return { started: false, reason: 'daemon already running', pidFile };
228
+ }
229
+
230
+ // Spawn daemon as detached background process
231
+ const nodeBin = process.execPath;
232
+ const daemonScript = path.join(__dirname, 'daemon-run.js');
233
+ const logPath = path.join(rootDir, DAEMON_LOG);
234
+
235
+ const args = [daemonScript, rootDir];
236
+ if (opts.verbose) args.push('--verbose');
237
+
238
+ const logStream = fs.openSync(logPath, 'a');
239
+
240
+ const child = spawn(nodeBin, args, {
241
+ detached: true,
242
+ stdio: ['ignore', logStream, logStream],
243
+ cwd: rootDir,
244
+ });
245
+
246
+ child.unref();
247
+
248
+ // Wait a moment for PID file to appear
249
+ return new Promise((resolve) => {
250
+ setTimeout(() => {
251
+ if (fs.existsSync(pidFile)) {
252
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
253
+ resolve({ started: true, pid: data.pid, root: rootDir, logFile: logPath });
254
+ } else {
255
+ resolve({ started: false, reason: 'daemon failed to start — check log', logFile: logPath });
256
+ }
257
+ }, 1000);
258
+ });
259
+ }
260
+
261
+ function stopDaemon(rootDir) {
262
+ const pidFile = path.join(rootDir, DAEMON_FILE);
263
+ if (!fs.existsSync(pidFile)) {
264
+ return { stopped: false, reason: 'no daemon running' };
265
+ }
266
+
267
+ try {
268
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
269
+ const pid = data.pid;
270
+ if (pid) {
271
+ try {
272
+ process.kill(pid, 'SIGTERM');
273
+ } catch (e) {
274
+ // Process might already be dead
275
+ }
276
+ }
277
+ // Wait for PID file to be removed
278
+ return new Promise((resolve) => {
279
+ let tries = 0;
280
+ const interval = setInterval(() => {
281
+ if (!fs.existsSync(pidFile) || tries > 10) {
282
+ clearInterval(interval);
283
+ try { fs.unlinkSync(pidFile); } catch {}
284
+ resolve({ stopped: true, pid });
285
+ }
286
+ tries++;
287
+ }, 200);
288
+ });
289
+ } catch (e) {
290
+ try { fs.unlinkSync(pidFile); } catch {}
291
+ return { stopped: false, reason: e.message };
292
+ }
293
+ }
294
+
295
+ function isDaemonRunning(rootDir) {
296
+ const pidFile = path.join(rootDir, DAEMON_FILE);
297
+ if (!fs.existsSync(pidFile)) return false;
298
+ try {
299
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
300
+ const pid = data.pid;
301
+ if (!pid) return false;
302
+ // Check if process is alive
303
+ try {
304
+ process.kill(pid, 0);
305
+ return true;
306
+ } catch (e) {
307
+ // Process is dead — clean up stale PID file
308
+ try { fs.unlinkSync(pidFile); } catch {}
309
+ return false;
310
+ }
311
+ } catch {
312
+ try { fs.unlinkSync(pidFile); } catch {}
313
+ return false;
314
+ }
315
+ }
316
+
317
+ function getDaemonStatus(rootDir) {
318
+ const pidFile = path.join(rootDir, DAEMON_FILE);
319
+ const logPath = path.join(rootDir, DAEMON_LOG);
320
+ if (!fs.existsSync(pidFile)) {
321
+ return { running: false };
322
+ }
323
+ try {
324
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
325
+ const running = isDaemonRunning(rootDir);
326
+ return {
327
+ running,
328
+ pid: data.pid,
329
+ root: data.root,
330
+ startedAt: data.startedAt,
331
+ findings: data.findings || 0,
332
+ blocked: data.blocked || 0,
333
+ watched: data.watched || 0,
334
+ heartbeat: data.heartbeat,
335
+ logFile: logPath,
336
+ };
337
+ } catch {
338
+ return { running: false };
339
+ }
340
+ }
341
+
342
+ module.exports = { runDaemon, startDaemon, stopDaemon, isDaemonRunning, getDaemonStatus, DAEMON_FILE, DAEMON_LOG };
package/src/guard.js ADDED
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/guard.js — Node.js runtime guard.
5
+ *
6
+ * Usage:
7
+ * node --require ./src/guard.js agent.js
8
+ * node --require vibeguard/guard my-app.js
9
+ *
10
+ * Activates VibeGuard's runtime interceptor (wraps child_process.exec,
11
+ * fs.readFileSync, fetch, http.request) AND scans scripts before execution.
12
+ * Blocks dangerous commands, secret exfiltration, and sensitive file access
13
+ * at the Node.js runtime level — below the agent's code.
14
+ *
15
+ * 100% local. Zero network. Zero dependencies.
16
+ */
17
+
18
+ // Activate the interceptor (wraps exec, fetch, fs, http)
19
+ try {
20
+ const interceptor = require('./interceptor');
21
+ interceptor.activate({ throwOnBlock: false, logBlocked: true });
22
+ } catch (e) {
23
+ process.stderr.write(`[VibeGuard Guard] Interceptor activation failed: ${e.message}\n`);
24
+ }
25
+
26
+ // Also wrap child_process.execSync to scan commands before execution
27
+ try {
28
+ const { execSync } = require('child_process');
29
+ const { checkCommand } = require('./shell-guard');
30
+ const originalExecSync = execSync;
31
+ require('child_process').execSync = function (cmd, opts) {
32
+ const result = checkCommand(cmd);
33
+ if (result.blocked) {
34
+ process.stderr.write(`\x1b[31m[VibeGuard Guard] BLOCKED: ${result.reason}\x1b[0m\n`);
35
+ process.stderr.write(`\x1b[31m Command: ${result.command}\x1b[0m\n`);
36
+ process.stderr.write(`\x1b[31m Severity: ${result.severity}\x1b[0m\n`);
37
+ throw new Error(`VibeGuard Guard: ${result.reason}`);
38
+ }
39
+ return originalExecSync.call(this, cmd, opts);
40
+ };
41
+ } catch (e) {
42
+ // If wrapping fails, the interceptor above still covers exec/execSync
43
+ }
44
+
45
+ // Also wrap spawn to scan commands
46
+ try {
47
+ const { spawn } = require('child_process');
48
+ const { checkCommand } = require('./shell-guard');
49
+ const originalSpawn = spawn;
50
+ require('child_process').spawn = function (cmd, args, opts) {
51
+ const fullCmd = [cmd, ...(args || [])].join(' ');
52
+ const result = checkCommand(fullCmd);
53
+ if (result.blocked) {
54
+ process.stderr.write(`\x1b[31m[VibeGuard Guard] BLOCKED: ${result.reason}\x1b[0m\n`);
55
+ process.stderr.write(`\x1b[31m Command: ${result.command}\x1b[0m\n`);
56
+ process.stderr.write(`\x1b[31m Severity: ${result.severity}\x1b[0m\n`);
57
+ // Emit an error event instead of spawning
58
+ const { EventEmitter } = require('events');
59
+ const fakeProc = new EventEmitter();
60
+ fakeProc.stdout = new EventEmitter();
61
+ fakeProc.stderr = new EventEmitter();
62
+ fakeProc.pid = -1;
63
+ fakeProc.killed = true;
64
+ process.nextTick(() => {
65
+ fakeProc.emit('error', new Error(`VibeGuard Guard: ${result.reason}`));
66
+ fakeProc.emit('close', 1);
67
+ });
68
+ return fakeProc;
69
+ }
70
+ return originalSpawn.call(this, cmd, args, opts);
71
+ };
72
+ } catch (e) {
73
+ // If wrapping fails, continue — interceptor covers exec
74
+ }
75
+
76
+ process.stderr.write(`\x1b[32m[VibeGuard Guard] Active — runtime interceptor + command scanner engaged.\x1b[0m\n`);
77
+ process.stderr.write(`\x1b[2m[VibeGuard Guard] Wrapping: exec, execSync, spawn, fetch, http.request, fs.readFileSync\x1b[0m\n`);
78
+ process.stderr.write(`\x1b[2m[VibeGuard Guard] Override: set VG_OVERRIDE=1 to bypass\x1b[0m\n`);
79
+
80
+ module.exports = { active: true };
package/src/mcp-server.js CHANGED
@@ -239,11 +239,6 @@ const TOOLS = [
239
239
  description: 'Trace findings back to AI prompts that generated them. Reads Cursor/Claude session history.',
240
240
  inputSchema: DIR_SCHEMA,
241
241
  },
242
- {
243
- name: 'behavior_analysis',
244
- description: 'Analyze AI agent session history for risky behavior patterns (blind approvals, high delegation, skipping tests).',
245
- inputSchema: DIR_SCHEMA,
246
- },
247
242
  {
248
243
  name: 'list_rules',
249
244
  description: 'List all VibeGuard rules with their ID, severity, category, and description.',
package/src/rules-pack.js CHANGED
@@ -1873,7 +1873,7 @@ const phpRules = [
1873
1873
  ];
1874
1874
 
1875
1875
  const csharpRules = [
1876
- { id: 'csharp.sql-injection', severity: 'high', re: /SqlCommand\s*\(\s*["'].*\+\s*\w/, message: 'C# SqlCommand with string concatenation — SQL injection', cwe: 'CWE-89', owasp: 'A03', fix: 'Use SqlParameter: cmd.Parameters.AddWithValue("@id", id).' },
1876
+ { id: 'csharp.sql-injection', severity: 'high', re: /(?:SqlCommand|CommandText)\s*[\(=]\s*["'].*\+\s*\w/, message: 'C# SqlCommand with string concatenation — SQL injection', cwe: 'CWE-89', owasp: 'A03', fix: 'Use SqlParameter: cmd.Parameters.AddWithValue("@id", id).' },
1877
1877
  { id: 'csharp.command-injection', severity: 'high', re: /Process\.Start\s*\(\s*[^,]*\+/, message: 'C# Process.Start with string concatenation — command injection', cwe: 'CWE-78', owasp: 'A03', fix: 'Use ProcessStartInfo with separate arguments array.' },
1878
1878
  { id: 'csharp.random', severity: 'medium', re: /new\s+Random\s*\(\s*\)/, message: 'C# Random() without seed — predictable random numbers', cwe: 'CWE-330', owasp: 'A02', fix: 'Use RandomNumberGenerator for crypto or RandomNumberGenerator.Create().' },
1879
1879
  ];
@@ -2025,6 +2025,15 @@ const aiSecurityRulesExtra = [
2025
2025
  { id: 'ai.agent-loop-no-cap', severity: 'high', re: /while\s*\(\s*true\s*\)|for\s*\(\s*;\s*;\s*\)|maxIterations\s*:\s*(?:Infinity|0|-1|undefined)/, message: 'AI agent loop without iteration cap — infinite loop / cost', cwe: 'CWE-835', owasp: 'A04', fix: 'Set maxIterations to a finite number. Add timeout and budget.' },
2026
2026
  { id: 'ai.tool-result-injection', severity: 'high', re: /(?:response|result|output)\s*(?:\.text|\.content|\.body|\.json)\s*(?:\+|\`\$\{)/, message: 'Tool result concatenated into prompt — indirect prompt injection', cwe: 'CWE-94', owasp: 'A03', fix: 'Escape tool results before including in prompt. Use structured parsing.' },
2027
2027
  { id: 'ai.no-content-filter-bypass', severity: 'medium', re: /(?:moderation|filter|safety)\s*(?::\s*false|\.disable|\.bypass)/, message: 'AI content filter/safety disabled', cwe: 'CWE-693', owasp: 'A05', fix: 'Keep content moderation enabled. Use provider-side safety settings.' },
2028
+ // --- AI-code-generation-specific rules (the wedge: generic SAST misses these) ---
2029
+ { id: 'ai.user-input-in-system-prompt', severity: 'critical', re: /system['"`][^}]*content\s*:\s*[^}]*(?:req|request|user|input|body|query|params)\b/i, message: 'User input injected into system prompt — prompt injection root cause', cwe: 'CWE-94', owasp: 'A03', fix: 'Never put user input in the system prompt. Use the user message role only.' },
2030
+ { id: 'ai.llm-output-exec', severity: 'critical', re: /(?:exec|execSync|spawn|eval|Function)\s*\(\s*(?:completion|response|result|output|message|content|text|answer|reply)\b/i, message: 'LLM output passed to exec/eval — prompt injection becomes RCE', cwe: 'CWE-94', owasp: 'A03', fix: 'Never execute LLM output. Parse structured JSON and validate before any eval/exec.' },
2031
+ { id: 'ai.llm-output-sql-v2', severity: 'high', re: /(?:query|execute|raw)\s*\(\s*(?:completion|response|result|output|message|content|text|answer|reply)\b/i, message: 'LLM output passed to SQL query — prompt injection becomes SQL injection', cwe: 'CWE-89', owasp: 'A03', fix: 'Never use LLM output as SQL. Extract structured data and parameterize.' },
2032
+ { id: 'ai.no-prompt-injection-guard', severity: 'medium', re: /(?:openai|anthropic|gemini|claude)\.(?:chat|completions|messages)\.create\s*\(\s*\{[^}]*(?:messages|prompt)\s*:/i, confidence: 'low', message: 'LLM API call without prompt injection guard — no input sanitization', cwe: 'CWE-94', owasp: 'A03', fix: 'Add a prompt injection detection layer before sending user input to the LLM.' },
2033
+ { id: 'ai.mcp-tool-no-auth', severity: 'high', re: /server\.tool\s*\(\s*['"][^'"]+['"][^)]*(?:file|exec|shell|command|database|query|delete|write|read)/i, message: 'MCP tool with dangerous capability and no auth check — abuse by prompt injection', cwe: 'CWE-306', owasp: 'A01', fix: 'Add authentication/authorization to MCP tools that access files, commands, or databases.' },
2034
+ { id: 'ai.cursorrule-injection', severity: 'medium', re: /(?:IGNORE|DISREGARD|FORGET)\s+(?:all\s+)?(?:previous|prior|above)\s+(?:instructions|rules|guidelines)/i, fileFilter: '\\.(?:md|txt|cursorrules|cursorrule)$', message: 'Prompt injection pattern in rules file — AI may follow injected instructions', cwe: 'CWE-94', owasp: 'A03', fix: 'Remove injection patterns from rules files. Use structured rule format.' },
2035
+ { id: 'ai.hallucinated-import', severity: 'medium', re: /(?:require|import)\s*\(\s*['"](?:ai-|openai-|claude-|llm-|gpt-|chat-)[a-z0-9-]+['"]\)/i, confidence: 'low', message: 'Import of AI-specific package — verify it exists (slopsquatting risk)', cwe: 'CWE-1104', owasp: 'A06', fix: 'Verify the package exists on npm. AI tools sometimes hallucinate package names.' },
2036
+ { id: 'ai.agent-env-key-direct', severity: 'critical', re: /\bsk-[a-zA-Z0-9]{20,}\b(?!.*process\.env)/i, message: 'AI API key hardcoded in code — key visible to AI agents in context', cwe: 'CWE-798', owasp: 'A02', fix: 'Use a secret vault (vibeguard vault) to hide keys from AI agent context. Never expose keys in code AI tools can read.' },
2028
2037
  ];
2029
2038
 
2030
2039
  // ---------------------------------------------------------------------------
@@ -2360,9 +2369,7 @@ const powerRulesExtra = [
2360
2369
 
2361
2370
  // More AI security
2362
2371
  { id: 'ai.prompt-leak-via-error', severity: 'high', re: /catch\s*\(\s*\w+\s*\)\s*\{[^}]*(?:console\.log|throw|res\.(?:json|send))[^}]*(?:prompt|system|instructions)/i, message: 'AI prompt leaked via error handler — system prompt exposure', cwe: 'CWE-209', owasp: 'A01', fix: 'Never include prompt content in error responses. Log server-side only.' },
2363
- { id: 'ai.no-input-sanitization', severity: 'high', re: /(?:messages|prompt|input)\s*[:=]\s*req\.(?:body|query|params)\.(?:prompt|message|input|text)/i, confidence: 'low', message: 'AI input from user without sanitization — prompt injection', cwe: 'CWE-20', owasp: 'A03', fix: 'Sanitize user input before passing to LLM. Strip injection patterns.' },
2364
2372
  { id: 'ai.unbounded-output', severity: 'medium', re: /max_tokens\s*[:=]\s*(?:undefined|0|-1|Infinity|100000|1000000)/i, message: 'AI output without max_tokens limit — cost and DoS risk', cwe: 'CWE-770', owasp: 'A04', fix: 'Set max_tokens to a reasonable limit (e.g. 500-2000).' },
2365
- { id: 'ai.no-rate-limit', severity: 'medium', re: /(?:openai|anthropic|gemini|llama)\.(?:completions|chat|messages|generate)/i, confidence: 'low', message: 'LLM API call without rate limiting — cost abuse risk', cwe: 'CWE-770', owasp: 'A04', fix: 'Add rate limiting on AI endpoints. Track and limit per-user costs.' },
2366
2373
  { id: 'ai.response-not-validated', severity: 'medium', re: /(?:response|completion|output)\.(?:text|content|message|choices)\[0\]\.(?:text|content)/, confidence: 'low', message: 'AI response used without validation — may contain injection or malformed data', cwe: 'CWE-20', owasp: 'A08', fix: 'Validate AI output format with Zod schema before using.' },
2367
2374
  ];
2368
2375
 
@@ -2615,10 +2622,103 @@ const amazingRules = [
2615
2622
  { id: 'firewall.keylogger-install', severity: 'critical', re: /(?:install|create|deploy)\s+(?:a\s+)?keylogger/i, skipComments: true, message: 'Keylogger installation request', cwe: 'CWE-200', owasp: 'A01', fix: 'Block immediately. This is surveillance malware.' },
2616
2623
  ];
2617
2624
 
2625
+ // ---------------------------------------------------------------------------
2626
+ // HARDENED BATCH: 60 rules — rate limiting, input validation, secrets deep,
2627
+ // dependency vulns, error/info leakage, file upload safety
2628
+ // ---------------------------------------------------------------------------
2629
+
2630
+ // --- 10 Rate Limiting Rules ---
2631
+ const rateLimitRules = [
2632
+ { id: 'ratelimit.express-missing', severity: 'high', re: /app\.(?:get|post|put|delete|patch)\s*\([^)]*(?:req,\s*res)/, confidence: 'low', skipComments: true, message: 'Express route without rate limiting — brute force / DoS', cwe: 'CWE-770', owasp: 'A04', fix: 'Add express-rate-limit: rateLimit({ windowMs: 60000, max: 100 })' },
2633
+ { id: 'ratelimit.login-no-limit', severity: 'critical', re: /(?:login|signin|authenticate)\s*[:(]\s*(?:async\s+)?function|(?:login|signin).*app\.(?:post|get)/i, confidence: 'medium', skipComments: true, message: 'Login endpoint without rate limiting — credential stuffing', cwe: 'CWE-307', owasp: 'A07', fix: 'Add per-IP rate limit on login: max 5 attempts per 15 min. Add exponential backoff.' },
2634
+ { id: 'ratelimit.api-no-key', severity: 'medium', re: /app\.(?:get|post)\s*\(\s*['"]\/api\//, confidence: 'low', skipComments: true, message: 'API route without API key or rate limit — unbounded access', cwe: 'CWE-770', owasp: 'A04', fix: 'Add API key auth + rate limit per key. Use express-rate-limit.' },
2635
+ { id: 'ratelimit.no-burst-protection', severity: 'medium', re: /express\.json\s*\(\s*\{\s*\}\s*\)|bodyParser\s*\(\s*\)/, confidence: 'low', skipComments: true, message: 'No burst protection — large number of rapid requests can DoS', cwe: 'CWE-770', owasp: 'A04', fix: 'Add rate limiter middleware before body parser. Limit to 100 req/min per IP.' },
2636
+ { id: 'ratelimit.password-reset-no-limit', severity: 'high', re: /(?:reset|forgot).*password.*(post|route)/i, confidence: 'medium', skipComments: true, message: 'Password reset endpoint without rate limit — email bombing', cwe: 'CWE-307', owasp: 'A07', fix: 'Limit reset emails: max 3 per hour per email. Add CAPTCHA after 2 attempts.' },
2637
+ { id: 'ratelimit.no-global-limit', severity: 'medium', re: /app\.listen\s*\(/, confidence: 'low', skipComments: true, message: 'Server starts without global rate limiter — no DoS protection', cwe: 'CWE-770', owasp: 'A04', fix: 'Add app.use(rateLimit({ windowMs: 60000, max: 100 })) before routes.' },
2638
+ { id: 'ratelimit.otp-no-limit', severity: 'high', re: /(?:otp|verification|verify).*code.*(?:post|route|verify)/i, confidence: 'medium', skipComments: true, message: 'OTP/verification endpoint without rate limit — brute force OTP', cwe: 'CWE-307', owasp: 'A07', fix: 'Limit OTP attempts: max 5 per 10 min. Lock after 3 failures. Add exponential backoff.' },
2639
+ { id: 'ratelimit.websocket-no-limit', severity: 'medium', re: /(?:io|socket)\.(?:on|connect)\s*\(/, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'WebSocket without connection rate limit — resource exhaustion', cwe: 'CWE-770', owasp: 'A04', fix: 'Add connection rate limit: max 10 new connections per second per IP.' },
2640
+ { id: 'ratelimit.signup-no-limit', severity: 'high', re: /(?:signup|register|createUser).*app\.(?:post|route)/i, confidence: 'medium', skipComments: true, message: 'Signup endpoint without rate limit — account enumeration / mass registration', cwe: 'CWE-307', owasp: 'A07', fix: 'Add per-IP rate limit on signup: max 3 per hour. Add CAPTCHA.' },
2641
+ { id: 'ratelimit.ai-cost-no-cap', severity: 'high', re: /(?:openai|anthropic|gemini)\.(?:chat|completions|messages|generate)\.(?:create|stream)\b/i, confidence: 'low', skipComments: true, message: 'AI API call without cost cap — unlimited spend', cwe: 'CWE-770', owasp: 'A04', fix: 'Add per-user token budget. Set max_tokens. Track and cap daily spend.' },
2642
+ ];
2643
+
2644
+ // --- 10 Input Validation Rules ---
2645
+ const inputValidationRules = [
2646
+ { id: 'validation.missing-zod', severity: 'medium', re: /req\.(?:body|query|params)\s*(?:;|\n|\)|$)/, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Request body/query used without schema validation — type confusion / injection', cwe: 'CWE-20', owasp: 'A03', fix: 'Validate with Zod: const schema = z.object({ name: z.string().min(1) }); schema.parse(req.body).' },
2647
+ { id: 'validation.no-type-check', severity: 'medium', re: /parseInt\s*\(\s*req\.(?:body|query|params)\./, confidence: 'medium', skipComments: true, message: 'parseInt on request input without NaN check — type confusion', cwe: 'CWE-20', owasp: 'A03', fix: 'Check: if (isNaN(id)) return res.status(400).json({ error: "Invalid ID" });' },
2648
+ { id: 'validation.no-length-limit', severity: 'medium', re: /(?:req\.body|req\.query)\.(?:name|title|description|comment|bio|message|content|body|text)\b(?!.*(?:\.length|maxLength|truncate|slice|substring))/i, confidence: 'low', skipComments: true, message: 'String field from request without length validation — storage DoS', cwe: 'CWE-20', owasp: 'A04', fix: 'Limit length: if (req.body.name.length > 200) return 400; or use Zod .max(200).' },
2649
+ { id: 'validation.no-email-format', severity: 'medium', re: /req\.body\.(?:email|userEmail|user_email)\b(?!.*(?:validator|isEmail|z\.string\(\)\.email|includes\(['"]@))/i, confidence: 'low', skipComments: true, message: 'Email from request without format validation — invalid data / injection', cwe: 'CWE-20', owasp: 'A03', fix: 'Validate: if (!validator.isEmail(req.body.email)) return 400; or Zod: z.string().email().' },
2650
+ { id: 'validation.no-uuid-format', severity: 'medium', re: /req\.(?:params|body|query)\.(?:id|userId|postId|itemId|productId)\b(?!.*(?:uuid|isUUID|isValid|mongoose\.Types\.ObjectId))/i, confidence: 'low', skipComments: true, message: 'ID from request without format validation — NoSQL injection / IDOR', cwe: 'CWE-20', owasp: 'A01', fix: 'Validate ID format: if (!/^[a-f0-9]{24}$/i.test(req.params.id)) return 400;' },
2651
+ { id: 'validation.no-allowlist', severity: 'high', re: /req\.body\.(?:role|type|status|category|action|command|operation)\b(?!.*(?:allowlist|whitelist|includes|allowedTypes|validRoles))/i, confidence: 'medium', skipComments: true, message: 'User-controllable enum field without allowlist — privilege escalation / injection', cwe: 'CWE-20', owasp: 'A01', fix: 'Validate against allowlist: const allowed = ["user","admin"]; if (!allowed.includes(req.body.role)) return 400;' },
2652
+ { id: 'validation.mass-assignment-v2', severity: 'high', re: /(?:Object\.assign|spread|\.create|\.update|\.save)\s*\(\s*[^)]*req\.body\b(?!.*(?:pick|allowlist|whitelist|sanitize))/i, confidence: 'medium', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Mass assignment: req.body passed directly to model create/update — users can set role, isAdmin, etc.', cwe: 'CWE-915', owasp: 'A01', fix: 'Pick only allowed fields: const { name, email } = req.body; User.create({ name, email });' },
2653
+ { id: 'validation.no-regex-validation', severity: 'medium', re: /req\.body\.(?:username|slug|shortcode|handle)\b(?!.*(?:test|match|regex|pattern|validator))/i, confidence: 'low', skipComments: true, message: 'Username/slug/handle without regex validation — XSS / injection via special chars', cwe: 'CWE-20', owasp: 'A03', fix: 'Validate: if (!/^[a-zA-Z0-9_-]{3,20}$/.test(req.body.username)) return 400;' },
2654
+ { id: 'validation.no-array-validation', severity: 'medium', re: /req\.body\.(?:tags|categories|ids|items|list)\b(?!.*(?:isArray|Array\.isArray|z\.array))/i, confidence: 'low', skipComments: true, message: 'Array field from request without validation — type confusion / DoS via huge arrays', cwe: 'CWE-20', owasp: 'A04', fix: 'Validate: if (!Array.isArray(req.body.tags) || req.body.tags.length > 50) return 400;' },
2655
+ { id: 'validation.boolean-coercion', severity: 'low', re: /req\.body\.(?:active|enabled|disabled|confirmed|verified|isAdmin|isPublic)\b(?!.*(?:===\s*(?:true|false)|z\.boolean|Boolean\())/i, confidence: 'low', skipComments: true, message: 'Boolean field from request without strict check — truthy coercion ("false" string is truthy)', cwe: 'CWE-20', owasp: 'A03', fix: 'Use strict: if (req.body.isActive === true) or Zod: z.boolean().' },
2656
+ ];
2657
+
2658
+ // --- 10 Secrets Deep Rules ---
2659
+ const secretsDeepRules = [
2660
+ { id: 'secret.in-plain-config', severity: 'critical', re: /(?:password|secret|apiKey|api_key|token|privateKey)\s*[:=]\s*["'][^"']{6,}["']/i, confidence: 'high', skipComments: true, fileFilter: '\\.(?:json|yml|yaml|toml|ini|conf|cfg|env)$', message: 'Secret in plain config file — not in vault/KMS', cwe: 'CWE-798', owasp: 'A02', fix: 'Move to environment variable or secret vault. Never commit secrets in config files.' },
2661
+ { id: 'secret.hardcoded-jwt-secret', severity: 'critical', re: /jwt\.sign\s*\(\s*[^,]+,\s*["'][^"']{6,}["']/i, confidence: 'high', skipComments: true, message: 'JWT secret hardcoded in code — token forgery', cwe: 'CWE-798', owasp: 'A02', fix: 'Load from env: jwt.sign(payload, process.env.JWT_SECRET). Use at least 256-bit secret.' },
2662
+ { id: 'secret.hardcoded-session-secret', severity: 'critical', re: /session\s*\(\s*\{[^}]*secret\s*:\s*["'][^"']{6,}["']/i, confidence: 'high', skipComments: true, message: 'Session secret hardcoded — session forgery', cwe: 'CWE-798', owasp: 'A02', fix: 'Load from env: secret: process.env.SESSION_SECRET. Use 64+ random bytes.' },
2663
+ { id: 'secret.in-graphql-context', severity: 'high', re: /context\s*[:=]\s*\{[^}]*(?:apiKey|secret|token|password)\s*[:=]\s*["'][^"']{8,}["']/i, confidence: 'medium', skipComments: true, message: 'Secret hardcoded in GraphQL context — visible to all resolvers', cwe: 'CWE-798', owasp: 'A02', fix: 'Load from env or vault. Never put secrets in context object.' },
2664
+ { id: 'secret.in-dockerfile', severity: 'critical', re: /(?:ENV|ARG)\s+(?:PASSWORD|SECRET|TOKEN|API_KEY|PRIVATE_KEY)\s*=\s*["']?[^"'\s]{6,}/i, confidence: 'high', skipComments: true, fileFilter: 'Dockerfile$', message: 'Secret in Dockerfile ENV — baked into image layers forever', cwe: 'CWE-798', owasp: 'A05', fix: 'Use Docker secrets or --env-file at runtime. Never bake secrets into images.' },
2665
+ { id: 'secret.in-log', severity: 'high', re: /(?:console\.log|logger\.(?:info|debug|warn|error)|winston|bunyan|pino)\s*\([^)]*(?:password|secret|token|apiKey|privateKey|creditCard|ssn)/i, confidence: 'medium', skipComments: true, message: 'Secret written to log — credentials leaked via logs', cwe: 'CWE-532', owasp: 'A02', fix: 'Never log secrets. Redact: const { password, ...safe } = user; console.log(safe).' },
2666
+ { id: 'secret.in-error-response', severity: 'high', re: /res\.(?:json|send)\s*\(\s*\{[^}]*(?:stack|trace|error.*detail|internal).*\}/i, confidence: 'medium', skipComments: true, message: 'Error response includes stack trace or internal details — info leak', cwe: 'CWE-209', owasp: 'A05', fix: 'Send generic error: res.status(500).json({ error: "Internal error" }). Log details server-side.' },
2667
+ { id: 'secret.no-rotation-comment', severity: 'low', re: /(?:\/\/|#|\/\*)\s*(?:TODO|FIXME|HACK).*rotat/i, confidence: 'low', skipComments: false, message: 'TODO about key rotation — secrets may be stale', cwe: 'CWE-798', owasp: 'A02', fix: 'Rotate the key now. Set up automatic rotation every 90 days.' },
2668
+ { id: 'secret.k8s-secret-plaintext', severity: 'high', re: /kind:\s*Secret[\s\S]{0,500}stringData:[\s\S]{0,500}(?:password|token|key|secret)\s*:/i, confidence: 'high', fileFilter: '\\.ya?ml$', message: 'Kubernetes Secret with plaintext stringData — visible in kubectl describe', cwe: 'CWE-312', owasp: 'A02', fix: 'Use encrypted secrets: Sealed Secrets, External Secrets Operator, or Vault.' },
2669
+ { id: 'secret.in-url-query', severity: 'high', re: /https?:\/\/[^\s]*[?&](?:api_key|apikey|token|secret|password|access_token)\s*=/i, confidence: 'high', skipComments: true, message: 'Secret in URL query string — logged in server access logs, browser history, Referer headers', cwe: 'CWE-598', owasp: 'A02', fix: 'Send secrets in headers, not URL params. Use Authorization: Bearer <token>.' },
2670
+ ];
2671
+
2672
+ // --- 10 Dependency Vulnerability Rules ---
2673
+ const depVulnRules = [
2674
+ { id: 'dep.unpinned-exact', severity: 'medium', re: /"([a-z@][\w@.-]*)"\s*:\s*"\d+\.\d+\.\d+(?!\s*-\d)/, confidence: 'low', fileFilter: 'package\\.json$', message: 'Dependency pinned to exact version but no lockfile check — verify npm audit', cwe: 'CWE-1104', owasp: 'A06', fix: 'Run npm audit regularly. Consider Dependabot/Renovate for auto-updates.' },
2675
+ { id: 'dep.caret-range', severity: 'low', re: /"([a-z@][\w@.-]*)"\s*:\s*"\^\d+\.\d+\.\d+"/, confidence: 'low', fileFilter: 'package\\.json$', message: 'Dependency uses caret range (^) — minor updates may introduce vulnerabilities', cwe: 'CWE-1104', owasp: 'A06', fix: 'Run npm audit. Pin critical deps to exact versions. Use lockfile.' },
2676
+ { id: 'dep.deprecated-package', severity: 'high', re: /"(?:request|node-uuid|left-pad|colors|faker|mkdirp|lodash@4|moment|hapi|jade|gulp-util)"\s*:/, confidence: 'high', fileFilter: 'package\\.json$', message: 'Deprecated/abandoned package — security patches stopped', cwe: 'CWE-1104', owasp: 'A06', fix: 'Replace: request->got/axios, moment->day.js, colors->picocolors, faker->@faker-js/faker.' },
2677
+ { id: 'dep.no-lockfile', severity: 'medium', re: /"name"\s*:\s*"[^"]*"/, confidence: 'low', fileFilter: 'package\\.json$', message: 'package.json found — verify package-lock.json exists to prevent dependency confusion', cwe: 'CWE-1104', owasp: 'A06', fix: 'Run npm install to generate lockfile. Commit package-lock.json.' },
2678
+ { id: 'dep.preinstall-script', severity: 'critical', re: /"preinstall"\s*:\s*"/, confidence: 'high', fileFilter: 'package\\.json$', message: 'preinstall script in package.json — runs before install, can execute arbitrary code', cwe: 'CWE-506', owasp: 'A06', fix: 'Remove preinstall script. Never run arbitrary code during npm install.' },
2679
+ { id: 'dep.postinstall-script', severity: 'high', re: /"postinstall"\s*:\s*"/, confidence: 'medium', fileFilter: 'package\\.json$', message: 'postinstall script in package.json — runs arbitrary code after install', cwe: 'CWE-506', owasp: 'A06', fix: 'Review the script. Remove if not needed. Malicious packages use postinstall for malware.' },
2680
+ { id: 'dep.github-dep', severity: 'medium', re: /"[a-z@][\w@.-]*"\s*:\s*"github:[^"]+"/, confidence: 'low', fileFilter: 'package\\.json$', message: 'GitHub dependency — not on npm registry, no audit trail', cwe: 'CWE-1104', owasp: 'A06', fix: 'Prefer npm published packages. If using GitHub, pin to commit hash.' },
2681
+ { id: 'dep.trust-all', severity: 'critical', re: /npm\s+install\s+(?:--force|--no-audit)/, confidence: 'high', skipComments: true, message: 'npm install with --force or --no-audit — skipping vulnerability check', cwe: 'CWE-1104', owasp: 'A06', fix: 'Never use --force or --no-audit. Fix the vulnerability instead of suppressing it.' },
2682
+ { id: 'dep.no-engines', severity: 'low', re: /"name"\s*:\s*"[^"]*"/, confidence: 'low', fileFilter: 'package\\.json$', message: 'No engines field in package.json — node version mismatch risk', cwe: 'CWE-1104', owasp: 'A06', fix: 'Add "engines": { "node": ">=18.0.0" } to enforce Node version.' },
2683
+ { id: 'dep.unpackaged-bin', severity: 'medium', re: /(?:child_process\.exec|execSync|spawn)\s*\(\s*["'](?:npm|npx|yarn|pnpm)\s/i, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Executing package manager from code — supply chain risk if user input reaches it', cwe: 'CWE-78', owasp: 'A06', fix: 'Never exec npm from runtime code. Install deps at build time only.' },
2684
+ ];
2685
+
2686
+ // --- 10 Error Handling + Information Leakage Rules ---
2687
+ const errorLeakageRules = [
2688
+ { id: 'error.stack-to-client', severity: 'high', re: /res\.(?:json|send)\s*\(\s*(?:err|error|e)\.(?:stack|trace|message)/i, confidence: 'high', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Stack trace sent to client — internal paths, versions leaked', cwe: 'CWE-209', owasp: 'A05', fix: 'Send generic error: res.status(500).json({ error: "Something went wrong" }). Log stack server-side.' },
2689
+ { id: 'error.verbose-mode', severity: 'high', re: /(?:debug|verbose|showErrors|showStack)\s*:\s*true/i, confidence: 'medium', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Verbose/debug mode enabled — leaks internals to clients', cwe: 'CWE-489', owasp: 'A05', fix: 'Set debug: false in production. Use NODE_ENV=production.' },
2690
+ { id: 'error.sql-to-client', severity: 'high', re: /res\.(?:json|send)\s*\(\s*(?:err|error|e)\.(?:sql|sqlMessage|query|detail)/i, confidence: 'high', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'SQL error sent to client — schema/table names leaked', cwe: 'CWE-209', owasp: 'A05', fix: 'Catch DB errors: catch(e) { logger.error(e); res.status(500).json({ error: "Database error" }); }' },
2691
+ { id: 'error.console-in-prod', severity: 'medium', re: /console\.(?:log|debug|info|dir|trace)\s*\(/i, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'console.log in production code — info leak via logs', cwe: 'CWE-532', owasp: 'A05', fix: 'Use a logger (winston/pino) with level filtering. Remove console.log from prod.' },
2692
+ { id: 'error.no-catch-all', severity: 'medium', re: /app\.listen\s*\(/, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'No global error handler — unhandled rejections crash server', cwe: 'CWE-754', owasp: 'A05', fix: 'Add: process.on("uncaughtException", ...) and app.use((err, req, res, next) => res.status(500).json({ error: "Internal" })).' },
2693
+ { id: 'error.no-try-catch', severity: 'medium', re: /(?:JSON\.parse|parseInt|parseFloat|Number)\s*\(\s*req\.(?:body|query|params)\b(?!.*try)/i, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Parse of request data without try/catch — crashes on malformed input', cwe: 'CWE-754', owasp: 'A05', fix: 'Wrap: try { const data = JSON.parse(req.body.data); } catch(e) { return res.status(400).json({ error: "Invalid JSON" }); }' },
2694
+ { id: 'error.internal-msg-leak', severity: 'medium', re: /res\.(?:json|send|render)\s*\(\s*\{[^}]*(?:internal|database|connection|query|filesystem|ECONNREFUSED|ENOTFOUND)/i, confidence: 'medium', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Internal system details in error response — infrastructure leak', cwe: 'CWE-209', owasp: 'A05', fix: 'Send generic error. Map known errors to user-friendly messages.' },
2695
+ { id: 'error.xpoweredby', severity: 'low', re: /app\.(?:listen|use)\s*\(/, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', filter: (line, content, lines) => !lines.some(l => /helmet|disable.*x-powered-by/i.test(l)), message: 'X-Powered-By header not disabled — framework version leaked', cwe: 'CWE-200', owasp: 'A05', fix: 'Add: app.disable("x-powered-by"). Or use helmet middleware.' },
2696
+ { id: 'error.err-throw-to-client', severity: 'high', re: /(?:throw|next)\s*\(\s*(?:err|error|e)\b/i, confidence: 'medium', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Raw error thrown/forwarded to client — may contain stack trace or internal info', cwe: 'CWE-209', owasp: 'A05', fix: 'Map error to safe message: next(new Error("Request failed")). Never forward raw DB/system errors.' },
2697
+ { id: 'error.no-body-limit', severity: 'medium', re: /express\.json\s*\(\s*\{\s*(?:limit\s*:\s*['"]?(?:\d+['"]?\s*[GM]?B|Infinity)|)/i, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Body parser with no or large limit — DoS via huge payload', cwe: 'CWE-770', owasp: 'A04', fix: 'Set: express.json({ limit: "1mb" }). Default is 100kb which is fine.' },
2698
+ ];
2699
+
2700
+ // --- 10 File Upload Safety Rules ---
2701
+ const fileUploadRules = [
2702
+ { id: 'upload.no-size-limit', severity: 'high', re: /(?:multer|upload|formidable|busboy|multipart)\s*\(\s*\{\s*(?!.*limit)/i, confidence: 'medium', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'File upload without size limit — DoS via large files', cwe: 'CWE-770', owasp: 'A04', fix: 'Set: multer({ limits: { fileSize: 5 * 1024 * 1024 } }) — 5MB max.' },
2703
+ { id: 'upload.no-mime-check', severity: 'high', re: /multer\s*\(\s*\{[^}]*(?:dest|storage)[^}]*\}/i, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'File upload without MIME type validation — malicious file upload (webshell, polyglot)', cwe: 'CWE-434', owasp: 'A04', fix: 'Validate: fileFilter: (req, file, cb) => { if (["image/jpeg","image/png","application/pdf"].includes(file.mimetype)) cb(null, true); else cb(new Error("Invalid type")); }' },
2704
+ { id: 'upload.no-extension-check', severity: 'high', re: /req\.files?\b(?!.*(?:path\.extname|originalname|filename.*test|\.match|\.includes))/i, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Uploaded file used without extension validation — webshell upload (.php, .jsp, .exe)', cwe: 'CWE-434', owasp: 'A04', fix: 'Validate: const ext = path.extname(file.originalname).toLowerCase(); if (!["jpg","png","pdf"].includes(ext)) return 400;' },
2705
+ { id: 'upload.original-name-used', severity: 'critical', re: /(?:filename|dest|key|path)\s*:\s*req\.files?\.\w+\.originalName|fs\.(?:writeFile|createWriteStream)\s*\(\s*[^)]*req\.files?\b/i, confidence: 'high', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Uploaded file saved with original filename — path traversal via filename (../../etc/passwd)', cwe: 'CWE-22', owasp: 'A04', fix: 'Generate safe name: const name = crypto.randomUUID() + path.extname(file.originalname). Never use user-supplied filename.' },
2706
+ { id: 'upload.no-virus-scan', severity: 'medium', re: /multer\s*\(\s*\{[^}]*storage/i, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'File upload without virus scanning — malware storage/distribution', cwe: 'CWE-434', owasp: 'A04', fix: 'Scan with ClamAV or cloud scan API before storing. Reject infected files.' },
2707
+ { id: 'upload.executable-allowed', severity: 'critical', re: /(?:accept|allowedTypes|fileTypes|mimeTypes)\s*:\s*\[[^\]]*(?:\.exe|\.php|\.jsp|\.asp|\.sh|\.bat|\.cmd|\.jar|\.war|application\/(?:x-php|x-httpd-php|x-executable|octet-stream))/i, confidence: 'high', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Executable file type allowed in upload — webshell / RCE', cwe: 'CWE-434', owasp: 'A04', fix: 'Remove executable types from allowlist. Only allow images, PDFs, docs.' },
2708
+ { id: 'upload.no-s3-acl', severity: 'medium', re: /s3\.(?:upload|putObject)\s*\(\s*\{[^}]*Key\s*:/i, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'S3 upload without ACL — defaults to bucket ACL, may be public', cwe: 'CWE-732', owasp: 'A05', fix: 'Set: ACL: "private" or "bucket-owner-full-control". Never use "public-read" for user uploads.' },
2709
+ { id: 'upload.serve-from-upload-dir', severity: 'high', re: /app\.(?:get|use)\s*\(\s*['"]\/uploads/i, confidence: 'medium', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Serving files directly from upload directory — stored XSS via uploaded HTML/SVG', cwe: 'CWE-79', owasp: 'A03', fix: 'Serve uploads via a handler that sets Content-Disposition: attachment. Strip scripts from SVG. Never serve HTML/SVG as text/html.' },
2710
+ { id: 'upload.no-content-disposition', severity: 'medium', re: /res\.(?:sendFile|download)\s*\(\s*[^)]*upload/i, confidence: 'low', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Uploaded file served without Content-Disposition — XSS if browser renders HTML', cwe: 'CWE-79', owasp: 'A03', fix: 'Set: res.setHeader("Content-Disposition", "attachment"). Set correct Content-Type.' },
2711
+ { id: 'upload.field-name-dynamic', severity: 'medium', re: /multer\s*\(\s*\{[^}]*field\s*:\s*req\./i, confidence: 'medium', skipComments: true, fileFilter: '\\.(?:js|ts)$', message: 'Upload field name from request — multipart manipulation', cwe: 'CWE-20', owasp: 'A04', fix: 'Use fixed field names. Never accept field names from user input.' },
2712
+ ];
2713
+
2618
2714
  // ---------------------------------------------------------------------------
2619
2715
  // GAP BATCH: Assemble all line rules
2620
2716
  // ---------------------------------------------------------------------------
2621
2717
 
2718
+ // Gate language-specific rules by file extension so they don't fire on other
2719
+ // languages. Spread ...r last so a rule's own tighter fileFilter still wins.
2720
+ const withExt = (rules, ext) => rules.map((r) => ({ fileFilter: ext, ...r }));
2721
+
2622
2722
  const allLineRules = [
2623
2723
  ...clerkRules, ...authJsRules, ...oauthRules, ...supabaseAuthRules,
2624
2724
  ...drizzleRules, ...honoRules, ...trpcRules, ...convexRules,
@@ -2629,20 +2729,20 @@ const allLineRules = [
2629
2729
  ...aiSecurityRules,
2630
2730
  ...supplyChainRules,
2631
2731
  ...advancedSecurityRules,
2632
- ...goRules,
2732
+ ...withExt(goRules, '\\.go$'),
2633
2733
  ...mobileRules,
2634
2734
  ...deploymentRules,
2635
2735
  ...owaspApiRules,
2636
2736
  ...extraSecretRules,
2637
- ...javaRules,
2737
+ ...withExt(javaRules, '\\.java$'),
2638
2738
  ...rubyRules,
2639
- ...phpRules,
2640
- ...csharpRules,
2739
+ ...withExt(phpRules, '\\.php$'),
2740
+ ...withExt(csharpRules, '\\.cs$'),
2641
2741
  ...djangoRules,
2642
- ...flaskRules,
2643
- ...railsRules,
2644
- ...laravelRules,
2645
- ...springRules,
2742
+ ...withExt(flaskRules, '\\.py$'),
2743
+ ...withExt(railsRules, '\\.(rb|erb)$'),
2744
+ ...withExt(laravelRules, '\\.php$'),
2745
+ ...withExt(springRules, '\\.java$'),
2646
2746
  ...fastifyRules,
2647
2747
  ...svelteKitRules,
2648
2748
  ...nuxtRules,
@@ -2654,7 +2754,7 @@ const allLineRules = [
2654
2754
  ...deserializationRules,
2655
2755
  ...cloudRules,
2656
2756
  ...aiSecurityRulesExtra,
2657
- ...pythonDeepRules,
2757
+ ...withExt(pythonDeepRules, '\\.py$'),
2658
2758
  ...raceConditionRules,
2659
2759
  ...cicdDeepRules,
2660
2760
  ...rustRules,