@yagyeshvyas/vibeguard 1.12.0 → 1.13.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 (113) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +34 -17
  3. package/bin/cli.js +2753 -2753
  4. package/bin/cmd-mcp-firewall.js +1 -0
  5. package/bin/cmd-platform.js +3 -0
  6. package/ci/vibeguard.yml +42 -42
  7. package/package.json +2 -2
  8. package/scripts/counts.js +93 -93
  9. package/scripts/postinstall.js +26 -26
  10. package/src/auto.js +427 -427
  11. package/src/daemon.js +343 -343
  12. package/src/dashboard.js +278 -278
  13. package/src/engine.js +297 -297
  14. package/src/hook.js +151 -151
  15. package/src/install.js +298 -298
  16. package/src/integrity.js +1 -0
  17. package/src/integrity.json +9 -6
  18. package/src/mcp-firewall.js +11 -0
  19. package/src/platform/approval-service.js +124 -0
  20. package/src/platform/approval.js +16 -0
  21. package/src/platform/oauth-server.js +89 -0
  22. package/src/platform/os-sandbox.js +52 -1
  23. package/src/platform/runtime-monitor.js +69 -0
  24. package/src/platform/sandbox-manager.js +5 -0
  25. package/src/plugin.js +182 -182
  26. package/src/privacy-audit.js +272 -272
  27. package/src/repl.js +150 -150
  28. package/src/report.js +331 -331
  29. package/src/rules-pack.js +3068 -3068
  30. package/src/rules.js +1822 -1822
  31. package/src/sbom.js +193 -193
  32. package/src/scanner.js +1032 -1032
  33. package/src/shell-guard.js +302 -302
  34. package/src/slopsquat.js +144 -144
  35. package/src/trace.js +220 -220
  36. package/src/.vibeguard/cache/file-hashes.json +0 -60
  37. package/src/.vibeguard/latest-snapshot.json +0 -36
  38. package/src/.vibeguard/mcp-pins.json +0 -1
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +0 -428
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +0 -344
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +0 -279
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +0 -297
  43. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +0 -151
  44. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +0 -299
  45. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +0 -65
  46. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +0 -2051
  47. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +0 -168
  48. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +0 -362
  49. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +0 -150
  50. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +0 -1611
  51. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +0 -164
  52. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +0 -292
  53. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +0 -144
  54. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +0 -220
  55. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +0 -428
  56. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +0 -344
  57. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +0 -297
  58. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +0 -299
  59. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +0 -37
  60. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +0 -2055
  61. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +0 -168
  62. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +0 -362
  63. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +0 -220
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +0 -428
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +0 -344
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +0 -279
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +0 -297
  68. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +0 -151
  69. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +0 -299
  70. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +0 -65
  71. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +0 -2055
  72. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +0 -168
  73. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +0 -362
  74. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +0 -150
  75. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +0 -1611
  76. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +0 -164
  77. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +0 -292
  78. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +0 -144
  79. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +0 -220
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +0 -428
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +0 -344
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +0 -279
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +0 -297
  84. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +0 -151
  85. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +0 -299
  86. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +0 -65
  87. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +0 -2054
  88. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +0 -168
  89. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +0 -362
  90. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +0 -150
  91. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +0 -1611
  92. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +0 -164
  93. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +0 -292
  94. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +0 -144
  95. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +0 -220
  96. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +0 -428
  97. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +0 -344
  98. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +0 -297
  99. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +0 -299
  100. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +0 -37
  101. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +0 -2055
  102. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +0 -168
  103. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +0 -362
  104. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +0 -220
  105. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +0 -428
  106. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +0 -344
  107. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +0 -297
  108. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +0 -33
  109. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +0 -2055
  110. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +0 -1611
  111. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +0 -292
  112. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +0 -220
  113. package/src/.vibeguard-baseline.json +0 -5226
package/src/engine.js CHANGED
@@ -1,297 +1,297 @@
1
- 'use strict';
2
-
3
- /*
4
- * Engine gaps:
5
- * 1. Sanitizer recognition — stop taint propagation when a sanitizer is applied
6
- * 2. Incremental/diff-aware scanning — only scan changed files
7
- * 3. Auth coverage map — enumerate routes → middleware → guards
8
- * 4. Python taint — basic Python source-to-sink taint detection
9
- */
10
-
11
- const fs = require('fs');
12
- const path = require('path');
13
- const crypto = require('crypto');
14
-
15
- // ---------------------------------------------------------------------------
16
- // 1. SANITIZER RECOGNITION
17
- // ---------------------------------------------------------------------------
18
-
19
- const SANITIZERS = {
20
- xss: [
21
- 'DOMPurify', 'sanitize', 'sanitizeHtml', 'escape', 'escapeHtml',
22
- 'encodeURIComponent', 'encodeURI', 'textEncode', 'he.encode',
23
- 'React.createElement', 'textContent',
24
- ],
25
- sql: [
26
- 'parameterize', 'prepare', 'placeholder', 'bind', 'sql`', 'sql.query',
27
- 'prisma.$queryRaw', 'pool.query', 'client.query',
28
- ],
29
- cmd: [
30
- 'execFile', 'spawn', 'shell-quote', 'shellescape', 'sanitizeShell',
31
- ],
32
- path: [
33
- 'path.resolve', 'path.join', 'path.normalize', 'sanitize',
34
- ],
35
- };
36
-
37
- function isSanitized(expr, type) {
38
- if (!expr || typeof expr !== 'string') return false;
39
- const sanitizers = SANITIZERS[type] || [];
40
- return sanitizers.some((s) => expr.includes(s));
41
- }
42
-
43
- // ---------------------------------------------------------------------------
44
- // 2. INCREMENTAL / DIFF-AWARE SCANNING
45
- // ---------------------------------------------------------------------------
46
-
47
- const HASH_CACHE_DIR = '.vibeguard/cache';
48
-
49
- function loadHashCache(root) {
50
- const p = path.join(root, HASH_CACHE_DIR, 'file-hashes.json');
51
- if (fs.existsSync(p)) {
52
- try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch {}
53
- }
54
- return {};
55
- }
56
-
57
- function saveHashCache(root, cache) {
58
- const dir = path.join(root, HASH_CACHE_DIR);
59
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
60
- fs.writeFileSync(path.join(dir, 'file-hashes.json'), JSON.stringify(cache, null, 2));
61
- }
62
-
63
- function hashContent(content) {
64
- return crypto.createHash('sha256').update(content).digest('hex');
65
- }
66
-
67
- function getChangedFiles(root, allFiles) {
68
- const cache = loadHashCache(root);
69
- const changed = [];
70
- const newCache = {};
71
-
72
- for (const file of allFiles) {
73
- try {
74
- const content = fs.readFileSync(file, 'utf8');
75
- const hash = hashContent(content);
76
- newCache[file] = hash;
77
- if (cache[file] !== hash) changed.push(file);
78
- } catch {
79
- // can't read, skip
80
- }
81
- }
82
-
83
- saveHashCache(root, newCache);
84
- return { changed, total: allFiles.length, cached: allFiles.length - changed.length };
85
- }
86
-
87
- // ---------------------------------------------------------------------------
88
- // 3. AUTH COVERAGE MAP
89
- // ---------------------------------------------------------------------------
90
-
91
- const ROUTE_RE = /(?:app|router|server)\.(?:get|post|put|delete|patch|all|use)\s*\(\s*['"`]([^'"`]+)['"`]/gi;
92
- const MIDDLEWARE_RE = /(?:app|router)\.use\s*\(\s*['"`]([^'"`]+)['"`]/gi;
93
- const AUTH_GUARD_RE = /(?:requireAuth|withAuth|protect|guard|authMiddleware|isAuthenticated|verifyToken|authenticate|clerkMiddleware|auth\(\)|getServerSession|getSession)/i;
94
-
95
- function buildAuthCoverage(root, files) {
96
- const routes = [];
97
- const middlewares = [];
98
-
99
- for (const file of files) {
100
- try {
101
- const content = fs.readFileSync(file, 'utf8');
102
- const relPath = path.relative(root, file);
103
-
104
- let m;
105
- while ((m = ROUTE_RE.exec(content)) !== null) {
106
- const routePath = m[1];
107
- const beforeLines = content.slice(0, m.index).split('\n');
108
- const lineNum = beforeLines.length;
109
- const currentLine = content.slice(m.index, m.index + 300).split('\n')[0];
110
- const hasAuth = AUTH_GUARD_RE.test(currentLine);
111
- routes.push({
112
- path: routePath,
113
- file: relPath,
114
- line: lineNum,
115
- protected: hasAuth,
116
- });
117
- }
118
-
119
- while ((m = MIDDLEWARE_RE.exec(content)) !== null) {
120
- const mwPath = m[1];
121
- const lines = content.slice(0, m.index).split('\n');
122
- const lineNum = lines.length;
123
- const surrounding = content.slice(m.index, m.index + 300);
124
- const isAuth = AUTH_GUARD_RE.test(surrounding);
125
- if (isAuth) {
126
- middlewares.push({ path: mwPath, file: relPath, line: lineNum });
127
- }
128
- }
129
- } catch {}
130
- }
131
-
132
- const unprotected = routes.filter((r) => !r.protected && r.path.startsWith('/api/'));
133
- const protectedRoutes = routes.filter((r) => r.protected);
134
-
135
- return {
136
- totalRoutes: routes.length,
137
- protectedRoutes: protectedRoutes.length,
138
- unprotectedRoutes: unprotected.length,
139
- unprotected,
140
- middlewares,
141
- coverage: routes.length > 0 ? Math.round((protectedRoutes.length / routes.length) * 100) : 100,
142
- };
143
- }
144
-
145
- // ---------------------------------------------------------------------------
146
- // 4. PYTHON TAINT (basic — regex-based, no AST)
147
- // ---------------------------------------------------------------------------
148
-
149
- const PY_SOURCES = [
150
- { re: /request\.(?:form|args|data|json|values|cookies|headers)(?:\.\w+)?\s*\(/g, name: 'request' },
151
- { re: /request\.get\s*\(/g, name: 'request' },
152
- { re: /\binput\s*\(/g, name: 'input()' },
153
- { re: /os\.environ\.get\s*\(/g, name: 'os.environ' },
154
- { re: /sys\.argv/g, name: 'sys.argv' },
155
- { re: /os\.getenv\s*\(/g, name: 'os.getenv' },
156
- ];
157
-
158
- const PY_SINKS = [
159
- { re: /cursor\.execute\s*\(/g, name: 'cursor.execute', type: 'sql' },
160
- { re: /os\.system\s*\(/g, name: 'os.system', type: 'cmd' },
161
- { re: /subprocess\.(?:run|call|Popen)\s*\(/g, name: 'subprocess', type: 'cmd' },
162
- { re: /eval\s*\(/g, name: 'eval()', type: 'code' },
163
- { re: /exec\s*\(/g, name: 'exec()', type: 'code' },
164
- { re: /open\s*\(/g, name: 'open()', type: 'file' },
165
- { re: /pickle\.loads?\s*\(/g, name: 'pickle', type: 'deserialization' },
166
- { re: /yaml\.load\s*\(/g, name: 'yaml.load', type: 'deserialization' },
167
- { re: /shutil\.rmtree\s*\(/g, name: 'shutil.rmtree', type: 'file' },
168
- ];
169
-
170
- // Single-pass taint propagation (pure JS — no external parser, keeps VibeGuard
171
- // zero-dependency and offline). Tracks tainted variables top-to-bottom:
172
- // - a source assignment (v = request.form.get(...)) taints v;
173
- // - an assignment whose RHS references a tainted var propagates the taint to
174
- // the LHS (multi-hop: q = "..." + data → q is tainted);
175
- // - reassigning a tainted var to a clean/sanitized value clears it;
176
- // - a sink using a tainted var fires — UNLESS the value is parameterized
177
- // (SQL) or wrapped in a sanitizer at the sink.
178
- // This replaces the old "var appears anywhere between source and sink" heuristic,
179
- // which false-positived when a tainted name merely appeared near an unrelated sink.
180
- function analyzePythonTaint(content, lines, relPath) {
181
- const findings = [];
182
- const tainted = new Map(); // varName -> { name (source), line }
183
- const seen = new Set(); // dedupe sink:line
184
- const reOf = (v) => new RegExp('\\b' + escapeRe(v) + '\\b');
185
-
186
- for (let i = 0; i < lines.length; i++) {
187
- const line = lines[i];
188
- const lineNo = i + 1;
189
-
190
- // 1. Source assignment.
191
- let matchedSource = null;
192
- for (const src of PY_SOURCES) {
193
- src.re.lastIndex = 0;
194
- if (src.re.test(line)) { matchedSource = src.name; break; }
195
- }
196
- if (matchedSource) {
197
- const v = extractVarName(line);
198
- if (v) tainted.set(v, { name: matchedSource, line: lineNo });
199
- }
200
-
201
- // 2. Propagation / clearing via simple assignment `lhs = rhs`.
202
- if (!matchedSource) {
203
- const asn = /^\s*([A-Za-z_]\w*)\s*=\s*(.+)$/.exec(line);
204
- if (asn) {
205
- const lhs = asn[1];
206
- const rhs = asn[2];
207
- let carried = null;
208
- for (const [tv, info] of tainted) {
209
- if (reOf(tv).test(rhs) && !isSanitizedAtSink(rhs, tv)) { carried = info; break; }
210
- }
211
- if (carried) tainted.set(lhs, carried);
212
- else if (tainted.has(lhs)) tainted.delete(lhs); // reassigned to clean value
213
- }
214
- }
215
-
216
- // 3. Sinks.
217
- for (const sink of PY_SINKS) {
218
- sink.re.lastIndex = 0;
219
- if (!sink.re.test(line)) continue;
220
- for (const [tv, info] of tainted) {
221
- if (!reOf(tv).test(line)) continue;
222
- if (sink.type === 'sql' && isParameterizedExecute(line)) continue;
223
- if (isSanitizedAtSink(line, tv)) continue;
224
- const key = sink.name + ':' + lineNo;
225
- if (seen.has(key)) break;
226
- seen.add(key);
227
- findings.push({
228
- ruleId: 'py.taint-flow',
229
- file: relPath,
230
- line: lineNo,
231
- column: 1,
232
- severity: 'high',
233
- confidence: 'medium',
234
- title: `Python taint: ${info.name} → ${sink.name}`,
235
- snippet: line.trim().slice(0, 120),
236
- message: `User input (${info.name} at line ${info.line}) flows to ${sink.name} (line ${lineNo}) without sanitization.`,
237
- fix: `Sanitize or validate the input before passing it to ${sink.name}.`,
238
- owasp: 'A03:2025 Injection',
239
- cwe: sink.type === 'sql' ? 'CWE-89' : sink.type === 'cmd' ? 'CWE-77' : 'CWE-20',
240
- });
241
- break;
242
- }
243
- }
244
- }
245
-
246
- return findings;
247
- }
248
-
249
- function escapeRe(s) {
250
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
251
- }
252
-
253
- // Parameterized DB call: a placeholder in the query AND a second argument to
254
- // execute() = the driver binds/escapes the value, so it is NOT SQL injection.
255
- function isParameterizedExecute(line) {
256
- if (!/\.execute\s*\(/.test(line)) return false;
257
- const hasPlaceholder = /%s|%\(|%d|\?|:\w+/.test(line);
258
- const hasSecondArg = /\.execute\s*\([^)]*?,\s*[([{\w'"]/.test(line);
259
- return hasPlaceholder && hasSecondArg;
260
- }
261
-
262
- // Python sanitizers that neutralize a tainted value. If the tainted var appears
263
- // wrapped in one of these on the sink line, the flow is considered safe.
264
- const PY_SANITIZER_FNS = [
265
- 'int', 'float', 'bool', 'decimal.Decimal',
266
- 'shlex.quote', 'pipes.quote', 'shlex.split',
267
- 'html.escape', 'markupsafe.escape', 'escape', 'bleach.clean',
268
- 'urllib.parse.quote', 'urllib.parse.quote_plus', 're.escape',
269
- ];
270
- function isSanitizedAtSink(sinkLine, varName) {
271
- const v = varName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
272
- for (const fn of PY_SANITIZER_FNS) {
273
- const f = fn.replace(/\./g, '\\.');
274
- // e.g. int(<var>) / shlex.quote(<var>) directly wrapping the tainted var
275
- if (new RegExp('\\b' + f + '\\s*\\(\\s*' + v + '\\b').test(sinkLine)) return true;
276
- }
277
- return false;
278
- }
279
-
280
- function extractVarName(line) {
281
- const m = /\b(\w+)\s*=\s*(?:request\.|input\(|os\.environ|sys\.argv)/.exec(line);
282
- if (m) return m[1];
283
- const m2 = /\b(?:for\s+)?(\w+)\s+in\s+request\./.exec(line);
284
- if (m2) return m2[1];
285
- return null;
286
- }
287
-
288
- module.exports = {
289
- isSanitized,
290
- SANITIZERS,
291
- getChangedFiles,
292
- loadHashCache,
293
- saveHashCache,
294
- hashContent,
295
- buildAuthCoverage,
296
- analyzePythonTaint,
297
- };
1
+ 'use strict';
2
+
3
+ /*
4
+ * Engine gaps:
5
+ * 1. Sanitizer recognition — stop taint propagation when a sanitizer is applied
6
+ * 2. Incremental/diff-aware scanning — only scan changed files
7
+ * 3. Auth coverage map — enumerate routes → middleware → guards
8
+ * 4. Python taint — basic Python source-to-sink taint detection
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const crypto = require('crypto');
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // 1. SANITIZER RECOGNITION
17
+ // ---------------------------------------------------------------------------
18
+
19
+ const SANITIZERS = {
20
+ xss: [
21
+ 'DOMPurify', 'sanitize', 'sanitizeHtml', 'escape', 'escapeHtml',
22
+ 'encodeURIComponent', 'encodeURI', 'textEncode', 'he.encode',
23
+ 'React.createElement', 'textContent',
24
+ ],
25
+ sql: [
26
+ 'parameterize', 'prepare', 'placeholder', 'bind', 'sql`', 'sql.query',
27
+ 'prisma.$queryRaw', 'pool.query', 'client.query',
28
+ ],
29
+ cmd: [
30
+ 'execFile', 'spawn', 'shell-quote', 'shellescape', 'sanitizeShell',
31
+ ],
32
+ path: [
33
+ 'path.resolve', 'path.join', 'path.normalize', 'sanitize',
34
+ ],
35
+ };
36
+
37
+ function isSanitized(expr, type) {
38
+ if (!expr || typeof expr !== 'string') return false;
39
+ const sanitizers = SANITIZERS[type] || [];
40
+ return sanitizers.some((s) => expr.includes(s));
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // 2. INCREMENTAL / DIFF-AWARE SCANNING
45
+ // ---------------------------------------------------------------------------
46
+
47
+ const HASH_CACHE_DIR = '.vibeguard/cache';
48
+
49
+ function loadHashCache(root) {
50
+ const p = path.join(root, HASH_CACHE_DIR, 'file-hashes.json');
51
+ if (fs.existsSync(p)) {
52
+ try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch {}
53
+ }
54
+ return {};
55
+ }
56
+
57
+ function saveHashCache(root, cache) {
58
+ const dir = path.join(root, HASH_CACHE_DIR);
59
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
60
+ fs.writeFileSync(path.join(dir, 'file-hashes.json'), JSON.stringify(cache, null, 2));
61
+ }
62
+
63
+ function hashContent(content) {
64
+ return crypto.createHash('sha256').update(content).digest('hex');
65
+ }
66
+
67
+ function getChangedFiles(root, allFiles) {
68
+ const cache = loadHashCache(root);
69
+ const changed = [];
70
+ const newCache = {};
71
+
72
+ for (const file of allFiles) {
73
+ try {
74
+ const content = fs.readFileSync(file, 'utf8');
75
+ const hash = hashContent(content);
76
+ newCache[file] = hash;
77
+ if (cache[file] !== hash) changed.push(file);
78
+ } catch {
79
+ // can't read, skip
80
+ }
81
+ }
82
+
83
+ saveHashCache(root, newCache);
84
+ return { changed, total: allFiles.length, cached: allFiles.length - changed.length };
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // 3. AUTH COVERAGE MAP
89
+ // ---------------------------------------------------------------------------
90
+
91
+ const ROUTE_RE = /(?:app|router|server)\.(?:get|post|put|delete|patch|all|use)\s*\(\s*['"`]([^'"`]+)['"`]/gi;
92
+ const MIDDLEWARE_RE = /(?:app|router)\.use\s*\(\s*['"`]([^'"`]+)['"`]/gi;
93
+ const AUTH_GUARD_RE = /(?:requireAuth|withAuth|protect|guard|authMiddleware|isAuthenticated|verifyToken|authenticate|clerkMiddleware|auth\(\)|getServerSession|getSession)/i;
94
+
95
+ function buildAuthCoverage(root, files) {
96
+ const routes = [];
97
+ const middlewares = [];
98
+
99
+ for (const file of files) {
100
+ try {
101
+ const content = fs.readFileSync(file, 'utf8');
102
+ const relPath = path.relative(root, file);
103
+
104
+ let m;
105
+ while ((m = ROUTE_RE.exec(content)) !== null) {
106
+ const routePath = m[1];
107
+ const beforeLines = content.slice(0, m.index).split('\n');
108
+ const lineNum = beforeLines.length;
109
+ const currentLine = content.slice(m.index, m.index + 300).split('\n')[0];
110
+ const hasAuth = AUTH_GUARD_RE.test(currentLine);
111
+ routes.push({
112
+ path: routePath,
113
+ file: relPath,
114
+ line: lineNum,
115
+ protected: hasAuth,
116
+ });
117
+ }
118
+
119
+ while ((m = MIDDLEWARE_RE.exec(content)) !== null) {
120
+ const mwPath = m[1];
121
+ const lines = content.slice(0, m.index).split('\n');
122
+ const lineNum = lines.length;
123
+ const surrounding = content.slice(m.index, m.index + 300);
124
+ const isAuth = AUTH_GUARD_RE.test(surrounding);
125
+ if (isAuth) {
126
+ middlewares.push({ path: mwPath, file: relPath, line: lineNum });
127
+ }
128
+ }
129
+ } catch {}
130
+ }
131
+
132
+ const unprotected = routes.filter((r) => !r.protected && r.path.startsWith('/api/'));
133
+ const protectedRoutes = routes.filter((r) => r.protected);
134
+
135
+ return {
136
+ totalRoutes: routes.length,
137
+ protectedRoutes: protectedRoutes.length,
138
+ unprotectedRoutes: unprotected.length,
139
+ unprotected,
140
+ middlewares,
141
+ coverage: routes.length > 0 ? Math.round((protectedRoutes.length / routes.length) * 100) : 100,
142
+ };
143
+ }
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // 4. PYTHON TAINT (basic — regex-based, no AST)
147
+ // ---------------------------------------------------------------------------
148
+
149
+ const PY_SOURCES = [
150
+ { re: /request\.(?:form|args|data|json|values|cookies|headers)(?:\.\w+)?\s*\(/g, name: 'request' },
151
+ { re: /request\.get\s*\(/g, name: 'request' },
152
+ { re: /\binput\s*\(/g, name: 'input()' },
153
+ { re: /os\.environ\.get\s*\(/g, name: 'os.environ' },
154
+ { re: /sys\.argv/g, name: 'sys.argv' },
155
+ { re: /os\.getenv\s*\(/g, name: 'os.getenv' },
156
+ ];
157
+
158
+ const PY_SINKS = [
159
+ { re: /cursor\.execute\s*\(/g, name: 'cursor.execute', type: 'sql' },
160
+ { re: /os\.system\s*\(/g, name: 'os.system', type: 'cmd' },
161
+ { re: /subprocess\.(?:run|call|Popen)\s*\(/g, name: 'subprocess', type: 'cmd' },
162
+ { re: /eval\s*\(/g, name: 'eval()', type: 'code' },
163
+ { re: /exec\s*\(/g, name: 'exec()', type: 'code' },
164
+ { re: /open\s*\(/g, name: 'open()', type: 'file' },
165
+ { re: /pickle\.loads?\s*\(/g, name: 'pickle', type: 'deserialization' },
166
+ { re: /yaml\.load\s*\(/g, name: 'yaml.load', type: 'deserialization' },
167
+ { re: /shutil\.rmtree\s*\(/g, name: 'shutil.rmtree', type: 'file' },
168
+ ];
169
+
170
+ // Single-pass taint propagation (pure JS — no external parser, keeps VibeGuard
171
+ // zero-dependency and offline). Tracks tainted variables top-to-bottom:
172
+ // - a source assignment (v = request.form.get(...)) taints v;
173
+ // - an assignment whose RHS references a tainted var propagates the taint to
174
+ // the LHS (multi-hop: q = "..." + data → q is tainted);
175
+ // - reassigning a tainted var to a clean/sanitized value clears it;
176
+ // - a sink using a tainted var fires — UNLESS the value is parameterized
177
+ // (SQL) or wrapped in a sanitizer at the sink.
178
+ // This replaces the old "var appears anywhere between source and sink" heuristic,
179
+ // which false-positived when a tainted name merely appeared near an unrelated sink.
180
+ function analyzePythonTaint(content, lines, relPath) {
181
+ const findings = [];
182
+ const tainted = new Map(); // varName -> { name (source), line }
183
+ const seen = new Set(); // dedupe sink:line
184
+ const reOf = (v) => new RegExp('\\b' + escapeRe(v) + '\\b');
185
+
186
+ for (let i = 0; i < lines.length; i++) {
187
+ const line = lines[i];
188
+ const lineNo = i + 1;
189
+
190
+ // 1. Source assignment.
191
+ let matchedSource = null;
192
+ for (const src of PY_SOURCES) {
193
+ src.re.lastIndex = 0;
194
+ if (src.re.test(line)) { matchedSource = src.name; break; }
195
+ }
196
+ if (matchedSource) {
197
+ const v = extractVarName(line);
198
+ if (v) tainted.set(v, { name: matchedSource, line: lineNo });
199
+ }
200
+
201
+ // 2. Propagation / clearing via simple assignment `lhs = rhs`.
202
+ if (!matchedSource) {
203
+ const asn = /^\s*([A-Za-z_]\w*)\s*=\s*(.+)$/.exec(line);
204
+ if (asn) {
205
+ const lhs = asn[1];
206
+ const rhs = asn[2];
207
+ let carried = null;
208
+ for (const [tv, info] of tainted) {
209
+ if (reOf(tv).test(rhs) && !isSanitizedAtSink(rhs, tv)) { carried = info; break; }
210
+ }
211
+ if (carried) tainted.set(lhs, carried);
212
+ else if (tainted.has(lhs)) tainted.delete(lhs); // reassigned to clean value
213
+ }
214
+ }
215
+
216
+ // 3. Sinks.
217
+ for (const sink of PY_SINKS) {
218
+ sink.re.lastIndex = 0;
219
+ if (!sink.re.test(line)) continue;
220
+ for (const [tv, info] of tainted) {
221
+ if (!reOf(tv).test(line)) continue;
222
+ if (sink.type === 'sql' && isParameterizedExecute(line)) continue;
223
+ if (isSanitizedAtSink(line, tv)) continue;
224
+ const key = sink.name + ':' + lineNo;
225
+ if (seen.has(key)) break;
226
+ seen.add(key);
227
+ findings.push({
228
+ ruleId: 'py.taint-flow',
229
+ file: relPath,
230
+ line: lineNo,
231
+ column: 1,
232
+ severity: 'high',
233
+ confidence: 'medium',
234
+ title: `Python taint: ${info.name} → ${sink.name}`,
235
+ snippet: line.trim().slice(0, 120),
236
+ message: `User input (${info.name} at line ${info.line}) flows to ${sink.name} (line ${lineNo}) without sanitization.`,
237
+ fix: `Sanitize or validate the input before passing it to ${sink.name}.`,
238
+ owasp: 'A03:2025 Injection',
239
+ cwe: sink.type === 'sql' ? 'CWE-89' : sink.type === 'cmd' ? 'CWE-77' : 'CWE-20',
240
+ });
241
+ break;
242
+ }
243
+ }
244
+ }
245
+
246
+ return findings;
247
+ }
248
+
249
+ function escapeRe(s) {
250
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
251
+ }
252
+
253
+ // Parameterized DB call: a placeholder in the query AND a second argument to
254
+ // execute() = the driver binds/escapes the value, so it is NOT SQL injection.
255
+ function isParameterizedExecute(line) {
256
+ if (!/\.execute\s*\(/.test(line)) return false;
257
+ const hasPlaceholder = /%s|%\(|%d|\?|:\w+/.test(line);
258
+ const hasSecondArg = /\.execute\s*\([^)]*?,\s*[([{\w'"]/.test(line);
259
+ return hasPlaceholder && hasSecondArg;
260
+ }
261
+
262
+ // Python sanitizers that neutralize a tainted value. If the tainted var appears
263
+ // wrapped in one of these on the sink line, the flow is considered safe.
264
+ const PY_SANITIZER_FNS = [
265
+ 'int', 'float', 'bool', 'decimal.Decimal',
266
+ 'shlex.quote', 'pipes.quote', 'shlex.split',
267
+ 'html.escape', 'markupsafe.escape', 'escape', 'bleach.clean',
268
+ 'urllib.parse.quote', 'urllib.parse.quote_plus', 're.escape',
269
+ ];
270
+ function isSanitizedAtSink(sinkLine, varName) {
271
+ const v = varName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
272
+ for (const fn of PY_SANITIZER_FNS) {
273
+ const f = fn.replace(/\./g, '\\.');
274
+ // e.g. int(<var>) / shlex.quote(<var>) directly wrapping the tainted var
275
+ if (new RegExp('\\b' + f + '\\s*\\(\\s*' + v + '\\b').test(sinkLine)) return true;
276
+ }
277
+ return false;
278
+ }
279
+
280
+ function extractVarName(line) {
281
+ const m = /\b(\w+)\s*=\s*(?:request\.|input\(|os\.environ|sys\.argv)/.exec(line);
282
+ if (m) return m[1];
283
+ const m2 = /\b(?:for\s+)?(\w+)\s+in\s+request\./.exec(line);
284
+ if (m2) return m2[1];
285
+ return null;
286
+ }
287
+
288
+ module.exports = {
289
+ isSanitized,
290
+ SANITIZERS,
291
+ getChangedFiles,
292
+ loadHashCache,
293
+ saveHashCache,
294
+ hashContent,
295
+ buildAuthCoverage,
296
+ analyzePythonTaint,
297
+ };