@yagyeshvyas/vibeguard 1.0.0 → 1.1.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/ci/vibeguard.yml CHANGED
@@ -1,41 +1,42 @@
1
- name: VibeGuard
2
-
3
- # Runs VibeGuard on every push and pull request. Fails the job when a CRITICAL
4
- # issue is found, and uploads a SARIF report to GitHub code scanning so findings
5
- # show up inline on the PR.
6
- #
7
- # Scope reminder: VibeGuard catches high-frequency, well-defined issues (secrets,
8
- # injection, misconfig). It is not a full security review.
9
-
10
- on:
11
- push:
12
- branches: [main, master]
13
- pull_request:
14
-
15
- permissions:
16
- contents: read
17
- security-events: write # required to upload SARIF
18
-
19
- jobs:
20
- vibeguard:
21
- runs-on: ubuntu-latest
22
- steps:
23
- - uses: actions/checkout@v4
24
-
25
- - uses: actions/setup-node@v4
26
- with:
27
- node-version: 20
28
-
29
- # Produce a SARIF report for GitHub code scanning (does not fail the job).
30
- - name: VibeGuard scan (SARIF)
31
- run: npx -y vibeguard scan . --sarif --no-deps > vibeguard.sarif || true
32
-
33
- - name: Upload SARIF
34
- if: always()
35
- uses: github/codeql-action/upload-sarif@v3
36
- with:
37
- sarif_file: vibeguard.sarif
38
-
39
- # Gate the build: fail only on CRITICAL findings.
40
- - name: VibeGuard gate (block on CRITICAL)
41
- run: npx -y vibeguard scan . --precommit
1
+ name: VibeGuard
2
+
3
+ # Runs VibeGuard on every push and pull request. Fails the job when a CRITICAL
4
+ # issue is found, and uploads a SARIF report to GitHub code scanning so findings
5
+ # show up inline on the PR.
6
+ #
7
+ # Scope reminder: VibeGuard catches high-frequency, well-defined issues (secrets,
8
+ # injection, misconfig). It is not a full security review.
9
+
10
+ on:
11
+ push:
12
+ branches: [main, master]
13
+ pull_request:
14
+
15
+ permissions:
16
+ contents: read
17
+ security-events: write # required to upload SARIF
18
+
19
+ jobs:
20
+ vibeguard:
21
+ runs-on: ubuntu-latest
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+
25
+ - uses: actions/setup-node@v4
26
+ with:
27
+ node-version: 20
28
+
29
+ # Produce a SARIF report for GitHub code scanning (does not fail the job).
30
+ - name: VibeGuard scan (SARIF)
31
+ run: npx -y vibeguard scan . --sarif --no-deps > vibeguard.sarif || true
32
+
33
+ - name: Upload SARIF
34
+ if: always()
35
+ uses: github/codeql-action/upload-sarif@v3
36
+ with:
37
+ sarif_file: vibeguard.sarif
38
+
39
+ # Gate the build: fail on CRITICAL findings, and on a degraded scan
40
+ # (--strict) so an incomplete/parse-failed scan can't pass as clean.
41
+ - name: VibeGuard gate (block on CRITICAL)
42
+ run: npx -y vibeguard scan . --precommit --strict
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@yagyeshvyas/vibeguard",
3
- "version": "1.0.0",
4
- "description": "Offline security scanner for AI-generated code. 693 rules, 75 MCP tools, AST taint analysis, shell guard. Zero telemetry, zero dependencies.",
3
+ "version": "1.1.0",
4
+ "description": "Offline security scanner for AI-generated code. 699 rules, 75 MCP tools, AST taint analysis, shell guard. Zero telemetry, zero dependencies.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
7
7
  "author": "Yagyesh Vyas <https://www.linkedin.com/in/yagyeshvyas/>",
package/src/auto.js CHANGED
@@ -210,8 +210,12 @@ function autoStart(rootDir, opts) {
210
210
  }
211
211
  }
212
212
 
213
- // 5. Arm shell guard (install shell hook)
213
+ // 5. Arm shell guard (install shell hook) — requires consent
214
214
  if (!opts.noShell && !opts.ci) {
215
+ // Skip shell guard in auto unless --yes is passed (consent).
216
+ if (!opts.yes) {
217
+ steps.push({ step: 'shell-guard', installed: false, reason: 'skipped (use --yes to enable)' });
218
+ } else {
215
219
  try {
216
220
  const srcDir = path.join(__dirname);
217
221
  const home = os.homedir();
@@ -268,6 +272,7 @@ function autoStart(rootDir, opts) {
268
272
  } catch (e) {
269
273
  steps.push({ step: 'shell-guard', error: e.message });
270
274
  }
275
+ }
271
276
  }
272
277
 
273
278
  // Add .vibeguard/ to .gitignore
package/src/engine.js CHANGED
@@ -1,234 +1,294 @@
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
- ];
156
-
157
- const PY_SINKS = [
158
- { re: /cursor\.execute\s*\(/g, name: 'cursor.execute', type: 'sql' },
159
- { re: /os\.system\s*\(/g, name: 'os.system', type: 'cmd' },
160
- { re: /subprocess\.(?:run|call|Popen)\s*\(/g, name: 'subprocess', type: 'cmd' },
161
- { re: /eval\s*\(/g, name: 'eval()', type: 'code' },
162
- { re: /exec\s*\(/g, name: 'exec()', type: 'code' },
163
- { re: /open\s*\(/g, name: 'open()', type: 'file' },
164
- { re: /pickle\.loads?\s*\(/g, name: 'pickle', type: 'deserialization' },
165
- ];
166
-
167
- function analyzePythonTaint(content, lines, relPath) {
168
- const findings = [];
169
- const sources = [];
170
- const sinks = [];
171
-
172
- for (let i = 0; i < lines.length; i++) {
173
- const line = lines[i];
174
- for (const src of PY_SOURCES) {
175
- src.re.lastIndex = 0;
176
- if (src.re.test(line)) {
177
- sources.push({ line: i + 1, name: src.name, var: extractVarName(line) });
178
- }
179
- }
180
- for (const sink of PY_SINKS) {
181
- sink.re.lastIndex = 0;
182
- if (sink.re.test(line)) {
183
- sinks.push({ line: i + 1, name: sink.name, type: sink.type });
184
- }
185
- }
186
- }
187
-
188
- for (const src of sources) {
189
- for (const sink of sinks) {
190
- if (sink.line >= src.line) {
191
- const varName = src.var;
192
- if (!varName) continue;
193
- const linesBetween = lines.slice(src.line - 1, sink.line).join('\n');
194
- if (linesBetween.includes(varName)) {
195
- findings.push({
196
- ruleId: 'py.taint-flow',
197
- file: relPath,
198
- line: sink.line,
199
- column: 1,
200
- severity: 'high',
201
- confidence: 'medium',
202
- title: `Python taint: ${src.name} → ${sink.name}`,
203
- snippet: lines[sink.line - 1]?.trim().slice(0, 120) || '',
204
- message: `User input (${src.name} at line ${src.line}) flows to ${sink.name} (line ${sink.line}) without sanitization.`,
205
- fix: `Sanitize or validate the input before passing it to ${sink.name}.`,
206
- owasp: 'A03:2025 Injection',
207
- cwe: sink.type === 'sql' ? 'CWE-89' : sink.type === 'cmd' ? 'CWE-77' : 'CWE-20',
208
- });
209
- }
210
- }
211
- }
212
- }
213
-
214
- return findings;
215
- }
216
-
217
- function extractVarName(line) {
218
- const m = /\b(\w+)\s*=\s*(?:request\.|input\(|os\.environ|sys\.argv)/.exec(line);
219
- if (m) return m[1];
220
- const m2 = /\b(?:for\s+)?(\w+)\s+in\s+request\./.exec(line);
221
- if (m2) return m2[1];
222
- return null;
223
- }
224
-
225
- module.exports = {
226
- isSanitized,
227
- SANITIZERS,
228
- getChangedFiles,
229
- loadHashCache,
230
- saveHashCache,
231
- hashContent,
232
- buildAuthCoverage,
233
- analyzePythonTaint,
234
- };
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
+ ];
156
+
157
+ const PY_SINKS = [
158
+ { re: /cursor\.execute\s*\(/g, name: 'cursor.execute', type: 'sql' },
159
+ { re: /os\.system\s*\(/g, name: 'os.system', type: 'cmd' },
160
+ { re: /subprocess\.(?:run|call|Popen)\s*\(/g, name: 'subprocess', type: 'cmd' },
161
+ { re: /eval\s*\(/g, name: 'eval()', type: 'code' },
162
+ { re: /exec\s*\(/g, name: 'exec()', type: 'code' },
163
+ { re: /open\s*\(/g, name: 'open()', type: 'file' },
164
+ { re: /pickle\.loads?\s*\(/g, name: 'pickle', type: 'deserialization' },
165
+ ];
166
+
167
+ // Single-pass taint propagation (pure JS — no external parser, keeps VibeGuard
168
+ // zero-dependency and offline). Tracks tainted variables top-to-bottom:
169
+ // - a source assignment (v = request.form.get(...)) taints v;
170
+ // - an assignment whose RHS references a tainted var propagates the taint to
171
+ // the LHS (multi-hop: q = "..." + data → q is tainted);
172
+ // - reassigning a tainted var to a clean/sanitized value clears it;
173
+ // - a sink using a tainted var fires — UNLESS the value is parameterized
174
+ // (SQL) or wrapped in a sanitizer at the sink.
175
+ // This replaces the old "var appears anywhere between source and sink" heuristic,
176
+ // which false-positived when a tainted name merely appeared near an unrelated sink.
177
+ function analyzePythonTaint(content, lines, relPath) {
178
+ const findings = [];
179
+ const tainted = new Map(); // varName -> { name (source), line }
180
+ const seen = new Set(); // dedupe sink:line
181
+ const reOf = (v) => new RegExp('\\b' + escapeRe(v) + '\\b');
182
+
183
+ for (let i = 0; i < lines.length; i++) {
184
+ const line = lines[i];
185
+ const lineNo = i + 1;
186
+
187
+ // 1. Source assignment.
188
+ let matchedSource = null;
189
+ for (const src of PY_SOURCES) {
190
+ src.re.lastIndex = 0;
191
+ if (src.re.test(line)) { matchedSource = src.name; break; }
192
+ }
193
+ if (matchedSource) {
194
+ const v = extractVarName(line);
195
+ if (v) tainted.set(v, { name: matchedSource, line: lineNo });
196
+ }
197
+
198
+ // 2. Propagation / clearing via simple assignment `lhs = rhs`.
199
+ if (!matchedSource) {
200
+ const asn = /^\s*([A-Za-z_]\w*)\s*=\s*(.+)$/.exec(line);
201
+ if (asn) {
202
+ const lhs = asn[1];
203
+ const rhs = asn[2];
204
+ let carried = null;
205
+ for (const [tv, info] of tainted) {
206
+ if (reOf(tv).test(rhs) && !isSanitizedAtSink(rhs, tv)) { carried = info; break; }
207
+ }
208
+ if (carried) tainted.set(lhs, carried);
209
+ else if (tainted.has(lhs)) tainted.delete(lhs); // reassigned to clean value
210
+ }
211
+ }
212
+
213
+ // 3. Sinks.
214
+ for (const sink of PY_SINKS) {
215
+ sink.re.lastIndex = 0;
216
+ if (!sink.re.test(line)) continue;
217
+ for (const [tv, info] of tainted) {
218
+ if (!reOf(tv).test(line)) continue;
219
+ if (sink.type === 'sql' && isParameterizedExecute(line)) continue;
220
+ if (isSanitizedAtSink(line, tv)) continue;
221
+ const key = sink.name + ':' + lineNo;
222
+ if (seen.has(key)) break;
223
+ seen.add(key);
224
+ findings.push({
225
+ ruleId: 'py.taint-flow',
226
+ file: relPath,
227
+ line: lineNo,
228
+ column: 1,
229
+ severity: 'high',
230
+ confidence: 'medium',
231
+ title: `Python taint: ${info.name} → ${sink.name}`,
232
+ snippet: line.trim().slice(0, 120),
233
+ message: `User input (${info.name} at line ${info.line}) flows to ${sink.name} (line ${lineNo}) without sanitization.`,
234
+ fix: `Sanitize or validate the input before passing it to ${sink.name}.`,
235
+ owasp: 'A03:2025 Injection',
236
+ cwe: sink.type === 'sql' ? 'CWE-89' : sink.type === 'cmd' ? 'CWE-77' : 'CWE-20',
237
+ });
238
+ break;
239
+ }
240
+ }
241
+ }
242
+
243
+ return findings;
244
+ }
245
+
246
+ function escapeRe(s) {
247
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
248
+ }
249
+
250
+ // Parameterized DB call: a placeholder in the query AND a second argument to
251
+ // execute() = the driver binds/escapes the value, so it is NOT SQL injection.
252
+ function isParameterizedExecute(line) {
253
+ if (!/\.execute\s*\(/.test(line)) return false;
254
+ const hasPlaceholder = /%s|%\(|%d|\?|:\w+/.test(line);
255
+ const hasSecondArg = /\.execute\s*\([^)]*?,\s*[([{\w'"]/.test(line);
256
+ return hasPlaceholder && hasSecondArg;
257
+ }
258
+
259
+ // Python sanitizers that neutralize a tainted value. If the tainted var appears
260
+ // wrapped in one of these on the sink line, the flow is considered safe.
261
+ const PY_SANITIZER_FNS = [
262
+ 'int', 'float', 'bool', 'decimal.Decimal',
263
+ 'shlex.quote', 'pipes.quote', 'shlex.split',
264
+ 'html.escape', 'markupsafe.escape', 'escape', 'bleach.clean',
265
+ 'urllib.parse.quote', 'urllib.parse.quote_plus', 're.escape',
266
+ ];
267
+ function isSanitizedAtSink(sinkLine, varName) {
268
+ const v = varName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
269
+ for (const fn of PY_SANITIZER_FNS) {
270
+ const f = fn.replace(/\./g, '\\.');
271
+ // e.g. int(<var>) / shlex.quote(<var>) directly wrapping the tainted var
272
+ if (new RegExp('\\b' + f + '\\s*\\(\\s*' + v + '\\b').test(sinkLine)) return true;
273
+ }
274
+ return false;
275
+ }
276
+
277
+ function extractVarName(line) {
278
+ const m = /\b(\w+)\s*=\s*(?:request\.|input\(|os\.environ|sys\.argv)/.exec(line);
279
+ if (m) return m[1];
280
+ const m2 = /\b(?:for\s+)?(\w+)\s+in\s+request\./.exec(line);
281
+ if (m2) return m2[1];
282
+ return null;
283
+ }
284
+
285
+ module.exports = {
286
+ isSanitized,
287
+ SANITIZERS,
288
+ getChangedFiles,
289
+ loadHashCache,
290
+ saveHashCache,
291
+ hashContent,
292
+ buildAuthCoverage,
293
+ analyzePythonTaint,
294
+ };