@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/src/taint-ast.js CHANGED
@@ -20,28 +20,32 @@ const ast = require('./ast');
20
20
  // ---------------------------------------------------------------------------
21
21
 
22
22
  // Roots whose properties indicate attacker-controlled data.
23
- const SOURCE_ROOTS = new Set(['req', 'request', 'ctx', 'event', 'process']);
23
+ const SOURCE_ROOTS = new Set(['req', 'request', 'ctx', 'event', 'process', 'location', 'window', 'document']);
24
24
  const SOURCE_PROPS = new Set([
25
25
  'body', 'query', 'params', 'headers', 'cookies', 'url', 'originalUrl',
26
- 'hostname', 'searchParams', 'argv',
26
+ 'hostname', 'searchParams', 'argv', 'search', 'hash', 'href',
27
27
  'queryStringParameters', 'pathParameters',
28
28
  ]);
29
29
 
30
30
  function isSourceNode(node) {
31
31
  if (!node) return false;
32
- // process.argv
32
+ // process.argv, location.search, location.hash, document.URL
33
33
  if (node.type === 'MemberExpression') {
34
34
  const root = ast.rootName(node);
35
35
  const prop = node.property && node.property.name;
36
36
  if (SOURCE_ROOTS.has(root) && SOURCE_PROPS.has(prop)) return true;
37
37
  // .searchParams on any object
38
38
  if (prop === 'searchParams') return true;
39
+ // location.search, location.hash, document.URL
40
+ if ((root === 'location' || root === 'window' || root === 'document') && SOURCE_PROPS.has(prop)) return true;
39
41
  // request.body, req.body etc. — also match deeper: req.body.x
40
42
  if (SOURCE_ROOTS.has(root)) return true;
41
43
  return false;
42
44
  }
43
45
  // bare `req` / `request` identifier
44
46
  if (node.type === 'Identifier' && SOURCE_ROOTS.has(node.name)) return true;
47
+ // new URLSearchParams(...) — the constructor call is a source
48
+ if (node.type === 'NewExpression' && node.callee && node.callee.name === 'URLSearchParams') return true;
45
49
  return false;
46
50
  }
47
51
 
@@ -54,7 +58,7 @@ const SINKS_AST = [
54
58
  {
55
59
  match: (call) => {
56
60
  const name = ast.calleeName(call);
57
- return /(?:^|\.)(?:exec|execSync|spawn|spawnSync|execFile|execFileSync)$/.test(name);
61
+ return /(?:^|\.)(?:exec|execSync|execFile|execFileSync|spawn|spawnSync)$/.test(name);
58
62
  },
59
63
  ruleId: 'taint.command-injection',
60
64
  severity: 'high',
@@ -126,6 +130,63 @@ const SINKS_AST = [
126
130
  message: 'A value derived from user input is used as a redirect target — open redirect (phishing).',
127
131
  fix: 'Redirect only to an allowlist of internal paths; reject absolute/off-site URLs from input.',
128
132
  },
133
+ {
134
+ match: (call) => {
135
+ const prop = (call.callee && call.callee.property && call.callee.property.name) || '';
136
+ return prop === 'send' || prop === 'write' || prop === 'end';
137
+ },
138
+ ruleId: 'taint.xss-reflected',
139
+ severity: 'high',
140
+ title: 'User input reaches an HTML response (dataflow-confirmed)',
141
+ message: 'A value derived from user input flows into res.send/write/end — reflected XSS.',
142
+ fix: 'Escape/encode the value for HTML context, or return JSON (res.json) and render safely on the client.',
143
+ },
144
+ {
145
+ match: (call) => {
146
+ // fetch() to a known AI API host with tainted data in any argument.
147
+ const name = ast.calleeName(call);
148
+ if (name !== 'fetch' && name !== 'axios.post' && name !== 'axios.put' && name !== 'axios') return false;
149
+ // Check if any argument or nested property contains a known AI host URL.
150
+ const AI_HOSTS = ['api.openai.com', 'api.anthropic.com', 'generativelanguage.googleapis.com', 'api.groq.com', 'api.together.xyz', 'api.mistral.ai', 'api.cohere.ai', 'api.perplexity.ai'];
151
+ const args = call.arguments || [];
152
+ for (const arg of args) {
153
+ // Check if the first arg is a string literal or template with an AI host.
154
+ if (arg.type === 'Literal' && typeof arg.value === 'string' && AI_HOSTS.some(h => arg.value.includes(h))) return true;
155
+ if (arg.type === 'TemplateLiteral') {
156
+ for (const q of arg.quasi || []) {
157
+ if (q && q.value && AI_HOSTS.some(h => q.value.includes(h))) return true;
158
+ }
159
+ // Also check cooked template
160
+ if (arg.quasis) {
161
+ for (const q of arg.quasis) {
162
+ if (q && q.value && q.value.cooked && AI_HOSTS.some(h => q.value.cooked.includes(h))) return true;
163
+ }
164
+ }
165
+ }
166
+ }
167
+ return false;
168
+ },
169
+ ruleId: 'taint.pii-to-llm',
170
+ severity: 'high',
171
+ title: 'User data sent to AI API without redaction (dataflow-confirmed)',
172
+ message: 'A value derived from user input flows into a request to an AI API — potential PII leak.',
173
+ fix: 'Redact PII before sending to any AI API. Send only the fields the LLM needs, not raw user data.',
174
+ },
175
+ {
176
+ match: (call) => {
177
+ // SDK calls: openai.chat.completions.create, anthropic.messages.create, genAI.generateContent
178
+ const name = ast.calleeName(call);
179
+ const prop = (call.callee && call.callee.property && call.callee.property.name) || '';
180
+ if (prop === 'create' && name && (name.includes('completions') || name.includes('messages') || name.includes('generate'))) return true;
181
+ if (prop === 'generateContent' || prop === 'generate') return true;
182
+ return false;
183
+ },
184
+ ruleId: 'taint.pii-to-llm',
185
+ severity: 'high',
186
+ title: 'User data sent to AI SDK without redaction (dataflow-confirmed)',
187
+ message: 'A value derived from user input flows into an AI SDK call — potential PII leak.',
188
+ fix: 'Redact PII before sending to any AI API. Send only the fields the LLM needs, not raw user data.',
189
+ },
129
190
  ];
130
191
 
131
192
  // ---------------------------------------------------------------------------
@@ -134,7 +195,7 @@ const SINKS_AST = [
134
195
 
135
196
  const DEFAULT_SANITIZERS = [
136
197
  'parseInt', 'parseFloat', 'Number', 'String', 'Boolean',
137
- 'escape', 'encodeURI', 'encodeURIComponent',
198
+ 'escape', 'escapeHtml', 'encodeURI', 'encodeURIComponent',
138
199
  'basename',
139
200
  ];
140
201
 
@@ -316,6 +377,8 @@ function exprTaintInfo(node, scope) {
316
377
  const info = scope.lookup(root);
317
378
  return info;
318
379
  }
380
+ // Check if this is a direct source (req.body, location.search, etc.)
381
+ if (isSourceNode(node)) return { via: 'source', sanitized: false };
319
382
  // Check if the object part is tainted.
320
383
  return exprTaintInfo(node.object, scope);
321
384
  }
@@ -390,6 +453,16 @@ function exprTaintInfo(node, scope) {
390
453
  case 'SpreadElement': {
391
454
  return exprTaintInfo(node.argument, scope);
392
455
  }
456
+ case 'NewExpression': {
457
+ // new URLSearchParams(location.search) — if any arg is a source/tainted,
458
+ // the result is tainted.
459
+ if (isSourceNode(node)) return { via: 'source', sanitized: false };
460
+ for (const arg of node.arguments || []) {
461
+ const info = exprTaintInfo(arg, scope);
462
+ if (info) return info;
463
+ }
464
+ return null;
465
+ }
393
466
  default:
394
467
  return null;
395
468
  }
@@ -691,6 +764,32 @@ function analyzeTaintAst(content, lines, relPath, tree, sanitizers) {
691
764
  }
692
765
  // Member expression assignment: obj.prop = tainted => obj becomes tainted.
693
766
  if (left.type === 'MemberExpression') {
767
+ // Check for DOM XSS sinks: .innerHTML = tainted, .outerHTML = tainted
768
+ const leftProp = left.property && left.property.name;
769
+ if (leftProp === 'innerHTML' || leftProp === 'outerHTML') {
770
+ if (right.type === 'CallExpression' && isSanitizerCall(right, sanList)) return;
771
+ const ti = exprTaintInfo(right, currentScope);
772
+ if (ti && !ti.sanitized) {
773
+ const loc = left.loc && left.loc.start;
774
+ const line = loc ? loc.line : 1;
775
+ const col = loc ? loc.column + 1 : 1;
776
+ const snippet = lines[line - 1] ? lines[line - 1].trim().slice(0, 120) : '';
777
+ findings.push({
778
+ ruleId: 'taint.xss-dom',
779
+ severity: 'high',
780
+ confidence: 'high',
781
+ dataflow: true,
782
+ title: 'User input reaches DOM sink (dataflow-confirmed)',
783
+ message: `A value derived from user input (${ti.via}) is assigned to .${leftProp} — DOM XSS.`,
784
+ fix: 'Use textContent instead of innerHTML/outerHTML. If HTML is needed, sanitize with DOMPurify.',
785
+ file: relPath,
786
+ line,
787
+ column: col,
788
+ snippet,
789
+ });
790
+ return;
791
+ }
792
+ }
694
793
  const root = ast.rootName(left);
695
794
  if (root) {
696
795
  if (right.type === 'CallExpression' && isSanitizerCall(right, sanList)) {
@@ -710,13 +809,66 @@ function analyzeTaintAst(content, lines, relPath, tree, sanitizers) {
710
809
  }
711
810
 
712
811
  function handleCall(call) {
812
+
813
+ // Check if an expression tree contains a PII-specific source.
814
+ // Only fires for req.body.<pii_field> or whole-object sources like
815
+ // JSON.stringify(req.body) or JSON.stringify(userProfile).
816
+ function containsPiiSource(node, piiFields) {
817
+ if (!node || typeof node !== 'object') return false;
818
+ // Direct source: req.body (whole object), JSON.stringify(req.body)
819
+ if (isSourceNode(node)) {
820
+ // Check if it's a whole-object source (req.body, not req.body.q)
821
+ if (node.type === 'MemberExpression') {
822
+ const prop = node.property && node.property.name;
823
+ if (prop === 'body' || prop === 'query' || prop === 'params') return true;
824
+ // Check if the property name is a PII field
825
+ if (piiFields.includes(prop)) return true;
826
+ }
827
+ // NewExpression (new URLSearchParams) — not PII
828
+ if (node.type === 'NewExpression') return false;
829
+ return false;
830
+ }
831
+ // Recurse into children
832
+ for (const key in node) {
833
+ if (key === 'type' || key === 'loc' || key === 'start' || key === 'end' || key === 'range') continue;
834
+ const child = node[key];
835
+ if (Array.isArray(child)) {
836
+ for (const c of child) {
837
+ if (containsPiiSource(c, piiFields)) return true;
838
+ }
839
+ } else if (child && typeof child === 'object' && child.type) {
840
+ if (containsPiiSource(child, piiFields)) return true;
841
+ }
842
+ }
843
+ return false;
844
+ }
845
+
713
846
  // Check each sink.
714
847
  for (const sinkDef of SINKS_AST) {
715
848
  if (!sinkDef.match(call)) continue;
716
- // Check if any argument is tainted.
717
- for (const arg of call.arguments || []) {
849
+ // Determine which arguments to check.
850
+ // For execFile/spawn: only arg[0] (command) — args array (arg[1]) is safe.
851
+ // For query/execute/raw: only arg[0] (SQL string) — params array (arg[1]) is safe.
852
+ const name = ast.calleeName(call);
853
+ const isFirstArgOnly = /(?:^|\.)(?:execFile|execFileSync|spawn|spawnSync)$/.test(name) ||
854
+ (sinkDef.ruleId === 'taint.sql-injection');
855
+ const argsToCheck = isFirstArgOnly ? (call.arguments || []).slice(0, 1) : (call.arguments || []);
856
+
857
+ for (const arg of argsToCheck) {
718
858
  // Skip if the argument itself is a source — regex rules handle that.
719
- if (exprIsSource(arg)) continue;
859
+ // BUT: for PII-to-LLM and XSS-reflected sinks, the source may be nested
860
+ // deep inside an object (e.g. { messages: [{ content: req.body.x }] })
861
+ // and regex rules don't catch that — so don't skip for those sinks.
862
+ if (sinkDef.ruleId !== 'taint.pii-to-llm' && sinkDef.ruleId !== 'taint.xss-reflected' && exprIsSource(arg)) continue;
863
+
864
+ // For PII-to-LLM: only fire if the tainted value is a whole-object source
865
+ // (req.body, JSON.stringify(userProfile)) or a PII-specific field.
866
+ // Generic fields like req.body.q (user's question) are NOT PII.
867
+ if (sinkDef.ruleId === 'taint.pii-to-llm') {
868
+ const PII_FIELDS = ['email', 'phone', 'ssn', 'address', 'dob', 'name', 'password', 'creditCard', 'medicalHistory', 'healthData', 'patient', 'medical', 'biometric', 'profile', 'userProfile', 'userData'];
869
+ // Check if the arg contains a PII-specific source
870
+ if (!containsPiiSource(arg, PII_FIELDS)) continue;
871
+ }
720
872
 
721
873
  let taintInfo = exprTaintInfo(arg, currentScope);
722
874
  if (!taintInfo) {
@@ -849,4 +1001,4 @@ function analyzeTaintAst(content, lines, relPath, tree, sanitizers) {
849
1001
  });
850
1002
  }
851
1003
 
852
- module.exports = { analyzeTaintAst, DEFAULT_SANITIZERS, SINKS_AST, isSourceNode, isSanitizerCall, TaintScope, bindingNames, exprTaintInfo, isScopeNode };
1004
+ module.exports = { analyzeTaintAst, DEFAULT_SANITIZERS, SINKS_AST, isSourceNode, isSanitizerCall, TaintScope, bindingNames, exprTaintInfo, exprIsSource, isScopeNode };
package/src/taint.js CHANGED
@@ -114,8 +114,10 @@ function newlyTainted(line, tainted) {
114
114
  }
115
115
 
116
116
  function referencesTainted(line, tainted) {
117
+ // Strip string literals so we don't match variable names inside SQL strings.
118
+ const stripped = line.replace(/(["'`])(?:[^\\]|\\.)*?\1/g, '""');
117
119
  for (const t of tainted) {
118
- if (new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`).test(line)) return t;
120
+ if (new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`).test(stripped)) return t;
119
121
  }
120
122
  return null;
121
123
  }
@@ -140,6 +142,17 @@ function analyzeTaintRegex(content, lines, relPath) {
140
142
  // Skip the inline source case — the regex rules already report it; taint
141
143
  // exists to catch the *multi-step* case where the source is elsewhere.
142
144
  if (SOURCE_RE.test(line)) continue;
145
+ // Skip parameterized queries: if the tainted var is inside an array
146
+ // literal (second arg), it's a bound parameter, not SQL injection.
147
+ // Heuristic: if the line has "query(" or "execute(" or "raw(" and the
148
+ // tainted var appears after a comma followed by [, skip it.
149
+ if (sink.ruleId === 'taint.sql-injection' && /,\s*\[/.test(line)) {
150
+ // Check if the tainted var is ONLY in the array, not in the SQL string.
151
+ const beforeArray = line.split(/,\s*\[/)[0];
152
+ const afterArray = ',' + line.split(/,\s*\[/).slice(1).join(',[');
153
+ const viaSql = referencesTainted(beforeArray, tainted);
154
+ if (!viaSql) continue; // tainted var only in params array — safe
155
+ }
143
156
  const via = referencesTainted(line, tainted);
144
157
  if (via) {
145
158
  findings.push({