@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,136 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * CVE Intelligence Pipeline for VibeGuard.
5
+ *
6
+ * Queries OSV.dev API (https://osv.dev) for known vulnerabilities.
7
+ * Zero runtime dependencies — uses built-in https module.
8
+ *
9
+ * Flow:
10
+ * 1. Read package.json / package-lock.json
11
+ * 2. For each dependency, query OSV.dev POST /query with package+version
12
+ * 3. Map results to VibeGuard finding shape
13
+ * 4. Optional: check reachability (is the package actually imported?)
14
+ */
15
+
16
+ const https = require('https');
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+
20
+ function postJSON(url, body) {
21
+ return new Promise((resolve, reject) => {
22
+ const data = JSON.stringify(body);
23
+ const req = https.request(
24
+ url,
25
+ {
26
+ method: 'POST',
27
+ headers: {
28
+ 'Content-Type': 'application/json',
29
+ 'Content-Length': Buffer.byteLength(data),
30
+ },
31
+ timeout: 10000,
32
+ },
33
+ (res) => {
34
+ let buf = '';
35
+ res.on('data', (chunk) => (buf += chunk));
36
+ res.on('end', () => {
37
+ try {
38
+ resolve(JSON.parse(buf));
39
+ } catch {
40
+ resolve(null);
41
+ }
42
+ });
43
+ }
44
+ );
45
+ req.on('error', reject);
46
+ req.on('timeout', () => req.destroy());
47
+ req.write(data);
48
+ req.end();
49
+ });
50
+ }
51
+
52
+ function getDeps(root) {
53
+ const pkgPath = path.join(root, 'package.json');
54
+ if (!fs.existsSync(pkgPath)) return {};
55
+ let pkg;
56
+ try {
57
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
58
+ } catch {
59
+ return {};
60
+ }
61
+ return Object.assign(
62
+ {},
63
+ pkg.dependencies || {},
64
+ pkg.devDependencies || {},
65
+ pkg.optionalDependencies || {}
66
+ );
67
+ }
68
+
69
+ function cleanVersion(ver) {
70
+ return ver.replace(/^[^0-9]*/, '').split(' ')[0].split('||')[0].split('&&')[0].trim();
71
+ }
72
+
73
+ async function checkPackage(pkgName, version) {
74
+ const v = cleanVersion(version);
75
+ if (!v) return [];
76
+ try {
77
+ const resp = await postJSON('https://api.osv.dev/v1/query', {
78
+ package: { name: pkgName, ecosystem: 'npm' },
79
+ version: v,
80
+ });
81
+ if (!resp || !resp.vulns) return [];
82
+ return resp.vulns.map((vuln) => ({
83
+ id: vuln.id,
84
+ summary: vuln.summary || '',
85
+ severity: vuln.severity && vuln.severity[0] && vuln.severity[0].score,
86
+ aliases: vuln.aliases || [],
87
+ published: vuln.published,
88
+ modified: vuln.modified,
89
+ affected: (vuln.affected || []).map((a) => ({
90
+ package: a.package && a.package.name,
91
+ ranges: a.ranges,
92
+ })),
93
+ }));
94
+ } catch {
95
+ return [];
96
+ }
97
+ }
98
+
99
+ async function scanCVEs(root, opts) {
100
+ opts = opts || {};
101
+ const deps = getDeps(root);
102
+ const findings = [];
103
+ const entries = Object.entries(deps);
104
+ const batchSize = opts.batchSize || 5;
105
+
106
+ for (let i = 0; i < entries.length; i += batchSize) {
107
+ const batch = entries.slice(i, i + batchSize);
108
+ const results = await Promise.all(
109
+ batch.map(async ([name, version]) => {
110
+ const vulns = await checkPackage(name, version);
111
+ return { name, version, vulns };
112
+ })
113
+ );
114
+ for (const r of results) {
115
+ for (const vuln of r.vulns) {
116
+ findings.push({
117
+ ruleId: 'cve.osv',
118
+ file: 'package.json',
119
+ line: 1,
120
+ column: 1,
121
+ severity: vuln.severity ? 'high' : 'medium',
122
+ confidence: 'high',
123
+ title: `${r.name}@${r.version} — ${vuln.id}`,
124
+ snippet: `"${r.name}": "${r.version}"`,
125
+ message: `${vuln.id}: ${vuln.summary || 'Known vulnerability'}. Package: ${r.name}@${r.version}. See https://osv.dev/vulnerability/${vuln.id}`,
126
+ fix: `Upgrade ${r.name} to a patched version. See https://osv.dev/vulnerability/${vuln.id}`,
127
+ cve: vuln.id,
128
+ });
129
+ }
130
+ }
131
+ }
132
+
133
+ return { findings, checked: entries.length };
134
+ }
135
+
136
+ module.exports = { scanCVEs, checkPackage, getDeps, cleanVersion };
@@ -0,0 +1,279 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * VibeGuard Beautiful Terminal Dashboard.
5
+ *
6
+ * Renders a stunning ASCII dashboard with:
7
+ * - Visual grade meter (A-F) with color
8
+ * - Severity bar chart (critical/high/medium/low)
9
+ * - Top findings table with severity colors
10
+ * - Risk score gauge (0-100)
11
+ * - Category breakdown matrix
12
+ * - Auto-fix summary
13
+ * - Compliance posture
14
+ *
15
+ * Zero dependencies. Pure ASCII art with ANSI colors.
16
+ */
17
+
18
+ const C = {
19
+ reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m', underline: '\x1b[4m',
20
+ red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', blue: '\x1b[34m',
21
+ magenta: '\x1b[35m', cyan: '\x1b[36m', white: '\x1b[37m',
22
+ bgRed: '\x1b[41m', bgGreen: '\x1b[42m', bgYellow: '\x1b[43m', bgBlue: '\x1b[44m',
23
+ bgMagenta: '\x1b[45m', bgCyan: '\x1b[46m', bgWhite: '\x1b[47m',
24
+ gray: '\x1b[90m', brightRed: '\x1b[91m', brightGreen: '\x1b[92m',
25
+ brightYellow: '\x1b[93m', brightBlue: '\x1b[94m', brightMagenta: '\x1b[95m',
26
+ brightCyan: '\x1b[96m',
27
+ };
28
+
29
+ function severityColor(sev) {
30
+ return { critical: C.red, high: C.yellow, medium: C.cyan, low: C.gray }[sev] || C.white;
31
+ }
32
+
33
+ function gradeColor(grade) {
34
+ if (grade === 'A') return C.green;
35
+ if (grade === 'B') return C.green;
36
+ if (grade === 'C') return C.yellow;
37
+ if (grade === 'D') return C.yellow;
38
+ if (grade === 'F') return C.red;
39
+ return C.white;
40
+ }
41
+
42
+ // Render a visual bar: ████████░░░░ 67%
43
+ function bar(count, max, width = 20, color = C.red) {
44
+ if (max === 0) max = 1;
45
+ const filled = Math.round((count / max) * width);
46
+ return color + '█'.repeat(filled) + C.gray + '░'.repeat(width - filled) + C.reset;
47
+ }
48
+
49
+ // Render the grade as a large ASCII art meter
50
+ function gradeMeter(grade) {
51
+ const g = gradeColor(grade);
52
+ const meter = [
53
+ '┌─────────────────────────────────────────────────────────┐',
54
+ '│ │',
55
+ '│' + g + C.bold + ` GRADE: ${grade} ` + C.reset + '│',
56
+ '│ │',
57
+ '└─────────────────────────────────────────────────────────┘',
58
+ ];
59
+ return meter.join('\n');
60
+ }
61
+
62
+ // Risk score gauge (0-100)
63
+ function riskGauge(score, level) {
64
+ const colors = { NONE: C.green, LOW: C.green, MEDIUM: C.yellow, HIGH: C.yellow, CRITICAL: C.red };
65
+ const color = colors[level] || C.white;
66
+ const pct = Math.min(100, score);
67
+ const filled = Math.round((pct / 100) * 30);
68
+ const gauge = color + '▰'.repeat(filled) + C.gray + '▱'.repeat(30 - filled) + C.reset;
69
+ return `${C.bold}Risk Score${C.reset} ${gauge} ${color}${C.bold}${score}${C.reset} ${color}(${level})${C.reset}`;
70
+ }
71
+
72
+ // Severity bar chart
73
+ function severityBars(counts) {
74
+ const max = Math.max(counts.critical, counts.high, counts.medium, counts.low, 1);
75
+ const lines = [
76
+ `${C.bold}Severity Distribution${C.reset}`,
77
+ '',
78
+ ` ${C.red}Critical ${C.reset} ${bar(counts.critical, max, 25, C.red)} ${C.red}${C.bold}${counts.critical}${C.reset}`,
79
+ ` ${C.yellow}High ${C.reset} ${bar(counts.high, max, 25, C.yellow)} ${C.yellow}${C.bold}${counts.high}${C.reset}`,
80
+ ` ${C.cyan}Medium ${C.reset} ${bar(counts.medium, max, 25, C.cyan)} ${C.cyan}${C.bold}${counts.medium}${C.reset}`,
81
+ ` ${C.gray}Low ${C.reset} ${bar(counts.low, max, 25, C.gray)} ${C.gray}${C.bold}${counts.low}${C.reset}`,
82
+ '',
83
+ ];
84
+ return lines.join('\n');
85
+ }
86
+
87
+ // Category breakdown matrix
88
+ function categoryMatrix(findings) {
89
+ const matrix = {};
90
+ for (const f of findings) {
91
+ const cat = f.ruleId.split('.')[0];
92
+ if (!matrix[cat]) matrix[cat] = { critical: 0, high: 0, medium: 0, low: 0, total: 0 };
93
+ matrix[cat][f.severity]++;
94
+ matrix[cat].total++;
95
+ }
96
+ const sorted = Object.entries(matrix).sort((a, b) => b[1].total - a[1].total).slice(0, 12);
97
+ if (sorted.length === 0) return `${C.green}No findings — clean codebase!${C.reset}`;
98
+ const lines = [
99
+ `${C.bold}Category Breakdown${C.reset}`,
100
+ '',
101
+ ` ${C.dim}Category Total Crit High Med Low${C.reset}`,
102
+ ` ${C.dim}────────────── ───── ──── ──── ──── ───${C.reset}`,
103
+ ];
104
+ for (const [cat, c] of sorted) {
105
+ const catColor = c.critical > 0 ? C.red : c.high > 0 ? C.yellow : c.medium > 0 ? C.cyan : C.gray;
106
+ lines.push(
107
+ ` ${catColor}${cat.padEnd(14)}${C.reset} ${String(c.total).padStart(5)} ` +
108
+ `${c.critical > 0 ? C.red + String(c.critical).padStart(4) + C.reset : ' 0'} ` +
109
+ `${c.high > 0 ? C.yellow + String(c.high).padStart(4) + C.reset : ' 0'} ` +
110
+ `${c.medium > 0 ? C.cyan + String(c.medium).padStart(4) + C.reset : ' 0'} ` +
111
+ `${c.low > 0 ? C.gray + String(c.low).padStart(4) + C.reset : ' 0'}`
112
+ );
113
+ }
114
+ return lines.join('\n');
115
+ }
116
+
117
+ // Top findings table
118
+ function topFindings(findings, limit = 10) {
119
+ if (findings.length === 0) return `${C.green}${C.bold}✓ No security issues found — clean codebase!${C.reset}`;
120
+ const sorted = findings.slice().sort((a, b) => {
121
+ const order = { critical: 0, high: 1, medium: 2, low: 3 };
122
+ return (order[a.severity] || 4) - (order[b.severity] || 4);
123
+ }).slice(0, limit);
124
+ const lines = [
125
+ `${C.bold}Top Findings${C.reset}`,
126
+ '',
127
+ ];
128
+ for (const f of sorted) {
129
+ const sc = severityColor(f.severity);
130
+ const sevTag = sc + C.bold + `[${f.severity.toUpperCase().padEnd(8)}]` + C.reset;
131
+ lines.push(` ${sevTag} ${C.brightCyan}${f.ruleId}${C.reset}`);
132
+ lines.push(` ${C.dim}${f.file}:${f.line}${C.reset} — ${f.message.slice(0, 70)}`);
133
+ if (f.fix) lines.push(` ${C.green}fix:${C.reset} ${f.fix.slice(0, 70)}`);
134
+ lines.push('');
135
+ }
136
+ if (findings.length > limit) {
137
+ lines.push(` ${C.dim}... and ${findings.length - limit} more findings${C.reset}`);
138
+ }
139
+ return lines.join('\n');
140
+ }
141
+
142
+ // Auto-fix summary
143
+ function autoFixSummary(findings) {
144
+ try {
145
+ const { isAutoFixable } = require('./autofix');
146
+ const fixable = findings.filter(f => isAutoFixable(f.ruleId));
147
+ if (fixable.length === 0) return '';
148
+ const lines = [
149
+ `${C.green}${C.bold}Auto-Fix Available${C.reset}`,
150
+ '',
151
+ ` ${C.green}✓${C.reset} ${fixable.length} of ${findings.length} findings can be auto-fixed`,
152
+ ` ${C.dim}Run: vibeguard fix${C.reset}`,
153
+ '',
154
+ ];
155
+ return lines.join('\n');
156
+ } catch { return ''; }
157
+ }
158
+
159
+ // Compliance posture
160
+ function compliancePosture(findings) {
161
+ try {
162
+ const { generateComplianceReport } = require('./compliance');
163
+ const report = generateComplianceReport(findings);
164
+ if (typeof report === 'string') return report;
165
+ const lines = [`${C.bold}Compliance Posture${C.reset}`, ''];
166
+ for (const [framework, data] of Object.entries(report)) {
167
+ const failed = data.failed || data.failures || 0;
168
+ const passed = data.passed || data.pass || 0;
169
+ const status = failed === 0 ? C.green + '✓ PASS' : failed < 3 ? C.yellow + '⚠ REVIEW' : C.red + '✗ FAIL';
170
+ lines.push(` ${status}${C.reset} ${framework.padEnd(12)} ${C.dim}${failed} findings${C.reset}`);
171
+ }
172
+ return lines.join('\n');
173
+ } catch { return `${C.dim}Compliance analysis unavailable${C.reset}`; }
174
+ }
175
+
176
+ // Full dashboard render
177
+ function renderDashboard(result) {
178
+ const counts = result.counts;
179
+ const weights = { critical: 10, high: 5, medium: 2, low: 1 };
180
+ let score = 0;
181
+ for (const f of result.findings) score += weights[f.severity] || 1;
182
+ const maxScore = result.scannedFiles * 10 || 1;
183
+ const riskPercent = Math.min(100, Math.round((score / maxScore) * 100));
184
+ const riskLevel = score === 0 ? 'NONE' : score < 10 ? 'LOW' : score < 30 ? 'MEDIUM' : score < 60 ? 'HIGH' : 'CRITICAL';
185
+
186
+ const W = 60;
187
+ const border = C.cyan + '═'.repeat(W) + C.reset;
188
+ const borderThin = C.dim + '─'.repeat(W) + C.reset;
189
+
190
+ const sections = [
191
+ '',
192
+ border,
193
+ C.cyan + C.bold + ' VibeGuard Security Dashboard' + C.reset + C.dim + ' — ' + new Date().toISOString().slice(0, 19) + C.reset,
194
+ border,
195
+ '',
196
+ gradeMeter(result.grade),
197
+ '',
198
+ riskGauge(score, riskLevel),
199
+ '',
200
+ borderThin,
201
+ '',
202
+ severityBars(counts),
203
+ borderThin,
204
+ '',
205
+ ` ${C.bold}Scan Summary${C.reset}`,
206
+ ` ${C.dim}Files scanned:${C.reset} ${result.scannedFiles}`,
207
+ ` ${C.dim}Total findings:${C.reset} ${result.findings.length}`,
208
+ ` ${C.dim}Grade:${C.reset} ${gradeColor(result.grade)}${C.bold}${result.grade}${C.reset}`,
209
+ '',
210
+ borderThin,
211
+ '',
212
+ categoryMatrix(result.findings),
213
+ '',
214
+ borderThin,
215
+ '',
216
+ topFindings(result.findings),
217
+ autoFixSummary(result.findings),
218
+ borderThin,
219
+ '',
220
+ compliancePosture(result.findings),
221
+ '',
222
+ border,
223
+ C.dim + ' Run "vibeguard scan" for full report | "vibeguard fix" to auto-fix | "vibeguard why <rule>" for details' + C.reset,
224
+ border,
225
+ '',
226
+ ];
227
+
228
+ return sections.join('\n');
229
+ }
230
+
231
+ // GitHub PR comment format (markdown)
232
+ function renderPRComment(result) {
233
+ const counts = result.counts;
234
+ const gradeEmoji = { A: '🟢', B: '🟢', C: '🟡', D: '🟡', F: '🔴' };
235
+ const emoji = gradeEmoji[result.grade] || '⚪';
236
+
237
+ let md = `## ${emoji} VibeGuard Security Report\n\n`;
238
+ md += `| Metric | Value |\n|--------|-------|\n`;
239
+ md += `| Grade | **${result.grade}** |\n`;
240
+ md += `| Files Scanned | ${result.scannedFiles} |\n`;
241
+ md += `| Total Findings | ${result.findings.length} |\n`;
242
+ md += `| Critical | ${counts.critical} |\n`;
243
+ md += `| High | ${counts.high} |\n`;
244
+ md += `| Medium | ${counts.medium} |\n`;
245
+ md += `| Low | ${counts.low} |\n\n`;
246
+
247
+ if (result.findings.length > 0) {
248
+ md += `### Top Findings\n\n`;
249
+ md += `| Severity | Rule | File:Line | Message |\n`;
250
+ md += `|----------|------|-----------|--------|\n`;
251
+ const sorted = result.findings.slice().sort((a, b) => {
252
+ const order = { critical: 0, high: 1, medium: 2, low: 3 };
253
+ return (order[a.severity] || 4) - (order[b.severity] || 4);
254
+ }).slice(0, 15);
255
+ for (const f of sorted) {
256
+ const sevEmoji = { critical: '🔴', high: '🟠', medium: '🟡', low: '⚪' }[f.severity] || '⚪';
257
+ md += `| ${sevEmoji} ${f.severity} | \`${f.ruleId}\` | \`${f.file}:${f.line}\` | ${f.message.slice(0, 60)} |\n`;
258
+ }
259
+ if (result.findings.length > 15) md += `\n_...and ${result.findings.length - 15} more findings_\n`;
260
+ } else {
261
+ md += `### ✅ No security issues found!\n\nClean codebase. Great job! 🎉\n`;
262
+ }
263
+
264
+ // Auto-fix
265
+ try {
266
+ const { isAutoFixable } = require('./autofix');
267
+ const fixable = result.findings.filter(f => isAutoFixable(f.ruleId));
268
+ if (fixable.length > 0) {
269
+ md += `\n### 🔧 Auto-Fix Available\n\n`;
270
+ md += `${fixable.length} findings can be automatically fixed. Run:\n`;
271
+ md += '```\nvibeguard fix\n```\n';
272
+ }
273
+ } catch {}
274
+
275
+ md += `\n---\n_VibeGuard — Free, zero-dependency security scanner. [Learn more](https://github.com/vibeguard/vibeguard)_\n`;
276
+ return md;
277
+ }
278
+
279
+ module.exports = { renderDashboard, renderPRComment, gradeMeter, riskGauge, severityBars, categoryMatrix, topFindings, autoFixSummary, compliancePosture };
package/src/deps.js ADDED
@@ -0,0 +1,159 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Dependency vulnerability scanning.
5
+ *
6
+ * We do NOT reinvent an advisory database. We shell out to the tools that already
7
+ * do this well — `npm audit --json` and `pip-audit --format json` — and fold
8
+ * their results into VibeGuard's findings. Failures are non-fatal: if a tool is
9
+ * missing or offline, we skip and say so rather than blocking a scan.
10
+ */
11
+
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const { execFileSync, execSync } = require('child_process');
15
+
16
+ const AUDIT_TIMEOUT_MS = 60000;
17
+
18
+ // npm severity -> VibeGuard severity. npm uses low/moderate/high/critical.
19
+ const NPM_SEV = { critical: 'critical', high: 'high', moderate: 'medium', low: 'low', info: 'low' };
20
+ const PIP_SEV = { critical: 'critical', high: 'high', medium: 'medium', moderate: 'medium', low: 'low' };
21
+
22
+ function fileExists(p) {
23
+ try {
24
+ return fs.existsSync(p);
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ const isWin = process.platform === 'win32';
31
+
32
+ // Run a fixed command and parse its JSON stdout.
33
+ // SECURITY NOTE: `cmd` and `args` here are always hardcoded literals in this
34
+ // module — never user input — so the Windows shell path cannot be injected.
35
+ // POSIX uses execFileSync (no shell at all); Windows uses execSync with a
36
+ // constant string because npm/pip-audit ship as shim scripts that need a shell
37
+ // to resolve, and passing an args array with shell:true triggers DEP0190.
38
+ function runJson(cmd, args, cwd) {
39
+ const opts = {
40
+ cwd,
41
+ timeout: AUDIT_TIMEOUT_MS,
42
+ maxBuffer: 20 * 1024 * 1024,
43
+ stdio: ['ignore', 'pipe', 'ignore'],
44
+ windowsHide: true,
45
+ };
46
+ const out = isWin
47
+ ? execSync([cmd, ...args].join(' '), opts)
48
+ : execFileSync(cmd, args, opts);
49
+ return JSON.parse(out.toString('utf8') || '{}');
50
+ }
51
+
52
+ function npmAudit(root) {
53
+ const findings = [];
54
+ const hasNode = fileExists(path.join(root, 'package.json'));
55
+ if (!hasNode) return { findings, ran: false, note: 'no package.json' };
56
+
57
+ let data;
58
+ try {
59
+ // npm audit exits non-zero when vulns exist; execFileSync throws but still
60
+ // gives us stdout on err.stdout.
61
+ try {
62
+ data = runJson('npm', ['audit', '--json'], root);
63
+ } catch (err) {
64
+ if (err && err.stdout) data = JSON.parse(err.stdout.toString('utf8') || '{}');
65
+ else throw err;
66
+ }
67
+ } catch (err) {
68
+ return { findings, ran: false, note: `npm audit unavailable (${err.code || err.message})` };
69
+ }
70
+
71
+ return { findings: parseNpmAudit(data), ran: true, note: null };
72
+ }
73
+
74
+ // Pure parser (testable without running npm).
75
+ function parseNpmAudit(data) {
76
+ const findings = [];
77
+ const vulns = (data && data.vulnerabilities) || {};
78
+ for (const name of Object.keys(vulns)) {
79
+ const v = vulns[name];
80
+ const sev = NPM_SEV[v.severity] || 'medium';
81
+ const viaTitles = Array.isArray(v.via)
82
+ ? v.via.filter((x) => typeof x === 'object').map((x) => x.title).filter(Boolean)
83
+ : [];
84
+ const detail = viaTitles.length ? `: ${viaTitles.slice(0, 2).join('; ')}` : '';
85
+ findings.push({
86
+ ruleId: 'dep.npm-vulnerability',
87
+ severity: sev,
88
+ confidence: 'high',
89
+ title: 'Vulnerable npm dependency',
90
+ message: `${name} (${v.range || 'installed version'}) has a known ${v.severity} vulnerability${detail}.`,
91
+ fix: v.fixAvailable
92
+ ? `Run 'npm audit fix'${v.fixAvailable === true ? '' : ' --force (may include a breaking major bump)'} or update ${name}.`
93
+ : `No automatic fix yet — review the advisory for ${name} and pin/replace if needed.`,
94
+ file: 'package.json',
95
+ line: 1,
96
+ column: 1,
97
+ snippet: `dependency: ${name}`,
98
+ });
99
+ }
100
+ return findings;
101
+ }
102
+
103
+ function pipAudit(root) {
104
+ const findings = [];
105
+ const hasPy =
106
+ fileExists(path.join(root, 'requirements.txt')) ||
107
+ fileExists(path.join(root, 'pyproject.toml')) ||
108
+ fileExists(path.join(root, 'Pipfile.lock'));
109
+ if (!hasPy) return { findings, ran: false, note: 'no python manifest' };
110
+
111
+ let data;
112
+ try {
113
+ try {
114
+ data = runJson('pip-audit', ['--format', 'json'], root);
115
+ } catch (err) {
116
+ if (err && err.stdout) data = JSON.parse(err.stdout.toString('utf8') || '{}');
117
+ else throw err;
118
+ }
119
+ } catch (err) {
120
+ return { findings, ran: false, note: `pip-audit unavailable (${err.code || err.message})` };
121
+ }
122
+
123
+ // pip-audit json: { dependencies: [ { name, version, vulns: [ { id, fix_versions, ... } ] } ] }
124
+ const deps = data.dependencies || data || [];
125
+ for (const dep of deps) {
126
+ const vulns = dep.vulns || [];
127
+ for (const vuln of vulns) {
128
+ const sev = PIP_SEV[(vuln.severity || '').toLowerCase()] || 'high';
129
+ findings.push({
130
+ ruleId: 'dep.pip-vulnerability',
131
+ severity: sev,
132
+ confidence: 'high',
133
+ title: 'Vulnerable Python dependency',
134
+ message: `${dep.name} ${dep.version} is affected by ${vuln.id}${vuln.description ? ': ' + String(vuln.description).slice(0, 120) : ''}.`,
135
+ fix:
136
+ vuln.fix_versions && vuln.fix_versions.length
137
+ ? `Upgrade ${dep.name} to ${vuln.fix_versions.join(' / ')}.`
138
+ : `No fixed version listed for ${vuln.id} — review the advisory.`,
139
+ file: 'requirements.txt',
140
+ line: 1,
141
+ column: 1,
142
+ snippet: `dependency: ${dep.name} ${dep.version}`,
143
+ });
144
+ }
145
+ }
146
+ return { findings, ran: true, note: null };
147
+ }
148
+
149
+ function scanDependencies(root) {
150
+ const npm = npmAudit(root);
151
+ const pip = pipAudit(root);
152
+ return {
153
+ findings: [...npm.findings, ...pip.findings],
154
+ ran: { npm: npm.ran, pip: pip.ran },
155
+ notes: [npm.note, pip.note].filter(Boolean),
156
+ };
157
+ }
158
+
159
+ module.exports = { scanDependencies, npmAudit, pipAudit, parseNpmAudit };
package/src/doctor.js ADDED
@@ -0,0 +1,111 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * `vibeguard doctor` — audit the AI coding HOST (not your project source) for
5
+ * known compromise vectors:
6
+ * - hook injection via .claude/settings.json (CVE-2025-59536 class)
7
+ * - API-key exfil via ANTHROPIC_BASE_URL / OPENAI_BASE_URL override
8
+ * - MCP configs that launch suspicious commands (curl|sh, file://, etc.)
9
+ *
10
+ * Read-only. Scans the project's ./.claude + ./.vscode and the user's
11
+ * ~/.claude, ~/.cursor, ~/.codeium, ~/.codex configs.
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const os = require('os');
16
+ const path = require('path');
17
+
18
+ const HOME = os.homedir();
19
+ const SUSPICIOUS_CMD = /curl|wget|\|\s*(?:sh|bash)|base64\s+-d|eval\s|Invoke-Expression|iex\b|nc\s|ncat\s|python\s+-c/i;
20
+
21
+ function readJson(p) {
22
+ try {
23
+ return JSON.parse(fs.readFileSync(p, 'utf8'));
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+ function exists(p) {
29
+ try { return fs.existsSync(p); } catch { return false; }
30
+ }
31
+
32
+ function checkHooks(file, findings) {
33
+ const cfg = readJson(file);
34
+ if (!cfg || !cfg.hooks) return;
35
+ const walk = (node) => {
36
+ if (!node || typeof node !== 'object') return;
37
+ if (typeof node.command === 'string' && SUSPICIOUS_CMD.test(node.command)) {
38
+ findings.push({
39
+ ruleId: 'doctor.hook-injection', severity: 'critical', confidence: 'high',
40
+ title: 'Suspicious command in an AI hook',
41
+ message: `A hook in ${file} runs a suspicious command: ${node.command.slice(0, 80)}. Malicious hooks execute automatically on tool events (CVE-2025-59536 class).`,
42
+ fix: 'Remove or vet this hook. Never accept a repo whose .claude/settings.json injects shell hooks you did not write.',
43
+ file, line: 1, column: 1, snippet: node.command.slice(0, 80),
44
+ });
45
+ }
46
+ for (const k of Object.keys(node)) walk(node[k]);
47
+ };
48
+ walk(cfg.hooks);
49
+ }
50
+
51
+ function checkEnv(findings) {
52
+ for (const v of ['ANTHROPIC_BASE_URL', 'OPENAI_BASE_URL', 'ANTHROPIC_API_URL']) {
53
+ const val = process.env[v];
54
+ if (val && !/^https:\/\/(?:api\.anthropic\.com|api\.openai\.com)/.test(val)) {
55
+ findings.push({
56
+ ruleId: 'doctor.base-url-hijack', severity: 'high', confidence: 'high',
57
+ title: 'AI provider base URL overridden',
58
+ message: `${v}=${val} points AI traffic (including your API key) at a non-official host — possible key exfiltration (CVE-2026-21852 class).`,
59
+ fix: `Unset ${v} unless you deliberately use a proxy you control.`,
60
+ file: `env:${v}`, line: 1, column: 1, snippet: `${v}=${val}`,
61
+ });
62
+ }
63
+ }
64
+ }
65
+
66
+ function checkMcp(file, findings) {
67
+ const cfg = readJson(file);
68
+ if (!cfg) return;
69
+ const servers = cfg.mcpServers || cfg.servers || {};
70
+ for (const name of Object.keys(servers)) {
71
+ const s = servers[name] || {};
72
+ const cmd = [s.command, ...(s.args || [])].join(' ');
73
+ if (SUSPICIOUS_CMD.test(cmd) || /file:\/\//.test(cmd)) {
74
+ findings.push({
75
+ ruleId: 'doctor.mcp-suspicious', severity: 'high', confidence: 'medium',
76
+ title: 'MCP server launches a suspicious command',
77
+ message: `MCP server "${name}" in ${file} runs: ${cmd.slice(0, 80)}. An untrusted MCP server can run arbitrary code and exfiltrate data.`,
78
+ fix: 'Remove MCP servers you did not add; only install servers from sources you trust.',
79
+ file, line: 1, column: 1, snippet: cmd.slice(0, 80),
80
+ });
81
+ }
82
+ }
83
+ }
84
+
85
+ function runDoctor(root, opts = {}) {
86
+ const findings = [];
87
+ const scope = opts.scope || 'full';
88
+ const projectFiles = [
89
+ path.join(root, '.claude', 'settings.json'),
90
+ path.join(root, '.claude', 'settings.local.json'),
91
+ path.join(root, '.mcp.json'),
92
+ path.join(root, '.vscode', 'mcp.json'),
93
+ ];
94
+ const hostFiles = [
95
+ path.join(HOME, '.claude.json'),
96
+ path.join(HOME, '.claude', 'settings.json'),
97
+ path.join(HOME, '.cursor', 'mcp.json'),
98
+ path.join(HOME, '.codeium', 'windsurf', 'mcp_config.json'),
99
+ ];
100
+
101
+ if (scope !== 'host') {
102
+ for (const f of projectFiles) if (exists(f)) { checkHooks(f, findings); checkMcp(f, findings); }
103
+ }
104
+ if (scope !== 'project') {
105
+ for (const f of hostFiles) if (exists(f)) { checkHooks(f, findings); checkMcp(f, findings); }
106
+ checkEnv(findings);
107
+ }
108
+ return findings;
109
+ }
110
+
111
+ module.exports = { runDoctor };