@yagyeshvyas/vibeguard 1.13.0 → 1.13.1
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/CHANGELOG.md +11 -0
- package/README.md +18 -2
- package/bin/cli.js +2753 -2753
- package/ci/vibeguard.yml +42 -42
- package/package.json +1 -1
- package/scripts/counts.js +93 -93
- package/scripts/postinstall.js +26 -26
- package/src/auto.js +427 -427
- package/src/daemon.js +343 -343
- package/src/dashboard.js +278 -278
- package/src/engine.js +297 -297
- package/src/hook.js +151 -151
- package/src/install.js +298 -298
- package/src/integrity.json +1 -1
- package/src/plugin.js +182 -182
- package/src/privacy-audit.js +272 -272
- package/src/repl.js +150 -150
- package/src/report.js +331 -331
- package/src/rules-pack.js +3068 -3068
- package/src/rules.js +1822 -1822
- package/src/sbom.js +193 -193
- package/src/scanner.js +1032 -1032
- package/src/shell-guard.js +302 -302
- package/src/slopsquat.js +144 -144
- package/src/trace.js +220 -220
- package/src/.vibeguard/cache/file-hashes.json +0 -60
- package/src/.vibeguard/latest-snapshot.json +0 -36
- package/src/.vibeguard/mcp-pins.json +0 -1
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +0 -428
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +0 -344
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +0 -279
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +0 -297
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +0 -151
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +0 -299
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +0 -65
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +0 -2051
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +0 -168
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +0 -362
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +0 -150
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +0 -1611
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +0 -164
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +0 -292
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +0 -144
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +0 -220
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +0 -428
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +0 -344
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +0 -297
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +0 -299
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +0 -37
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +0 -2055
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +0 -168
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +0 -362
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +0 -220
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +0 -428
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +0 -344
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +0 -279
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +0 -297
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +0 -151
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +0 -299
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +0 -65
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +0 -2055
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +0 -168
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +0 -362
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +0 -150
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +0 -1611
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +0 -164
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +0 -292
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +0 -144
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +0 -220
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +0 -428
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +0 -344
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +0 -279
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +0 -297
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +0 -151
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +0 -299
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +0 -65
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +0 -2054
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +0 -168
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +0 -362
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +0 -150
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +0 -1611
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +0 -164
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +0 -292
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +0 -144
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +0 -220
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +0 -428
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +0 -344
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +0 -297
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +0 -299
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +0 -37
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +0 -2055
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +0 -168
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +0 -362
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +0 -220
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +0 -428
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +0 -344
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +0 -297
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +0 -33
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +0 -2055
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +0 -1611
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +0 -292
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +0 -220
- package/src/.vibeguard-baseline.json +0 -5226
|
@@ -1,2055 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
'use strict';
|
|
3
|
-
|
|
4
|
-
/*
|
|
5
|
-
* VibeGuard MCP server.
|
|
6
|
-
*
|
|
7
|
-
* Exposes the scanner to MCP clients (Claude Code, Cursor) over stdio.
|
|
8
|
-
* Tools: scan_project, suggest_fixes, verify_fixes.
|
|
9
|
-
*
|
|
10
|
-
* Uses the low-level Server API from the official SDK so we don't pull in zod;
|
|
11
|
-
* input schemas are plain JSON Schema.
|
|
12
|
-
*
|
|
13
|
-
* Install into Claude Code:
|
|
14
|
-
* claude mcp add vibeguard -- npx -y @yagyeshvyas/vibeguard mcp
|
|
15
|
-
* or, from a checkout:
|
|
16
|
-
* claude mcp add vibeguard -- node /abs/path/src/mcp-server.js
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
|
|
20
|
-
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
|
|
21
|
-
const {
|
|
22
|
-
ListToolsRequestSchema,
|
|
23
|
-
CallToolRequestSchema,
|
|
24
|
-
} = require('@modelcontextprotocol/sdk/types.js');
|
|
25
|
-
|
|
26
|
-
const { scan, computeGrade, sortFindings, walk } = require('./scanner');
|
|
27
|
-
const { verify, writeBaseline } = require('./verify');
|
|
28
|
-
const { renderFixPrompt } = require('./report');
|
|
29
|
-
const { scanUrl } = require('./urlscan');
|
|
30
|
-
const { generateComplianceReport } = require('./compliance');
|
|
31
|
-
const { analyzePrompt } = require('./secure-prompt');
|
|
32
|
-
const { scanSlopsquat } = require('./slopsquat');
|
|
33
|
-
const { trace } = require('./trace');
|
|
34
|
-
const { buildAuthCoverage, getChangedFiles, analyzePythonTaint } = require('./engine');
|
|
35
|
-
const { scanCVEs } = require('./cve-intel');
|
|
36
|
-
const { allRules } = require('./rules');
|
|
37
|
-
const fs = require('fs');
|
|
38
|
-
const path = require('path');
|
|
39
|
-
|
|
40
|
-
const DIR_SCHEMA = {
|
|
41
|
-
type: 'object',
|
|
42
|
-
properties: {
|
|
43
|
-
dir: {
|
|
44
|
-
type: 'string',
|
|
45
|
-
description: 'Path to the project directory to analyze. Defaults to the current working directory.',
|
|
46
|
-
},
|
|
47
|
-
},
|
|
48
|
-
required: [],
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
const TOOLS = [
|
|
52
|
-
{
|
|
53
|
-
name: 'scan_project',
|
|
54
|
-
description: 'Scan a project for security issues. Returns findings with letter grade.',
|
|
55
|
-
inputSchema: { type: 'object', properties: { dir: DIR_SCHEMA.properties.dir, saveBaseline: { type: 'boolean' } }, required: [] },
|
|
56
|
-
},
|
|
57
|
-
{
|
|
58
|
-
name: 'suggest_fixes',
|
|
59
|
-
description: 'Scan and return a concrete fix plan per finding plus a paste-ready prompt.',
|
|
60
|
-
inputSchema: DIR_SCHEMA,
|
|
61
|
-
},
|
|
62
|
-
{
|
|
63
|
-
name: 'verify_fixes',
|
|
64
|
-
description: 'Re-scan and report resolved/remaining/new issues vs the baseline.',
|
|
65
|
-
inputSchema: DIR_SCHEMA,
|
|
66
|
-
},
|
|
67
|
-
{
|
|
68
|
-
name: 'review_hotspots',
|
|
69
|
-
description: 'Deep semantic review: identifies security hotspot files + structured checklist for manual review.',
|
|
70
|
-
inputSchema: DIR_SCHEMA,
|
|
71
|
-
},
|
|
72
|
-
{
|
|
73
|
-
name: 'scan_url',
|
|
74
|
-
description: 'Scan a live deployed URL for missing security headers, insecure cookies, server leakage.',
|
|
75
|
-
inputSchema: { type: 'object', properties: { url: { type: 'string' } }, required: ['url'] },
|
|
76
|
-
},
|
|
77
|
-
{
|
|
78
|
-
name: 'check_code',
|
|
79
|
-
description: 'Scan a code snippet (string) for security issues without writing to disk.',
|
|
80
|
-
inputSchema: { type: 'object', properties: { code: { type: 'string' }, language: { type: 'string' } }, required: ['code'] },
|
|
81
|
-
},
|
|
82
|
-
{
|
|
83
|
-
name: 'scan_staged',
|
|
84
|
-
description: 'Scan only staged git changes (pre-commit). Returns findings for files in the git diff.',
|
|
85
|
-
inputSchema: DIR_SCHEMA,
|
|
86
|
-
},
|
|
87
|
-
{
|
|
88
|
-
name: 'scan_dependencies',
|
|
89
|
-
description: 'Query OSV.dev for known vulnerabilities in package.json dependencies.',
|
|
90
|
-
inputSchema: DIR_SCHEMA,
|
|
91
|
-
},
|
|
92
|
-
{
|
|
93
|
-
name: 'scan_secrets',
|
|
94
|
-
description: 'Scan project for hardcoded secrets and API keys only (faster than full scan).',
|
|
95
|
-
inputSchema: DIR_SCHEMA,
|
|
96
|
-
},
|
|
97
|
-
{
|
|
98
|
-
name: 'check_package_health',
|
|
99
|
-
description: 'Check if npm packages referenced in the project are real (anti-slopsquat) and check typosquat risk.',
|
|
100
|
-
inputSchema: DIR_SCHEMA,
|
|
101
|
-
},
|
|
102
|
-
{
|
|
103
|
-
name: 'compliance_report',
|
|
104
|
-
description: 'Map findings to compliance frameworks (SOC2, PCI-DSS, HIPAA, GDPR, ISO27001, EU AI Act).',
|
|
105
|
-
inputSchema: { type: 'object', properties: { dir: DIR_SCHEMA.properties.dir, framework: { type: 'string', enum: ['SOC2', 'PCI-DSS', 'HIPAA', 'GDPR', 'ISO27001', 'EUAIAct'] } }, required: [] },
|
|
106
|
-
},
|
|
107
|
-
{
|
|
108
|
-
name: 'export_sarif',
|
|
109
|
-
description: 'Export scan results as SARIF 2.1.0 JSON with CWE/OWASP tags.',
|
|
110
|
-
inputSchema: { type: 'object', properties: { dir: DIR_SCHEMA.properties.dir }, required: [] },
|
|
111
|
-
},
|
|
112
|
-
{
|
|
113
|
-
name: 'fix_code',
|
|
114
|
-
description: 'Return structured patch suggestions for findings (exactEdit or manualFix). Does not edit files.',
|
|
115
|
-
inputSchema: DIR_SCHEMA,
|
|
116
|
-
},
|
|
117
|
-
{
|
|
118
|
-
name: 'secure_this',
|
|
119
|
-
description: 'Full pipeline: scan → suggest fixes → (after user applies) re-verify → rollback if new issues. Returns the plan only.',
|
|
120
|
-
inputSchema: DIR_SCHEMA,
|
|
121
|
-
},
|
|
122
|
-
{
|
|
123
|
-
name: 'guard_action',
|
|
124
|
-
description: 'Agent action firewall — inspect an action BEFORE running it and block secret/PII exfiltration, dangerous commands, or sending sensitive data to an untrusted host. Call this before any shell command, network request, file write, LLM prompt, or MCP tool call. Returns allow | warn | block. Nothing leaves the machine that would leak an API key or personal data.',
|
|
125
|
-
inputSchema: {
|
|
126
|
-
type: 'object',
|
|
127
|
-
properties: {
|
|
128
|
-
type: { type: 'string', enum: ['shell', 'network', 'file-write', 'prompt', 'mcp', 'generic'], description: 'The kind of action.' },
|
|
129
|
-
command: { type: 'string', description: 'For type=shell: the command line.' },
|
|
130
|
-
url: { type: 'string', description: 'For type=network: the request URL.' },
|
|
131
|
-
method: { type: 'string' },
|
|
132
|
-
body: { description: 'For type=network: the request body (string or object).' },
|
|
133
|
-
path: { type: 'string', description: 'For type=file-write: the destination path.' },
|
|
134
|
-
content: { type: 'string', description: 'For file-write/prompt/generic: the content.' },
|
|
135
|
-
provider: { type: 'string', description: 'For type=prompt: the LLM provider name.' },
|
|
136
|
-
tool: { type: 'string', description: 'For type=mcp: the tool name.' },
|
|
137
|
-
args: { description: 'For type=mcp: the tool arguments.' },
|
|
138
|
-
trustedHosts: { type: 'array', items: { type: 'string' }, description: 'Hosts allowed to receive sensitive data.' },
|
|
139
|
-
},
|
|
140
|
-
required: ['type'],
|
|
141
|
-
},
|
|
142
|
-
},
|
|
143
|
-
{
|
|
144
|
-
name: 'agent_scan',
|
|
145
|
-
description: 'AI Agent Security Posture — one graded verdict across every agent-era risk: MCP server trust, PII/secret leakage to LLM providers, LLM output reaching exec/eval/SQL/DOM, prompt injection, agent capability/loop safety, and hallucinated dependencies. Use this to answer "is my AI-agent setup safe?" Offline; aggregates VibeGuard\'s agent checks.',
|
|
146
|
-
inputSchema: { type: 'object', properties: { dir: DIR_SCHEMA.properties.dir }, required: [] },
|
|
147
|
-
},
|
|
148
|
-
{
|
|
149
|
-
name: 'mcp_audit',
|
|
150
|
-
description: 'Audit the MCP servers this project trusts (.mcp.json / .cursor / .vscode) for tool poisoning (prompt injection), unpinned auto-install / rug-pull, remote-code commands, secrets in env, and definition drift since last approval. 100% offline — reads config only, never runs a server.',
|
|
151
|
-
inputSchema: { type: 'object', properties: { dir: DIR_SCHEMA.properties.dir, pin: { type: 'boolean', description: 'Re-baseline server definition hashes after review.' } }, required: [] },
|
|
152
|
-
},
|
|
153
|
-
{
|
|
154
|
-
name: 'audit_config',
|
|
155
|
-
description: 'Cross-file config audit: checks .env, next.config, docker-compose, k8s, CI workflows for security misconfig.',
|
|
156
|
-
inputSchema: DIR_SCHEMA,
|
|
157
|
-
},
|
|
158
|
-
{
|
|
159
|
-
name: 'generate_policy',
|
|
160
|
-
description: 'Generate security policy templates: CSP headers, CORS config, RLS policies, rate-limit middleware.',
|
|
161
|
-
inputSchema: { type: 'object', properties: { type: { type: 'string', enum: ['csp', 'cors', 'rls', 'rate-limit'] }, dir: DIR_SCHEMA.properties.dir }, required: ['type'] },
|
|
162
|
-
},
|
|
163
|
-
{
|
|
164
|
-
name: 'review_pr',
|
|
165
|
-
description: 'Review a git diff (unstaged or branch diff) for security issues in changed lines.',
|
|
166
|
-
inputSchema: { type: 'object', properties: { dir: DIR_SCHEMA.properties.dir, base: { type: 'string', description: 'Base branch (default: main)' } }, required: [] },
|
|
167
|
-
},
|
|
168
|
-
{
|
|
169
|
-
name: 'scan_secrets_history',
|
|
170
|
-
description: 'Scan git history for committed-then-removed secrets.',
|
|
171
|
-
inputSchema: DIR_SCHEMA,
|
|
172
|
-
},
|
|
173
|
-
{
|
|
174
|
-
name: 'analyze_dataflow',
|
|
175
|
-
description: 'Run taint analysis on a single file to trace user input to dangerous sinks.',
|
|
176
|
-
inputSchema: { type: 'object', properties: { file: { type: 'string', description: 'File path to analyze' } }, required: ['file'] },
|
|
177
|
-
},
|
|
178
|
-
{
|
|
179
|
-
name: 'analyze_cross_file_dataflow',
|
|
180
|
-
description: 'Run cross-file taint analysis across the project import/export graph.',
|
|
181
|
-
inputSchema: DIR_SCHEMA,
|
|
182
|
-
},
|
|
183
|
-
{
|
|
184
|
-
name: 'check_command',
|
|
185
|
-
description: 'Analyze a shell command string for security risks (pipe-to-bash, rm -rf, chmod 777, sudo).',
|
|
186
|
-
inputSchema: { type: 'object', properties: { command: { type: 'string' } }, required: ['command'] },
|
|
187
|
-
},
|
|
188
|
-
{
|
|
189
|
-
name: 'scan_config_change',
|
|
190
|
-
description: 'Detect if security-relevant config files were weakened since last scan (config downgrade detection).',
|
|
191
|
-
inputSchema: DIR_SCHEMA,
|
|
192
|
-
},
|
|
193
|
-
{
|
|
194
|
-
name: 'repo_security_posture',
|
|
195
|
-
description: 'Overall security posture: grade, coverage, auth map, dependency health, compliance gaps.',
|
|
196
|
-
inputSchema: DIR_SCHEMA,
|
|
197
|
-
},
|
|
198
|
-
{
|
|
199
|
-
name: 'explain_remediation',
|
|
200
|
-
description: 'Get detailed remediation guidance for a specific rule ID.',
|
|
201
|
-
inputSchema: { type: 'object', properties: { ruleId: { type: 'string' } }, required: ['ruleId'] },
|
|
202
|
-
},
|
|
203
|
-
{
|
|
204
|
-
name: 'scan_file',
|
|
205
|
-
description: 'Scan a single file for security issues (for real-time post-edit checks).',
|
|
206
|
-
inputSchema: { type: 'object', properties: { file: { type: 'string' } }, required: ['file'] },
|
|
207
|
-
},
|
|
208
|
-
{
|
|
209
|
-
name: 'scan_changed_files',
|
|
210
|
-
description: 'Incremental scan: only re-scan files that changed since last scan (file-hash cache).',
|
|
211
|
-
inputSchema: DIR_SCHEMA,
|
|
212
|
-
},
|
|
213
|
-
{
|
|
214
|
-
name: 'security_stats',
|
|
215
|
-
description: 'Dashboard: finding counts by category, grade trend, top risky files, rule coverage.',
|
|
216
|
-
inputSchema: DIR_SCHEMA,
|
|
217
|
-
},
|
|
218
|
-
{
|
|
219
|
-
name: 'guardvibe_doctor',
|
|
220
|
-
description: 'AI host security audit: check for hook injection, base URL hijack, MCP config abuse.',
|
|
221
|
-
inputSchema: DIR_SCHEMA,
|
|
222
|
-
},
|
|
223
|
-
{
|
|
224
|
-
name: 'auth_coverage',
|
|
225
|
-
description: 'Enumerate routes → middleware → auth guards. Shows which API routes are unprotected.',
|
|
226
|
-
inputSchema: DIR_SCHEMA,
|
|
227
|
-
},
|
|
228
|
-
{
|
|
229
|
-
name: 'deep_scan',
|
|
230
|
-
description: 'Agentic deep review: combines scan + hotspot analysis + auth coverage + behavior trace. Emits structured review contracts for your AI client to act on.',
|
|
231
|
-
inputSchema: DIR_SCHEMA,
|
|
232
|
-
},
|
|
233
|
-
{
|
|
234
|
-
name: 'full_audit',
|
|
235
|
-
description: 'Run ALL checks: scan + CVE + slopsquat + compliance + auth coverage + history. Returns full verdict + hash.',
|
|
236
|
-
inputSchema: DIR_SCHEMA,
|
|
237
|
-
},
|
|
238
|
-
{
|
|
239
|
-
name: 'remediation_plan',
|
|
240
|
-
description: 'Generate a prioritized fix checklist with effort estimates and dependencies.',
|
|
241
|
-
inputSchema: DIR_SCHEMA,
|
|
242
|
-
},
|
|
243
|
-
{
|
|
244
|
-
name: 'verify_remediation',
|
|
245
|
-
description: 'Compare before/after scan results. Run scan, apply fixes, then run this to see what improved.',
|
|
246
|
-
inputSchema: { type: 'object', properties: { dir: DIR_SCHEMA.properties.dir, baselineHash: { type: 'string' } }, required: [] },
|
|
247
|
-
},
|
|
248
|
-
{
|
|
249
|
-
name: 'secure_prompt',
|
|
250
|
-
description: 'Analyze an AI prompt for security risks BEFORE code is generated. Catches injection, insecure requests, missing constraints.',
|
|
251
|
-
inputSchema: { type: 'object', properties: { prompt: { type: 'string' } }, required: ['prompt'] },
|
|
252
|
-
},
|
|
253
|
-
{
|
|
254
|
-
name: 'scan_hallucinated_packages',
|
|
255
|
-
description: 'Check if packages referenced in source code actually exist on npm (anti-slopsquat).',
|
|
256
|
-
inputSchema: DIR_SCHEMA,
|
|
257
|
-
},
|
|
258
|
-
{
|
|
259
|
-
name: 'redact_pii',
|
|
260
|
-
description: 'Redact personal/sensitive data (emails, SSNs, credit cards, phone numbers, AWS keys, JWTs, IPs, IBANs, private keys) from text. Call this BEFORE sending user text to another model, tool, log, or external service. Returns scrubbed text. 100% local, zero network.',
|
|
261
|
-
inputSchema: { type: 'object', properties: { text: { type: 'string', description: 'The text to scrub.' }, types: { type: 'array', items: { type: 'string' }, description: 'Optional: only redact these entity types.' } }, required: ['text'] },
|
|
262
|
-
},
|
|
263
|
-
{
|
|
264
|
-
name: 'detect_pii',
|
|
265
|
-
description: 'Detect (without redacting) personal/sensitive data in text. Returns entity types, counts, and offsets so you can decide whether text is safe to send onward.',
|
|
266
|
-
inputSchema: { type: 'object', properties: { text: { type: 'string', description: 'The text to inspect.' }, types: { type: 'array', items: { type: 'string' }, description: 'Optional: only look for these entity types.' } }, required: ['text'] },
|
|
267
|
-
},
|
|
268
|
-
{
|
|
269
|
-
name: 'trace_prompt',
|
|
270
|
-
description: 'Trace findings back to AI prompts that generated them. Reads Cursor/Claude session history.',
|
|
271
|
-
inputSchema: DIR_SCHEMA,
|
|
272
|
-
},
|
|
273
|
-
{
|
|
274
|
-
name: 'list_rules',
|
|
275
|
-
description: 'List all VibeGuard rules with their ID, severity, category, and description.',
|
|
276
|
-
inputSchema: { type: 'object', properties: { category: { type: 'string' } }, required: [] },
|
|
277
|
-
},
|
|
278
|
-
{
|
|
279
|
-
name: 'cve_intel',
|
|
280
|
-
description: 'Query OSV.dev for known vulnerabilities in dependencies. Returns CVE IDs and fix versions.',
|
|
281
|
-
inputSchema: DIR_SCHEMA,
|
|
282
|
-
},
|
|
283
|
-
{
|
|
284
|
-
name: 'generate_html_report',
|
|
285
|
-
description: 'Generate a self-contained HTML security report with findings, grade, and charts.',
|
|
286
|
-
inputSchema: DIR_SCHEMA,
|
|
287
|
-
},
|
|
288
|
-
{
|
|
289
|
-
name: 'risk_score',
|
|
290
|
-
description: 'Calculate a weighted risk score (0-100) with risk level and top 5 risks. Faster than full scan for quick posture checks.',
|
|
291
|
-
inputSchema: DIR_SCHEMA,
|
|
292
|
-
},
|
|
293
|
-
{
|
|
294
|
-
name: 'batch_fix',
|
|
295
|
-
description: 'Auto-fix all fixable issues in one pass. Snapshots before applying. Returns list of applied fixes.',
|
|
296
|
-
inputSchema: DIR_SCHEMA,
|
|
297
|
-
},
|
|
298
|
-
{
|
|
299
|
-
name: 'ignore_rule',
|
|
300
|
-
description: 'Add a rule to the ignore list in .vibeguardrc.json. Suppresses false positives.',
|
|
301
|
-
inputSchema: {
|
|
302
|
-
type: 'object',
|
|
303
|
-
properties: {
|
|
304
|
-
ruleId: { type: 'string', description: 'The rule ID to ignore (e.g. "secret.openai-key")' },
|
|
305
|
-
dir: { type: 'string', description: 'Project directory. Defaults to cwd.' },
|
|
306
|
-
},
|
|
307
|
-
required: ['ruleId'],
|
|
308
|
-
},
|
|
309
|
-
},
|
|
310
|
-
{
|
|
311
|
-
name: 'baseline',
|
|
312
|
-
description: 'Save current findings as a baseline (.vibeguard-baseline.json) for trend tracking. Compare future scans against this.',
|
|
313
|
-
inputSchema: DIR_SCHEMA,
|
|
314
|
-
},
|
|
315
|
-
{
|
|
316
|
-
name: 'rule_info',
|
|
317
|
-
description: 'Get detailed info about a specific rule: severity, confidence, CWE, OWASP, auto-fixability, and remediation guidance.',
|
|
318
|
-
inputSchema: {
|
|
319
|
-
type: 'object',
|
|
320
|
-
properties: {
|
|
321
|
-
ruleId: { type: 'string', description: 'The rule ID to query (e.g. "secret.openai-key")' },
|
|
322
|
-
},
|
|
323
|
-
required: ['ruleId'],
|
|
324
|
-
},
|
|
325
|
-
},
|
|
326
|
-
{
|
|
327
|
-
name: 'severity_matrix',
|
|
328
|
-
description: 'Show a severity-by-category matrix showing where risks cluster. Useful for prioritizing remediation.',
|
|
329
|
-
inputSchema: DIR_SCHEMA,
|
|
330
|
-
},
|
|
331
|
-
{
|
|
332
|
-
name: 'dependency_tree',
|
|
333
|
-
description: 'Analyze package-lock.json: list all dependencies, integrity hash coverage, and dev vs prod split.',
|
|
334
|
-
inputSchema: DIR_SCHEMA,
|
|
335
|
-
},
|
|
336
|
-
{
|
|
337
|
-
name: 'config_dump',
|
|
338
|
-
description: 'Dump all VibeGuard configuration: .vibeguardrc.json, MCP install status, hook status, baseline status.',
|
|
339
|
-
inputSchema: DIR_SCHEMA,
|
|
340
|
-
},
|
|
341
|
-
{
|
|
342
|
-
name: 'trend_report',
|
|
343
|
-
description: 'Compare current scan against saved baseline. Shows resolved, new, and persisted findings. Tracks security posture over time.',
|
|
344
|
-
inputSchema: DIR_SCHEMA,
|
|
345
|
-
},
|
|
346
|
-
{
|
|
347
|
-
name: 'security_scorecard',
|
|
348
|
-
description: 'Generate a comprehensive security scorecard with grade, risk score, compliance posture, top risks, and remediation priority. JSON output for CI/CD.',
|
|
349
|
-
inputSchema: DIR_SCHEMA,
|
|
350
|
-
},
|
|
351
|
-
{
|
|
352
|
-
name: 'pr_comment',
|
|
353
|
-
description: 'Generate a GitHub PR comment in markdown format with security findings summary, grade emoji, and top findings table. Paste directly into PR reviews.',
|
|
354
|
-
inputSchema: DIR_SCHEMA,
|
|
355
|
-
},
|
|
356
|
-
{
|
|
357
|
-
name: 'slack_notify',
|
|
358
|
-
description: 'Generate a Slack-formatted security alert message with color-coded attachment, grade, and critical findings. For Slack webhook integration.',
|
|
359
|
-
inputSchema: DIR_SCHEMA,
|
|
360
|
-
},
|
|
361
|
-
{
|
|
362
|
-
name: 'preset_apply',
|
|
363
|
-
description: 'Apply a rule pack preset for your tech stack (nextjs, django, rails, spring, aws, gcp, azure, api, mobile, fullstack). Reduces noise by enabling only relevant rules.',
|
|
364
|
-
inputSchema: {
|
|
365
|
-
type: 'object',
|
|
366
|
-
properties: {
|
|
367
|
-
preset: { type: 'string', description: 'Preset name: nextjs, django, rails, spring, aws, gcp, azure, api, mobile, fullstack' },
|
|
368
|
-
dir: { type: 'string', description: 'Project directory. Defaults to cwd.' },
|
|
369
|
-
},
|
|
370
|
-
required: ['preset'],
|
|
371
|
-
},
|
|
372
|
-
},
|
|
373
|
-
{
|
|
374
|
-
name: 'interactive_dashboard',
|
|
375
|
-
description: 'Generate a beautiful terminal dashboard with ASCII art grade meter, severity bars, risk gauge, category matrix, and top findings. For CLI display.',
|
|
376
|
-
inputSchema: DIR_SCHEMA,
|
|
377
|
-
},
|
|
378
|
-
{
|
|
379
|
-
name: 'privacy_audit',
|
|
380
|
-
description: 'Inventory all PII collection, storage, and transmission in the codebase. Shows what personal data is collected, where it is stored, where it is sent, and what consent/encryption/retention mechanisms exist. GDPR/CCPA compliance check.',
|
|
381
|
-
inputSchema: DIR_SCHEMA,
|
|
382
|
-
},
|
|
383
|
-
{
|
|
384
|
-
name: 'network_audit',
|
|
385
|
-
description: 'Map every outbound HTTP/HTTPS call in the codebase. Shows all external endpoints, flags unknown/suspicious domains. Privacy: shows exactly where your data goes.',
|
|
386
|
-
inputSchema: DIR_SCHEMA,
|
|
387
|
-
},
|
|
388
|
-
{
|
|
389
|
-
name: 'ai_data_guard',
|
|
390
|
-
description: 'Detect user data (PII, secrets) sent to AI/LLM APIs without redaction. Catches the #1 privacy risk with AI agents: user data leaking to OpenAI/Anthropic/Gemini as part of prompts.',
|
|
391
|
-
inputSchema: DIR_SCHEMA,
|
|
392
|
-
},
|
|
393
|
-
{
|
|
394
|
-
name: 'generate_privacy_policy',
|
|
395
|
-
description: 'Auto-generate a privacy policy (markdown) from code analysis. Detects what PII is collected, where it is stored, what third-party services are used, and what consent/encryption/retention mechanisms exist. GDPR/CCPA ready. Must be reviewed by legal before publication.',
|
|
396
|
-
inputSchema: DIR_SCHEMA,
|
|
397
|
-
},
|
|
398
|
-
{
|
|
399
|
-
name: 'generate_csp',
|
|
400
|
-
description: 'Auto-generate a Content-Security-Policy header from code analysis. Scans HTML/JS files for external script/style/image sources and builds a CSP with only the domains your code actually uses. Returns CSP header value and Helmet config.',
|
|
401
|
-
inputSchema: DIR_SCHEMA,
|
|
402
|
-
},
|
|
403
|
-
{
|
|
404
|
-
name: 'generate_sbom',
|
|
405
|
-
description: 'Generate a CycloneDX 1.5 Software Bill of Materials (SBOM) from package-lock.json + source import graph. Lists all dependencies with versions, licenses, hashes, and which are actually imported in the code. 100% local.',
|
|
406
|
-
inputSchema: DIR_SCHEMA,
|
|
407
|
-
},
|
|
408
|
-
{
|
|
409
|
-
name: 'dep_reachability',
|
|
410
|
-
description: 'Cross-reference CVE results against the actual import graph — determines whether a vulnerable dependency is actually reachable in the code, not just listed in node_modules. Filters noise from transitive-only vulns.',
|
|
411
|
-
inputSchema: DIR_SCHEMA,
|
|
412
|
-
},
|
|
413
|
-
{
|
|
414
|
-
name: 'scan_container_image',
|
|
415
|
-
description: 'Scan a container image for vulnerabilities using trivy (if installed). Returns parsed findings (CVEs, secrets, misconfig). Gracefully reports if trivy is not available.',
|
|
416
|
-
inputSchema: {
|
|
417
|
-
type: 'object',
|
|
418
|
-
properties: {
|
|
419
|
-
image: { type: 'string', description: 'Container image name (e.g., myapp:latest).' },
|
|
420
|
-
},
|
|
421
|
-
required: ['image'],
|
|
422
|
-
},
|
|
423
|
-
},
|
|
424
|
-
{
|
|
425
|
-
name: 'license_compliance',
|
|
426
|
-
description: 'Check package.json licenses against an allowlist. Flags GPL/AGPL/unlicensed/unknown packages that may violate your license policy. Returns compliant + non-compliant lists.',
|
|
427
|
-
inputSchema: DIR_SCHEMA,
|
|
428
|
-
},
|
|
429
|
-
{
|
|
430
|
-
name: 'ai_firewall',
|
|
431
|
-
description: 'AI Firewall — inspect a prompt BEFORE sending to an LLM. Blocks prompt injection, jailbreaks, secret access requests, data exfiltration, and redacts PII. Returns verdict (block/redact/warn/allow) with threat details.',
|
|
432
|
-
inputSchema: {
|
|
433
|
-
type: 'object',
|
|
434
|
-
properties: {
|
|
435
|
-
prompt: { type: 'string', description: 'The prompt to inspect before sending to the LLM.' },
|
|
436
|
-
},
|
|
437
|
-
required: ['prompt'],
|
|
438
|
-
},
|
|
439
|
-
},
|
|
440
|
-
{
|
|
441
|
-
name: 'agent_guard',
|
|
442
|
-
description: 'Check if an AI agent action is safe. Validates file access (blocks .env, secrets, .ssh), command execution (blocks rm -rf, sudo), and network access (blocks metadata services, internal IPs). Returns allowed/blocked with violations.',
|
|
443
|
-
inputSchema: {
|
|
444
|
-
type: 'object',
|
|
445
|
-
properties: {
|
|
446
|
-
type: { type: 'string', description: 'Action type: file_read, file_write, file_delete, exec, network' },
|
|
447
|
-
path: { type: 'string', description: 'File path (for file operations)' },
|
|
448
|
-
command: { type: 'string', description: 'Command to execute (for exec)' },
|
|
449
|
-
url: { type: 'string', description: 'URL to access (for network)' },
|
|
450
|
-
},
|
|
451
|
-
required: ['type'],
|
|
452
|
-
},
|
|
453
|
-
},
|
|
454
|
-
{
|
|
455
|
-
name: 'exfil_check',
|
|
456
|
-
description: 'Exfiltration Firewall — check if data contains PII or secrets before sending it externally. Blocks if credit cards, API keys, SSNs, or private keys are detected. Returns sanitized data if PII found.',
|
|
457
|
-
inputSchema: {
|
|
458
|
-
type: 'object',
|
|
459
|
-
properties: {
|
|
460
|
-
data: { type: 'string', description: 'The data to check before sending externally.' },
|
|
461
|
-
destination: { type: 'string', description: 'Where the data is being sent (URL or service).' },
|
|
462
|
-
},
|
|
463
|
-
required: ['data'],
|
|
464
|
-
},
|
|
465
|
-
},
|
|
466
|
-
{
|
|
467
|
-
name: 'dep_firewall',
|
|
468
|
-
description: 'Dependency Firewall — check a package name before npm/pip install. Detects malicious package names, typosquats, and suspicious patterns. Run BEFORE installing any package.',
|
|
469
|
-
inputSchema: {
|
|
470
|
-
type: 'object',
|
|
471
|
-
properties: {
|
|
472
|
-
package: { type: 'string', description: 'Package name to check (e.g. "lodash", "reactt")' },
|
|
473
|
-
},
|
|
474
|
-
required: ['package'],
|
|
475
|
-
},
|
|
476
|
-
},
|
|
477
|
-
{
|
|
478
|
-
name: 'threat_model',
|
|
479
|
-
description: 'Generate a threat model for the project. Identifies attack surfaces, threat actors, attack vectors, and mitigation recommendations based on code analysis.',
|
|
480
|
-
inputSchema: DIR_SCHEMA,
|
|
481
|
-
},
|
|
482
|
-
{
|
|
483
|
-
name: 'output_guard',
|
|
484
|
-
description: 'Sanitize an AI response for PII and secrets BEFORE showing it to the user. Catches secrets, API keys, PII, env var dumps, and sensitive file paths that leak into AI output.',
|
|
485
|
-
inputSchema: {
|
|
486
|
-
type: 'object',
|
|
487
|
-
properties: {
|
|
488
|
-
response: { type: 'string', description: 'The AI response text to sanitize.' },
|
|
489
|
-
},
|
|
490
|
-
required: ['response'],
|
|
491
|
-
},
|
|
492
|
-
},
|
|
493
|
-
{
|
|
494
|
-
name: 'env_lock',
|
|
495
|
-
description: 'Lock environment variables — hide all secrets (API keys, tokens, passwords) from the AI. Returns list of protected variables. Hides values at the Node.js runtime level so they do not appear in process.env reads within the same process. Raises the bar for accidental and adversarial exfil — not a hard sandbox against arbitrary native code execution.',
|
|
496
|
-
inputSchema: { type: 'object', properties: {} },
|
|
497
|
-
},
|
|
498
|
-
{
|
|
499
|
-
name: 'self_check',
|
|
500
|
-
description: 'Check if VibeGuard itself has been tampered with. Verifies all modules are intact, rules are loaded, config is valid, and .env is in .gitignore. Run after any AI session.',
|
|
501
|
-
inputSchema: DIR_SCHEMA,
|
|
502
|
-
},
|
|
503
|
-
{
|
|
504
|
-
name: 'tamper_check',
|
|
505
|
-
description: 'Check if a prompt contains attempts to disable, bypass, or uninstall VibeGuard itself. Detects tampering patterns even in obfuscated or encoded prompts.',
|
|
506
|
-
inputSchema: {
|
|
507
|
-
type: 'object',
|
|
508
|
-
properties: {
|
|
509
|
-
prompt: { type: 'string', description: 'The prompt to check for tampering attempts.' },
|
|
510
|
-
},
|
|
511
|
-
required: ['prompt'],
|
|
512
|
-
},
|
|
513
|
-
},
|
|
514
|
-
{
|
|
515
|
-
name: 'sandbox_exec',
|
|
516
|
-
description: 'Execute AI-generated code in a locked-down sandbox. No process.env, no fs, no child_process, no network. Time-limited and memory-limited. Full audit log of every operation attempted. Best with isolated-vm installed for V8 isolate enforcement; Level 1 (vm only) is a raised floor, not a hard boundary.',
|
|
517
|
-
inputSchema: {
|
|
518
|
-
type: 'object',
|
|
519
|
-
properties: {
|
|
520
|
-
code: { type: 'string', description: 'The code to execute in sandbox.' },
|
|
521
|
-
timeout: { type: 'number', description: 'Execution timeout in ms (default: 5000).' },
|
|
522
|
-
},
|
|
523
|
-
required: ['code'],
|
|
524
|
-
},
|
|
525
|
-
},
|
|
526
|
-
{
|
|
527
|
-
name: 'behavior_analysis',
|
|
528
|
-
description: 'Analyze AI agent behavior patterns over a session. Detects trust-building, data gathering, slow exfiltration, privilege escalation, repeated blocks, tamper attempts, off-hours access, and rapid-fire patterns.',
|
|
529
|
-
inputSchema: DIR_SCHEMA,
|
|
530
|
-
},
|
|
531
|
-
{
|
|
532
|
-
name: 'supply_chain_audit',
|
|
533
|
-
description: 'Full supply chain audit: lockfile integrity, dangerous scripts, license risks, unpinned versions, non-registry sources. Run before npm install.',
|
|
534
|
-
inputSchema: DIR_SCHEMA,
|
|
535
|
-
},
|
|
536
|
-
{
|
|
537
|
-
name: 'vault_manage',
|
|
538
|
-
description: 'Encrypted in-memory secret vault. Store secrets encrypted — AI cannot read them via process.env. Use vault instead of env vars for maximum security.',
|
|
539
|
-
inputSchema: {
|
|
540
|
-
type: 'object',
|
|
541
|
-
properties: {
|
|
542
|
-
action: { type: 'string', enum: ['list', 'store', 'get', 'clear'], description: 'Vault action' },
|
|
543
|
-
key: { type: 'string', description: 'Secret key (for store/get)' },
|
|
544
|
-
value: { type: 'string', description: 'Secret value (for store)' },
|
|
545
|
-
},
|
|
546
|
-
required: ['action'],
|
|
547
|
-
},
|
|
548
|
-
},
|
|
549
|
-
{
|
|
550
|
-
name: 'audit_log',
|
|
551
|
-
description: 'Tamper-proof audit trail of every AI action, blocked attempt, and secret access. Uses chained SHA-256 hashes. Export, verify, or show the log.',
|
|
552
|
-
inputSchema: {
|
|
553
|
-
type: 'object',
|
|
554
|
-
properties: {
|
|
555
|
-
action: { type: 'string', enum: ['show', 'export', 'verify', 'log'], description: 'Audit action' },
|
|
556
|
-
type: { type: 'string', description: 'Filter by entry type (blocked, tamper, etc.)' },
|
|
557
|
-
limit: { type: 'number', description: 'Limit number of entries' },
|
|
558
|
-
},
|
|
559
|
-
},
|
|
560
|
-
},
|
|
561
|
-
{
|
|
562
|
-
name: 'pre_deploy',
|
|
563
|
-
description: 'Run ALL 13 security gates before deployment. If ANY gate fails, deployment is blocked. Gates: static scan, secrets, git history, dependencies, supply chain, privacy, network, AI data guard, compliance, config, self-check, tamper check, behavioral check. Returns deploy-ready verdict.',
|
|
564
|
-
inputSchema: DIR_SCHEMA,
|
|
565
|
-
},
|
|
566
|
-
];
|
|
567
|
-
|
|
568
|
-
function summarize(result) {
|
|
569
|
-
const c = result.counts;
|
|
570
|
-
let s = `Grade ${result.grade} — ${c.critical} critical, ${c.high} high, ${c.medium} medium, ${c.low} low across ${result.scannedFiles} files.`;
|
|
571
|
-
if (result.engine && result.engine.mode === 'regex-only') {
|
|
572
|
-
s += ' ⚠ engine: regex-only (acorn not installed) — AST/taint precision disabled; do not treat as an all-clear.';
|
|
573
|
-
}
|
|
574
|
-
if (result.diagnostics && result.diagnostics.degradedFileCount > 0) {
|
|
575
|
-
s += ` ⚠ ${result.diagnostics.degradedFileCount} file(s) only partially analyzed (degraded coverage).`;
|
|
576
|
-
}
|
|
577
|
-
return s;
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
function textResult(text, isError) {
|
|
581
|
-
return { content: [{ type: 'text', text }], isError: !!isError };
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
async function handleScan(args) {
|
|
585
|
-
const dir = args.dir || process.cwd();
|
|
586
|
-
const result = scan(dir);
|
|
587
|
-
if (args.saveBaseline) writeBaseline(dir, result);
|
|
588
|
-
const payload = {
|
|
589
|
-
grade: result.grade,
|
|
590
|
-
counts: result.counts,
|
|
591
|
-
scannedFiles: result.scannedFiles,
|
|
592
|
-
// Coverage transparency: tell the agent whether the scan ran at full
|
|
593
|
-
// precision and whether any file was only partially analyzed. An agent
|
|
594
|
-
// must not treat a degraded/regex-only scan as an all-clear.
|
|
595
|
-
engine: result.engine,
|
|
596
|
-
diagnostics: result.diagnostics && {
|
|
597
|
-
degradedFileCount: result.diagnostics.degradedFileCount,
|
|
598
|
-
parseFailedFiles: result.diagnostics.parseFailedFiles,
|
|
599
|
-
},
|
|
600
|
-
findings: result.findings.map((f) => ({
|
|
601
|
-
severity: f.severity,
|
|
602
|
-
ruleId: f.ruleId,
|
|
603
|
-
file: f.file,
|
|
604
|
-
line: f.line,
|
|
605
|
-
message: f.message,
|
|
606
|
-
fix: f.fix,
|
|
607
|
-
})),
|
|
608
|
-
};
|
|
609
|
-
return textResult(
|
|
610
|
-
summarize(result) + '\n\n' + JSON.stringify(payload, null, 2)
|
|
611
|
-
);
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
async function handleSuggest(args) {
|
|
615
|
-
const dir = args.dir || process.cwd();
|
|
616
|
-
const result = scan(dir);
|
|
617
|
-
if (result.findings.length === 0) {
|
|
618
|
-
return textResult('No issues found — nothing to fix.');
|
|
619
|
-
}
|
|
620
|
-
return textResult(
|
|
621
|
-
summarize(result) +
|
|
622
|
-
'\n\nApply these fixes under review (VibeGuard does not edit files):\n\n' +
|
|
623
|
-
renderFixPrompt(result)
|
|
624
|
-
);
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
async function handleVerify(args) {
|
|
628
|
-
const dir = args.dir || process.cwd();
|
|
629
|
-
const res = verify(dir);
|
|
630
|
-
if (!res.hasBaseline) {
|
|
631
|
-
return textResult(
|
|
632
|
-
'No baseline found. Run scan_project with saveBaseline=true before fixing to enable a before/after diff.\n\n' +
|
|
633
|
-
summarize(res.current)
|
|
634
|
-
);
|
|
635
|
-
}
|
|
636
|
-
const lines = [];
|
|
637
|
-
lines.push(
|
|
638
|
-
`${res.resolved.length} resolved, ${res.remaining.length} remaining, ${res.introduced.length} new. Current ${summarize(res.current)}`
|
|
639
|
-
);
|
|
640
|
-
lines.push('');
|
|
641
|
-
for (const f of res.resolved) lines.push(`RESOLVED ${f.file}:${f.line} [${f.ruleId}]`);
|
|
642
|
-
for (const f of res.remaining) lines.push(`REMAINING ${f.file}:${f.line} [${f.ruleId}]`);
|
|
643
|
-
for (const f of res.introduced) lines.push(`NEW ${f.file}:${f.line} [${f.ruleId}]`);
|
|
644
|
-
return textResult(lines.join('\n'));
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
const HOTSPOT_RE = /(auth|login|signin|signup|register|password|session|token|jwt|payment|billing|checkout|charge|invoice|admin|role|permission|acl|account|user|profile|order|route|controller|api|middleware|upload|webhook)/i;
|
|
648
|
-
|
|
649
|
-
async function handleReviewHotspots(args) {
|
|
650
|
-
const dir = args.dir || process.cwd();
|
|
651
|
-
const result = scan(dir);
|
|
652
|
-
|
|
653
|
-
// Hotspot files: those with heuristic/auth findings, plus files named like a
|
|
654
|
-
// security-sensitive area.
|
|
655
|
-
const fromFindings = new Set(
|
|
656
|
-
result.findings
|
|
657
|
-
.filter((f) => /^(auth|idor|backdoor|upload|ratelimit|taint|web|supabase)\./.test(f.ruleId))
|
|
658
|
-
.map((f) => f.file)
|
|
659
|
-
);
|
|
660
|
-
const hotspots = new Set(fromFindings);
|
|
661
|
-
for (const f of result.findings) if (HOTSPOT_RE.test(f.file)) hotspots.add(f.file);
|
|
662
|
-
|
|
663
|
-
const reviewList = result.findings
|
|
664
|
-
.filter((f) => f.confidence !== 'high')
|
|
665
|
-
.map((f) => `- ${f.file}:${f.line} [${f.ruleId}] ${f.message}`)
|
|
666
|
-
.slice(0, 40);
|
|
667
|
-
|
|
668
|
-
const checklist = [
|
|
669
|
-
'For EACH mutating route/endpoint: is there an authentication AND an authorization check? Who can call it?',
|
|
670
|
-
'For EACH data read/write using an id from the request: is ownership verified (record belongs to req.user)? (IDOR)',
|
|
671
|
-
'Payments/amounts/quantities: can the client tamper with price, total, currency, or quantity? Is the amount re-derived server-side?',
|
|
672
|
-
'Any hardcoded credential comparison, magic token, or `if (user === "admin")` style bypass? (backdoor)',
|
|
673
|
-
'Is input validated (type, range, length) before use? Any mass-assignment (spreading req.body into a model)?',
|
|
674
|
-
'Access control: are admin-only actions actually gated, or only hidden in the UI?',
|
|
675
|
-
'Secrets/config: anything sensitive logged, returned in a response, or sent to the client?',
|
|
676
|
-
'State-changing GETs / missing CSRF protection on cookie-authenticated mutations?',
|
|
677
|
-
];
|
|
678
|
-
|
|
679
|
-
const text =
|
|
680
|
-
summarize(result) +
|
|
681
|
-
`\n\nHOTSPOT FILES to review manually (regex cannot judge logic/authz):\n` +
|
|
682
|
-
(hotspots.size ? [...hotspots].map((f) => `- ${f}`).join('\n') : '- (none obvious; review routes and data-access code)') +
|
|
683
|
-
`\n\nVibeGuard "review" findings (low/medium confidence — verify each):\n` +
|
|
684
|
-
(reviewList.length ? reviewList.join('\n') : '- none') +
|
|
685
|
-
`\n\nNOW DO A SEMANTIC REVIEW. Open the hotspot files and answer this checklist per file:\n` +
|
|
686
|
-
checklist.map((c, i) => `${i + 1}. ${c}`).join('\n') +
|
|
687
|
-
`\n\nReport concrete issues with file:line and a fix. Be honest about what you could not verify.`;
|
|
688
|
-
|
|
689
|
-
return textResult(text);
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
async function handleGuardAction(args) {
|
|
693
|
-
const { inspectAction } = require('./action-guard');
|
|
694
|
-
const verdict = inspectAction(args, { trustedHosts: args.trustedHosts });
|
|
695
|
-
const head = verdict.blocked
|
|
696
|
-
? `🛑 BLOCKED — ${verdict.reason}`
|
|
697
|
-
: verdict.action === 'warn'
|
|
698
|
-
? `⚠ WARN — ${verdict.reason}`
|
|
699
|
-
: '✓ ALLOW — no secret/PII exfiltration or dangerous action detected.';
|
|
700
|
-
return textResult(head + '\n\n' + JSON.stringify(verdict, null, 2));
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
async function handleAgentScan(args) {
|
|
704
|
-
const dir = args.dir || process.cwd();
|
|
705
|
-
const { agentScan } = require('./agent-scan');
|
|
706
|
-
const result = agentScan(dir);
|
|
707
|
-
const cats = Object.entries(result.categories)
|
|
708
|
-
.map(([k, v]) => `${k}=${v.length}`).join(', ');
|
|
709
|
-
const summary = `Agent Risk Grade ${result.grade} — ${result.counts.critical} critical, ${result.counts.high} high, ${result.counts.medium} medium across ${result.mcpServers} MCP server(s) and ${result.scannedFiles} files.` +
|
|
710
|
-
(cats ? ` [${cats}]` : '') +
|
|
711
|
-
(result.mcpDrifted && result.mcpDrifted.length ? ` ⚠ MCP drift: ${result.mcpDrifted.join(', ')}.` : '');
|
|
712
|
-
return textResult(summary + '\n\n' + JSON.stringify(result, null, 2));
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
async function handleMcpAudit(args) {
|
|
716
|
-
const dir = args.dir || process.cwd();
|
|
717
|
-
const { auditMcp } = require('./mcp-audit');
|
|
718
|
-
const result = auditMcp(dir, { pin: !!args.pin });
|
|
719
|
-
if (!result.configFound) {
|
|
720
|
-
return textResult('No MCP config found (.mcp.json / .cursor/mcp.json / .vscode/mcp.json).');
|
|
721
|
-
}
|
|
722
|
-
const c = result.counts;
|
|
723
|
-
const summary = `MCP audit: ${result.servers.length} server(s), ${c.critical} critical, ${c.high} high, ${c.medium} medium.` +
|
|
724
|
-
(result.drifted.length ? ` ⚠ definition drift on: ${result.drifted.join(', ')} (rug-pull risk — re-review).` : '');
|
|
725
|
-
return textResult(summary + '\n\n' + JSON.stringify(result, null, 2));
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
async function handleScanUrl(args) {
|
|
729
|
-
if (!args.url) return textResult('scan_url requires a "url" argument.', true);
|
|
730
|
-
let res;
|
|
731
|
-
try {
|
|
732
|
-
res = await scanUrl(args.url);
|
|
733
|
-
} catch (err) {
|
|
734
|
-
return textResult(`Could not scan URL: ${err && err.message ? err.message : err}`, true);
|
|
735
|
-
}
|
|
736
|
-
const findings = sortFindings(res.findings);
|
|
737
|
-
const { grade, counts } = computeGrade(findings);
|
|
738
|
-
const payload = {
|
|
739
|
-
url: res.url,
|
|
740
|
-
status: res.status,
|
|
741
|
-
grade,
|
|
742
|
-
counts,
|
|
743
|
-
findings: findings.map((f) => ({
|
|
744
|
-
severity: f.severity,
|
|
745
|
-
ruleId: f.ruleId,
|
|
746
|
-
message: f.message,
|
|
747
|
-
fix: f.fix,
|
|
748
|
-
})),
|
|
749
|
-
};
|
|
750
|
-
return textResult(
|
|
751
|
-
`${res.url} (HTTP ${res.status}) — grade ${grade}, ${counts.critical} critical, ${counts.high} high, ${counts.medium} medium, ${counts.low} low.\n\n` +
|
|
752
|
-
JSON.stringify(payload, null, 2)
|
|
753
|
-
);
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
// ---------------------------------------------------------------------------
|
|
757
|
-
// NEW TOOL HANDLERS (34 tools)
|
|
758
|
-
// ---------------------------------------------------------------------------
|
|
759
|
-
|
|
760
|
-
const { execSync } = require('child_process');
|
|
761
|
-
const { renderSarif, renderHtml } = require('./report');
|
|
762
|
-
const { allRules: getAllRules } = require('./rules');
|
|
763
|
-
const { suggestFixes: autoFix } = require('./autofix');
|
|
764
|
-
|
|
765
|
-
async function handleCheckCode(args) {
|
|
766
|
-
const code = args.code || '';
|
|
767
|
-
const lang = args.language || 'js';
|
|
768
|
-
const fakePath = `snippet.${lang}`;
|
|
769
|
-
const { scanFileContent } = require('./scanner');
|
|
770
|
-
const findings = scanFileContent(fakePath, fakePath, code, null);
|
|
771
|
-
if (findings.length === 0) return textResult('No issues found in the code snippet.');
|
|
772
|
-
return textResult(JSON.stringify(findings.map(f => ({ ruleId: f.ruleId, severity: f.severity, line: f.line, message: f.message, fix: f.fix })), null, 2));
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
async function handleScanStaged(args) {
|
|
776
|
-
const dir = args.dir || process.cwd();
|
|
777
|
-
let staged;
|
|
778
|
-
try { staged = execSync('git diff --cached --name-only --diff-filter=ACM', { cwd: dir, encoding: 'utf8' }).trim().split('\n').filter(Boolean); }
|
|
779
|
-
catch { return textResult('Not a git repo or no staged changes.'); }
|
|
780
|
-
if (staged.length === 0) return textResult('No staged files to scan.');
|
|
781
|
-
const { scan } = require('./scanner');
|
|
782
|
-
const all = scan(dir);
|
|
783
|
-
const stagedSet = new Set(staged);
|
|
784
|
-
const stagedFindings = all.findings.filter(f => stagedSet.has(f.file));
|
|
785
|
-
return textResult(`${stagedFindings.length} findings in ${staged.length} staged files.\n\n` + JSON.stringify(stagedFindings.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId, severity: f.severity, message: f.message, fix: f.fix })), null, 2));
|
|
786
|
-
}
|
|
787
|
-
|
|
788
|
-
async function handleScanDeps(args) {
|
|
789
|
-
const dir = args.dir || process.cwd();
|
|
790
|
-
const { scanCVEs } = require('./cve-intel');
|
|
791
|
-
const result = await scanCVEs(dir);
|
|
792
|
-
return textResult(`Checked ${result.checked} packages. ${result.findings.length} vulnerabilities found.\n\n` + JSON.stringify(result.findings, null, 2));
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
async function handleScanSecrets(args) {
|
|
796
|
-
const dir = args.dir || process.cwd();
|
|
797
|
-
const result = scan(dir);
|
|
798
|
-
const secrets = result.findings.filter(f => f.ruleId.startsWith('secret.') || f.ruleId.startsWith('keys.'));
|
|
799
|
-
return textResult(`${secrets.length} secret findings.\n\n` + JSON.stringify(secrets.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId, severity: f.severity, message: f.message })), null, 2));
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
async function handleSlopsquat(args) {
|
|
803
|
-
const dir = args.dir || process.cwd();
|
|
804
|
-
const { walk } = require('./scanner');
|
|
805
|
-
const files = walk(dir, []);
|
|
806
|
-
const { scanSlopsquat } = require('./slopsquat');
|
|
807
|
-
const result = await scanSlopsquat(dir, files);
|
|
808
|
-
return textResult(`Checked ${result.checked} imports. ${result.findings.length} suspicious packages.\n\n` + JSON.stringify(result.findings.map(f => ({ ruleId: f.ruleId, title: f.title, message: f.message, fix: f.fix })), null, 2));
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
async function handleCompliance(args) {
|
|
812
|
-
const dir = args.dir || process.cwd();
|
|
813
|
-
const result = scan(dir);
|
|
814
|
-
const { generateComplianceReport } = require('./compliance');
|
|
815
|
-
const report = generateComplianceReport(result.findings, args.framework);
|
|
816
|
-
return textResult(JSON.stringify(report, null, 2));
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
async function handleSarif(args) {
|
|
820
|
-
const dir = args.dir || process.cwd();
|
|
821
|
-
const result = scan(dir);
|
|
822
|
-
const sarif = renderSarif(result);
|
|
823
|
-
return textResult(JSON.stringify(sarif, null, 2));
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
async function handleFixCode(args) {
|
|
827
|
-
const dir = args.dir || process.cwd();
|
|
828
|
-
const result = scan(dir);
|
|
829
|
-
if (result.findings.length === 0) return textResult('No issues to fix.');
|
|
830
|
-
const { computeAutoFixes } = require('./autofix');
|
|
831
|
-
const autoChanges = computeAutoFixes(dir, result);
|
|
832
|
-
const autoFileSet = new Set(autoChanges.map(c => c.file));
|
|
833
|
-
const patches = result.findings.map(f => {
|
|
834
|
-
const isAuto = autoFileSet.has(f.file) || (f.fix && /process\.env|console\.error|vibeguard:/.test(f.fix));
|
|
835
|
-
return {
|
|
836
|
-
file: f.file,
|
|
837
|
-
line: f.line,
|
|
838
|
-
ruleId: f.ruleId,
|
|
839
|
-
severity: f.severity,
|
|
840
|
-
type: isAuto ? 'exactEdit' : 'manualFix',
|
|
841
|
-
fix: f.fix || 'No automated fix available — manual review required.',
|
|
842
|
-
verify: `vibeguard verify --baseline ${f.fingerprint || ''}`,
|
|
843
|
-
};
|
|
844
|
-
});
|
|
845
|
-
return textResult(JSON.stringify({
|
|
846
|
-
agent: 'vibeguard.v1',
|
|
847
|
-
summary: summarize(result),
|
|
848
|
-
patches,
|
|
849
|
-
verify: 'After applying, run: vibeguard verify',
|
|
850
|
-
}, null, 2));
|
|
851
|
-
}
|
|
852
|
-
|
|
853
|
-
async function handleSecureThis(args) {
|
|
854
|
-
const dir = args.dir || process.cwd();
|
|
855
|
-
const result = scan(dir);
|
|
856
|
-
const plan = {
|
|
857
|
-
step1_scan: summarize(result),
|
|
858
|
-
step2_fixes: renderFixPrompt(result),
|
|
859
|
-
step3_verify: 'After applying fixes, run: vibeguard verify — it will compare against the baseline and report resolved/remaining/new.',
|
|
860
|
-
step4_rollback: 'If verify introduces new issues, run: vibeguard rollback to restore the pre-fix state.',
|
|
861
|
-
};
|
|
862
|
-
return textResult(JSON.stringify(plan, null, 2));
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
async function handleAuditConfig(args) {
|
|
866
|
-
const dir = args.dir || process.cwd();
|
|
867
|
-
const result = scan(dir);
|
|
868
|
-
const configFindings = result.findings.filter(f =>
|
|
869
|
-
f.file && (f.file.includes('.env') || f.file.includes('next.config') || f.file.includes('docker-compose') || f.file.includes('Dockerfile') || f.file.includes('.github/workflows') || f.file.includes('vercel.json') || f.file.includes('netlify.toml') || f.file.includes('k8s') || f.file.includes('terraform'))
|
|
870
|
-
);
|
|
871
|
-
return textResult(`${configFindings.length} config issues.\n\n` + JSON.stringify(configFindings.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId, message: f.message, fix: f.fix })), null, 2));
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
async function handleGeneratePolicy(args) {
|
|
875
|
-
const type = args.type || 'csp';
|
|
876
|
-
const templates = {
|
|
877
|
-
csp: "Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{nonce}'; style-src 'self' 'nonce-${nonce}'; img-src 'self' data: https:; connect-src 'self'; font-src 'self'; object-src 'none'; frame-ancestors 'none';",
|
|
878
|
-
cors: "const allowedOrigins = ['https://yourdomain.com'];\napp.use(cors({ origin: (origin, cb) => { if (!origin || allowedOrigins.includes(origin)) cb(null, true); else cb(new Error('Not allowed by CORS')); }, credentials: true }));",
|
|
879
|
-
rls: "CREATE POLICY \"users_select_own\" ON users FOR SELECT USING (auth.uid() = id);\nCREATE POLICY \"users_update_own\" ON users FOR UPDATE USING (auth.uid() = id);\nCREATE POLICY \"users_delete_own\" ON users FOR DELETE USING (auth.uid() = id);",
|
|
880
|
-
'rate-limit': "const rateLimit = require('express-rate-limit');\napp.use('/api/', rateLimit({ windowMs: 15 * 60 * 1000, max: 100, standardHeaders: true, legacyHeaders: false }));",
|
|
881
|
-
};
|
|
882
|
-
return textResult(templates[type] || 'Unknown policy type.');
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
async function handleReviewPr(args) {
|
|
886
|
-
const dir = args.dir || process.cwd();
|
|
887
|
-
const base = args.base || 'main';
|
|
888
|
-
let diffFiles;
|
|
889
|
-
try { diffFiles = execSync(`git diff ${base} --name-only`, { cwd: dir, encoding: 'utf8' }).trim().split('\n').filter(Boolean); }
|
|
890
|
-
catch { return textResult('Not a git repo or no diff available.'); }
|
|
891
|
-
const result = scan(dir);
|
|
892
|
-
const diffSet = new Set(diffFiles);
|
|
893
|
-
const prFindings = result.findings.filter(f => diffSet.has(f.file));
|
|
894
|
-
return textResult(`${prFindings.length} findings in ${diffFiles.length} changed files.\n\n` + JSON.stringify(prFindings.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId, severity: f.severity, message: f.message, fix: f.fix })), null, 2));
|
|
895
|
-
}
|
|
896
|
-
|
|
897
|
-
async function handleScanHistory(args) {
|
|
898
|
-
const dir = args.dir || process.cwd();
|
|
899
|
-
const { scanHistory } = require('./history');
|
|
900
|
-
let res;
|
|
901
|
-
try { res = scanHistory(dir); }
|
|
902
|
-
catch { return textResult('Not a git repo or git history not available.'); }
|
|
903
|
-
const findings = Array.isArray(res) ? res : (res && res.findings) || [];
|
|
904
|
-
return textResult(`${findings.length} findings in git history.\n\n` + JSON.stringify(findings.map(f => ({ commit: f.commit, file: f.file, line: f.line, ruleId: f.ruleId, message: f.message })), null, 2));
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
async function handleAnalyzeDataflow(args) {
|
|
908
|
-
const fs = require('fs');
|
|
909
|
-
const path = require('path');
|
|
910
|
-
const file = args.file;
|
|
911
|
-
if (!file) return textResult('analyze_dataflow requires a "file" argument.', true);
|
|
912
|
-
const abs = path.resolve(file);
|
|
913
|
-
if (!fs.existsSync(abs)) return textResult(`File not found: ${abs}`, true);
|
|
914
|
-
const content = fs.readFileSync(abs, 'utf8');
|
|
915
|
-
const { scanFileContent } = require('./scanner');
|
|
916
|
-
const findings = scanFileContent(abs, path.basename(abs), content, null);
|
|
917
|
-
const taintFindings = findings.filter(f => f.ruleId.includes('taint') || f.ruleId.includes('injection') || f.ruleId.includes('eval') || f.ruleId.includes('exec'));
|
|
918
|
-
return textResult(`${taintFindings.length} taint/dataflow findings.\n\n` + JSON.stringify(taintFindings.map(f => ({ line: f.line, ruleId: f.ruleId, message: f.message, fix: f.fix })), null, 2));
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
async function handleCrossFileTaint(args) {
|
|
922
|
-
const dir = args.dir || process.cwd();
|
|
923
|
-
const { analyzeCrossFileTaint } = require('./crosstaint');
|
|
924
|
-
let findings;
|
|
925
|
-
try { findings = analyzeCrossFileTaint(dir); }
|
|
926
|
-
catch { return textResult('Cross-file taint analysis requires acorn (optional dependency).'); }
|
|
927
|
-
return textResult(`${findings.length} cross-file taint findings.\n\n` + JSON.stringify(findings.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId, message: f.message })), null, 2));
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
async function handleCheckCommand(args) {
|
|
931
|
-
const cmd = args.command || '';
|
|
932
|
-
const risks = [];
|
|
933
|
-
if (/\bcurl\b.*\|\s*(?:sh|bash)/i.test(cmd)) risks.push({ risk: 'critical', msg: 'Pipe to bash — arbitrary code execution' });
|
|
934
|
-
if (/chmod\s+777/i.test(cmd)) risks.push({ risk: 'low', msg: 'chmod 777 — world-writable' });
|
|
935
|
-
if (/rm\s+-rf?\s+(?:\/|~|\.\.\/\.\.)/i.test(cmd)) risks.push({ risk: 'high', msg: 'rm -rf on root/parent — filesystem destruction' });
|
|
936
|
-
if (/sudo\s+--?password/i.test(cmd)) risks.push({ risk: 'high', msg: 'sudo with password on command line' });
|
|
937
|
-
if (/\beval\b/i.test(cmd)) risks.push({ risk: 'high', msg: 'eval in command — code injection' });
|
|
938
|
-
if (risks.length === 0) return textResult('No security risks detected in the command.');
|
|
939
|
-
return textResult(JSON.stringify(risks, null, 2));
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
async function handleScanConfigChange(args) {
|
|
943
|
-
const dir = args.dir || process.cwd();
|
|
944
|
-
const result = scan(dir);
|
|
945
|
-
const configFindings = result.findings.filter(f => f.file && /\.(?:env|json|ya?ml|toml|ini|conf|config)$/i.test(f.file));
|
|
946
|
-
return textResult(`${configFindings.length} config-related findings.\n\n` + JSON.stringify(configFindings.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId, message: f.message })), null, 2));
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
async function handlePosture(args) {
|
|
950
|
-
const dir = args.dir || process.cwd();
|
|
951
|
-
const result = scan(dir);
|
|
952
|
-
const { walk } = require('./scanner');
|
|
953
|
-
const files = walk(dir, []);
|
|
954
|
-
const { buildAuthCoverage } = require('./engine');
|
|
955
|
-
const auth = buildAuthCoverage(dir, files);
|
|
956
|
-
return textResult(JSON.stringify({
|
|
957
|
-
grade: result.grade,
|
|
958
|
-
counts: result.counts,
|
|
959
|
-
scannedFiles: result.scannedFiles,
|
|
960
|
-
authCoverage: auth.coverage + '% (' + auth.protectedRoutes + '/' + auth.totalRoutes + ' routes protected)',
|
|
961
|
-
unprotectedRoutes: auth.unprotected.length,
|
|
962
|
-
topRiskyFiles: [...new Set(result.findings.map(f => f.file))].slice(0, 10),
|
|
963
|
-
ruleCoverage: allRules().length + ' rules active',
|
|
964
|
-
}, null, 2));
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
async function handleExplainRemediation(args) {
|
|
968
|
-
const ruleId = args.ruleId;
|
|
969
|
-
if (!ruleId) return textResult('explain_remediation requires a "ruleId" argument.', true);
|
|
970
|
-
const rule = allRules().find(r => r.id === ruleId);
|
|
971
|
-
if (!rule) return textResult(`Unknown rule: ${ruleId}`, true);
|
|
972
|
-
const { isAutoFixable } = require('./autofix');
|
|
973
|
-
const isFixable = isAutoFixable ? isAutoFixable(ruleId) : false;
|
|
974
|
-
return textResult(JSON.stringify({
|
|
975
|
-
id: rule.id,
|
|
976
|
-
severity: rule.severity,
|
|
977
|
-
confidence: rule.confidence,
|
|
978
|
-
title: rule.title,
|
|
979
|
-
message: rule.message,
|
|
980
|
-
fix: rule.fix,
|
|
981
|
-
owasp: rule.owasp,
|
|
982
|
-
cwe: rule.cwe,
|
|
983
|
-
autoFixable: isFixable,
|
|
984
|
-
fixContract: {
|
|
985
|
-
type: isFixable ? 'mechanical' : 'agentic',
|
|
986
|
-
description: isFixable
|
|
987
|
-
? 'VibeGuard can auto-fix this with `vibeguard fix --apply`.'
|
|
988
|
-
: 'This requires a semantic fix. Use the fix guidance above and apply via your AI client.',
|
|
989
|
-
constraint: 'The fix must not introduce new findings. Re-scan after applying to verify.',
|
|
990
|
-
reviewPrompt: `Fix ${rule.id} (${rule.severity}): ${rule.message}. Approach: ${rule.fix}. Verify the fix does not introduce new security issues.`,
|
|
991
|
-
},
|
|
992
|
-
}, null, 2));
|
|
993
|
-
}
|
|
994
|
-
|
|
995
|
-
async function handleScanFile(args) {
|
|
996
|
-
const fs = require('fs');
|
|
997
|
-
const path = require('path');
|
|
998
|
-
const file = args.file;
|
|
999
|
-
if (!file) return textResult('scan_file requires a "file" argument.', true);
|
|
1000
|
-
const abs = path.resolve(file);
|
|
1001
|
-
if (!fs.existsSync(abs)) return textResult(`File not found: ${abs}`, true);
|
|
1002
|
-
const content = fs.readFileSync(abs, 'utf8');
|
|
1003
|
-
const { scanFileContent } = require('./scanner');
|
|
1004
|
-
const findings = scanFileContent(abs, path.basename(abs), content, null);
|
|
1005
|
-
return textResult(`${findings.length} findings in ${path.basename(abs)}.\n\n` + JSON.stringify(findings.map(f => ({ line: f.line, ruleId: f.ruleId, severity: f.severity, message: f.message, fix: f.fix })), null, 2));
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1008
|
-
async function handleScanChanged(args) {
|
|
1009
|
-
const dir = args.dir || process.cwd();
|
|
1010
|
-
const { walk } = require('./scanner');
|
|
1011
|
-
const allFiles = walk(dir, []);
|
|
1012
|
-
const { getChangedFiles } = require('./engine');
|
|
1013
|
-
const { changed, total, cached } = getChangedFiles(dir, allFiles);
|
|
1014
|
-
if (changed.length === 0) return textResult(`No files changed since last scan. (${cached}/${total} cached)`);
|
|
1015
|
-
const result = scan(dir);
|
|
1016
|
-
const changedSet = new Set(changed.map(f => path.relative(dir, f)));
|
|
1017
|
-
const changedFindings = result.findings.filter(f => changedSet.has(f.file));
|
|
1018
|
-
return textResult(`${changedFindings.length} findings in ${changed.length} changed files (${cached}/${total} cached).\n\n` + JSON.stringify(changedFindings.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId, message: f.message })), null, 2));
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
async function handleStats(args) {
|
|
1022
|
-
const dir = args.dir || process.cwd();
|
|
1023
|
-
const result = scan(dir);
|
|
1024
|
-
const byCategory = {};
|
|
1025
|
-
for (const f of result.findings) {
|
|
1026
|
-
const cat = f.ruleId.split('.')[0];
|
|
1027
|
-
byCategory[cat] = (byCategory[cat] || 0) + 1;
|
|
1028
|
-
}
|
|
1029
|
-
const byFile = {};
|
|
1030
|
-
for (const f of result.findings) {
|
|
1031
|
-
byFile[f.file] = (byFile[f.file] || 0) + 1;
|
|
1032
|
-
}
|
|
1033
|
-
const topFiles = Object.entries(byFile).sort((a, b) => b[1] - a[1]).slice(0, 10);
|
|
1034
|
-
return textResult(JSON.stringify({
|
|
1035
|
-
grade: result.grade,
|
|
1036
|
-
counts: result.counts,
|
|
1037
|
-
byCategory,
|
|
1038
|
-
topRiskyFiles: topFiles,
|
|
1039
|
-
totalRules: allRules().length,
|
|
1040
|
-
filesScanned: result.scannedFiles,
|
|
1041
|
-
}, null, 2));
|
|
1042
|
-
}
|
|
1043
|
-
|
|
1044
|
-
async function handleDoctor(args) {
|
|
1045
|
-
const dir = args.dir || process.cwd();
|
|
1046
|
-
const { runDoctor } = require('./doctor');
|
|
1047
|
-
const report = runDoctor(dir);
|
|
1048
|
-
return textResult(JSON.stringify(report, null, 2));
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
async function handleAuthCoverage(args) {
|
|
1052
|
-
const dir = args.dir || process.cwd();
|
|
1053
|
-
const { walk } = require('./scanner');
|
|
1054
|
-
const files = walk(dir, []);
|
|
1055
|
-
const { buildAuthCoverage } = require('./engine');
|
|
1056
|
-
const coverage = buildAuthCoverage(dir, files);
|
|
1057
|
-
return textResult(JSON.stringify(coverage, null, 2));
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
|
-
async function handleDeepScan(args) {
|
|
1061
|
-
const dir = args.dir || process.cwd();
|
|
1062
|
-
const result = scan(dir);
|
|
1063
|
-
const { walk } = require('./scanner');
|
|
1064
|
-
const files = walk(dir, []);
|
|
1065
|
-
const { buildAuthCoverage } = require('./engine');
|
|
1066
|
-
const auth = buildAuthCoverage(dir, files);
|
|
1067
|
-
const { trace } = require('./trace');
|
|
1068
|
-
const tr = trace(dir, result.findings);
|
|
1069
|
-
|
|
1070
|
-
// Build structured review contracts for the consuming AI agent.
|
|
1071
|
-
// VibeGuard itself never calls an LLM — these contracts are payloads
|
|
1072
|
-
// the user's AI client (Claude/Cursor/etc.) reviews and acts on.
|
|
1073
|
-
const hotspotFiles = [...new Set(result.findings.filter(f => /auth|payment|admin|upload|webhook/i.test(f.file)).map(f => f.file))].slice(0, 20);
|
|
1074
|
-
const reviewContracts = result.findings.slice(0, 50).map(f => ({
|
|
1075
|
-
findingId: f.ruleId + ':' + f.file + ':' + f.line,
|
|
1076
|
-
file: f.file,
|
|
1077
|
-
line: f.line,
|
|
1078
|
-
ruleId: f.ruleId,
|
|
1079
|
-
severity: f.severity,
|
|
1080
|
-
message: f.message,
|
|
1081
|
-
suggestedFix: f.fix,
|
|
1082
|
-
reviewPrompt: `Review ${f.file}:${f.line} — ${f.ruleId} (${f.severity}): ${f.message}. Confirm whether this is a true positive and propose a fix. Constraint: the fix must not introduce new findings.`,
|
|
1083
|
-
}));
|
|
1084
|
-
|
|
1085
|
-
return textResult(JSON.stringify({
|
|
1086
|
-
scan: summarize(result),
|
|
1087
|
-
reviewContracts,
|
|
1088
|
-
authCoverage: auth,
|
|
1089
|
-
behaviorTrace: tr.behavior,
|
|
1090
|
-
hotspotFiles,
|
|
1091
|
-
note: 'These review contracts are designed for your AI client to process. VibeGuard does not call an LLM itself.',
|
|
1092
|
-
}, null, 2));
|
|
1093
|
-
}
|
|
1094
|
-
|
|
1095
|
-
async function handleFullAudit(args) {
|
|
1096
|
-
const dir = args.dir || process.cwd();
|
|
1097
|
-
const result = scan(dir);
|
|
1098
|
-
const { walk } = require('./scanner');
|
|
1099
|
-
const files = walk(dir, []);
|
|
1100
|
-
const { buildAuthCoverage } = require('./engine');
|
|
1101
|
-
const auth = buildAuthCoverage(dir, files);
|
|
1102
|
-
const { generateComplianceReport } = require('./compliance');
|
|
1103
|
-
const compliance = generateComplianceReport(result.findings);
|
|
1104
|
-
let cveFindings = [];
|
|
1105
|
-
try {
|
|
1106
|
-
const { scanCVEs } = require('./cve-intel');
|
|
1107
|
-
const cveRes = await scanCVEs(dir);
|
|
1108
|
-
cveFindings = cveRes.findings;
|
|
1109
|
-
} catch (err) { console.error(err); }
|
|
1110
|
-
const crypto = require('crypto');
|
|
1111
|
-
const hash = crypto.createHash('sha256').update(JSON.stringify(result.findings)).digest('hex').slice(0, 16);
|
|
1112
|
-
return textResult(JSON.stringify({
|
|
1113
|
-
verdict: result.grade === 'A' ? 'PASS' : result.grade <= 'C' ? 'FAIL' : 'WARN',
|
|
1114
|
-
grade: result.grade,
|
|
1115
|
-
counts: result.counts,
|
|
1116
|
-
hash,
|
|
1117
|
-
authCoverage: auth.coverage + '%',
|
|
1118
|
-
compliance: Object.fromEntries(Object.entries(compliance).map(([k, v]) => [k, v.summary])),
|
|
1119
|
-
cveCount: cveFindings.length,
|
|
1120
|
-
totalFindings: result.findings.length,
|
|
1121
|
-
filesScanned: result.scannedFiles,
|
|
1122
|
-
}, null, 2));
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
async function handleRemediationPlan(args) {
|
|
1126
|
-
const dir = args.dir || process.cwd();
|
|
1127
|
-
const result = scan(dir);
|
|
1128
|
-
const bySeverity = { critical: [], high: [], medium: [], low: [] };
|
|
1129
|
-
for (const f of result.findings) bySeverity[f.severity] = (bySeverity[f.severity] || []).concat(f);
|
|
1130
|
-
const plan = [];
|
|
1131
|
-
let priority = 1;
|
|
1132
|
-
for (const sev of ['critical', 'high', 'medium', 'low']) {
|
|
1133
|
-
for (const f of bySeverity[sev] || []) {
|
|
1134
|
-
plan.push({
|
|
1135
|
-
priority: priority++,
|
|
1136
|
-
severity: f.severity,
|
|
1137
|
-
file: f.file,
|
|
1138
|
-
line: f.line,
|
|
1139
|
-
ruleId: f.ruleId,
|
|
1140
|
-
fix: f.fix || 'Manual review required',
|
|
1141
|
-
effort: f.severity === 'critical' || f.severity === 'high' ? '30min' : '15min',
|
|
1142
|
-
});
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
return textResult(JSON.stringify({ totalSteps: plan.length, plan }, null, 2));
|
|
1146
|
-
}
|
|
1147
|
-
|
|
1148
|
-
async function handleVerifyRemediation(args) {
|
|
1149
|
-
const dir = args.dir || process.cwd();
|
|
1150
|
-
const result = verify(dir);
|
|
1151
|
-
if (!result.hasBaseline) {
|
|
1152
|
-
return textResult('No baseline found. Run scan_project with saveBaseline=true first.');
|
|
1153
|
-
}
|
|
1154
|
-
return textResult(JSON.stringify({
|
|
1155
|
-
resolved: result.resolved.length,
|
|
1156
|
-
remaining: result.remaining.length,
|
|
1157
|
-
introduced: result.introduced.length,
|
|
1158
|
-
resolvedList: result.resolved.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId })),
|
|
1159
|
-
remainingList: result.remaining.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId })),
|
|
1160
|
-
newList: result.introduced.map(f => ({ file: f.file, line: f.line, ruleId: f.ruleId })),
|
|
1161
|
-
}, null, 2));
|
|
1162
|
-
}
|
|
1163
|
-
|
|
1164
|
-
async function handleRedactPII(args) {
|
|
1165
|
-
const text = typeof args.text === 'string' ? args.text : '';
|
|
1166
|
-
if (!text) return textResult('redact_pii requires a "text" argument.', true);
|
|
1167
|
-
const { redactText } = require('./pii');
|
|
1168
|
-
const res = redactText(text, { types: Array.isArray(args.types) ? args.types : undefined });
|
|
1169
|
-
return textResult(JSON.stringify(res, null, 2));
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
async function handleDetectPII(args) {
|
|
1173
|
-
const text = typeof args.text === 'string' ? args.text : '';
|
|
1174
|
-
if (!text) return textResult('detect_pii requires a "text" argument.', true);
|
|
1175
|
-
const { detectPII } = require('./pii');
|
|
1176
|
-
const res = detectPII(text, { types: Array.isArray(args.types) ? args.types : undefined });
|
|
1177
|
-
// Do not echo raw values back — return only type/severity/token/offsets.
|
|
1178
|
-
return textResult(JSON.stringify({
|
|
1179
|
-
total: res.total,
|
|
1180
|
-
counts: res.counts,
|
|
1181
|
-
types: res.types,
|
|
1182
|
-
matches: res.matches.map((m) => ({ type: m.type, severity: m.severity, token: m.token, start: m.start, end: m.end })),
|
|
1183
|
-
}, null, 2));
|
|
1184
|
-
}
|
|
1185
|
-
|
|
1186
|
-
async function handleSecurePrompt(args) {
|
|
1187
|
-
const prompt = args.prompt || '';
|
|
1188
|
-
if (!prompt) return textResult('secure_prompt requires a "prompt" argument.', true);
|
|
1189
|
-
const { analyzePrompt } = require('./secure-prompt');
|
|
1190
|
-
const result = analyzePrompt(prompt);
|
|
1191
|
-
return textResult(JSON.stringify(result, null, 2));
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
async function handleTracePrompt(args) {
|
|
1195
|
-
const dir = args.dir || process.cwd();
|
|
1196
|
-
const result = scan(dir);
|
|
1197
|
-
const { trace } = require('./trace');
|
|
1198
|
-
const tr = trace(dir, result.findings);
|
|
1199
|
-
return textResult(JSON.stringify({ sessions: tr.sessions, traces: tr.traces }, null, 2));
|
|
1200
|
-
}
|
|
1201
|
-
|
|
1202
|
-
async function handleBehaviorAnalysis(args) {
|
|
1203
|
-
const dir = args.dir || process.cwd();
|
|
1204
|
-
const { findSessionFiles, parseSession, analyzeBehavior } = require('./trace');
|
|
1205
|
-
const sessionFiles = findSessionFiles(dir);
|
|
1206
|
-
if (sessionFiles.length === 0) return textResult('No AI session history found. Looked for: .cursor, .claude, .windsurf, .continue');
|
|
1207
|
-
const sessions = sessionFiles.map(parseSession);
|
|
1208
|
-
const allMessages = sessions.flatMap(s => s.messages);
|
|
1209
|
-
const analysis = analyzeBehavior(allMessages);
|
|
1210
|
-
return textResult(JSON.stringify({ sessions: sessions.length, ...analysis }, null, 2));
|
|
1211
|
-
}
|
|
1212
|
-
|
|
1213
|
-
async function handleListRules(args) {
|
|
1214
|
-
let rules = allRules();
|
|
1215
|
-
if (args.category) rules = rules.filter(r => r.id.startsWith(args.category + '.'));
|
|
1216
|
-
return textResult(JSON.stringify(rules.map(r => ({ id: r.id, severity: r.severity, confidence: r.confidence, title: r.title, category: r.id.split('.')[0] })), null, 2));
|
|
1217
|
-
}
|
|
1218
|
-
|
|
1219
|
-
async function handleHtmlReport(args) {
|
|
1220
|
-
const dir = args.dir || process.cwd();
|
|
1221
|
-
const result = scan(dir);
|
|
1222
|
-
const { renderHtml } = require('./report');
|
|
1223
|
-
const html = renderHtml(result);
|
|
1224
|
-
return textResult(html);
|
|
1225
|
-
}
|
|
1226
|
-
|
|
1227
|
-
async function handleRiskScore(args) {
|
|
1228
|
-
const dir = args.dir || process.cwd();
|
|
1229
|
-
const result = scan(dir);
|
|
1230
|
-
const weights = { critical: 10, high: 5, medium: 2, low: 1 };
|
|
1231
|
-
let score = 0;
|
|
1232
|
-
for (const f of result.findings) score += weights[f.severity] || 1;
|
|
1233
|
-
const maxScore = result.scannedFiles * 10 || 1;
|
|
1234
|
-
const riskPercent = Math.min(100, Math.round((score / maxScore) * 100));
|
|
1235
|
-
const riskLevel = score === 0 ? 'NONE' : score < 10 ? 'LOW' : score < 30 ? 'MEDIUM' : score < 60 ? 'HIGH' : 'CRITICAL';
|
|
1236
|
-
const summary = {
|
|
1237
|
-
riskScore: score,
|
|
1238
|
-
riskLevel,
|
|
1239
|
-
riskPercent,
|
|
1240
|
-
filesScanned: result.scannedFiles,
|
|
1241
|
-
totalFindings: result.findings.length,
|
|
1242
|
-
grade: result.grade,
|
|
1243
|
-
topRisks: sortFindings(result.findings).slice(0, 5).map(f => ({
|
|
1244
|
-
ruleId: f.ruleId, severity: f.severity, file: f.file, line: f.line, message: f.message,
|
|
1245
|
-
})),
|
|
1246
|
-
};
|
|
1247
|
-
return textResult(JSON.stringify(summary, null, 2));
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
async function handleBatchFix(args) {
|
|
1251
|
-
const dir = args.dir || process.cwd();
|
|
1252
|
-
const result = scan(dir);
|
|
1253
|
-
const { computeAutoFixes, snapshot, applyChanges } = require('./autofix');
|
|
1254
|
-
const changes = computeAutoFixes(dir, result);
|
|
1255
|
-
if (changes.length === 0) return textResult('No auto-fixable issues found.');
|
|
1256
|
-
snapshot(dir, changes);
|
|
1257
|
-
const applied = [];
|
|
1258
|
-
for (const c of changes) {
|
|
1259
|
-
try { applyChanges(dir, [c]); applied.push(`${c.file}: ${c.description}`); } catch {}
|
|
1260
|
-
}
|
|
1261
|
-
return textResult(`Auto-fixed ${applied.length} issues:\n` + applied.join('\n'));
|
|
1262
|
-
}
|
|
1263
|
-
|
|
1264
|
-
async function handleIgnoreRule(args) {
|
|
1265
|
-
const ruleId = args.ruleId;
|
|
1266
|
-
if (!ruleId) return textResult('Error: ruleId required', true);
|
|
1267
|
-
const dir = args.dir || process.cwd();
|
|
1268
|
-
const configPath = path.join(dir, '.vibeguardrc.json');
|
|
1269
|
-
let config = {};
|
|
1270
|
-
try { config = JSON.parse(fs.readFileSync(configPath, 'utf8')); } catch {}
|
|
1271
|
-
if (!config.ignoreRules) config.ignoreRules = [];
|
|
1272
|
-
if (!config.ignoreRules.includes(ruleId)) config.ignoreRules.push(ruleId);
|
|
1273
|
-
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
|
|
1274
|
-
return textResult(`Rule '${ruleId}' added to ignore list in ${configPath}`);
|
|
1275
|
-
}
|
|
1276
|
-
|
|
1277
|
-
async function handleBaseline(args) {
|
|
1278
|
-
const dir = args.dir || process.cwd();
|
|
1279
|
-
const result = scan(dir);
|
|
1280
|
-
const baselinePath = path.join(dir, '.vibeguard-baseline.json');
|
|
1281
|
-
const baseline = {
|
|
1282
|
-
generatedAt: new Date().toISOString(),
|
|
1283
|
-
grade: result.grade,
|
|
1284
|
-
counts: result.counts,
|
|
1285
|
-
findings: result.findings.map(f => ({ ruleId: f.ruleId, file: f.file, line: f.line, fingerprint: f.fingerprint })),
|
|
1286
|
-
};
|
|
1287
|
-
fs.writeFileSync(baselinePath, JSON.stringify(baseline, null, 2) + '\n');
|
|
1288
|
-
return textResult(`Baseline saved to ${baselinePath} with ${baseline.findings.length} findings (grade: ${result.grade})`);
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
async function handleRuleInfo(args) {
|
|
1292
|
-
const ruleId = args.ruleId;
|
|
1293
|
-
if (!ruleId) return textResult('Error: ruleId required', true);
|
|
1294
|
-
const all = allRules();
|
|
1295
|
-
const rule = all.find(r => r.id === ruleId);
|
|
1296
|
-
if (!rule) return textResult(`Rule '${ruleId}' not found`, true);
|
|
1297
|
-
const info = {
|
|
1298
|
-
id: rule.id,
|
|
1299
|
-
severity: rule.severity,
|
|
1300
|
-
confidence: rule.confidence || 'high',
|
|
1301
|
-
message: rule.message,
|
|
1302
|
-
fix: rule.fix,
|
|
1303
|
-
cwe: rule.cwe || null,
|
|
1304
|
-
owasp: rule.owasp || null,
|
|
1305
|
-
fileFilter: rule.fileFilter ? String(rule.fileFilter) : null,
|
|
1306
|
-
autoFixable: require('./autofix').isAutoFixable(rule.id),
|
|
1307
|
-
};
|
|
1308
|
-
return textResult(JSON.stringify(info, null, 2));
|
|
1309
|
-
}
|
|
1310
|
-
|
|
1311
|
-
async function handleSeverityMatrix(args) {
|
|
1312
|
-
const dir = args.dir || process.cwd();
|
|
1313
|
-
const result = scan(dir);
|
|
1314
|
-
const matrix = {};
|
|
1315
|
-
for (const f of result.findings) {
|
|
1316
|
-
const cat = f.ruleId.split('.')[0];
|
|
1317
|
-
if (!matrix[cat]) matrix[cat] = { critical: 0, high: 0, medium: 0, low: 0 };
|
|
1318
|
-
matrix[cat][f.severity]++;
|
|
1319
|
-
}
|
|
1320
|
-
const sorted = Object.entries(matrix).sort((a, b) => {
|
|
1321
|
-
const sa = a[1].critical * 10 + a[1].high * 5 + a[1].medium * 2 + a[1].low;
|
|
1322
|
-
const sb = b[1].critical * 10 + b[1].high * 5 + b[1].medium * 2 + b[1].low;
|
|
1323
|
-
return sb - sa;
|
|
1324
|
-
});
|
|
1325
|
-
const lines = ['Category Critical High Medium Low', '────────── ──────── ──── ────── ───'];
|
|
1326
|
-
for (const [cat, counts] of sorted) {
|
|
1327
|
-
lines.push(`${cat.padEnd(10)} ${String(counts.critical).padStart(8)} ${String(counts.high).padStart(4)} ${String(counts.medium).padStart(6)} ${String(counts.low).padStart(3)}`);
|
|
1328
|
-
}
|
|
1329
|
-
return textResult(lines.join('\n'));
|
|
1330
|
-
}
|
|
1331
|
-
|
|
1332
|
-
async function handleDependencyTree(args) {
|
|
1333
|
-
const dir = args.dir || process.cwd();
|
|
1334
|
-
const lockPath = path.join(dir, 'package-lock.json');
|
|
1335
|
-
try {
|
|
1336
|
-
const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
|
|
1337
|
-
const deps = lock.dependencies || {};
|
|
1338
|
-
const tree = {};
|
|
1339
|
-
for (const [name, info] of Object.entries(deps)) {
|
|
1340
|
-
tree[name] = {
|
|
1341
|
-
version: info.version,
|
|
1342
|
-
resolved: info.resolved ? info.resolved.split('/').pop() : null,
|
|
1343
|
-
integrity: info.integrity ? info.integrity.split('-')[0] : 'none',
|
|
1344
|
-
dev: info.dev || false,
|
|
1345
|
-
};
|
|
1346
|
-
}
|
|
1347
|
-
const total = Object.keys(tree).length;
|
|
1348
|
-
const withIntegrity = Object.values(tree).filter(d => d.integrity !== 'none').length;
|
|
1349
|
-
const devDeps = Object.values(tree).filter(d => d.dev).length;
|
|
1350
|
-
return textResult(`Dependency tree: ${total} packages (${withIntegrity} with integrity, ${devDeps} dev)\n\n` + JSON.stringify(tree, null, 2).slice(0, 4000));
|
|
1351
|
-
} catch {
|
|
1352
|
-
return textResult('No package-lock.json found or invalid. Run npm install first.');
|
|
1353
|
-
}
|
|
1354
|
-
}
|
|
1355
|
-
|
|
1356
|
-
async function handleConfigDump(args) {
|
|
1357
|
-
const dir = args.dir || process.cwd();
|
|
1358
|
-
const configPaths = ['.vibeguardrc.json', 'vibeguard.config.json', '.vibeguard/config.json'];
|
|
1359
|
-
const result = {};
|
|
1360
|
-
for (const p of configPaths) {
|
|
1361
|
-
try { result[p] = JSON.parse(fs.readFileSync(path.join(dir, p), 'utf8')); } catch { result[p] = null; }
|
|
1362
|
-
}
|
|
1363
|
-
result.mcpInstalled = fs.existsSync(path.join(dir, '.mcp.json'));
|
|
1364
|
-
result.hookInstalled = fs.existsSync(path.join(dir, '.claude', 'settings.json'));
|
|
1365
|
-
result.baselineExists = fs.existsSync(path.join(dir, '.vibeguard-baseline.json'));
|
|
1366
|
-
return textResult(JSON.stringify(result, null, 2));
|
|
1367
|
-
}
|
|
1368
|
-
|
|
1369
|
-
async function handleTrendReport(args) {
|
|
1370
|
-
const dir = args.dir || process.cwd();
|
|
1371
|
-
const baselinePath = path.join(dir, '.vibeguard-baseline.json');
|
|
1372
|
-
let baseline = null;
|
|
1373
|
-
try { baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf8')); } catch {
|
|
1374
|
-
return textResult('No baseline found. Run baseline tool first to start tracking trends.');
|
|
1375
|
-
}
|
|
1376
|
-
const current = scan(dir);
|
|
1377
|
-
const baselineFingerprints = new Set(baseline.findings.map(f => f.fingerprint));
|
|
1378
|
-
const currentFingerprints = new Set(current.findings.map(f => f.fingerprint));
|
|
1379
|
-
const resolved = [...baselineFingerprints].filter(f => !currentFingerprints.has(f));
|
|
1380
|
-
const newFindings = [...currentFingerprints].filter(f => !baselineFingerprints.has(f));
|
|
1381
|
-
const persisted = [...baselineFingerprints].filter(f => currentFingerprints.has(f));
|
|
1382
|
-
const trend = {
|
|
1383
|
-
baselineDate: baseline.generatedAt,
|
|
1384
|
-
currentDate: current.generatedAt,
|
|
1385
|
-
baselineGrade: baseline.grade,
|
|
1386
|
-
currentGrade: current.grade,
|
|
1387
|
-
baselineCount: baseline.findings.length,
|
|
1388
|
-
currentCount: current.findings.length,
|
|
1389
|
-
resolved: resolved.length,
|
|
1390
|
-
new: newFindings.length,
|
|
1391
|
-
persisted: persisted.length,
|
|
1392
|
-
improving: resolved.length > newFindings.length,
|
|
1393
|
-
newFindings: current.findings.filter(f => !baselineFingerprints.has(f.fingerprint)).map(f => ({ ruleId: f.ruleId, file: f.file, line: f.line, severity: f.severity })).slice(0, 20),
|
|
1394
|
-
};
|
|
1395
|
-
return textResult(JSON.stringify(trend, null, 2));
|
|
1396
|
-
}
|
|
1397
|
-
|
|
1398
|
-
async function handleScorecard(args) {
|
|
1399
|
-
const dir = args.dir || process.cwd();
|
|
1400
|
-
const result = scan(dir);
|
|
1401
|
-
const weights = { critical: 10, high: 5, medium: 2, low: 1 };
|
|
1402
|
-
let score = 0;
|
|
1403
|
-
for (const f of result.findings) score += weights[f.severity] || 1;
|
|
1404
|
-
const maxScore = result.scannedFiles * 10 || 1;
|
|
1405
|
-
const riskPercent = Math.min(100, Math.round((score / maxScore) * 100));
|
|
1406
|
-
const riskLevel = score === 0 ? 'NONE' : score < 10 ? 'LOW' : score < 30 ? 'MEDIUM' : score < 60 ? 'HIGH' : 'CRITICAL';
|
|
1407
|
-
|
|
1408
|
-
let compliance = {};
|
|
1409
|
-
try {
|
|
1410
|
-
const { generateComplianceReport } = require('./compliance');
|
|
1411
|
-
compliance = generateComplianceReport(result.findings);
|
|
1412
|
-
} catch {}
|
|
1413
|
-
|
|
1414
|
-
const fixable = result.findings.filter(f => {
|
|
1415
|
-
try { return require('./autofix').isAutoFixable(f.ruleId); } catch { return false; }
|
|
1416
|
-
});
|
|
1417
|
-
|
|
1418
|
-
const scorecard = {
|
|
1419
|
-
grade: result.grade,
|
|
1420
|
-
riskScore: score,
|
|
1421
|
-
riskLevel,
|
|
1422
|
-
riskPercent,
|
|
1423
|
-
filesScanned: result.scannedFiles,
|
|
1424
|
-
totalFindings: result.findings.length,
|
|
1425
|
-
counts: result.counts,
|
|
1426
|
-
autoFixable: fixable.length,
|
|
1427
|
-
compliance,
|
|
1428
|
-
topRisks: sortFindings(result.findings).slice(0, 10).map(f => ({
|
|
1429
|
-
ruleId: f.ruleId, severity: f.severity, file: f.file, line: f.line, message: f.message, cwe: f.cwe, fix: f.fix ? f.fix.slice(0, 100) : null,
|
|
1430
|
-
})),
|
|
1431
|
-
generatedAt: new Date().toISOString(),
|
|
1432
|
-
};
|
|
1433
|
-
return textResult(JSON.stringify(scorecard, null, 2));
|
|
1434
|
-
}
|
|
1435
|
-
|
|
1436
|
-
async function handlePRComment(args) {
|
|
1437
|
-
const dir = args.dir || process.cwd();
|
|
1438
|
-
const result = scan(dir);
|
|
1439
|
-
const { renderPRComment } = require('./dashboard');
|
|
1440
|
-
return textResult(renderPRComment(result));
|
|
1441
|
-
}
|
|
1442
|
-
|
|
1443
|
-
async function handleSlackNotify(args) {
|
|
1444
|
-
const dir = args.dir || process.cwd();
|
|
1445
|
-
const result = scan(dir);
|
|
1446
|
-
const c = result.counts;
|
|
1447
|
-
const color = c.critical > 0 ? '#FF0000' : c.high > 0 ? '#FFA500' : c.medium > 0 ? '#FFFF00' : '#00FF00';
|
|
1448
|
-
const emoji = result.grade === 'A' || result.grade === 'B' ? ':white_check_mark:' : result.grade === 'F' ? ':x:' : ':warning:';
|
|
1449
|
-
const attachment = {
|
|
1450
|
-
color,
|
|
1451
|
-
title: `${emoji} VibeGuard Security Scan`,
|
|
1452
|
-
fields: [
|
|
1453
|
-
{ title: 'Grade', value: result.grade, short: true },
|
|
1454
|
-
{ title: 'Risk Score', value: String(c.critical * 10 + c.high * 5 + c.medium * 2 + c.low), short: true },
|
|
1455
|
-
{ title: 'Critical', value: String(c.critical), short: true },
|
|
1456
|
-
{ title: 'High', value: String(c.high), short: true },
|
|
1457
|
-
{ title: 'Medium', value: String(c.medium), short: true },
|
|
1458
|
-
{ title: 'Low', value: String(c.low), short: true },
|
|
1459
|
-
],
|
|
1460
|
-
footer: 'VibeGuard Security Scanner',
|
|
1461
|
-
ts: Math.floor(Date.now() / 1000),
|
|
1462
|
-
};
|
|
1463
|
-
if (c.critical > 0) {
|
|
1464
|
-
const top = sortFindings(result.findings).filter(f => f.severity === 'critical').slice(0, 3);
|
|
1465
|
-
attachment.fields.push({ title: 'Top Critical Findings', value: top.map(f => `• \`${f.ruleId}\` — ${f.file}:${f.line}`).join('\n'), short: false });
|
|
1466
|
-
}
|
|
1467
|
-
const payload = { text: `Security scan complete: Grade ${result.grade} (${result.findings.length} findings)`, attachments: [attachment] };
|
|
1468
|
-
return textResult(JSON.stringify(JSON.stringify(payload, null, 2)));
|
|
1469
|
-
}
|
|
1470
|
-
|
|
1471
|
-
async function handlePresetApply(args) {
|
|
1472
|
-
const presetName = args.preset;
|
|
1473
|
-
const dir = args.dir || process.cwd();
|
|
1474
|
-
const { getPreset, listPresets } = require('./presets');
|
|
1475
|
-
if (!presetName) {
|
|
1476
|
-
const list = listPresets();
|
|
1477
|
-
return textResult('Available presets:\n' + list.map(p => ` ${p.key.padEnd(12)} ${p.name}`).join('\n'));
|
|
1478
|
-
}
|
|
1479
|
-
const preset = getPreset(presetName);
|
|
1480
|
-
if (!preset) return textResult(`Unknown preset: ${presetName}. Available: ${Object.keys(require('./presets').PRESETS).join(', ')}`, true);
|
|
1481
|
-
const configPath = path.join(dir, '.vibeguardrc.json');
|
|
1482
|
-
let config = {};
|
|
1483
|
-
try { config = JSON.parse(fs.readFileSync(configPath, 'utf8')); } catch {}
|
|
1484
|
-
config.preset = presetName;
|
|
1485
|
-
config.presetName = preset.name;
|
|
1486
|
-
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
|
|
1487
|
-
return textResult(`Applied preset: ${preset.name}\n${preset.description}\nConfig written to ${configPath}`);
|
|
1488
|
-
}
|
|
1489
|
-
|
|
1490
|
-
async function handleDashboard(args) {
|
|
1491
|
-
const dir = args.dir || process.cwd();
|
|
1492
|
-
const result = scan(dir);
|
|
1493
|
-
const { renderDashboard } = require('./dashboard');
|
|
1494
|
-
return textResult(renderDashboard(result));
|
|
1495
|
-
}
|
|
1496
|
-
|
|
1497
|
-
async function handlePrivacyAudit(args) {
|
|
1498
|
-
const dir = args.dir || process.cwd();
|
|
1499
|
-
const { walk } = require('./scanner');
|
|
1500
|
-
const { auditPrivacy, renderPrivacyReport } = require('./privacy-audit');
|
|
1501
|
-
const files = walk(dir, []);
|
|
1502
|
-
const inventory = auditPrivacy(dir, files);
|
|
1503
|
-
return textResult(renderPrivacyReport(inventory));
|
|
1504
|
-
}
|
|
1505
|
-
|
|
1506
|
-
async function handleNetworkAudit(args) {
|
|
1507
|
-
const dir = args.dir || process.cwd();
|
|
1508
|
-
const { walk } = require('./scanner');
|
|
1509
|
-
const { auditNetwork, renderNetworkReport } = require('./net-audit');
|
|
1510
|
-
const files = walk(dir, []);
|
|
1511
|
-
const result = auditNetwork(dir, files);
|
|
1512
|
-
return textResult(renderNetworkReport(result));
|
|
1513
|
-
}
|
|
1514
|
-
|
|
1515
|
-
async function handleAIDataGuard(args) {
|
|
1516
|
-
const dir = args.dir || process.cwd();
|
|
1517
|
-
const { walk } = require('./scanner');
|
|
1518
|
-
const { auditAIData, renderAIGuardReport } = require('./ai-guard');
|
|
1519
|
-
const files = walk(dir, []);
|
|
1520
|
-
const result = auditAIData(dir, files);
|
|
1521
|
-
return textResult(renderAIGuardReport(result));
|
|
1522
|
-
}
|
|
1523
|
-
|
|
1524
|
-
async function handlePrivacyPolicy(args) {
|
|
1525
|
-
const dir = args.dir || process.cwd();
|
|
1526
|
-
const { walk } = require('./scanner');
|
|
1527
|
-
const { generatePrivacyPolicy } = require('./policy-gen');
|
|
1528
|
-
const files = walk(dir, []);
|
|
1529
|
-
const policy = generatePrivacyPolicy(dir, files);
|
|
1530
|
-
return textResult(policy);
|
|
1531
|
-
}
|
|
1532
|
-
|
|
1533
|
-
async function handleCSP(args) {
|
|
1534
|
-
const dir = args.dir || process.cwd();
|
|
1535
|
-
const { walk } = require('./scanner');
|
|
1536
|
-
const { generateCSP } = require('./policy-gen');
|
|
1537
|
-
const files = walk(dir, []);
|
|
1538
|
-
const result = generateCSP(dir, files);
|
|
1539
|
-
return textResult(JSON.stringify(result, null, 2));
|
|
1540
|
-
}
|
|
1541
|
-
|
|
1542
|
-
async function handleSBOM(args) {
|
|
1543
|
-
const dir = args.dir || process.cwd();
|
|
1544
|
-
const { generateSBOM } = require('./sbom');
|
|
1545
|
-
const bom = generateSBOM(dir);
|
|
1546
|
-
return textResult(JSON.stringify(bom, null, 2));
|
|
1547
|
-
}
|
|
1548
|
-
|
|
1549
|
-
async function handleDepReachability(args) {
|
|
1550
|
-
const dir = args.dir || process.cwd();
|
|
1551
|
-
const { generateSBOM, buildImportGraph } = require('./sbom');
|
|
1552
|
-
const { scanCVEs } = require('./cve-intel');
|
|
1553
|
-
const importGraph = buildImportGraph(dir);
|
|
1554
|
-
let cveFindings = [];
|
|
1555
|
-
try {
|
|
1556
|
-
const cveRes = await scanCVEs(dir);
|
|
1557
|
-
cveFindings = cveRes.findings || [];
|
|
1558
|
-
} catch {
|
|
1559
|
-
return textResult(JSON.stringify({ error: 'CVE scan failed or cve-intel unavailable' }, null, 2));
|
|
1560
|
-
}
|
|
1561
|
-
const reachable = [];
|
|
1562
|
-
const unreachable = [];
|
|
1563
|
-
for (const f of cveFindings) {
|
|
1564
|
-
const pkgMatch = f.message && f.message.match(/([@a-z0-9/-]+)\s/);
|
|
1565
|
-
const pkgName = pkgMatch ? pkgMatch[1] : '';
|
|
1566
|
-
if (pkgName && importGraph[pkgName]) {
|
|
1567
|
-
reachable.push({ ...f, reachable: true, importedBy: importGraph[pkgName] });
|
|
1568
|
-
} else {
|
|
1569
|
-
unreachable.push({ ...f, reachable: false });
|
|
1570
|
-
}
|
|
1571
|
-
}
|
|
1572
|
-
return textResult(JSON.stringify({
|
|
1573
|
-
summary: { total: cveFindings.length, reachable: reachable.length, unreachable: unreachable.length },
|
|
1574
|
-
reachable,
|
|
1575
|
-
unreachable,
|
|
1576
|
-
}, null, 2));
|
|
1577
|
-
}
|
|
1578
|
-
|
|
1579
|
-
async function handleContainerScan(args) {
|
|
1580
|
-
const image = args.image;
|
|
1581
|
-
if (!image) return textResult('scan_container_image requires an "image" argument.', true);
|
|
1582
|
-
const { execFileSync } = require('child_process');
|
|
1583
|
-
try {
|
|
1584
|
-
const output = execFileSync('trivy', ['image', '--format', 'json', '--quiet', image], {
|
|
1585
|
-
timeout: 120000,
|
|
1586
|
-
encoding: 'utf8',
|
|
1587
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
1588
|
-
});
|
|
1589
|
-
const result = JSON.parse(output);
|
|
1590
|
-
const vulns = (result.Results || []).flatMap(r => (r.Vulnerabilities || []).map(v => ({
|
|
1591
|
-
cve: v.VulnerabilityID,
|
|
1592
|
-
package: v.PkgName,
|
|
1593
|
-
severity: v.Severity,
|
|
1594
|
-
installed: v.InstalledVersion,
|
|
1595
|
-
fixed: v.FixedVersion,
|
|
1596
|
-
title: v.Title,
|
|
1597
|
-
})));
|
|
1598
|
-
return textResult(JSON.stringify({
|
|
1599
|
-
image,
|
|
1600
|
-
summary: { vulnerabilities: vulns.length, critical: vulns.filter(v => v.severity === 'CRITICAL').length, high: vulns.filter(v => v.severity === 'HIGH').length },
|
|
1601
|
-
vulnerabilities: vulns,
|
|
1602
|
-
}, null, 2));
|
|
1603
|
-
} catch (err) {
|
|
1604
|
-
if (err.code === 'ENOENT' || (err.message && err.message.includes('not found'))) {
|
|
1605
|
-
return textResult(JSON.stringify({ error: 'trivy is not installed or not on PATH. Install from https://trivy.dev', image }, null, 2), true);
|
|
1606
|
-
}
|
|
1607
|
-
if (err.killed) {
|
|
1608
|
-
return textResult(JSON.stringify({ error: 'trivy scan timed out (120s)', image }, null, 2), true);
|
|
1609
|
-
}
|
|
1610
|
-
return textResult(JSON.stringify({ error: 'trivy scan failed: ' + err.message, image }, null, 2), true);
|
|
1611
|
-
}
|
|
1612
|
-
}
|
|
1613
|
-
|
|
1614
|
-
async function handleLicenseCompliance(args) {
|
|
1615
|
-
const dir = args.dir || process.cwd();
|
|
1616
|
-
const fs = require('fs');
|
|
1617
|
-
const path = require('path');
|
|
1618
|
-
const pkgFile = path.join(dir, 'package.json');
|
|
1619
|
-
if (!fs.existsSync(pkgFile)) {
|
|
1620
|
-
return textResult(`license_compliance: no package.json found in ${dir}`, true);
|
|
1621
|
-
}
|
|
1622
|
-
const pkgJson = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
|
|
1623
|
-
const allDeps = { ...(pkgJson.dependencies || {}), ...(pkgJson.devDependencies || {}) };
|
|
1624
|
-
const ALLOWED = ['MIT', 'ISC', 'BSD-2-Clause', 'BSD-3-Clause', 'Apache-2.0', '0BSD', 'Unlicensed', 'CC0-1.0', 'Python-2.0'];
|
|
1625
|
-
const compliant = [];
|
|
1626
|
-
const nonCompliant = [];
|
|
1627
|
-
for (const [name, version] of Object.entries(allDeps)) {
|
|
1628
|
-
let depPkg = null;
|
|
1629
|
-
try {
|
|
1630
|
-
depPkg = JSON.parse(fs.readFileSync(path.join(dir, 'node_modules', name, 'package.json'), 'utf8'));
|
|
1631
|
-
} catch {
|
|
1632
|
-
nonCompliant.push({ name, version, license: 'unknown', reason: 'package.json not found' });
|
|
1633
|
-
continue;
|
|
1634
|
-
}
|
|
1635
|
-
const lic = depPkg.license || 'unknown';
|
|
1636
|
-
const licStr = typeof lic === 'string' ? lic : (lic && lic.type) || 'unknown';
|
|
1637
|
-
if (ALLOWED.includes(licStr)) {
|
|
1638
|
-
compliant.push({ name, version, license: licStr });
|
|
1639
|
-
} else {
|
|
1640
|
-
nonCompliant.push({ name, version, license: licStr, reason: 'license not in allowlist' });
|
|
1641
|
-
}
|
|
1642
|
-
}
|
|
1643
|
-
return textResult(JSON.stringify({
|
|
1644
|
-
summary: { total: Object.keys(allDeps).length, compliant: compliant.length, nonCompliant: nonCompliant.length },
|
|
1645
|
-
allowlist: ALLOWED,
|
|
1646
|
-
compliant,
|
|
1647
|
-
nonCompliant,
|
|
1648
|
-
}, null, 2));
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
|
-
async function handleAIFirewall(args) {
|
|
1652
|
-
const prompt = args.prompt;
|
|
1653
|
-
if (!prompt) return textResult('ai_firewall requires a "prompt" argument.', true);
|
|
1654
|
-
const { inspectPrompt, renderFirewallReport } = require('./firewall');
|
|
1655
|
-
const verdict = inspectPrompt(prompt);
|
|
1656
|
-
return textResult(renderFirewallReport(verdict));
|
|
1657
|
-
}
|
|
1658
|
-
|
|
1659
|
-
async function handleAgentGuard(args) {
|
|
1660
|
-
const { checkAgentAction, AGENT_CONSTRAINTS } = require('./firewall');
|
|
1661
|
-
if (!args.type) return textResult(JSON.stringify({ constraints: AGENT_CONSTRAINTS }, null, 2));
|
|
1662
|
-
const result = checkAgentAction(args);
|
|
1663
|
-
return textResult(JSON.stringify(result, null, 2));
|
|
1664
|
-
}
|
|
1665
|
-
|
|
1666
|
-
async function handleExfilCheck(args) {
|
|
1667
|
-
const data = args.data;
|
|
1668
|
-
if (!data) return textResult('exfil_check requires a "data" argument.', true);
|
|
1669
|
-
const { checkExfiltration } = require('./firewall');
|
|
1670
|
-
const result = checkExfiltration(data, args.destination);
|
|
1671
|
-
return textResult(JSON.stringify(result, null, 2));
|
|
1672
|
-
}
|
|
1673
|
-
|
|
1674
|
-
async function handleDepFirewall(args) {
|
|
1675
|
-
const pkg = args.package;
|
|
1676
|
-
if (!pkg) return textResult('dep_firewall requires a "package" argument.', true);
|
|
1677
|
-
const { checkPackage } = require('./firewall');
|
|
1678
|
-
const result = checkPackage(pkg);
|
|
1679
|
-
return textResult(JSON.stringify(result, null, 2));
|
|
1680
|
-
}
|
|
1681
|
-
|
|
1682
|
-
async function handleThreatModel(args) {
|
|
1683
|
-
const dir = args.dir || process.cwd();
|
|
1684
|
-
const result = scan(dir);
|
|
1685
|
-
const { auditPrivacy } = require('./privacy-audit');
|
|
1686
|
-
const { auditNetwork } = require('./net-audit');
|
|
1687
|
-
const { walk } = require('./scanner');
|
|
1688
|
-
const files = walk(dir, []);
|
|
1689
|
-
const privacy = auditPrivacy(dir, files);
|
|
1690
|
-
const network = auditNetwork(dir, files);
|
|
1691
|
-
|
|
1692
|
-
const attackSurfaces = [];
|
|
1693
|
-
const threats = [];
|
|
1694
|
-
const mitigations = [];
|
|
1695
|
-
|
|
1696
|
-
if (result.findings.some(f => f.ruleId.startsWith('secret.'))) {
|
|
1697
|
-
attackSurfaces.push('Hardcoded secrets in source code');
|
|
1698
|
-
threats.push({ actor: 'Attacker with repo access', vector: 'Read secrets from code', severity: 'critical', impact: 'Credential theft' });
|
|
1699
|
-
mitigations.push('Move all secrets to environment variables. Run: vibeguard fix --apply');
|
|
1700
|
-
}
|
|
1701
|
-
if (result.findings.some(f => f.ruleId.includes('injection'))) {
|
|
1702
|
-
attackSurfaces.push('User input handlers (injection points)');
|
|
1703
|
-
threats.push({ actor: 'External attacker', vector: 'SQL/command injection', severity: 'high', impact: 'Data breach, RCE' });
|
|
1704
|
-
mitigations.push('Use parameterized queries. Validate all input.');
|
|
1705
|
-
}
|
|
1706
|
-
if (result.findings.some(f => f.ruleId.includes('auth'))) {
|
|
1707
|
-
attackSurfaces.push('Authentication endpoints');
|
|
1708
|
-
threats.push({ actor: 'External attacker', vector: 'Auth bypass, brute force', severity: 'high', impact: 'Account takeover' });
|
|
1709
|
-
mitigations.push('Add rate limiting. Verify JWT. Use bcrypt.');
|
|
1710
|
-
}
|
|
1711
|
-
if (network.summary.unknownDomains > 0) {
|
|
1712
|
-
attackSurfaces.push('Outbound HTTP calls to unknown domains');
|
|
1713
|
-
threats.push({ actor: 'Malicious third party', vector: 'Intercept outbound data', severity: 'medium', impact: 'Data exfiltration' });
|
|
1714
|
-
mitigations.push('Review all unknown endpoints. Use allowlist.');
|
|
1715
|
-
}
|
|
1716
|
-
if (privacy.summary.piiFieldCount > 0) {
|
|
1717
|
-
attackSurfaces.push('PII collection and storage');
|
|
1718
|
-
threats.push({ actor: 'Insider or data broker', vector: 'Access PII without consent', severity: 'high', impact: 'Privacy violation, GDPR fines' });
|
|
1719
|
-
mitigations.push('Implement consent. Encrypt PII. Define retention policy.');
|
|
1720
|
-
}
|
|
1721
|
-
|
|
1722
|
-
const model = {
|
|
1723
|
-
generatedAt: new Date().toISOString(),
|
|
1724
|
-
grade: result.grade,
|
|
1725
|
-
attackSurfaces,
|
|
1726
|
-
threats,
|
|
1727
|
-
mitigations,
|
|
1728
|
-
riskScore: result.counts.critical * 10 + result.counts.high * 5 + result.counts.medium * 2 + result.counts.low,
|
|
1729
|
-
summary: {
|
|
1730
|
-
totalThreats: threats.length,
|
|
1731
|
-
criticalThreats: threats.filter(t => t.severity === 'critical').length,
|
|
1732
|
-
mitigations: mitigations.length,
|
|
1733
|
-
},
|
|
1734
|
-
};
|
|
1735
|
-
return textResult(JSON.stringify(model, null, 2));
|
|
1736
|
-
}
|
|
1737
|
-
|
|
1738
|
-
async function handleOutputGuard(args) {
|
|
1739
|
-
const response = args.response;
|
|
1740
|
-
if (!response) return textResult('output_guard requires a "response" argument.', true);
|
|
1741
|
-
const { sanitizeAIResponse } = require('./interceptor');
|
|
1742
|
-
const result = sanitizeAIResponse(response);
|
|
1743
|
-
return textResult(JSON.stringify(result, null, 2));
|
|
1744
|
-
}
|
|
1745
|
-
|
|
1746
|
-
async function handleEnvLock(args) {
|
|
1747
|
-
const { lockEnvironment } = require('./interceptor');
|
|
1748
|
-
const lock = lockEnvironment();
|
|
1749
|
-
return textResult(JSON.stringify({
|
|
1750
|
-
locked: true,
|
|
1751
|
-
hiddenCount: lock.hiddenCount,
|
|
1752
|
-
totalKeys: lock.totalKeys,
|
|
1753
|
-
hiddenKeys: lock.hiddenKeys,
|
|
1754
|
-
}, null, 2));
|
|
1755
|
-
}
|
|
1756
|
-
|
|
1757
|
-
async function handleSelfCheck(args) {
|
|
1758
|
-
const dir = args.dir || process.cwd();
|
|
1759
|
-
const fs = require('fs');
|
|
1760
|
-
const path = require('path');
|
|
1761
|
-
const checks = [];
|
|
1762
|
-
let ok = true;
|
|
1763
|
-
const modules = ['firewall', 'interceptor', 'scanner', 'pii', 'mcp-server', 'autofix'];
|
|
1764
|
-
for (const mod of modules) {
|
|
1765
|
-
try { require('./' + mod); checks.push({ module: mod, status: 'intact' }); }
|
|
1766
|
-
catch { checks.push({ module: mod, status: 'corrupted' }); ok = false; }
|
|
1767
|
-
}
|
|
1768
|
-
try { const r = require('./rules'); checks.push({ module: 'rules', status: 'loaded', count: r.lineRules.length }); }
|
|
1769
|
-
catch { checks.push({ module: 'rules', status: 'corrupted' }); ok = false; }
|
|
1770
|
-
const gi = path.join(dir, '.gitignore');
|
|
1771
|
-
checks.push({ check: 'gitignore', hasEnv: fs.existsSync(gi) ? /\.env/.test(fs.readFileSync(gi, 'utf8')) : false });
|
|
1772
|
-
return textResult(JSON.stringify({ allPassed: ok, checks }, null, 2));
|
|
1773
|
-
}
|
|
1774
|
-
|
|
1775
|
-
async function handleTamperCheck(args) {
|
|
1776
|
-
const prompt = args.prompt;
|
|
1777
|
-
if (!prompt) return textResult('tamper_check requires a "prompt" argument.', true);
|
|
1778
|
-
const { detectTamper } = require('./interceptor');
|
|
1779
|
-
const result = detectTamper(prompt);
|
|
1780
|
-
return textResult(JSON.stringify(result, null, 2));
|
|
1781
|
-
}
|
|
1782
|
-
|
|
1783
|
-
async function handleSandboxExec(args) {
|
|
1784
|
-
const code = args.code;
|
|
1785
|
-
if (!code) return textResult('sandbox_exec requires a "code" argument.', true);
|
|
1786
|
-
const { runInSandbox, renderSandboxReport } = require('./sandbox');
|
|
1787
|
-
const result = runInSandbox(code, { timeout: args.timeout });
|
|
1788
|
-
return textResult(renderSandboxReport(result));
|
|
1789
|
-
}
|
|
1790
|
-
|
|
1791
|
-
async function handleBehaviorAnalysis(args) {
|
|
1792
|
-
const dir = args.dir || process.cwd();
|
|
1793
|
-
const result = scan(dir);
|
|
1794
|
-
const { createSession, recordEvent, analyzeSession, renderBehaviorReport } = require('./behavior');
|
|
1795
|
-
const session = createSession();
|
|
1796
|
-
for (const f of result.findings.slice(0, 50)) {
|
|
1797
|
-
recordEvent(session, f.ruleId.startsWith('secret.') ? 'secret_access' : f.ruleId.includes('injection') ? 'exec' : 'file_read', { ruleId: f.ruleId });
|
|
1798
|
-
}
|
|
1799
|
-
recordEvent(session, 'network', { detail: 'scan complete' });
|
|
1800
|
-
const analysis = analyzeSession(session);
|
|
1801
|
-
return textResult(renderBehaviorReport(analysis));
|
|
1802
|
-
}
|
|
1803
|
-
|
|
1804
|
-
async function handleSupplyAudit(args) {
|
|
1805
|
-
const dir = args.dir || process.cwd();
|
|
1806
|
-
const { auditLockfile, auditPackageJson } = require('./supply-firewall');
|
|
1807
|
-
const lockResult = auditLockfile(dir);
|
|
1808
|
-
const pkgResult = auditPackageJson(dir);
|
|
1809
|
-
return textResult(JSON.stringify({ lockfile: lockResult, packageJson: pkgResult }, null, 2));
|
|
1810
|
-
}
|
|
1811
|
-
|
|
1812
|
-
async function handleVaultManage(args) {
|
|
1813
|
-
const vault = require('./vault');
|
|
1814
|
-
const action = args.action || 'list';
|
|
1815
|
-
if (action === 'list') return textResult(vault.renderVaultReport());
|
|
1816
|
-
if (action === 'store') {
|
|
1817
|
-
if (!args.key || !args.value) return textResult('store requires key and value', true);
|
|
1818
|
-
vault.store(args.key, args.value);
|
|
1819
|
-
return textResult(`Stored "${args.key}" in encrypted vault`);
|
|
1820
|
-
}
|
|
1821
|
-
if (action === 'get') {
|
|
1822
|
-
if (!args.key) return textResult('get requires key', true);
|
|
1823
|
-
const value = vault.get(args.key, { purpose: 'mcp' });
|
|
1824
|
-
return textResult(value ? `Decrypted: ${value.slice(0, 10)}...` : 'Key not found');
|
|
1825
|
-
}
|
|
1826
|
-
if (action === 'clear') { vault.clear(); return textResult('Vault cleared'); }
|
|
1827
|
-
return textResult('Unknown action: ' + action, true);
|
|
1828
|
-
}
|
|
1829
|
-
|
|
1830
|
-
async function handleAuditLog(args) {
|
|
1831
|
-
const audit = require('./audit-trail');
|
|
1832
|
-
const action = args.action || 'show';
|
|
1833
|
-
if (action === 'show') return textResult(audit.renderAuditReport());
|
|
1834
|
-
if (action === 'export') return textResult(audit.exportLog());
|
|
1835
|
-
if (action === 'verify') {
|
|
1836
|
-
const v = audit.verifyChain();
|
|
1837
|
-
return textResult(JSON.stringify(v, null, 2));
|
|
1838
|
-
}
|
|
1839
|
-
if (action === 'log') {
|
|
1840
|
-
const entries = audit.getEntries({ type: args.type, limit: args.limit });
|
|
1841
|
-
return textResult(JSON.stringify(entries, null, 2));
|
|
1842
|
-
}
|
|
1843
|
-
return textResult('Unknown action: ' + action, true);
|
|
1844
|
-
}
|
|
1845
|
-
|
|
1846
|
-
async function handlePreDeploy(args) {
|
|
1847
|
-
const dir = args.dir || process.cwd();
|
|
1848
|
-
const { runPreDeployGate, renderPreDeployReport } = require('./pre-deploy');
|
|
1849
|
-
const summary = runPreDeployGate(dir, { strict: args.strict });
|
|
1850
|
-
return textResult(renderPreDeployReport(summary));
|
|
1851
|
-
}
|
|
1852
|
-
|
|
1853
|
-
async function main() {
|
|
1854
|
-
// ─── AUTO-ACTIVATE ALL PROTECTION LAYERS ON STARTUP ────────────────
|
|
1855
|
-
const audit = require('./audit-trail');
|
|
1856
|
-
const { lockEnvironment } = require('./interceptor');
|
|
1857
|
-
const { createSession, recordEvent, analyzeSession } = require('./behavior');
|
|
1858
|
-
|
|
1859
|
-
// Layer 7: Lock environment variables
|
|
1860
|
-
const envLock = lockEnvironment();
|
|
1861
|
-
audit.log('system', { event: 'env_locked', hidden: envLock.hiddenCount });
|
|
1862
|
-
|
|
1863
|
-
// Layer 13: Audit trail is active
|
|
1864
|
-
audit.log('system', { event: 'mcp_server_start', version: require('../package.json').version });
|
|
1865
|
-
|
|
1866
|
-
// Layer 10: Behavioral analysis session
|
|
1867
|
-
const behaviorSession = createSession();
|
|
1868
|
-
|
|
1869
|
-
// Layer 4: Runtime interceptor (activate silently, don't break existing code)
|
|
1870
|
-
let interceptorActive = false;
|
|
1871
|
-
try {
|
|
1872
|
-
const interceptor = require('./interceptor');
|
|
1873
|
-
// We don't call activate() here because it wraps global fetch which
|
|
1874
|
-
// could break MCP transport. Instead, we use check functions manually
|
|
1875
|
-
// in every tool handler below.
|
|
1876
|
-
interceptorActive = true;
|
|
1877
|
-
audit.log('system', { event: 'interceptor_loaded' });
|
|
1878
|
-
} catch (e) {
|
|
1879
|
-
audit.log('warning', { event: 'interceptor_load_failed', error: e.message });
|
|
1880
|
-
}
|
|
1881
|
-
|
|
1882
|
-
process.stderr.write(`vibeguard MCP server: all defense layers active (env lock: ${envLock.hiddenCount} vars hidden, interceptor: ${interceptorActive ? 'ready' : 'off'}, audit: recording, behavior: monitoring)\n`);
|
|
1883
|
-
|
|
1884
|
-
const server = new Server(
|
|
1885
|
-
{ name: 'vibeguard', version: require('../package.json').version },
|
|
1886
|
-
{ capabilities: { tools: {} } }
|
|
1887
|
-
);
|
|
1888
|
-
|
|
1889
|
-
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
|
1890
|
-
|
|
1891
|
-
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
1892
|
-
// The MCP SDK delivers the full JSON-RPC request object; params carries the
|
|
1893
|
-
// tool name + arguments (SDK >= 1.x). Reading from `req` directly yields
|
|
1894
|
-
// `name: undefined` and every tool call fails with "Unknown tool".
|
|
1895
|
-
const { name, arguments: args = {} } = (req && req.params) || {};
|
|
1896
|
-
const startTime = Date.now();
|
|
1897
|
-
|
|
1898
|
-
// ─── LAYER 2: AI FIREWALL — auto-inspect any prompt argument ─────
|
|
1899
|
-
if (args.prompt && typeof args.prompt === 'string') {
|
|
1900
|
-
try {
|
|
1901
|
-
const { inspectPrompt } = require('./firewall');
|
|
1902
|
-
const verdict = inspectPrompt(args.prompt);
|
|
1903
|
-
recordEvent(behaviorSession, 'ai_api', { tool: name, action: verdict.action });
|
|
1904
|
-
audit.log('ai_firewall', { tool: name, action: verdict.action, threats: verdict.threatCount });
|
|
1905
|
-
if (verdict.action === 'block') {
|
|
1906
|
-
recordEvent(behaviorSession, 'blocked', { tool: name, reason: verdict.reason });
|
|
1907
|
-
return textResult(`VibeGuard AI Firewall BLOCKED this request:\n${verdict.reason}\n\nThreats: ${JSON.stringify(verdict.findings, null, 2)}`);
|
|
1908
|
-
}
|
|
1909
|
-
if (verdict.action === 'redact') {
|
|
1910
|
-
args.prompt = verdict.sanitizedPrompt;
|
|
1911
|
-
}
|
|
1912
|
-
} catch {}
|
|
1913
|
-
}
|
|
1914
|
-
|
|
1915
|
-
// ─── LAYER 8: TAMPER DETECTION — check for VibeGuard bypass ──────
|
|
1916
|
-
if (args.prompt || args.code || args.response || args.data) {
|
|
1917
|
-
const checkText = [args.prompt, args.code, args.response, args.data].filter(Boolean).join(' ');
|
|
1918
|
-
try {
|
|
1919
|
-
const { detectTamper } = require('./interceptor');
|
|
1920
|
-
const tamper = detectTamper(checkText);
|
|
1921
|
-
if (tamper.detected) {
|
|
1922
|
-
recordEvent(behaviorSession, 'tamper', { tool: name, threat: tamper.threat });
|
|
1923
|
-
audit.log('tamper_blocked', { tool: name, threat: tamper.threat, severity: tamper.severity });
|
|
1924
|
-
return textResult(`VibeGuard SELF-PROTECTION blocked this request:\nTampering attempt detected: ${tamper.threat}\n\nThis request tried to disable, bypass, or uninstall VibeGuard security controls.`);
|
|
1925
|
-
}
|
|
1926
|
-
} catch {}
|
|
1927
|
-
}
|
|
1928
|
-
|
|
1929
|
-
try {
|
|
1930
|
-
let result;
|
|
1931
|
-
|
|
1932
|
-
if (name === 'scan_project') result = await handleScan(args);
|
|
1933
|
-
else if (name === 'suggest_fixes') result = await handleSuggest(args);
|
|
1934
|
-
else if (name === 'verify_fixes') result = await handleVerify(args);
|
|
1935
|
-
else if (name === 'scan_url') result = await handleScanUrl(args);
|
|
1936
|
-
else if (name === 'review_hotspots') result = await handleReviewHotspots(args);
|
|
1937
|
-
else if (name === 'check_code') result = await handleCheckCode(args);
|
|
1938
|
-
else if (name === 'scan_staged') result = await handleScanStaged(args);
|
|
1939
|
-
else if (name === 'scan_dependencies' || name === 'cve_intel') result = await handleScanDeps(args);
|
|
1940
|
-
else if (name === 'scan_secrets') result = await handleScanSecrets(args);
|
|
1941
|
-
else if (name === 'check_package_health' || name === 'scan_hallucinated_packages') result = await handleSlopsquat(args);
|
|
1942
|
-
else if (name === 'redact_pii') result = await handleRedactPII(args);
|
|
1943
|
-
else if (name === 'detect_pii') result = await handleDetectPII(args);
|
|
1944
|
-
else if (name === 'compliance_report') result = await handleCompliance(args);
|
|
1945
|
-
else if (name === 'export_sarif') result = await handleSarif(args);
|
|
1946
|
-
else if (name === 'fix_code') result = await handleFixCode(args);
|
|
1947
|
-
else if (name === 'secure_this') result = await handleSecureThis(args);
|
|
1948
|
-
else if (name === 'audit_config') result = await handleAuditConfig(args);
|
|
1949
|
-
else if (name === 'generate_policy') result = await handleGeneratePolicy(args);
|
|
1950
|
-
else if (name === 'review_pr') result = await handleReviewPr(args);
|
|
1951
|
-
else if (name === 'scan_secrets_history') result = await handleScanHistory(args);
|
|
1952
|
-
else if (name === 'analyze_dataflow') result = await handleAnalyzeDataflow(args);
|
|
1953
|
-
else if (name === 'analyze_cross_file_dataflow') result = await handleCrossFileTaint(args);
|
|
1954
|
-
else if (name === 'check_command') result = await handleCheckCommand(args);
|
|
1955
|
-
else if (name === 'scan_config_change') result = await handleScanConfigChange(args);
|
|
1956
|
-
else if (name === 'repo_security_posture') result = await handlePosture(args);
|
|
1957
|
-
else if (name === 'explain_remediation') result = await handleExplainRemediation(args);
|
|
1958
|
-
else if (name === 'scan_file') result = await handleScanFile(args);
|
|
1959
|
-
else if (name === 'scan_changed_files') result = await handleScanChanged(args);
|
|
1960
|
-
else if (name === 'security_stats') result = await handleStats(args);
|
|
1961
|
-
else if (name === 'guardvibe_doctor') result = await handleDoctor(args);
|
|
1962
|
-
else if (name === 'auth_coverage') result = await handleAuthCoverage(args);
|
|
1963
|
-
else if (name === 'deep_scan') result = await handleDeepScan(args);
|
|
1964
|
-
else if (name === 'full_audit') result = await handleFullAudit(args);
|
|
1965
|
-
else if (name === 'remediation_plan') result = await handleRemediationPlan(args);
|
|
1966
|
-
else if (name === 'verify_remediation') result = await handleVerifyRemediation(args);
|
|
1967
|
-
else if (name === 'secure_prompt') result = await handleSecurePrompt(args);
|
|
1968
|
-
else if (name === 'trace_prompt') result = await handleTracePrompt(args);
|
|
1969
|
-
else if (name === 'behavior_analysis') result = await handleBehaviorAnalysis(args);
|
|
1970
|
-
else if (name === 'list_rules') result = await handleListRules(args);
|
|
1971
|
-
else if (name === 'generate_html_report') result = await handleHtmlReport(args);
|
|
1972
|
-
else if (name === 'risk_score') result = await handleRiskScore(args);
|
|
1973
|
-
else if (name === 'batch_fix') result = await handleBatchFix(args);
|
|
1974
|
-
else if (name === 'ignore_rule') result = await handleIgnoreRule(args);
|
|
1975
|
-
else if (name === 'baseline') result = await handleBaseline(args);
|
|
1976
|
-
else if (name === 'rule_info') result = await handleRuleInfo(args);
|
|
1977
|
-
else if (name === 'severity_matrix') result = await handleSeverityMatrix(args);
|
|
1978
|
-
else if (name === 'dependency_tree') result = await handleDependencyTree(args);
|
|
1979
|
-
else if (name === 'config_dump') result = await handleConfigDump(args);
|
|
1980
|
-
else if (name === 'trend_report') result = await handleTrendReport(args);
|
|
1981
|
-
else if (name === 'security_scorecard') result = await handleScorecard(args);
|
|
1982
|
-
else if (name === 'pr_comment') result = await handlePRComment(args);
|
|
1983
|
-
else if (name === 'slack_notify') result = await handleSlackNotify(args);
|
|
1984
|
-
else if (name === 'preset_apply') result = await handlePresetApply(args);
|
|
1985
|
-
else if (name === 'interactive_dashboard') result = await handleDashboard(args);
|
|
1986
|
-
else if (name === 'privacy_audit') result = await handlePrivacyAudit(args);
|
|
1987
|
-
else if (name === 'network_audit') result = await handleNetworkAudit(args);
|
|
1988
|
-
else if (name === 'ai_data_guard') result = await handleAIDataGuard(args);
|
|
1989
|
-
else if (name === 'mcp_audit') result = await handleMcpAudit(args);
|
|
1990
|
-
else if (name === 'agent_scan') result = await handleAgentScan(args);
|
|
1991
|
-
else if (name === 'guard_action') result = await handleGuardAction(args);
|
|
1992
|
-
else if (name === 'generate_privacy_policy') result = await handlePrivacyPolicy(args);
|
|
1993
|
-
else if (name === 'generate_csp') result = await handleCSP(args);
|
|
1994
|
-
else if (name === 'generate_sbom') result = await handleSBOM(args);
|
|
1995
|
-
else if (name === 'dep_reachability') result = await handleDepReachability(args);
|
|
1996
|
-
else if (name === 'scan_container_image') result = await handleContainerScan(args);
|
|
1997
|
-
else if (name === 'license_compliance') result = await handleLicenseCompliance(args);
|
|
1998
|
-
else if (name === 'ai_firewall') result = await handleAIFirewall(args);
|
|
1999
|
-
else if (name === 'agent_guard') result = await handleAgentGuard(args);
|
|
2000
|
-
else if (name === 'exfil_check') result = await handleExfilCheck(args);
|
|
2001
|
-
else if (name === 'dep_firewall') result = await handleDepFirewall(args);
|
|
2002
|
-
else if (name === 'threat_model') result = await handleThreatModel(args);
|
|
2003
|
-
else if (name === 'output_guard') result = await handleOutputGuard(args);
|
|
2004
|
-
else if (name === 'env_lock') result = await handleEnvLock(args);
|
|
2005
|
-
else if (name === 'self_check') result = await handleSelfCheck(args);
|
|
2006
|
-
else if (name === 'tamper_check') result = await handleTamperCheck(args);
|
|
2007
|
-
else if (name === 'sandbox_exec') result = await handleSandboxExec(args);
|
|
2008
|
-
else if (name === 'supply_chain_audit') result = await handleSupplyAudit(args);
|
|
2009
|
-
else if (name === 'vault_manage') result = await handleVaultManage(args);
|
|
2010
|
-
else if (name === 'audit_log') result = await handleAuditLog(args);
|
|
2011
|
-
else if (name === 'pre_deploy') result = await handlePreDeploy(args);
|
|
2012
|
-
else result = textResult(`Unknown tool: ${name}`, true);
|
|
2013
|
-
|
|
2014
|
-
// ─── LAYER 5: OUTPUT GUARD — auto-sanitize any text result ────
|
|
2015
|
-
if (result && result.content && result.content[0] && result.content[0].text) {
|
|
2016
|
-
try {
|
|
2017
|
-
const { sanitizeAIResponse } = require('./interceptor');
|
|
2018
|
-
const sanitized = sanitizeAIResponse(result.content[0].text);
|
|
2019
|
-
if (!sanitized.safe && sanitized.blockedCount > 0) {
|
|
2020
|
-
result = textResult(sanitized.sanitized);
|
|
2021
|
-
audit.log('output_guard', { tool: name, blocked: sanitized.blockedCount });
|
|
2022
|
-
}
|
|
2023
|
-
} catch {}
|
|
2024
|
-
}
|
|
2025
|
-
|
|
2026
|
-
// ─── LAYER 13: AUDIT TRAIL — log every tool call ───────────────
|
|
2027
|
-
const duration = Date.now() - startTime;
|
|
2028
|
-
recordEvent(behaviorSession, 'file_read', { tool: name, duration });
|
|
2029
|
-
audit.log('tool_call', { tool: name, duration, success: !result?.isError });
|
|
2030
|
-
|
|
2031
|
-
// ─── LAYER 10: BEHAVIORAL ANALYSIS — check patterns every 20 calls ─
|
|
2032
|
-
if (behaviorSession.events.length % 20 === 0 && behaviorSession.events.length > 0) {
|
|
2033
|
-
const analysis = analyzeSession(behaviorSession);
|
|
2034
|
-
if (analysis.patternsCount > 0) {
|
|
2035
|
-
audit.log('behavior_alert', { patterns: analysis.patterns.map(p => p.pattern) });
|
|
2036
|
-
process.stderr.write(`VibeGuard Behavioral Alert: ${analysis.patternsCount} pattern(s) detected — ${analysis.patterns.map(p => p.message).join('; ')}\n`);
|
|
2037
|
-
}
|
|
2038
|
-
}
|
|
2039
|
-
|
|
2040
|
-
return result;
|
|
2041
|
-
} catch (err) {
|
|
2042
|
-
audit.log('error', { tool: name, error: err.message });
|
|
2043
|
-
return textResult(`VibeGuard error: ${err && err.message ? err.message : err}`, true);
|
|
2044
|
-
}
|
|
2045
|
-
});
|
|
2046
|
-
|
|
2047
|
-
const transport = new StdioServerTransport();
|
|
2048
|
-
await server.connect(transport);
|
|
2049
|
-
process.stderr.write(`vibeguard MCP server running on stdio — all defense layers active\n`);
|
|
2050
|
-
}
|
|
2051
|
-
|
|
2052
|
-
main().catch((err) => {
|
|
2053
|
-
process.stderr.write(`fatal: ${err && err.stack ? err.stack : err}\n`);
|
|
2054
|
-
process.exit(1);
|
|
2055
|
-
});
|