@yagyeshvyas/vibeguard 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,6 +26,10 @@
26
26
  */
27
27
 
28
28
  const { detectPII, redactText } = require('./pii');
29
+ // Eager-require the unified action firewall at load time so the runtime hot path
30
+ // never has to require() inside a window where fs is already wrapped.
31
+ let _actionGuard = null;
32
+ try { _actionGuard = require('./action-guard'); } catch { _actionGuard = null; }
29
33
 
30
34
  // ─── Configuration ──────────────────────────────────────────────────────
31
35
 
@@ -77,6 +81,20 @@ function logAllow(type, detail) {
77
81
  stats.allowed++;
78
82
  }
79
83
 
84
+ // Delegate to the unified Agent Action Firewall (src/action-guard.js) for the
85
+ // hardened, shared exfiltration logic: anti-evasion shell checks, secret-in-URL,
86
+ // external-host awareness, and the allowlist. Lazy-required and fail-open on
87
+ // error so a guard bug never takes down the wrapped runtime. CONFIG.allowDomains
88
+ // are treated as trusted destinations.
89
+ function runActionGuard(action) {
90
+ if (!_actionGuard) return { blocked: false, action: 'allow', violations: [] };
91
+ try {
92
+ return _actionGuard.inspectAction(action, { trustedHosts: CONFIG.allowDomains });
93
+ } catch {
94
+ return { blocked: false, action: 'allow', violations: [] };
95
+ }
96
+ }
97
+
80
98
  // ─── Check Functions ────────────────────────────────────────────────────
81
99
 
82
100
  function checkOutboundData(data) {
@@ -214,6 +232,17 @@ function activate(opts = {}) {
214
232
  }
215
233
  }
216
234
 
235
+ // Second layer: unified action firewall (catches secrets in the URL
236
+ // itself, and applies external-host awareness the inline check lacks).
237
+ const ag = runActionGuard({ type: 'network', url, body });
238
+ if (ag.blocked) {
239
+ logBlock('fetch_exfil', `${url}: ${ag.reason}`);
240
+ return new Response(JSON.stringify({ error: 'Blocked by VibeGuard', reason: ag.reason }), {
241
+ status: 403,
242
+ headers: { 'Content-Type': 'application/json' },
243
+ });
244
+ }
245
+
217
246
  logAllow('fetch', url);
218
247
  return originalFetch.call(this, input, init);
219
248
  };
@@ -253,11 +282,13 @@ function activate(opts = {}) {
253
282
  interceptors.exec = exec;
254
283
  require('child_process').exec = function(cmd, opts, callback) {
255
284
  const cmdCheck = checkCommand(cmd);
256
- if (!cmdCheck.allowed) {
257
- logBlock('exec_command', cmdCheck.reason);
285
+ const ag = runActionGuard({ type: 'shell', command: cmd });
286
+ if (!cmdCheck.allowed || ag.blocked) {
287
+ const reason = !cmdCheck.allowed ? cmdCheck.reason : ag.reason;
288
+ logBlock('exec_command', reason);
258
289
  if (typeof opts === 'function') { callback = opts; opts = null; }
259
290
  if (callback) {
260
- process.nextTick(() => callback(new Error(`VibeGuard: ${cmdCheck.reason}`), '', ''));
291
+ process.nextTick(() => callback(new Error(`VibeGuard: ${reason}`), '', ''));
261
292
  return;
262
293
  }
263
294
  return;
@@ -269,9 +300,11 @@ function activate(opts = {}) {
269
300
  interceptors.execSync = execSync;
270
301
  require('child_process').execSync = function(cmd, opts) {
271
302
  const cmdCheck = checkCommand(cmd);
272
- if (!cmdCheck.allowed) {
273
- logBlock('execSync_command', cmdCheck.reason);
274
- throw new Error(`VibeGuard: ${cmdCheck.reason}`);
303
+ const ag = runActionGuard({ type: 'shell', command: cmd });
304
+ if (!cmdCheck.allowed || ag.blocked) {
305
+ const reason = !cmdCheck.allowed ? cmdCheck.reason : ag.reason;
306
+ logBlock('execSync_command', reason);
307
+ throw new Error(`VibeGuard: ${reason}`);
275
308
  }
276
309
  return execSync.call(this, cmd, opts);
277
310
  };
@@ -287,7 +320,9 @@ function activate(opts = {}) {
287
320
  logBlock('readFileSync_path', pathCheck.reason);
288
321
  throw new Error(`VibeGuard: ${pathCheck.reason}`);
289
322
  }
290
- return fs.readFileSync.call(this, p, ...args);
323
+ // Call the ORIGINAL, not the wrapper — calling fs.readFileSync here would
324
+ // recurse into this same function (infinite recursion / stack overflow).
325
+ return interceptors.readFileSync.call(this, p, ...args);
291
326
  };
292
327
  }
293
328
 
@@ -0,0 +1,245 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/mcp-audit.js — MCP server security audit (100% offline, zero network).
5
+ *
6
+ * MCP is the tool-plane for AI agents (Claude Code, Cursor, Windsurf). It is a
7
+ * young, under-secured surface. This audits the MCP servers an agent is
8
+ * configured to trust, statically, from the config file:
9
+ *
10
+ * 1. Prompt injection in server args / tool descriptions (tool poisoning).
11
+ * 2. Unpinned auto-install (`npx -y pkg`) — the server's code can silently
12
+ * change between runs (rug-pull) because no version is locked.
13
+ * 3. Remote-code / shell commands (curl|sh, node <url>, raw sh/bash).
14
+ * 4. Hardcoded secrets in the server's `env` block.
15
+ * 5. Over-broad filesystem grants (a filesystem server rooted at / or ~).
16
+ * 6. Definition drift: pin a hash of each server's config on first audit;
17
+ * on re-audit, flag any server whose config changed since you approved it
18
+ * (the classic MCP rug-pull — approve a benign tool, it mutates later).
19
+ *
20
+ * Nothing here executes a server or hits the network. It reads config only.
21
+ */
22
+
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+ const crypto = require('crypto');
26
+
27
+ let SECRET_PATTERNS = [];
28
+ try { ({ SECRET_PATTERNS } = require('./shell-guard')); } catch { /* optional */ }
29
+
30
+ // Prompt-injection / tool-poisoning signatures in text an agent will read.
31
+ const INJECTION_PATTERNS = [
32
+ { re: /ignore\s+(?:all\s+)?(?:the\s+)?(?:previous|prior|above|earlier)\s+instructions?/i, name: 'ignore-previous-instructions' },
33
+ { re: /disregard\s+(?:the\s+)?(?:system\s+prompt|previous|above|all)/i, name: 'disregard-system' },
34
+ { re: /you\s+are\s+now\s+(?:a|an|the)\b/i, name: 'role-override' },
35
+ { re: /new\s+instructions?\s*:/i, name: 'injected-instructions' },
36
+ { re: /<\s*\|?\s*(?:im_start|im_end|system|endoftext)\s*\|?\s*>/i, name: 'special-token-injection' },
37
+ { re: /\[\s*system\s*\]|\bsystem\s*prompt\s*override\b/i, name: 'system-role-injection' },
38
+ ];
39
+ // Invisible / bidi control chars used to smuggle hidden instructions.
40
+ const HIDDEN_CHARS_RE = /[​-‏‪-‮⁦-⁩]/;
41
+
42
+ function scanTextForInjection(text) {
43
+ const hits = [];
44
+ if (!text || typeof text !== 'string') return hits;
45
+ for (const p of INJECTION_PATTERNS) {
46
+ if (p.re.test(text)) hits.push(p.name);
47
+ }
48
+ if (HIDDEN_CHARS_RE.test(text)) hits.push('hidden-unicode-control-chars');
49
+ return hits;
50
+ }
51
+
52
+ // Which config files hold MCP server definitions.
53
+ function findConfigs(root) {
54
+ const out = [];
55
+ for (const name of ['.mcp.json', '.cursor/mcp.json', '.vscode/mcp.json']) {
56
+ const p = path.join(root, name);
57
+ if (fs.existsSync(p)) out.push(p);
58
+ }
59
+ return out;
60
+ }
61
+
62
+ // Normalize the two common shapes: { mcpServers: {...} } and { servers: {...} }.
63
+ function extractServers(json) {
64
+ const map = json.mcpServers || json.servers || {};
65
+ return Object.entries(map).map(([name, cfg]) => ({ name, cfg: cfg || {} }));
66
+ }
67
+
68
+ function stableHash(obj) {
69
+ return crypto.createHash('sha256').update(JSON.stringify(obj)).digest('hex').slice(0, 16);
70
+ }
71
+
72
+ const PIN_FILE = '.vibeguard/mcp-pins.json';
73
+ function loadPins(root) {
74
+ try { return JSON.parse(fs.readFileSync(path.join(root, PIN_FILE), 'utf8')); } catch { return {}; }
75
+ }
76
+ function savePins(root, pins) {
77
+ const dir = path.join(root, '.vibeguard');
78
+ try {
79
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
80
+ fs.writeFileSync(path.join(root, PIN_FILE), JSON.stringify(pins, null, 2));
81
+ } catch { /* best-effort */ }
82
+ }
83
+
84
+ function looksUnpinned(pkg) {
85
+ // A version pin is "@1.2.3" AFTER the package name. Scoped: @scope/name@1.2.3.
86
+ if (pkg.startsWith('@')) {
87
+ // @scope/name[@version]
88
+ const rest = pkg.slice(1);
89
+ const at = rest.indexOf('@');
90
+ return at === -1; // no version after scope/name
91
+ }
92
+ return !pkg.includes('@');
93
+ }
94
+
95
+ function auditServer(name, cfg) {
96
+ const findings = [];
97
+ const add = (severity, id, message, fix) => findings.push({ server: name, severity, id, message, fix });
98
+
99
+ const command = String(cfg.command || '');
100
+ const args = Array.isArray(cfg.args) ? cfg.args.map(String) : [];
101
+ const argStr = args.join(' ');
102
+ const env = cfg.env && typeof cfg.env === 'object' ? cfg.env : {};
103
+
104
+ // 1. Injection in the server name, args, or any description-like field.
105
+ const textBlob = [name, argStr, cfg.description || ''].join('\n');
106
+ const inj = scanTextForInjection(textBlob);
107
+ for (const kind of inj) {
108
+ add('critical', 'mcp.tool-poisoning',
109
+ `Server "${name}" contains a prompt-injection pattern (${kind}) an agent will read — possible tool poisoning.`,
110
+ 'Remove the injected text. Only trust MCP servers from sources you control or have reviewed.');
111
+ }
112
+
113
+ // 2/3. Remote-code / shell command.
114
+ if (/^(?:sh|bash|zsh|cmd|powershell)$/i.test(command) || /\|\s*(?:sh|bash|zsh)\b/.test(argStr)) {
115
+ add('critical', 'mcp.remote-code',
116
+ `Server "${name}" runs a raw shell (${command || 'pipe to shell'}) — arbitrary code execution on every agent session.`,
117
+ 'Replace with a pinned, published package. Never wire a shell pipe into an MCP server.');
118
+ }
119
+ if (/https?:\/\//.test(argStr) && /(?:curl|wget|node|deno|bun)\b/i.test(command + ' ' + argStr)) {
120
+ add('critical', 'mcp.remote-fetch-exec',
121
+ `Server "${name}" fetches and runs remote code (${command}). The remote can change at any time.`,
122
+ 'Vendor the code locally or use a version-pinned registry package.');
123
+ }
124
+
125
+ // 2b. Unpinned auto-install via npx -y (rug-pull surface).
126
+ if (/^(?:npx|bunx|pnpm)$/i.test(command)) {
127
+ const auto = args.some((a) => a === '-y' || a === '--yes');
128
+ const pkg = args.find((a) => a && !a.startsWith('-') && a !== 'dlx');
129
+ if (pkg && looksUnpinned(pkg)) {
130
+ add(auto ? 'high' : 'medium', 'mcp.unpinned-install',
131
+ `Server "${name}" auto-installs "${pkg}" with no version pin — its code can change between runs (rug-pull risk).`,
132
+ `Pin a version, e.g. "${pkg}@1.2.3", so the server code can't silently change.`);
133
+ }
134
+ }
135
+
136
+ // 4. Secrets in env.
137
+ for (const [k, v] of Object.entries(env)) {
138
+ if (typeof v !== 'string') continue;
139
+ for (const { re, type } of SECRET_PATTERNS) {
140
+ if (re.test(v)) {
141
+ add('critical', 'mcp.secret-in-config',
142
+ `Server "${name}" has a hardcoded ${type} in env var ${k} — committed secrets leak.`,
143
+ `Move ${k} to a local environment variable reference, and rotate the exposed credential.`);
144
+ break;
145
+ }
146
+ }
147
+ }
148
+
149
+ // 5. Over-broad filesystem grant.
150
+ const broadFs = args.find((a) => a === '/' || a === '~' || a === process.env.HOME || /^([A-Za-z]:[\\/])$/.test(a));
151
+ if (broadFs && /file|fs|filesystem/i.test(name + ' ' + argStr)) {
152
+ add('high', 'mcp.broad-filesystem',
153
+ `Server "${name}" is granted a very broad filesystem root ("${broadFs}") — the agent can read/write your whole disk.`,
154
+ 'Scope the filesystem server to a specific project directory.');
155
+ }
156
+
157
+ return findings;
158
+ }
159
+
160
+ // Main entry. opts.pin = true to (re)write the pin baseline this run.
161
+ function auditMcp(root, opts = {}) {
162
+ const configs = findConfigs(root);
163
+ const servers = [];
164
+ const findings = [];
165
+ let configFound = configs.length > 0;
166
+
167
+ const pins = loadPins(root);
168
+ const newPins = {};
169
+ const drifted = [];
170
+
171
+ for (const cfgPath of configs) {
172
+ let json;
173
+ try { json = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch { continue; }
174
+ const rel = path.relative(root, cfgPath).split(path.sep).join('/');
175
+ for (const { name, cfg } of extractServers(json)) {
176
+ const hash = stableHash(cfg);
177
+ newPins[name] = hash;
178
+ servers.push({ name, config: rel, command: cfg.command, hash });
179
+
180
+ // Definition drift (rug-pull): known server whose config changed.
181
+ if (pins[name] && pins[name] !== hash) {
182
+ drifted.push(name);
183
+ findings.push({
184
+ server: name, severity: 'high', id: 'mcp.definition-drift',
185
+ message: `Server "${name}" definition changed since it was last approved (rug-pull risk). Re-review before trusting it.`,
186
+ fix: 'Diff the change against what you approved. Re-pin with --pin only after review.',
187
+ });
188
+ }
189
+
190
+ for (const f of auditServer(name, cfg)) findings.push({ ...f, config: rel });
191
+ }
192
+ }
193
+
194
+ // First run (no pins yet) or explicit --pin: write the baseline.
195
+ if (opts.pin || Object.keys(pins).length === 0) savePins(root, newPins);
196
+
197
+ const bySev = { critical: 0, high: 0, medium: 0, low: 0 };
198
+ for (const f of findings) bySev[f.severity] = (bySev[f.severity] || 0) + 1;
199
+
200
+ return {
201
+ configFound,
202
+ servers,
203
+ findings,
204
+ drifted,
205
+ counts: bySev,
206
+ pinned: opts.pin || Object.keys(pins).length === 0,
207
+ };
208
+ }
209
+
210
+ function renderMcpAudit(result) {
211
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
212
+ const c = (code) => (useColor ? code : '');
213
+ const R = c('\x1b[0m'), B = c('\x1b[1m'), DIM = c('\x1b[2m');
214
+ const RED = c('\x1b[31m'), YEL = c('\x1b[33m'), GRN = c('\x1b[32m'), CYAN = c('\x1b[36m');
215
+ const sevColor = { critical: RED, high: YEL, medium: YEL, low: DIM };
216
+
217
+ const out = [];
218
+ out.push(`${B}${CYAN}VibeGuard MCP audit${R} ${DIM}(offline)${R}`);
219
+ if (!result.configFound) {
220
+ out.push(` ${DIM}No MCP config found (.mcp.json / .cursor/mcp.json / .vscode/mcp.json).${R}`);
221
+ return out.join('\n');
222
+ }
223
+ out.push(` ${DIM}${result.servers.length} server(s) configured${R}`);
224
+ out.push('');
225
+
226
+ if (result.findings.length === 0) {
227
+ out.push(` ${GRN}No MCP security issues found.${R}`);
228
+ return out.join('\n');
229
+ }
230
+
231
+ const order = ['critical', 'high', 'medium', 'low'];
232
+ const sorted = result.findings.slice().sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity));
233
+ for (const f of sorted) {
234
+ const col = sevColor[f.severity] || '';
235
+ out.push(` ${col}${B}${f.severity.toUpperCase().padEnd(8)}${R} [${f.id}] ${f.server}`);
236
+ out.push(` ${f.message}`);
237
+ out.push(` ${GRN}fix:${R} ${f.fix}`);
238
+ out.push('');
239
+ }
240
+ const cc = result.counts;
241
+ out.push(`${B}${cc.critical} critical, ${cc.high} high, ${cc.medium} medium${R}`);
242
+ return out.join('\n');
243
+ }
244
+
245
+ module.exports = { auditMcp, auditServer, scanTextForInjection, looksUnpinned, renderMcpAudit };
package/src/mcp-server.js CHANGED
@@ -119,6 +119,37 @@ const TOOLS = [
119
119
  description: 'Full pipeline: scan → suggest fixes → (after user applies) re-verify → rollback if new issues. Returns the plan only.',
120
120
  inputSchema: DIR_SCHEMA,
121
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
+ },
122
153
  {
123
154
  name: 'audit_config',
124
155
  description: 'Cross-file config audit: checks .env, next.config, docker-compose, k8s, CI workflows for security misconfig.',
@@ -632,6 +663,42 @@ async function handleReviewHotspots(args) {
632
663
  return textResult(text);
633
664
  }
634
665
 
666
+ async function handleGuardAction(args) {
667
+ const { inspectAction } = require('./action-guard');
668
+ const verdict = inspectAction(args, { trustedHosts: args.trustedHosts });
669
+ const head = verdict.blocked
670
+ ? `🛑 BLOCKED — ${verdict.reason}`
671
+ : verdict.action === 'warn'
672
+ ? `⚠ WARN — ${verdict.reason}`
673
+ : '✓ ALLOW — no secret/PII exfiltration or dangerous action detected.';
674
+ return textResult(head + '\n\n' + JSON.stringify(verdict, null, 2));
675
+ }
676
+
677
+ async function handleAgentScan(args) {
678
+ const dir = args.dir || process.cwd();
679
+ const { agentScan } = require('./agent-scan');
680
+ const result = agentScan(dir);
681
+ const cats = Object.entries(result.categories)
682
+ .map(([k, v]) => `${k}=${v.length}`).join(', ');
683
+ 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.` +
684
+ (cats ? ` [${cats}]` : '') +
685
+ (result.mcpDrifted && result.mcpDrifted.length ? ` ⚠ MCP drift: ${result.mcpDrifted.join(', ')}.` : '');
686
+ return textResult(summary + '\n\n' + JSON.stringify(result, null, 2));
687
+ }
688
+
689
+ async function handleMcpAudit(args) {
690
+ const dir = args.dir || process.cwd();
691
+ const { auditMcp } = require('./mcp-audit');
692
+ const result = auditMcp(dir, { pin: !!args.pin });
693
+ if (!result.configFound) {
694
+ return textResult('No MCP config found (.mcp.json / .cursor/mcp.json / .vscode/mcp.json).');
695
+ }
696
+ const c = result.counts;
697
+ const summary = `MCP audit: ${result.servers.length} server(s), ${c.critical} critical, ${c.high} high, ${c.medium} medium.` +
698
+ (result.drifted.length ? ` ⚠ definition drift on: ${result.drifted.join(', ')} (rug-pull risk — re-review).` : '');
699
+ return textResult(summary + '\n\n' + JSON.stringify(result, null, 2));
700
+ }
701
+
635
702
  async function handleScanUrl(args) {
636
703
  if (!args.url) return textResult('scan_url requires a "url" argument.', true);
637
704
  let res;
@@ -1752,6 +1819,9 @@ async function main() {
1752
1819
  else if (name === 'privacy_audit') result = await handlePrivacyAudit(args);
1753
1820
  else if (name === 'network_audit') result = await handleNetworkAudit(args);
1754
1821
  else if (name === 'ai_data_guard') result = await handleAIDataGuard(args);
1822
+ else if (name === 'mcp_audit') result = await handleMcpAudit(args);
1823
+ else if (name === 'agent_scan') result = await handleAgentScan(args);
1824
+ else if (name === 'guard_action') result = await handleGuardAction(args);
1755
1825
  else if (name === 'generate_privacy_policy') result = await handlePrivacyPolicy(args);
1756
1826
  else if (name === 'generate_csp') result = await handleCSP(args);
1757
1827
  else if (name === 'ai_firewall') result = await handleAIFirewall(args);