@yagyeshvyas/vibeguard 0.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.
Files changed (52) hide show
  1. package/README.md +600 -0
  2. package/bin/cli.js +1640 -0
  3. package/ci/vibeguard.yml +41 -0
  4. package/ci-templates/Jenkinsfile +26 -0
  5. package/ci-templates/azure-pipelines.yml +29 -0
  6. package/ci-templates/circleci.yml +24 -0
  7. package/ci-templates/gitlab.yml +19 -0
  8. package/hooks/pre-commit +31 -0
  9. package/package.json +94 -0
  10. package/src/ai-guard.js +205 -0
  11. package/src/ast.js +319 -0
  12. package/src/audit-trail.js +154 -0
  13. package/src/autofix.js +524 -0
  14. package/src/badge.js +42 -0
  15. package/src/behavior.js +205 -0
  16. package/src/compliance.js +151 -0
  17. package/src/crosstaint.js +324 -0
  18. package/src/cve-intel.js +136 -0
  19. package/src/dashboard.js +279 -0
  20. package/src/deps.js +159 -0
  21. package/src/doctor.js +111 -0
  22. package/src/engine.js +234 -0
  23. package/src/external.js +160 -0
  24. package/src/firewall.js +517 -0
  25. package/src/history.js +87 -0
  26. package/src/hook.js +151 -0
  27. package/src/install.js +248 -0
  28. package/src/interceptor.js +476 -0
  29. package/src/mcp-server.js +1804 -0
  30. package/src/net-audit.js +208 -0
  31. package/src/pii.js +212 -0
  32. package/src/plugin.js +80 -0
  33. package/src/policy-gen.js +288 -0
  34. package/src/pre-deploy.js +282 -0
  35. package/src/presets.js +113 -0
  36. package/src/privacy-audit.js +273 -0
  37. package/src/repl.js +150 -0
  38. package/src/report.js +312 -0
  39. package/src/rules-pack.js +2753 -0
  40. package/src/rules.js +1446 -0
  41. package/src/sandbox.js +139 -0
  42. package/src/scanner.js +651 -0
  43. package/src/secure-prompt.js +140 -0
  44. package/src/slopsquat.js +144 -0
  45. package/src/supply-firewall.js +243 -0
  46. package/src/suppress.js +89 -0
  47. package/src/taint.js +168 -0
  48. package/src/trace.js +220 -0
  49. package/src/urlscan.js +142 -0
  50. package/src/vault.js +145 -0
  51. package/src/verify.js +98 -0
  52. package/src/verifykeys.js +87 -0
@@ -0,0 +1,205 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * VibeGuard Behavioral Analysis Engine.
5
+ *
6
+ * Analyzes AI agent behavior over time to detect:
7
+ * - Anomalous access patterns (sudden access to secrets)
8
+ * - Data gathering (collecting data from many sources before exfil)
9
+ * - Slow exfiltration (small amounts over time)
10
+ * - Privilege escalation attempts (progressive access to higher-risk resources)
11
+ * - Trust building then exploit (innocent actions followed by attack)
12
+ * - Resource exhaustion patterns (infinite loops, memory bombs)
13
+ *
14
+ * Builds a behavioral profile per session and flags suspicious patterns.
15
+ * 100% local. Zero network. Zero dependencies.
16
+ */
17
+
18
+ const MAX_EVENTS = 10000; // Per session
19
+
20
+ // Risk score per action type
21
+ const ACTION_RISK = {
22
+ file_read: 1, file_write: 2, exec: 3, network: 2,
23
+ secret_access: 10, env_access: 8, ai_api: 2,
24
+ blocked: 5, tamper: 20,
25
+ };
26
+
27
+ // Suspicious patterns
28
+ const PATTERNS = {
29
+ // Accessing secrets after many normal actions (trust building)
30
+ TRUST_BUILDING: {
31
+ detect: (events) => {
32
+ if (events.length < 10) return false;
33
+ const recent = events.slice(-5);
34
+ const earlier = events.slice(0, -5);
35
+ const earlierNormal = earlier.every(e => ACTION_RISK[e.type] <= 2);
36
+ const recentDanger = recent.some(e => ACTION_RISK[e.type] >= 8);
37
+ return earlierNormal && recentDanger;
38
+ },
39
+ severity: 'high',
40
+ message: 'Trust building pattern: many normal actions followed by secret/env access',
41
+ },
42
+ // Data gathering: reading many files before a network request
43
+ DATA_GATHERING: {
44
+ detect: (events) => {
45
+ const recent = events.slice(-15);
46
+ const reads = recent.filter(e => e.type === 'file_read').length;
47
+ const network = recent.filter(e => e.type === 'network').length;
48
+ return reads >= 5 && network >= 1 && reads > network * 3;
49
+ },
50
+ severity: 'high',
51
+ message: 'Data gathering pattern: many file reads before network request',
52
+ },
53
+ // Slow exfiltration: multiple small network requests over time
54
+ SLOW_EXFIL: {
55
+ detect: (events) => {
56
+ const networkEvents = events.filter(e => e.type === 'network');
57
+ if (networkEvents.length < 5) return false;
58
+ const timeSpan = networkEvents[networkEvents.length - 1].timestamp - networkEvents[0].timestamp;
59
+ return timeSpan > 30000 && networkEvents.length > 5; // 30s+ with 5+ requests
60
+ },
61
+ severity: 'high',
62
+ message: 'Slow exfiltration pattern: multiple network requests over time',
63
+ },
64
+ // Privilege escalation: progressively higher risk actions
65
+ PRIVILEGE_ESCALATION: {
66
+ detect: (events) => {
67
+ if (events.length < 5) return false;
68
+ const recent = events.slice(-10);
69
+ const risks = recent.map(e => ACTION_RISK[e.type] || 0);
70
+ for (let i = 1; i < risks.length; i++) {
71
+ if (risks[i] > risks[i - 1] + 2) return true; // Sudden jump in risk
72
+ }
73
+ return false;
74
+ },
75
+ severity: 'critical',
76
+ message: 'Privilege escalation pattern: progressively higher-risk actions',
77
+ },
78
+ // Repeated blocked attempts (trying to bypass security)
79
+ REPEATED_BLOCKS: {
80
+ detect: (events) => {
81
+ const blocks = events.filter(e => e.type === 'blocked');
82
+ return blocks.length >= 3;
83
+ },
84
+ severity: 'critical',
85
+ message: 'Repeated blocked attempts: AI is trying to bypass security controls',
86
+ },
87
+ // Tamper attempts
88
+ TAMPER_DETECTED: {
89
+ detect: (events) => events.some(e => e.type === 'tamper'),
90
+ severity: 'critical',
91
+ message: 'Tampering attempt detected: AI tried to disable or modify VibeGuard',
92
+ },
93
+ // Off-hours access (accessing secrets at unusual times)
94
+ OFF_HOURS: {
95
+ detect: (events) => {
96
+ const secretAccess = events.filter(e => e.type === 'secret_access' || e.type === 'env_access');
97
+ if (secretAccess.length === 0) return false;
98
+ const hour = new Date(secretAccess[0].timestamp).getHours();
99
+ return hour < 6 || hour > 22; // Before 6am or after 10pm
100
+ },
101
+ severity: 'medium',
102
+ message: 'Off-hours secret access: accessing secrets at unusual times',
103
+ },
104
+ // Unusual frequency: too many actions in short time
105
+ RAPID_FIRE: {
106
+ detect: (events) => {
107
+ if (events.length < 20) return false;
108
+ const timeSpan = events[events.length - 1].timestamp - events[0].timestamp;
109
+ return timeSpan < 5000 && events.length > 20; // 20+ events in 5s
110
+ },
111
+ severity: 'medium',
112
+ message: 'Rapid-fire pattern: too many actions in short time (automated attack?)',
113
+ },
114
+ };
115
+
116
+ function createSession() {
117
+ return {
118
+ events: [],
119
+ startTime: Date.now(),
120
+ riskScore: 0,
121
+ patterns: [],
122
+ };
123
+ }
124
+
125
+ function recordEvent(session, type, detail = {}) {
126
+ const event = {
127
+ type,
128
+ detail,
129
+ timestamp: Date.now(),
130
+ risk: ACTION_RISK[type] || 0,
131
+ };
132
+ session.events.push(event);
133
+ if (session.events.length > MAX_EVENTS) session.events.shift();
134
+ session.riskScore += event.risk;
135
+ return event;
136
+ }
137
+
138
+ function analyzeSession(session) {
139
+ const detected = [];
140
+ for (const [name, pattern] of Object.entries(PATTERNS)) {
141
+ if (pattern.detect(session.events)) {
142
+ detected.push({ pattern: name, severity: pattern.severity, message: pattern.message });
143
+ }
144
+ }
145
+
146
+ // Calculate behavioral risk level
147
+ const riskLevel = session.riskScore === 0 ? 'NONE' :
148
+ session.riskScore < 20 ? 'LOW' :
149
+ session.riskScore < 50 ? 'MEDIUM' :
150
+ session.riskScore < 100 ? 'HIGH' : 'CRITICAL';
151
+
152
+ // Check for blocked actions ratio
153
+ const blockedCount = session.events.filter(e => e.type === 'blocked').length;
154
+ const blockedRatio = session.events.length > 0 ? blockedCount / session.events.length : 0;
155
+
156
+ return {
157
+ totalEvents: session.events.length,
158
+ riskScore: session.riskScore,
159
+ riskLevel,
160
+ blockedCount,
161
+ blockedRatio: Math.round(blockedRatio * 100) + '%',
162
+ patterns: detected,
163
+ patternsCount: detected.length,
164
+ sessionDuration: Date.now() - session.startTime,
165
+ recommendation: detected.length === 0 ? 'No suspicious patterns detected' :
166
+ detected.some(p => p.severity === 'critical') ? 'IMMEDIATE ACTION: Critical behavioral pattern detected. Terminate AI session.' :
167
+ detected.some(p => p.severity === 'high') ? 'WARNING: Suspicious behavior pattern detected. Review AI session.' :
168
+ 'CAUTION: Minor behavioral anomaly detected. Monitor.',
169
+ };
170
+ }
171
+
172
+ function renderBehaviorReport(analysis) {
173
+ const C = { red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', cyan: '\x1b[36m', dim: '\x1b[2m', bold: '\x1b[1m', reset: '\x1b[0m' };
174
+ const riskColor = { NONE: C.green, LOW: C.green, MEDIUM: C.yellow, HIGH: C.yellow, CRITICAL: C.red };
175
+ const color = riskColor[analysis.riskLevel] || C.white;
176
+
177
+ const lines = [
178
+ `${C.bold}VibeGuard Behavioral Analysis${C.reset}`,
179
+ `${C.dim}${'─'.repeat(60)}${C.reset}`,
180
+ '',
181
+ ` Risk Score: ${color}${analysis.riskScore}${C.reset} (${color}${analysis.riskLevel}${C.reset})`,
182
+ ` Total Events: ${analysis.totalEvents}`,
183
+ ` Blocked: ${C.red}${analysis.blockedCount}${C.reset} (${analysis.blockedRatio})`,
184
+ ` Patterns: ${analysis.patternsCount}`,
185
+ ` Duration: ${analysis.sessionDuration}ms`,
186
+ '',
187
+ ];
188
+
189
+ if (analysis.patterns.length > 0) {
190
+ lines.push(`${C.bold}Detected Patterns${C.reset}`, '');
191
+ for (const p of analysis.patterns) {
192
+ const sc = p.severity === 'critical' ? C.red : p.severity === 'high' ? C.yellow : C.dim;
193
+ lines.push(` ${sc}[${p.severity}]${C.reset} ${p.pattern}`);
194
+ lines.push(` ${p.message}`);
195
+ lines.push('');
196
+ }
197
+ }
198
+
199
+ lines.push(`${C.bold}Recommendation${C.reset}`);
200
+ lines.push(` ${color}${analysis.recommendation}${C.reset}`);
201
+
202
+ return lines.join('\n');
203
+ }
204
+
205
+ module.exports = { createSession, recordEvent, analyzeSession, renderBehaviorReport, PATTERNS, ACTION_RISK };
@@ -0,0 +1,151 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Compliance mapping module for VibeGuard.
5
+ *
6
+ * Maps findings to SOC2, PCI-DSS, HIPAA, GDPR, ISO 27001, and EU AI Act
7
+ * control IDs using the CWE-based COMPLIANCE_MAP from rules-pack.js.
8
+ *
9
+ * Generates a compliance report showing which controls have findings
10
+ * and which are satisfied (clean).
11
+ */
12
+
13
+ const { COMPLIANCE_MAP } = require('./rules-pack');
14
+
15
+ const FRAMEWORKS = ['SOC2', 'PCI-DSS', 'HIPAA', 'GDPR', 'ISO27001', 'EUAIAct'];
16
+
17
+ const FRAMEWORK_NAMES = {
18
+ SOC2: 'SOC 2 Type II',
19
+ 'PCI-DSS': 'PCI DSS v4.0',
20
+ HIPAA: 'HIPAA Security Rule',
21
+ GDPR: 'GDPR (Regulation 2016/679)',
22
+ ISO27001: 'ISO/IEC 27001:2022',
23
+ EUAIAct: 'EU AI Act (Regulation 2024/1689)',
24
+ };
25
+
26
+ function mapFindingsToCompliance(findings) {
27
+ const report = {};
28
+
29
+ for (const fw of FRAMEWORKS) {
30
+ report[fw] = {
31
+ name: FRAMEWORK_NAMES[fw],
32
+ controls: {},
33
+ summary: { total: 0, failing: 0, passing: 0 },
34
+ };
35
+ }
36
+
37
+ for (const f of findings) {
38
+ const cwe = f.cwe || extractCWE(f);
39
+ if (!cwe) continue;
40
+
41
+ for (const fw of FRAMEWORKS) {
42
+ const map = COMPLIANCE_MAP[fw];
43
+ if (!map || !map[cwe]) continue;
44
+
45
+ for (const controlId of map[cwe]) {
46
+ if (!report[fw].controls[controlId]) {
47
+ report[fw].controls[controlId] = {
48
+ id: controlId,
49
+ status: 'fail',
50
+ findings: [],
51
+ };
52
+ report[fw].summary.total++;
53
+ report[fw].summary.failing++;
54
+ }
55
+ report[fw].controls[controlId].findings.push({
56
+ ruleId: f.ruleId,
57
+ file: f.file,
58
+ line: f.line,
59
+ severity: f.severity,
60
+ title: f.title,
61
+ });
62
+ }
63
+ }
64
+ }
65
+
66
+ return report;
67
+ }
68
+
69
+ function extractCWE(f) {
70
+ if (!f.cwe) return null;
71
+ const m = /CWE-(\d+)/.exec(f.cwe);
72
+ return m ? `CWE-${m[1]}` : null;
73
+ }
74
+
75
+ function generateComplianceReport(findings, framework) {
76
+ if (framework && !FRAMEWORKS.includes(framework)) {
77
+ return { error: `Unknown framework: ${framework}. Available: ${FRAMEWORKS.join(', ')}` };
78
+ }
79
+
80
+ const report = mapFindingsToCompliance(findings);
81
+ if (framework) {
82
+ return report[framework];
83
+ }
84
+ return report;
85
+ }
86
+
87
+ function getControlDescription(framework, controlId) {
88
+ const descriptions = {
89
+ SOC2: {
90
+ 'CC6.1': 'The entity implements logical access controls',
91
+ 'CC6.3': 'The entity authorizes, modifies, and removes access',
92
+ 'CC6.7': 'The entity restricts access to information',
93
+ 'CC7.1': 'The entity detects security events',
94
+ 'CC7.2': 'The entity responds to security events',
95
+ 'CC7.3': 'The entity recovers from security events',
96
+ 'CC7.4': 'The entity detects deviations from established processes',
97
+ },
98
+ 'PCI-DSS': {
99
+ '3.1': 'Minimize storage of cardholder data',
100
+ '3.34': 'Render PAN unreadable wherever stored',
101
+ '4.1': 'Encrypt transmission of cardholder data',
102
+ '6.5.1': 'Injection flaws',
103
+ '6.5.3': 'Insecure cryptographic storage',
104
+ '6.5.7': 'Cross-site scripting',
105
+ '6.5.8': 'Improper access control',
106
+ '6.5.9': 'Cross-site request forgery',
107
+ '6.5.10': 'Broken authentication',
108
+ '7.1': 'Limit access to system components',
109
+ '8.2.1': 'Strong authentication',
110
+ },
111
+ HIPAA: {
112
+ '164.312(a)(1)': 'Access control',
113
+ '164.312(a)(2)(i)': 'Unique user identification',
114
+ '164.312(a)(2)(iv)': 'Encryption and decryption',
115
+ '164.312(b)': 'Audit controls',
116
+ '164.312(d)': 'Person or entity authentication',
117
+ '164.312(e)(1)': 'Transmission security',
118
+ '164.312(e)(2)(ii)': 'Encryption',
119
+ },
120
+ GDPR: {
121
+ 'Art.5': 'Principles relating to processing of personal data',
122
+ 'Art.25': 'Data protection by design and by default',
123
+ 'Art.32': 'Security of processing',
124
+ },
125
+ ISO27001: {
126
+ 'A.9.4.1': 'Information access restriction',
127
+ 'A.9.4.3': 'Password management',
128
+ 'A.9.4.4': 'Use of privileged utility programs',
129
+ 'A.10.1.1': 'Policy on the use of cryptographic controls',
130
+ 'A.12.4.1': 'Event logging',
131
+ 'A.13.1.1': 'Network controls',
132
+ 'A.13.2.1': 'Information transfer policies',
133
+ 'A.14.2.5': 'Secure system engineering principles',
134
+ 'A.15.1.1': 'Supplier relationships policy',
135
+ },
136
+ EUAIAct: {
137
+ 'Art.15': 'Accuracy, robustness, and cybersecurity',
138
+ 'Art.27': 'Fundamental rights impact assessment',
139
+ },
140
+ };
141
+
142
+ return (descriptions[framework] && descriptions[framework][controlId]) || 'No description available';
143
+ }
144
+
145
+ module.exports = {
146
+ FRAMEWORKS,
147
+ FRAMEWORK_NAMES,
148
+ mapFindingsToCompliance,
149
+ generateComplianceReport,
150
+ getControlDescription,
151
+ };
@@ -0,0 +1,324 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Cross-file taint via an import/export graph (requires acorn).
5
+ *
6
+ * Flags request data reaching a dangerous sink across module boundaries.
7
+ * Handles:
8
+ * - any argument position (not just the first) and destructured params;
9
+ * - local variable reassignment inside a helper (param -> local -> sink);
10
+ * - transitive sink-reaching (depth > 1) via a per-parameter-slot fixpoint;
11
+ * - barrel / re-exports (export * / export {x} from / module.exports = require);
12
+ * - return-value taint (exec(getInput(req)) where getInput returns its input).
13
+ *
14
+ * Bounded/best-effort: relative imports, positional argument->parameter mapping.
15
+ * Confidence medium.
16
+ */
17
+
18
+ const ast = require('./ast');
19
+
20
+ const CANDIDATE_EXTS = ['.js', '.ts', '.jsx', '.tsx', '.mjs', '.cjs', '/index.js', '/index.ts'];
21
+
22
+ function norm(p) {
23
+ const parts = [];
24
+ for (const seg of p.split('/')) {
25
+ if (seg === '' || seg === '.') continue;
26
+ if (seg === '..') parts.pop();
27
+ else parts.push(seg);
28
+ }
29
+ return parts.join('/');
30
+ }
31
+ function resolveModule(fromRel, spec, knownRels) {
32
+ if (!spec.startsWith('.')) return null;
33
+ const dir = fromRel.includes('/') ? fromRel.slice(0, fromRel.lastIndexOf('/')) : '';
34
+ const base = norm(dir + '/' + spec);
35
+ if (knownRels.has(base)) return base;
36
+ for (const ext of CANDIDATE_EXTS) if (knownRels.has(base + ext)) return base + ext;
37
+ return null;
38
+ }
39
+
40
+ const asFn = (n) =>
41
+ n && (n.type === 'FunctionDeclaration' || n.type === 'FunctionExpression' || n.type === 'ArrowFunctionExpression') ? n : null;
42
+ const isReq = (node) =>
43
+ node && ((node.type === 'MemberExpression' && ast.rootName(node) === 'req') || (node.type === 'Identifier' && node.name === 'req'));
44
+ const requireCall = (n) => n && n.type === 'CallExpression' && n.callee.name === 'require' && n.arguments[0] && typeof n.arguments[0].value === 'string';
45
+
46
+ // Names a parameter binds (handles destructuring, defaults, rest).
47
+ function bindingNames(param, out) {
48
+ out = out || [];
49
+ if (!param) return out;
50
+ if (param.type === 'Identifier') out.push(param.name);
51
+ else if (param.type === 'AssignmentPattern') bindingNames(param.left, out);
52
+ else if (param.type === 'RestElement') bindingNames(param.argument, out);
53
+ else if (param.type === 'ObjectPattern') for (const p of param.properties) bindingNames(p.type === 'RestElement' ? p.argument : p.value, out);
54
+ else if (param.type === 'ArrayPattern') for (const e of param.elements) if (e) bindingNames(e, out);
55
+ return out;
56
+ }
57
+
58
+ // All identifier names referenced in an expression subtree.
59
+ function collectRefs(node, out) {
60
+ out = out || new Set();
61
+ if (!node || typeof node !== 'object') return out;
62
+ if (node.type === 'Identifier') { out.add(node.name); return out; }
63
+ if (node.type === 'MemberExpression') { const r = ast.rootName(node); if (r) out.add(r); return out; }
64
+ for (const k in node) {
65
+ if (k === 'type' || k === 'loc' || k === 'start' || k === 'end' || k === 'range') continue;
66
+ const v = node[k];
67
+ if (Array.isArray(v)) v.forEach((x) => collectRefs(x, out));
68
+ else if (v && typeof v === 'object' && v.type) collectRefs(v, out);
69
+ }
70
+ return out;
71
+ }
72
+
73
+ // Analyze one function: which parameter SLOTS reach a sink, what it forwards, and
74
+ // which slots it returns. Tracks taint through local reassignments (fixpoint).
75
+ function analyzeFunction(node, walk, resolveCallee) {
76
+ const params = node.params || [];
77
+ const taintOf = new Map(); // varName -> Set(paramSlot)
78
+ params.forEach((p, i) => bindingNames(p).forEach((n) => { if (!taintOf.has(n)) taintOf.set(n, new Set([i])); }));
79
+
80
+ const assigns = [];
81
+ walk.simple(node, {
82
+ VariableDeclarator(n) { if (n.id && n.id.type === 'Identifier' && n.init) assigns.push({ t: n.id.name, e: n.init }); },
83
+ AssignmentExpression(n) { if (n.left && n.left.type === 'Identifier') assigns.push({ t: n.left.name, e: n.right }); },
84
+ });
85
+ for (let pass = 0; pass < 5; pass++) {
86
+ let changed = false;
87
+ for (const a of assigns) {
88
+ const slots = new Set();
89
+ for (const r of collectRefs(a.e)) { const s = taintOf.get(r); if (s) for (const x of s) slots.add(x); }
90
+ if (slots.size) {
91
+ let cur = taintOf.get(a.t);
92
+ if (!cur) { cur = new Set(); taintOf.set(a.t, cur); }
93
+ const before = cur.size;
94
+ for (const x of slots) cur.add(x);
95
+ if (cur.size !== before) changed = true;
96
+ }
97
+ }
98
+ if (!changed) break;
99
+ }
100
+ const slotsFor = (n) => {
101
+ const s = new Set();
102
+ for (const r of collectRefs(n)) { const t = taintOf.get(r); if (t) for (const x of t) s.add(x); }
103
+ return s;
104
+ };
105
+
106
+ const sinkSlots = new Map(); // slot -> label
107
+ const forwards = []; // { toArgIndex, fromSlot, target }
108
+ const returnsSlots = new Set();
109
+ walk.simple(node, {
110
+ CallExpression(call) {
111
+ const kind = ast.sinkKindOfCall(call);
112
+ if (kind) for (const arg of call.arguments || []) for (const slot of slotsFor(arg)) sinkSlots.set(slot, kind.label);
113
+ const target = resolveCallee(call.callee);
114
+ if (target) (call.arguments || []).forEach((arg, k) => { for (const slot of slotsFor(arg)) forwards.push({ toArgIndex: k, fromSlot: slot, target }); });
115
+ },
116
+ ReturnStatement(r) { for (const slot of slotsFor(r.argument)) returnsSlots.add(slot); },
117
+ });
118
+ return { sinkSlots, forwards, returnsSlots };
119
+ }
120
+
121
+ function analyzeCrossFile(files, treesCache) {
122
+ if (!ast.isAvailable()) return [];
123
+ const walk = ast.getWalk();
124
+ const knownRels = new Set(files.map((f) => f.rel));
125
+
126
+ const trees = new Map();
127
+ for (const f of files) {
128
+ if (!/\.(?:js|jsx|ts|tsx|mjs|cjs)$/.test(f.rel)) continue;
129
+ const t = (treesCache && treesCache.get(f.rel)) || ast.parseSource(f.content, f.rel);
130
+ if (t) trees.set(f.rel, t);
131
+ }
132
+
133
+ const funcs = new Map(); // gid -> { sinkSlots, forwards, returnsSlots }
134
+ const exportsOf = new Map();
135
+ const reExports = new Map();
136
+ const importsOf = new Map();
137
+ const gid = (rel, name) => `${rel}#${name}`;
138
+
139
+ for (const [rel, tree] of trees) {
140
+ const localFns = new Map();
141
+ const exp = new Map();
142
+ const re = [];
143
+ const named = new Map();
144
+ const ns = new Map();
145
+
146
+ walk.simple(tree, {
147
+ FunctionDeclaration(n) { if (n.id) localFns.set(n.id.name, n); },
148
+ VariableDeclarator(n) { if (n.id && n.id.type === 'Identifier' && asFn(n.init)) localFns.set(n.id.name, n.init); },
149
+ });
150
+ walk.simple(tree, {
151
+ ImportDeclaration(n) {
152
+ const mod = resolveModule(rel, n.source.value, knownRels);
153
+ if (!mod) return;
154
+ for (const sp of n.specifiers) {
155
+ if (sp.type === 'ImportSpecifier') named.set(sp.local.name, { mod, exported: sp.imported.name });
156
+ else if (sp.type === 'ImportDefaultSpecifier') named.set(sp.local.name, { mod, exported: 'default' });
157
+ else if (sp.type === 'ImportNamespaceSpecifier') ns.set(sp.local.name, mod);
158
+ }
159
+ },
160
+ VariableDeclarator(n) {
161
+ const init = n.init;
162
+ if (!init) return;
163
+ if (requireCall(init)) {
164
+ const mod = resolveModule(rel, init.arguments[0].value, knownRels);
165
+ if (!mod) return;
166
+ if (n.id.type === 'Identifier') ns.set(n.id.name, mod);
167
+ else if (n.id.type === 'ObjectPattern') for (const pr of n.id.properties) if (pr.key && pr.value && pr.value.type === 'Identifier') named.set(pr.value.name, { mod, exported: pr.key.name });
168
+ } else if (init.type === 'MemberExpression' && requireCall(init.object) && init.property && init.property.name) {
169
+ const mod = resolveModule(rel, init.object.arguments[0].value, knownRels);
170
+ if (mod && n.id.type === 'Identifier') named.set(n.id.name, { mod, exported: init.property.name });
171
+ }
172
+ },
173
+ });
174
+
175
+ const regExport = (exportedName, localName) => { if (localFns.has(localName)) exp.set(exportedName, gid(rel, localName)); };
176
+ walk.simple(tree, {
177
+ ExportNamedDeclaration(n) {
178
+ if (n.source) {
179
+ const mod = resolveModule(rel, n.source.value, knownRels);
180
+ if (mod) for (const sp of n.specifiers || []) re.push({ kind: 'named', mod, exported: sp.local.name, as: sp.exported.name });
181
+ return;
182
+ }
183
+ if (n.declaration) {
184
+ if (n.declaration.type === 'FunctionDeclaration' && n.declaration.id) regExport(n.declaration.id.name, n.declaration.id.name);
185
+ else if (n.declaration.declarations) for (const d of n.declaration.declarations) if (asFn(d.init) && d.id.name) regExport(d.id.name, d.id.name);
186
+ }
187
+ for (const sp of n.specifiers || []) regExport(sp.exported.name, sp.local.name);
188
+ },
189
+ ExportAllDeclaration(n) { const mod = resolveModule(rel, n.source.value, knownRels); if (mod) re.push({ kind: 'all', mod }); },
190
+ ExportDefaultDeclaration(n) { const fn = asFn(n.declaration); if (fn) { localFns.set('$default', fn); exp.set('default', gid(rel, '$default')); } },
191
+ AssignmentExpression(n) {
192
+ const left = n.left;
193
+ if (left.type === 'MemberExpression' && left.property && left.property.name) {
194
+ const obj = left.object;
195
+ const isExports = (obj.type === 'Identifier' && obj.name === 'exports') || (obj.type === 'MemberExpression' && obj.object.name === 'module' && obj.property.name === 'exports');
196
+ if (isExports) {
197
+ if (n.right.type === 'Identifier') regExport(left.property.name, n.right.name);
198
+ else if (asFn(n.right)) { const nm = `$export$${left.property.name}`; localFns.set(nm, n.right); exp.set(left.property.name, gid(rel, nm)); }
199
+ }
200
+ }
201
+ if (left.type === 'MemberExpression' && left.object.name === 'module' && left.property.name === 'exports') {
202
+ if (n.right.type === 'ObjectExpression') for (const p of n.right.properties) { const ex = p.key && (p.key.name || p.key.value); const loc = (p.value && p.value.name) || ex; if (ex) regExport(ex, loc); }
203
+ else if (requireCall(n.right)) { const mod = resolveModule(rel, n.right.arguments[0].value, knownRels); if (mod) re.push({ kind: 'all', mod }); }
204
+ }
205
+ },
206
+ });
207
+
208
+ const resolveCallee = (c) => {
209
+ if (c.type === 'Identifier') {
210
+ if (localFns.has(c.name)) return { id: gid(rel, c.name) };
211
+ if (named.has(c.name)) return { ref: named.get(c.name) };
212
+ } else if (c.type === 'MemberExpression' && c.object.type === 'Identifier' && ns.has(c.object.name) && c.property.name) {
213
+ return { ref: { mod: ns.get(c.object.name), exported: c.property.name } };
214
+ }
215
+ return null;
216
+ };
217
+ for (const [name, fnNode] of localFns) funcs.set(gid(rel, name), analyzeFunction(fnNode, walk, resolveCallee));
218
+
219
+ exportsOf.set(rel, exp);
220
+ reExports.set(rel, re);
221
+ importsOf.set(rel, { named, ns });
222
+ }
223
+
224
+ // export table + re-export fixpoint
225
+ const exportTable = new Map();
226
+ for (const [rel, exp] of exportsOf) for (const [name, id] of exp) exportTable.set(`${rel}::${name}`, id);
227
+ for (let pass = 0; pass < 6; pass++) {
228
+ let changed = false;
229
+ for (const [rel, edges] of reExports) for (const e of edges) {
230
+ if (e.kind === 'named') {
231
+ const src = exportTable.get(`${e.mod}::${e.exported}`);
232
+ if (src && !exportTable.has(`${rel}::${e.as}`)) { exportTable.set(`${rel}::${e.as}`, src); changed = true; }
233
+ } else if (e.kind === 'all') {
234
+ for (const key of [...exportTable.keys()]) if (key.startsWith(e.mod + '::')) {
235
+ const name = key.slice(e.mod.length + 2);
236
+ const tkey = `${rel}::${name}`;
237
+ if (!exportTable.has(tkey)) { exportTable.set(tkey, exportTable.get(key)); changed = true; }
238
+ }
239
+ }
240
+ }
241
+ if (!changed) break;
242
+ }
243
+ const resolveExport = (mod, exported) => exportTable.get(`${mod}::${exported}`) || null;
244
+
245
+ // per-slot sink-reaching fixpoint
246
+ const sinkOf = new Map(); // gid -> Map(slot -> label)
247
+ for (const [id, f] of funcs) if (f.sinkSlots.size) sinkOf.set(id, new Map(f.sinkSlots));
248
+ for (let pass = 0; pass < 8; pass++) {
249
+ let changed = false;
250
+ for (const [id, f] of funcs) {
251
+ for (const fw of f.forwards) {
252
+ const targetId = fw.target.id || (fw.target.ref && resolveExport(fw.target.ref.mod, fw.target.ref.exported));
253
+ if (!targetId) continue;
254
+ const targetSlots = sinkOf.get(targetId);
255
+ if (targetSlots && targetSlots.has(fw.toArgIndex)) {
256
+ let m = sinkOf.get(id);
257
+ if (!m) { m = new Map(); sinkOf.set(id, m); }
258
+ if (!m.has(fw.fromSlot)) { m.set(fw.fromSlot, targetSlots.get(fw.toArgIndex)); changed = true; }
259
+ }
260
+ }
261
+ }
262
+ if (!changed) break;
263
+ }
264
+
265
+ // registry: export key -> { slots: Map(slot->label) }; returns: key -> Set(slots)
266
+ const registry = new Map();
267
+ const returnsExport = new Map();
268
+ for (const [key, id] of exportTable) {
269
+ if (sinkOf.has(id)) registry.set(key, { slots: sinkOf.get(id) });
270
+ const f = funcs.get(id);
271
+ if (f && f.returnsSlots.size) returnsExport.set(key, f.returnsSlots);
272
+ }
273
+
274
+ // call sites
275
+ const findings = [];
276
+ const seen = new Set();
277
+ const emit = (rel, node, msg, fix) => {
278
+ const key = `${rel}:${node.loc ? node.loc.start.line : 0}:${msg.slice(0, 40)}`;
279
+ if (seen.has(key)) return;
280
+ seen.add(key);
281
+ findings.push({ ruleId: 'taint.cross-file', severity: 'high', confidence: 'medium', title: 'Request data flows across files into a sink (AST-confirmed)', message: msg, fix, file: rel, line: (node.loc && node.loc.start.line) || 1, column: (node.loc && node.loc.start.column + 1) || 1 });
282
+ };
283
+
284
+ for (const [rel, tree] of trees) {
285
+ const { named, ns } = importsOf.get(rel);
286
+ const resolve = (c) => {
287
+ if (c.type === 'Identifier' && named.has(c.name)) { const im = named.get(c.name); return { key: `${im.mod}::${im.exported}`, name: c.name, mod: im.mod }; }
288
+ if (c.type === 'MemberExpression' && c.object.type === 'Identifier' && ns.has(c.object.name) && c.property.name) { const mod = ns.get(c.object.name); return { key: `${mod}::${c.property.name}`, name: `${c.object.name}.${c.property.name}`, mod }; }
289
+ return null;
290
+ };
291
+ walk.simple(tree, {
292
+ CallExpression(node) {
293
+ const args = node.arguments || [];
294
+ // (1) call an imported sink-reaching function, request data at a sink slot
295
+ const r = resolve(node.callee);
296
+ if (r && registry.has(r.key)) {
297
+ const slots = registry.get(r.key).slots;
298
+ for (let i = 0; i < args.length; i++) if (isReq(args[i]) && slots.has(i)) {
299
+ emit(rel, node, `Request data (arg ${i + 1}) is passed to ${r.name}() (from ${r.mod}), which routes it into ${slots.get(i)} — injection across a module boundary.`, `Validate/sanitize inside ${r.name}(); parameterize the sink.`);
300
+ break;
301
+ }
302
+ }
303
+ // (2) return-value taint: local sink whose arg is an imported taint-returning call
304
+ if (ast.sinkKindOfCall(node)) {
305
+ for (const a of args) {
306
+ if (a && a.type === 'CallExpression') {
307
+ const ir = resolve(a.callee);
308
+ if (ir && returnsExport.has(ir.key)) {
309
+ const retSlots = returnsExport.get(ir.key);
310
+ const inner = a.arguments || [];
311
+ if (inner.some((x, j) => isReq(x) && retSlots.has(j))) {
312
+ emit(rel, node, `Return value of ${ir.name}() (from ${ir.mod}) carries request data into ${ast.sinkKindOfCall(node).label} — cross-file taint via a return value.`, `Sanitize the value returned by ${ir.name}() before using it in the sink.`);
313
+ }
314
+ }
315
+ }
316
+ }
317
+ }
318
+ },
319
+ });
320
+ }
321
+ return findings;
322
+ }
323
+
324
+ module.exports = { analyzeCrossFile, resolveModule };