@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.
@@ -0,0 +1,852 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Scope-aware, AST-based intra-file taint analysis (requires acorn).
5
+ *
6
+ * Replaces the regex taint pass when a file parses successfully.
7
+ * Handles: variable declarations, assignments, template literals, binary
8
+ * string concat, function parameters, object property reads/writes, array
9
+ * element access, block/function scope with shadowing, reassignment clearing,
10
+ * and sanitizer recognition.
11
+ *
12
+ * Falls back to regex taint (in taint.js) when acorn is unavailable or the
13
+ * file doesn't parse.
14
+ */
15
+
16
+ const ast = require('./ast');
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Sources — matched on AST MemberExpression nodes, not text.
20
+ // ---------------------------------------------------------------------------
21
+
22
+ // Roots whose properties indicate attacker-controlled data.
23
+ const SOURCE_ROOTS = new Set(['req', 'request', 'ctx', 'event', 'process']);
24
+ const SOURCE_PROPS = new Set([
25
+ 'body', 'query', 'params', 'headers', 'cookies', 'url', 'originalUrl',
26
+ 'hostname', 'searchParams', 'argv',
27
+ 'queryStringParameters', 'pathParameters',
28
+ ]);
29
+
30
+ function isSourceNode(node) {
31
+ if (!node) return false;
32
+ // process.argv
33
+ if (node.type === 'MemberExpression') {
34
+ const root = ast.rootName(node);
35
+ const prop = node.property && node.property.name;
36
+ if (SOURCE_ROOTS.has(root) && SOURCE_PROPS.has(prop)) return true;
37
+ // .searchParams on any object
38
+ if (prop === 'searchParams') return true;
39
+ // request.body, req.body etc. — also match deeper: req.body.x
40
+ if (SOURCE_ROOTS.has(root)) return true;
41
+ return false;
42
+ }
43
+ // bare `req` / `request` identifier
44
+ if (node.type === 'Identifier' && SOURCE_ROOTS.has(node.name)) return true;
45
+ return false;
46
+ }
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Sinks — matched on CallExpression nodes.
50
+ // Kept identical ruleId/severity/title/message/fix to the regex SINKS in taint.js.
51
+ // ---------------------------------------------------------------------------
52
+
53
+ const SINKS_AST = [
54
+ {
55
+ match: (call) => {
56
+ const name = ast.calleeName(call);
57
+ return /(?:^|\.)(?:exec|execSync|spawn|spawnSync|execFile|execFileSync)$/.test(name);
58
+ },
59
+ ruleId: 'taint.command-injection',
60
+ severity: 'high',
61
+ title: 'User input reaches a shell command (dataflow-confirmed)',
62
+ message: 'A value derived from user input flows into a shell command — command injection.',
63
+ fix: 'Pass arguments as an array (execFile("cmd",[arg])) and never build a shell string from input; validate/allowlist.',
64
+ },
65
+ {
66
+ match: (call) => {
67
+ const prop = (call.callee && call.callee.property && call.callee.property.name) || '';
68
+ const name = ast.calleeName(call);
69
+ if (prop === 'query' || prop === 'raw' || prop === 'execute') return true;
70
+ if (name === 'sequelize.query') return true;
71
+ return false;
72
+ },
73
+ ruleId: 'taint.sql-injection',
74
+ severity: 'high',
75
+ title: 'User input reaches a SQL query (dataflow-confirmed)',
76
+ message: 'A value derived from user input flows into a SQL query call — SQL injection.',
77
+ fix: 'Use parameterized queries / prepared statements; pass input as bound parameters, not concatenated SQL.',
78
+ },
79
+ {
80
+ match: (call) => {
81
+ const name = ast.calleeName(call);
82
+ return name === 'eval' || /^new\s/.test('') && call.callee && call.callee.name === 'Function';
83
+ },
84
+ ruleId: 'taint.code-injection',
85
+ severity: 'critical',
86
+ title: 'User input reaches eval()/Function() (dataflow-confirmed)',
87
+ message: 'A value derived from user input flows into eval()/new Function() — remote code execution.',
88
+ fix: 'Remove eval/Function on dynamic input. Use JSON.parse or an explicit dispatch table.',
89
+ },
90
+ {
91
+ match: (call) => {
92
+ const prop = (call.callee && call.callee.property && call.callee.property.name) || '';
93
+ const name = ast.calleeName(call);
94
+ if (['readFile', 'readFileSync', 'writeFile', 'writeFileSync', 'createReadStream', 'createWriteStream', 'unlink', 'unlinkSync', 'appendFile', 'sendFile'].includes(prop)) return true;
95
+ if (name === 'path.join' || name === 'path.resolve') return true;
96
+ return false;
97
+ },
98
+ ruleId: 'taint.path-traversal',
99
+ severity: 'high',
100
+ title: 'User input reaches a filesystem path (dataflow-confirmed)',
101
+ message: 'A value derived from user input is used to build a filesystem path — path traversal.',
102
+ fix: 'Sanitize with path.basename(), resolve against a fixed base, and reject paths that escape it.',
103
+ },
104
+ {
105
+ match: (call) => {
106
+ const name = ast.calleeName(call);
107
+ const prop = (call.callee && call.callee.property && call.callee.property.name) || '';
108
+ if (/(?:^|\.)(?:fetch|got)$/.test(name)) return true;
109
+ if (['get', 'post', 'put', 'delete', 'request'].includes(prop) && /axios|http|https|got/.test(name)) return true;
110
+ return false;
111
+ },
112
+ ruleId: 'taint.ssrf',
113
+ severity: 'high',
114
+ title: 'User input reaches an outbound request URL (dataflow-confirmed)',
115
+ message: 'A value derived from user input is used as an outbound request target — server-side request forgery (SSRF).',
116
+ fix: 'Allowlist permitted hosts/schemes; never fetch a URL built from raw user input; block internal/metadata addresses.',
117
+ },
118
+ {
119
+ match: (call) => {
120
+ const prop = (call.callee && call.callee.property && call.callee.property.name) || '';
121
+ return prop === 'redirect' || prop === 'location';
122
+ },
123
+ ruleId: 'taint.open-redirect',
124
+ severity: 'medium',
125
+ title: 'User input reaches a redirect target (dataflow-confirmed)',
126
+ message: 'A value derived from user input is used as a redirect target — open redirect (phishing).',
127
+ fix: 'Redirect only to an allowlist of internal paths; reject absolute/off-site URLs from input.',
128
+ },
129
+ ];
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // Sanitizers — configurable array of function names that clear taint.
133
+ // ---------------------------------------------------------------------------
134
+
135
+ const DEFAULT_SANITIZERS = [
136
+ 'parseInt', 'parseFloat', 'Number', 'String', 'Boolean',
137
+ 'escape', 'encodeURI', 'encodeURIComponent',
138
+ 'basename',
139
+ ];
140
+
141
+ function isSanitizerCall(call, sanitizers) {
142
+ const name = ast.calleeName(call);
143
+ const prop = (call.callee && call.callee.property && call.callee.property.name) || '';
144
+ for (const s of sanitizers) {
145
+ if (name === s || prop === s) return true;
146
+ // validator.escape, DOMPurify.sanitize etc.
147
+ if (name.endsWith('.' + s) || prop === s) return true;
148
+ }
149
+ // DOMPurify.sanitize — always recognized
150
+ if (prop === 'sanitize') return true;
151
+ // path.basename — always recognized
152
+ if (name === 'path.basename') return true;
153
+ return false;
154
+ }
155
+
156
+ // ---------------------------------------------------------------------------
157
+ // Scope tree: build a scope hierarchy from the AST.
158
+ // ---------------------------------------------------------------------------
159
+
160
+ // We walk the tree manually (not acorn-walk) so we can track enter/exit of
161
+ // scopes precisely and maintain a scope stack.
162
+
163
+ function isScopeNode(node) {
164
+ return node && (
165
+ node.type === 'Program' ||
166
+ node.type === 'FunctionDeclaration' ||
167
+ node.type === 'FunctionExpression' ||
168
+ node.type === 'ArrowFunctionExpression' ||
169
+ node.type === 'BlockStatement'
170
+ );
171
+ }
172
+
173
+ function getScopeDeclarations(node) {
174
+ // Returns names declared in this scope (var/let/const/function).
175
+ const names = new Set();
176
+ if (!node) return names;
177
+ if (node.type === 'Program' || node.type === 'BlockStatement') {
178
+ if (node.body && Array.isArray(node.body)) {
179
+ for (const stmt of node.body) {
180
+ collectDeclarations(stmt, names);
181
+ }
182
+ }
183
+ }
184
+ // Function params are declared in the function scope (not the block).
185
+ if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
186
+ if (node.params) {
187
+ for (const p of node.params) {
188
+ bindingNames(p, names);
189
+ }
190
+ }
191
+ // Function name (for FunctionDeclaration)
192
+ if (node.type === 'FunctionDeclaration' && node.id) names.add(node.id.name);
193
+ }
194
+ return names;
195
+ }
196
+
197
+ function bindingNames(param, out) {
198
+ out = out || new Set();
199
+ if (!param) return out;
200
+ if (param.type === 'Identifier') out.add(param.name);
201
+ else if (param.type === 'AssignmentPattern') bindingNames(param.left, out);
202
+ else if (param.type === 'RestElement') bindingNames(param.argument, out);
203
+ else if (param.type === 'ObjectPattern') {
204
+ for (const p of param.properties) {
205
+ bindingNames(p.type === 'RestElement' ? p.argument : p.value, out);
206
+ }
207
+ }
208
+ else if (param.type === 'ArrayPattern') {
209
+ for (const e of param.elements) if (e) bindingNames(e, out);
210
+ }
211
+ return out;
212
+ }
213
+
214
+ function collectDeclarations(stmt, names) {
215
+ if (!stmt) return;
216
+ switch (stmt.type) {
217
+ case 'VariableDeclaration':
218
+ for (const d of stmt.declarations) {
219
+ if (d.id) bindingNames(d.id, names);
220
+ }
221
+ break;
222
+ case 'FunctionDeclaration':
223
+ if (stmt.id) names.add(stmt.id.name);
224
+ break;
225
+ case 'ExportNamedDeclaration':
226
+ if (stmt.declaration) collectDeclarations(stmt.declaration, names);
227
+ break;
228
+ case 'ExportDefaultDeclaration':
229
+ if (stmt.declaration && stmt.declaration.type === 'FunctionDeclaration' && stmt.declaration.id) {
230
+ names.add(stmt.declaration.id.name);
231
+ }
232
+ break;
233
+ default:
234
+ break;
235
+ }
236
+ }
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // Taint analysis engine
240
+ // ---------------------------------------------------------------------------
241
+
242
+ // A TaintScope tracks tainted variables within a lexical scope.
243
+ // Shadowing: if an inner scope declares a name that's tainted in an outer
244
+ // scope, the inner declaration starts clean (it's a different variable).
245
+
246
+ class TaintScope {
247
+ constructor(parent, decls) {
248
+ this.parent = parent;
249
+ this.decls = decls; // Set of names declared in this scope
250
+ this.tainted = new Map(); // name -> { via: string, sanitized: boolean }
251
+ }
252
+
253
+ // Look up a name: return taint info if found in this or any parent scope.
254
+ // Returns { via, sanitized } or null. Respects shadowing: if this scope
255
+ // declares the name but it's not tainted here, return null (shadowed).
256
+ lookup(name) {
257
+ if (this.decls.has(name)) {
258
+ // Declared in this scope — only this scope's taint matters.
259
+ return this.tainted.get(name) || null;
260
+ }
261
+ if (this.parent) return this.parent.lookup(name);
262
+ // No parent and not declared: check our own taint map (covers isolated
263
+ // function-analysis scopes where decls is empty but taint was set manually).
264
+ return this.tainted.get(name) || null;
265
+ }
266
+
267
+ // Set taint for a name that's declared in this or an ancestor scope.
268
+ // If the name is declared in an ancestor, set it there. Otherwise set it
269
+ // here (e.g., it was assigned without a var — implicit global, or we
270
+ // just track it locally).
271
+ setTaint(name, info) {
272
+ if (this.decls.has(name)) {
273
+ this.tainted.set(name, info);
274
+ return;
275
+ }
276
+ if (this.parent && this.parent.hasDecl(name)) {
277
+ this.parent.setTaint(name, info);
278
+ return;
279
+ }
280
+ // Not declared anywhere we can see — track in the nearest function/program scope.
281
+ this.tainted.set(name, info);
282
+ }
283
+
284
+ hasDecl(name) {
285
+ if (this.decls.has(name)) return true;
286
+ if (this.parent) return this.parent.hasDecl(name);
287
+ return false;
288
+ }
289
+
290
+ clearTaint(name) {
291
+ if (this.decls.has(name)) {
292
+ this.tainted.delete(name);
293
+ return;
294
+ }
295
+ if (this.parent && this.parent.hasDecl(name)) {
296
+ this.parent.clearTaint(name);
297
+ return;
298
+ }
299
+ this.tainted.delete(name);
300
+ }
301
+ }
302
+
303
+ // Check if an expression node references a tainted variable (considering scope).
304
+ function exprTaintInfo(node, scope) {
305
+ if (!node) return null;
306
+ switch (node.type) {
307
+ case 'Identifier': {
308
+ return scope.lookup(node.name);
309
+ }
310
+ case 'MemberExpression': {
311
+ // For member expressions like req.body.name, the root identifier matters.
312
+ // If the root is tainted (e.g., `const x = req; x.body.name`), the whole
313
+ // member is tainted. Also check the object chain.
314
+ const root = ast.rootName(node);
315
+ if (root && scope.lookup(root)) {
316
+ const info = scope.lookup(root);
317
+ return info;
318
+ }
319
+ // Check if the object part is tainted.
320
+ return exprTaintInfo(node.object, scope);
321
+ }
322
+ case 'BinaryExpression': {
323
+ const l = exprTaintInfo(node.left, scope);
324
+ if (l) return l;
325
+ const r = exprTaintInfo(node.right, scope);
326
+ return r;
327
+ }
328
+ case 'TemplateLiteral': {
329
+ for (const expr of node.expressions) {
330
+ const info = exprTaintInfo(expr, scope);
331
+ if (info) return info;
332
+ }
333
+ return null;
334
+ }
335
+ case 'CallExpression': {
336
+ // If this is a sanitizer call, the result is NOT tainted.
337
+ // (We handle this at the assignment site too, but check here for safety.)
338
+ const sanitizers = scope._sanitizers || DEFAULT_SANITIZERS;
339
+ if (isSanitizerCall(node, sanitizers)) return null;
340
+ // Check if any argument is tainted (taint through function call, best-effort).
341
+ for (const arg of node.arguments || []) {
342
+ const info = exprTaintInfo(arg, scope);
343
+ if (info) return info;
344
+ }
345
+ // Check if the callee is a tainted variable holding a function
346
+ const calleeInfo = exprTaintInfo(node.callee, scope);
347
+ if (calleeInfo) return calleeInfo;
348
+ return null;
349
+ }
350
+ case 'ConditionalExpression': {
351
+ const c = exprTaintInfo(node.consequent, scope);
352
+ if (c) return c;
353
+ return exprTaintInfo(node.alternate, scope);
354
+ }
355
+ case 'LogicalExpression': {
356
+ const l = exprTaintInfo(node.left, scope);
357
+ if (l) return l;
358
+ return exprTaintInfo(node.right, scope);
359
+ }
360
+ case 'ArrayExpression': {
361
+ for (const el of node.elements || []) {
362
+ const info = exprTaintInfo(el, scope);
363
+ if (info) return info;
364
+ }
365
+ return null;
366
+ }
367
+ case 'ObjectExpression': {
368
+ for (const prop of node.properties || []) {
369
+ if (prop.value) {
370
+ const info = exprTaintInfo(prop.value, scope);
371
+ if (info) return info;
372
+ }
373
+ }
374
+ return null;
375
+ }
376
+ case 'AssignmentExpression': {
377
+ return exprTaintInfo(node.right, scope);
378
+ }
379
+ case 'UnaryExpression': {
380
+ // typeof, void, !, etc. — these don't propagate taint meaningfully
381
+ // except for + which is string concat, but that's BinaryExpression.
382
+ return null;
383
+ }
384
+ case 'ChainExpression': {
385
+ return exprTaintInfo(node.expression, scope);
386
+ }
387
+ case 'AwaitExpression': {
388
+ return exprTaintInfo(node.argument, scope);
389
+ }
390
+ case 'SpreadElement': {
391
+ return exprTaintInfo(node.argument, scope);
392
+ }
393
+ default:
394
+ return null;
395
+ }
396
+ }
397
+
398
+ // Does the expression directly contain a source?
399
+ function exprIsSource(node) {
400
+ if (!node) return false;
401
+ if (isSourceNode(node)) return true;
402
+ switch (node.type) {
403
+ case 'MemberExpression':
404
+ return exprIsSource(node.object);
405
+ case 'BinaryExpression':
406
+ return exprIsSource(node.left) || exprIsSource(node.right);
407
+ case 'TemplateLiteral':
408
+ return node.expressions.some((e) => exprIsSource(e));
409
+ case 'CallExpression':
410
+ return (node.arguments || []).some(exprIsSource);
411
+ case 'ConditionalExpression':
412
+ return exprIsSource(node.consequent) || exprIsSource(node.alternate);
413
+ case 'LogicalExpression':
414
+ return exprIsSource(node.left) || exprIsSource(node.right);
415
+ case 'ArrayExpression':
416
+ return (node.elements || []).some(exprIsSource);
417
+ case 'ObjectExpression':
418
+ return (node.properties || []).some((p) => p.value && exprIsSource(p.value));
419
+ case 'AssignmentExpression':
420
+ return exprIsSource(node.right);
421
+ case 'ChainExpression':
422
+ return exprIsSource(node.expression);
423
+ case 'AwaitExpression':
424
+ return exprIsSource(node.argument);
425
+ default:
426
+ return false;
427
+ }
428
+ }
429
+
430
+ // ---------------------------------------------------------------------------
431
+ // Main analysis: walk the AST, maintain scope stack, track taint.
432
+ // ---------------------------------------------------------------------------
433
+
434
+ function analyzeTaintAst(content, lines, relPath, tree, sanitizers) {
435
+ const walk = ast.getWalk();
436
+ if (!walk || !tree) return [];
437
+ const ext = require('path').extname(relPath || '').toLowerCase();
438
+ const sanList = sanitizers || DEFAULT_SANITIZERS;
439
+
440
+ const findings = [];
441
+ const rootScope = new TaintScope(null, getScopeDeclarations(tree));
442
+ rootScope._sanitizers = sanList;
443
+
444
+ // Scope stack: maintain current scope as we traverse.
445
+ let currentScope = rootScope;
446
+
447
+ // We need to traverse manually to control scope entry/exit.
448
+ // But acorn-walk's `walk.recursive` gives us enter/exit callbacks.
449
+ // Since acorn-walk doesn't expose enter/exit in `walk.simple`, we'll
450
+ // use a custom recursive walker.
451
+
452
+ // First pass: collect all function definitions to support cross-function taint.
453
+ // Map: funcName -> { node, paramTaintSlots: Map(paramName -> Set(argIndex)), sinkCalls: [{call, paramRefs}] }
454
+ const functions = new Map();
455
+
456
+ // Collect function declarations and expressions.
457
+ function collectFunctions(node) {
458
+ if (!node || typeof node !== 'object') return;
459
+ if (node.type === 'FunctionDeclaration' && node.id) {
460
+ functions.set(node.id.name, { node, params: node.params || [] });
461
+ }
462
+ if (node.type === 'VariableDeclarator' && node.id && node.id.type === 'Identifier' && node.init) {
463
+ if (node.init.type === 'ArrowFunctionExpression' || node.init.type === 'FunctionExpression') {
464
+ functions.set(node.id.name, { node: node.init, params: node.init.params || [] });
465
+ }
466
+ }
467
+ // Recurse into children
468
+ for (const key in node) {
469
+ if (key === 'type' || key === 'loc' || key === 'start' || key === 'end' || key === 'range') continue;
470
+ const child = node[key];
471
+ if (Array.isArray(child)) {
472
+ child.forEach(collectFunctions);
473
+ } else if (child && typeof child === 'object' && child.type) {
474
+ collectFunctions(child);
475
+ }
476
+ }
477
+ }
478
+ collectFunctions(tree);
479
+
480
+ // Analyze each function: does any param reach a sink?
481
+ // We run proper intra-function taint tracking: params are tainted, then we
482
+ // propagate through local assignments (fixpoint), then check sink call args.
483
+ const funcSinkInfo = new Map(); // funcName -> [{ paramIndex, sinkDef }]
484
+
485
+ for (const [name, info] of functions) {
486
+ const paramNames = [];
487
+ (info.params || []).forEach((p, i) => {
488
+ for (const n of bindingNames(p)) paramNames.push({ name: n, index: i });
489
+ });
490
+ // Build a function-local scope with params tainted at their slot.
491
+ const fnScope = new TaintScope(null, new Set());
492
+ fnScope._sanitizers = sanList;
493
+ for (const { name: pn, index } of paramNames) {
494
+ fnScope.setTaint(pn, { via: `param:${index}`, sanitized: false });
495
+ }
496
+
497
+ // Collect all assignments in the function body (fixpoint for local propagation).
498
+ const assigns = [];
499
+ function collectAssigns(node) {
500
+ if (!node || typeof node !== 'object') return;
501
+ // Don't recurse into nested functions (their params shadow).
502
+ if (node !== info.node && isScopeNode(node) && node.type !== 'BlockStatement') return;
503
+ if (node.type === 'VariableDeclarator' && node.id && node.id.type === 'Identifier' && node.init) {
504
+ assigns.push({ name: node.id.name, expr: node.init });
505
+ }
506
+ if (node.type === 'AssignmentExpression' && node.left && node.left.type === 'Identifier') {
507
+ assigns.push({ name: node.left.name, expr: node.right });
508
+ }
509
+ for (const key in node) {
510
+ if (key === 'type' || key === 'loc' || key === 'start' || key === 'end' || key === 'range') continue;
511
+ const child = node[key];
512
+ if (Array.isArray(child)) {
513
+ child.forEach(collectAssigns);
514
+ } else if (child && typeof child === 'object' && child.type) {
515
+ collectAssigns(child);
516
+ }
517
+ }
518
+ }
519
+ collectAssigns(info.node);
520
+
521
+ // Fixpoint: propagate taint through local assignments.
522
+ for (let pass = 0; pass < 5; pass++) {
523
+ let changed = false;
524
+ for (const a of assigns) {
525
+ // Sanitizer check first.
526
+ if (a.expr.type === 'CallExpression' && isSanitizerCall(a.expr, sanList)) {
527
+ if (fnScope.lookup(a.name)) fnScope.clearTaint(a.name);
528
+ continue;
529
+ }
530
+ if (exprTaintInfo(a.expr, fnScope)) {
531
+ const info2 = exprTaintInfo(a.expr, fnScope);
532
+ fnScope.setTaint(a.name, { via: info2.via, sanitized: info2.sanitized });
533
+ changed = true;
534
+ }
535
+ }
536
+ if (!changed) break;
537
+ }
538
+
539
+ // Walk the function body for sink calls and check if args are tainted.
540
+ const sinks = [];
541
+ function walkForSinks(node) {
542
+ if (!node || typeof node !== 'object') return;
543
+ // Don't recurse into nested function bodies (they have their own scope).
544
+ if (node !== info.node && isScopeNode(node) && node.type !== 'BlockStatement') return;
545
+ if (node.type === 'CallExpression') {
546
+ for (const sinkDef of SINKS_AST) {
547
+ if (!sinkDef.match(node)) continue;
548
+ for (let ai = 0; ai < (node.arguments || []).length; ai++) {
549
+ const arg = node.arguments[ai];
550
+ // Check if the arg is tainted (through local propagation).
551
+ const taintInfo = exprTaintInfo(arg, fnScope);
552
+ if (taintInfo && !taintInfo.sanitized) {
553
+ // Find which param slot this taint originated from.
554
+ const viaMatch = /param:(\d+)/.exec(taintInfo.via);
555
+ if (viaMatch) {
556
+ const paramIndex = parseInt(viaMatch[1], 10);
557
+ sinks.push({ paramIndex, sinkDef, node });
558
+ } else {
559
+ // Taint from a source directly inside the function —
560
+ // this is a source->sink inside the helper, not cross-function.
561
+ // Skip it; the main visit pass handles source->sink.
562
+ }
563
+ }
564
+ }
565
+ }
566
+ }
567
+ for (const key in node) {
568
+ if (key === 'type' || key === 'loc' || key === 'start' || key === 'end' || key === 'range') continue;
569
+ const child = node[key];
570
+ if (Array.isArray(child)) {
571
+ child.forEach(walkForSinks);
572
+ } else if (child && typeof child === 'object' && child.type) {
573
+ walkForSinks(child);
574
+ }
575
+ }
576
+ }
577
+ walkForSinks(info.node);
578
+ if (sinks.length > 0) {
579
+ funcSinkInfo.set(name, sinks);
580
+ }
581
+ }
582
+
583
+ // Now walk the full tree, maintaining scopes and tracking taint.
584
+ // We detect sinks at call sites and check if arguments are tainted.
585
+
586
+ function pushScope(node) {
587
+ const decls = getScopeDeclarations(node);
588
+ const scope = new TaintScope(currentScope, decls);
589
+ scope._sanitizers = sanList;
590
+ currentScope = scope;
591
+ }
592
+
593
+ function popScope() {
594
+ currentScope = currentScope.parent || rootScope;
595
+ }
596
+
597
+ // Process a node: check for sinks, propagate taint through assignments.
598
+ function visit(node) {
599
+ if (!node || typeof node !== 'object') return;
600
+
601
+ // Enter scope nodes.
602
+ const isScope = isScopeNode(node);
603
+ if (isScope) pushScope(node);
604
+
605
+ // Handle VariableDeclarator: propagate taint from init to declared names.
606
+ if (node.type === 'VariableDeclarator' && node.id && node.init) {
607
+ handleDeclarator(node);
608
+ }
609
+
610
+ // Handle AssignmentExpression: propagate or clear taint.
611
+ if (node.type === 'AssignmentExpression') {
612
+ handleAssignment(node);
613
+ }
614
+
615
+ // Handle CallExpression: check sinks and cross-function taint.
616
+ if (node.type === 'CallExpression') {
617
+ handleCall(node);
618
+ }
619
+
620
+ // Recurse into children.
621
+ for (const key in node) {
622
+ if (key === 'type' || key === 'loc' || key === 'start' || key === 'end' || key === 'range') continue;
623
+ const child = node[key];
624
+ if (Array.isArray(child)) {
625
+ child.forEach(visit);
626
+ } else if (child && typeof child === 'object' && child.type) {
627
+ visit(child);
628
+ }
629
+ }
630
+
631
+ if (isScope) popScope();
632
+ }
633
+
634
+ function handleDeclarator(node) {
635
+ const init = node.init;
636
+ // Check sanitizer FIRST — parseInt(req.query.id) contains a source in its
637
+ // arg, but the sanitizer result is clean.
638
+ if (init.type === 'CallExpression' && isSanitizerCall(init, sanList)) {
639
+ const names = bindingNames(node.id);
640
+ for (const name of names) {
641
+ currentScope.clearTaint(name);
642
+ }
643
+ return;
644
+ }
645
+ // Check if the init is a source directly.
646
+ if (exprIsSource(init)) {
647
+ const names = bindingNames(node.id);
648
+ for (const name of names) {
649
+ currentScope.setTaint(name, { via: 'source', sanitized: false });
650
+ }
651
+ return;
652
+ }
653
+ // Check if the init expression references a tainted variable.
654
+ const taintInfo = exprTaintInfo(init, currentScope);
655
+ if (taintInfo) {
656
+ const names = bindingNames(node.id);
657
+ for (const name of names) {
658
+ currentScope.setTaint(name, { via: taintInfo.via, sanitized: taintInfo.sanitized });
659
+ }
660
+ return;
661
+ }
662
+ // Init is clean: clear taint for declared names (reassignment to clean).
663
+ const names = bindingNames(node.id);
664
+ for (const name of names) {
665
+ currentScope.clearTaint(name);
666
+ }
667
+ }
668
+
669
+ function handleAssignment(node) {
670
+ const left = node.left;
671
+ const right = node.right;
672
+
673
+ // Only handle identifier and member-expression targets.
674
+ if (left.type === 'Identifier') {
675
+ // Sanitizer check first — see handleDeclarator for rationale.
676
+ if (right.type === 'CallExpression' && isSanitizerCall(right, sanList)) {
677
+ currentScope.clearTaint(left.name);
678
+ return;
679
+ }
680
+ if (exprIsSource(right)) {
681
+ currentScope.setTaint(left.name, { via: 'source', sanitized: false });
682
+ return;
683
+ }
684
+ const taintInfo = exprTaintInfo(right, currentScope);
685
+ if (taintInfo) {
686
+ currentScope.setTaint(left.name, { via: taintInfo.via, sanitized: taintInfo.sanitized });
687
+ } else {
688
+ // Clean reassignment clears taint.
689
+ currentScope.clearTaint(left.name);
690
+ }
691
+ }
692
+ // Member expression assignment: obj.prop = tainted => obj becomes tainted.
693
+ if (left.type === 'MemberExpression') {
694
+ const root = ast.rootName(left);
695
+ if (root) {
696
+ if (right.type === 'CallExpression' && isSanitizerCall(right, sanList)) {
697
+ currentScope.clearTaint(root);
698
+ return;
699
+ }
700
+ if (exprIsSource(right)) {
701
+ currentScope.setTaint(root, { via: 'source', sanitized: false });
702
+ return;
703
+ }
704
+ const taintInfo = exprTaintInfo(right, currentScope);
705
+ if (taintInfo) {
706
+ currentScope.setTaint(root, { via: taintInfo.via, sanitized: taintInfo.sanitized });
707
+ }
708
+ }
709
+ }
710
+ }
711
+
712
+ function handleCall(call) {
713
+ // Check each sink.
714
+ for (const sinkDef of SINKS_AST) {
715
+ if (!sinkDef.match(call)) continue;
716
+ // Check if any argument is tainted.
717
+ for (const arg of call.arguments || []) {
718
+ // Skip if the argument itself is a source — regex rules handle that.
719
+ if (exprIsSource(arg)) continue;
720
+
721
+ let taintInfo = exprTaintInfo(arg, currentScope);
722
+ if (!taintInfo) {
723
+ // Also check: is the arg a call to a function whose param reaches a sink,
724
+ // and is the call's argument tainted? (cross-function, return-value taint)
725
+ // This is handled by the call-site cross-function check below.
726
+ continue;
727
+ }
728
+
729
+ // If the tainted value was sanitized, skip.
730
+ if (taintInfo.sanitized) continue;
731
+
732
+ const loc = call.loc && call.loc.start;
733
+ const line = loc ? loc.line : 1;
734
+ const col = loc ? loc.column + 1 : 1;
735
+ const snippet = lines[line - 1] ? lines[line - 1].trim().slice(0, 120) : '';
736
+
737
+ findings.push({
738
+ ruleId: sinkDef.ruleId,
739
+ severity: sinkDef.severity,
740
+ confidence: 'high',
741
+ dataflow: true,
742
+ title: sinkDef.title,
743
+ message: `${sinkDef.message} (tainted via \`${taintInfo.via}\`)`,
744
+ fix: sinkDef.fix,
745
+ file: relPath,
746
+ line,
747
+ column: col,
748
+ snippet,
749
+ });
750
+ break; // one finding per sink call
751
+ }
752
+ }
753
+
754
+ // Cross-function taint: if we call a function whose param reaches a sink,
755
+ // and the argument we pass is tainted, emit a finding.
756
+ const calleeName = call.callee && call.callee.type === 'Identifier' ? call.callee.name : '';
757
+ const sinkInfo = funcSinkInfo.get(calleeName);
758
+ if (sinkInfo) {
759
+ for (const { paramIndex, sinkDef, node: sinkNode } of sinkInfo) {
760
+ const arg = (call.arguments || [])[paramIndex];
761
+ if (!arg) continue;
762
+ if (exprIsSource(arg)) {
763
+ // Direct source -> function -> sink. This is already caught by interprocedural in ast.js,
764
+ // but we also catch it here for the taint.* rule IDs.
765
+ const loc = call.loc && call.loc.start;
766
+ const line = loc ? loc.line : 1;
767
+ const col = loc ? loc.column + 1 : 1;
768
+ const snippet = lines[line - 1] ? lines[line - 1].trim().slice(0, 120) : '';
769
+ findings.push({
770
+ ruleId: sinkDef.ruleId,
771
+ severity: sinkDef.severity,
772
+ confidence: 'high',
773
+ dataflow: true,
774
+ title: sinkDef.title,
775
+ message: `${sinkDef.message} (tainted via \`${calleeName}() param ${paramIndex + 1}\`)`,
776
+ fix: sinkDef.fix,
777
+ file: relPath,
778
+ line,
779
+ column: col,
780
+ snippet,
781
+ });
782
+ continue;
783
+ }
784
+ const taintInfo = exprTaintInfo(arg, currentScope);
785
+ if (taintInfo && !taintInfo.sanitized) {
786
+ const loc = call.loc && call.loc.start;
787
+ const line = loc ? loc.line : 1;
788
+ const col = loc ? loc.column + 1 : 1;
789
+ const snippet = lines[line - 1] ? lines[line - 1].trim().slice(0, 120) : '';
790
+ findings.push({
791
+ ruleId: sinkDef.ruleId,
792
+ severity: sinkDef.severity,
793
+ confidence: 'high',
794
+ dataflow: true,
795
+ title: sinkDef.title,
796
+ message: `${sinkDef.message} (tainted via \`${taintInfo.via}\` -> \`${calleeName}()\`)`,
797
+ fix: sinkDef.fix,
798
+ file: relPath,
799
+ line,
800
+ column: col,
801
+ snippet,
802
+ });
803
+ }
804
+ }
805
+ }
806
+
807
+ // Sanitizer awareness: if a tainted value is passed through a sanitizer,
808
+ // and the result is assigned to a variable, the variable is clean.
809
+ // This is handled in handleDeclarator/handleAssignment, but we also need
810
+ // to handle the case where the sanitizer result is used inline.
811
+ // (No action needed here — exprTaintInfo already checks for sanitizer calls.)
812
+ }
813
+
814
+ // Collect all identifier names referenced in a subtree.
815
+ function collectAllRefs(node, out) {
816
+ out = out || new Set();
817
+ if (!node || typeof node !== 'object') return out;
818
+ if (node.type === 'Identifier') {
819
+ out.add(node.name);
820
+ return out;
821
+ }
822
+ if (node.type === 'MemberExpression') {
823
+ const r = ast.rootName(node);
824
+ if (r) out.add(r);
825
+ return out;
826
+ }
827
+ for (const key in node) {
828
+ if (key === 'type' || key === 'loc' || key === 'start' || key === 'end' || key === 'range') continue;
829
+ const child = node[key];
830
+ if (Array.isArray(child)) {
831
+ child.forEach((c) => collectAllRefs(c, out));
832
+ } else if (child && typeof child === 'object' && child.type) {
833
+ collectAllRefs(child, out);
834
+ }
835
+ }
836
+ return out;
837
+ }
838
+
839
+ // Start the walk.
840
+ visit(tree);
841
+
842
+ // Deduplicate findings (same ruleId+file+line+column).
843
+ const seen = new Set();
844
+ return findings.filter((f) => {
845
+ const key = `${f.ruleId}:${f.file}:${f.line}:${f.column}`;
846
+ if (seen.has(key)) return false;
847
+ seen.add(key);
848
+ return true;
849
+ });
850
+ }
851
+
852
+ module.exports = { analyzeTaintAst, DEFAULT_SANITIZERS, SINKS_AST, isSourceNode, isSanitizerCall, TaintScope, bindingNames, exprTaintInfo, isScopeNode };