@yagyeshvyas/vibeguard 1.11.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,30 @@
3
3
  All notable changes to VibeGuard are documented here.
4
4
  Format based on [Keep a Changelog](https://keepachangelog.com/).
5
5
 
6
+ ## [1.12.0] - 2026-11-22
7
+
8
+ ### Added
9
+
10
+ - Linux bubblewrap backend with verified network, PID and filesystem isolation.
11
+ - Windows Job Object backend (process/memory containment; AppContainer/WFP still absent).
12
+ - External audit anchor file; `audit verify --anchor`.
13
+ - HTTPS/mTLS server options for the MCP HTTP bridge.
14
+ - Signed approver proof (`ApprovalBroker.signApproverProof`) and registered approver keys.
15
+
16
+ ### Changed — breaking approval behavior
17
+
18
+ - `ApprovalBroker.decide()` now requires a signed approver proof by default.
19
+ Register `approverKeys` and pass `proof` from the approver private key. Legacy
20
+ unauthenticated human strings are rejected.
21
+
22
+ ## [1.11.2] - 2026-11-22
23
+
24
+ ### Fixed
25
+
26
+ - Include `scripts/postinstall.js` in the npm tarball; the previous package
27
+ failed `npm install` with MODULE_NOT_FOUND. Clean install verified from the
28
+ registry.
29
+
6
30
  ## [1.11.1] - 2026-11-22
7
31
 
8
32
  ### Fixed
package/README.md CHANGED
@@ -32,7 +32,7 @@ Offline by default · Zero telemetry · No paid APIs · Free forever.
32
32
  <img src="https://img.shields.io/badge/compliance-10%20frameworks-orange?style=flat-square" alt="10 compliance frameworks" />
33
33
  <img src="https://img.shields.io/badge/AI--safety%20F1-96.8%25-brightgreen?style=flat-square" alt="AI-safety F1 96.8%" />
34
34
  <img src="https://img.shields.io/badge/telemetry-zero-brightgreen?style=flat-square" alt="Zero telemetry" />
35
- <img src="https://img.shields.io/badge/tests-623%20passed-blue?style=flat-square" alt="623 tests pass" />
35
+ <img src="https://img.shields.io/badge/tests-625%20passed-blue?style=flat-square" alt="625 tests pass" />
36
36
  <img src="https://img.shields.io/badge/self--scan-Grade%20A-brightgreen?style=flat-square" alt="Self-scan Grade A" />
37
37
  </p>
38
38
 
@@ -66,7 +66,7 @@ Offline by default · Zero telemetry · No paid APIs · Free forever.
66
66
 
67
67
  ---
68
68
 
69
- ## 🆕 What's New — v1.11.1
69
+ ## 🆕 What's New — v1.12.0
70
70
 
71
71
  **Security foundation v2 (internal testing).** This release is not beta or
72
72
  production-ready; it is the verified internal-testing build described in
@@ -81,12 +81,12 @@ production-ready; it is the verified internal-testing build described in
81
81
  - Linux `unshare` network/PID namespace sandbox with `sandbox verify`.
82
82
  - Memory provenance and multi-agent delegation guards; labeled detection corpus;
83
83
  AISVS-style readiness mapping.
84
- - **623 tests, 0 failures** on Windows Node24/Node18 and Linux Node22; 29/29
84
+ - **625 tests, 0 failures** on Windows Node24/Node18 and Linux Node22; 31/31
85
85
  platform tests on Windows/Linux/macOS CI.
86
86
 
87
- Install note: v1.11.1 is distributed as `@yagyeshvyas/vibeguard@1.11.1`. If a
87
+ Install note: v1.12.0 is distributed as `@yagyeshvyas/vibeguard@1.12.0`. If a
88
88
  registry mirror still serves an older build, use the exact
89
- [v1.11.1 GitHub release tarball](https://github.com/yagyeshVyas/VibeGuard/releases/tag/v1.11.1).
89
+ [v1.12.0 GitHub release tarball](https://github.com/yagyeshVyas/VibeGuard/releases/tag/v1.12.0).
90
90
 
91
91
  ## 🆕 What's New — v1.10.0
92
92
 
@@ -146,9 +146,9 @@ Full details, policy schema and honest limits: [MCP-FIREWALL.md](MCP-FIREWALL.md
146
146
 
147
147
  ---
148
148
 
149
- ## Security baseline v2 — v1.11.1 status (internal testing)
149
+ ## Security baseline v2 — v1.12.0 status (internal testing)
150
150
 
151
- This repository contains the v1.11.1 security foundation. It is **not** a
151
+ This repository contains the v1.12.0 security foundation. It is **not** a
152
152
  production-ready agent security platform. Linux network/PID namespace isolation
153
153
  is available; Windows/macOS OS isolation is not implemented.
154
154
 
@@ -165,8 +165,9 @@ Implemented and tested:
165
165
  prompts, unknown methods), size/depth limits and deep secret redaction.
166
166
  - Authenticated loopback **HTTP JSON-RPC + SSE** MCP bridge with upstream stdio.
167
167
  - Optional **kill-on-block/block-budget** quarantine response.
168
- - **Linux network/PID namespace** sandbox with a live verification probe
169
- (`vibeguard sandbox verify`); Windows/macOS OS backends remain unavailable.
168
+ - **Linux bubblewrap** sandbox with verified network/PID/filesystem isolation,
169
+ plus `unshare` fallback. **Windows Job Object** process/memory containment is
170
+ available; AppContainer/WFP and macOS VM are still absent.
170
171
  - Memory provenance guard and signed multi-agent delegation library.
171
172
  - Labeled detection corpus runner and AISVS-style readiness mapping.
172
173
  - Target-controlled scanner plugins are **disabled by default**; code execution
@@ -179,19 +180,21 @@ Implemented and tested:
179
180
 
180
181
  Not implemented or not verified:
181
182
 
182
- - **Windows AppContainer/Job Object/WFP and macOS VM backends**; Linux
183
- namespace filesystem is not isolated and is not a container/VM. Run
184
- `vibeguard sandbox verify` on Linux; Windows/macOS must not claim isolation.
185
- - **External audit anchor/transparency log**; local sidecar deletion/rollback
186
- is not detectable. Non-strict gateway audit is still the legacy hash chain.
187
- - **Authenticated approval service/UI**: the signed token verifier is
188
- implemented, but `ApprovalBroker.decide()` still accepts a human string.
189
- - Remote TLS/mTLS/OAuth multi-session deployment; HTTP bridge is loopback-tested
190
- JSON/SSE, not a full remote service.
183
+ - **Windows AppContainer/WFP and macOS VM backends are absent.** Windows Job
184
+ Object provides process/memory containment only; it does not isolate files or
185
+ network. Linux bubblewrap isolates network/PID/filesystem when installed, but
186
+ is not a VM/hardware boundary.
187
+ - **External audit anchor** is supported (`audit verify --anchor`); legacy
188
+ non-strict gateway audit is still the legacy hash chain.
189
+ - **Approval service/UI**: `ApprovalBroker.decide()` now requires a signed
190
+ approver proof; there is still no hosted approval UI/service.
191
+ - Remote OAuth multi-session deployment; TLS/mTLS server options exist, but
192
+ live OAuth authorization-server flow and persistence are not implemented.
191
193
  - Persistent memory/multi-agent runtime; `MemoryGuard`/`DelegationGraph` are
192
194
  tested libraries only.
193
195
  - Independent penetration test, representative precision/recall corpus, macOS
194
- full-suite evidence and npm registry publication (NPM_TOKEN missing).
196
+ full-suite evidence. npm 1.12.0 is published; GitHub Actions still lacks the
197
+ NPM_TOKEN secret and skips its publish step.
195
198
  - Dashboard/SDK and full AISVS certification; AISVS is an internal mapping.
196
199
 
197
200
 
package/bin/cli.js CHANGED
@@ -23,7 +23,7 @@ const {
23
23
  } = require('../src/report');
24
24
 
25
25
  // Flags that take a value (support both --flag=value and --flag value).
26
- const VALUE_FLAGS = new Set(['fail-on', 'scope', 'focus', 'model', 'since', 'base', 'o', 'output', 'file', 'types', 'min-confidence', 'trust', 'allow', 'save', 'max-blobs', 'max-commits', 'port', 'upstream', 'mode', 'api-key', 'token', 'token-header', 'timeout', 'pentest-url', 'pentest-verify-ssrf', 'budget', 'server', 'exec', 'command', 'policy', 'audit', 'check', 'tool', 'args', 'isolation', 'frameworks', 'framework', 'interval', 'dir', 'memory', 'pub', 'key', 'key-id', 'out', 'max-blocks', 'token-pub', 'token-issuer', 'token-tenant', 'token-key-id', 'approval-token', 'approval-pub', 'approval-issuer', 'approval-tenant', 'approval-key-id']);
26
+ const VALUE_FLAGS = new Set(['fail-on', 'scope', 'focus', 'model', 'since', 'base', 'o', 'output', 'file', 'types', 'min-confidence', 'trust', 'allow', 'save', 'max-blobs', 'max-commits', 'port', 'upstream', 'mode', 'api-key', 'token', 'token-header', 'timeout', 'pentest-url', 'pentest-verify-ssrf', 'budget', 'server', 'exec', 'command', 'policy', 'audit', 'check', 'tool', 'args', 'isolation', 'frameworks', 'framework', 'interval', 'dir', 'memory', 'pub', 'key', 'key-id', 'out', 'max-blocks', 'token-pub', 'token-issuer', 'token-tenant', 'token-key-id', 'approval-token', 'approval-pub', 'approval-issuer', 'approval-tenant', 'approval-key-id', 'anchor']);
27
27
 
28
28
  function parseArgs(argv) {
29
29
  const args = { _: [], flags: {} };
@@ -77,9 +77,9 @@ function cmdPolicy(args, flags) {
77
77
 
78
78
  function cmdAuditVerify(args, flags) {
79
79
  const log = args._[1] || flags.file;
80
- if (!log) { process.stderr.write('Usage: vibeguard audit verify <log.jsonl> --pub <key.pem> [--json]\n'); return 2; }
80
+ if (!log) { process.stderr.write('Usage: vibeguard audit verify <log.jsonl> --pub <key.pem> [--anchor file] [--json]\n'); return 2; }
81
81
  const publicKey = flags.pub ? loadPublicKey(fs.readFileSync(path.resolve(flags.pub))) : undefined;
82
- const result = SignedAuditLog.verifyFile(path.resolve(log), { publicKey });
82
+ const result = SignedAuditLog.verifyFile(path.resolve(log), { publicKey, anchorFile: flags.anchor ? path.resolve(flags.anchor) : undefined });
83
83
  if (flags.json) out(JSON.stringify({ ...result, signatureChecked: !!publicKey }, null, 2));
84
84
  else {
85
85
  out(`signed audit: ${publicKey ? (result.valid ? 'VALID' : 'INVALID') : 'UNVERIFIED'} — ${result.entries} entries`);
@@ -92,9 +92,15 @@ function cmdAuditVerify(args, flags) {
92
92
  async function cmdSandbox(args, flags) {
93
93
  const action = args._[1] || 'backends';
94
94
  if (action === 'verify') {
95
- const { getLinuxBackend } = require('../src/platform/os-sandbox');
96
- const backend = getLinuxBackend();
97
- if (!backend.available()) { process.stderr.write('Linux OS namespace backend unavailable on this host\n'); return 2; }
95
+ let backend;
96
+ if (process.platform === 'win32') {
97
+ const { WindowsJobSandbox } = require('../src/platform/windows-sandbox');
98
+ backend = new WindowsJobSandbox();
99
+ } else {
100
+ const { getLinuxBackend } = require('../src/platform/os-sandbox');
101
+ backend = getLinuxBackend();
102
+ }
103
+ if (!backend.available()) { process.stderr.write('OS backend unavailable on this host\n'); return 2; }
98
104
  const ok = await backend.verify();
99
105
  out(JSON.stringify({ backend: backend.id, verified: ok, verification: backend.verification, limitations: backend.limitations }, null, 2));
100
106
  return ok ? 0 : 1;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@yagyeshvyas/vibeguard",
3
- "version": "1.11.1",
4
- "description": "Offline-by-default security scanner and runtime firewall for AI-coded apps and MCP agents. 861 rules, 93 MCP tools, signed default-deny policy, tool-poisoning/prompt-injection/secret-exfiltration detection, signed audit, authenticated HTTP/SSE MCP bridge, Linux namespace sandboxing and OWASP Agentic AI + MCP coverage. Zero telemetry.",
3
+ "version": "1.12.0",
4
+ "description": "Offline-by-default security scanner and runtime firewall for AI-coded apps and MCP agents. 861 rules, 93 MCP tools, signed default-deny policy, tool-poisoning/prompt-injection/secret-exfiltration detection, signed audit with external anchor, authenticated HTTP/SSE MCP bridge with TLS, Linux bubblewrap network/PID/filesystem isolation, Windows Job Object containment, and OWASP Agentic AI + MCP coverage. Zero telemetry.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
7
7
  "author": "Yagyesh Vyas <https://www.linkedin.com/in/yagyeshvyas/>",
@@ -27,7 +27,8 @@
27
27
  "CHANGELOG.md",
28
28
  "MCP-FIREWALL.md",
29
29
  "docs",
30
- ".vibeguard-mcp.example.json"
30
+ ".vibeguard-mcp.example.json",
31
+ "scripts"
31
32
  ],
32
33
  "overrides": {
33
34
  "@hono/node-server": "^2.0.5",
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * scripts/counts.js — generates live counts of rules, MCP tools, and defense
5
+ * layers from the source. Used to keep README.md and package.json numbers
6
+ * from drifting. Run: `npm run counts`.
7
+ *
8
+ * Output: JSON to stdout: { rules, mcpTools, layers }
9
+ * Also writes a README block between <!-- COUNTS:START --> and <!-- COUNTS:END -->
10
+ * markers if --update-readme is passed.
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+
16
+ const ROOT = path.resolve(__dirname, '..');
17
+
18
+ // --- Rules ---
19
+ function countRules() {
20
+ const { allRules } = require(path.join(ROOT, 'src', 'rules'));
21
+ return allRules().length;
22
+ }
23
+
24
+ // --- MCP Tools ---
25
+ // Statically count tool registrations in mcp-server.js (can't require it
26
+ // directly — it starts an MCP server on load).
27
+ function countMcpTools() {
28
+ const code = fs.readFileSync(path.join(ROOT, 'src', 'mcp-server.js'), 'utf8');
29
+ const matches = [...code.matchAll(/name:\s*['"]([a-z_]+)['"]/g)].map((m) => m[1]);
30
+ const tools = matches.filter((n) => n !== 'vibeguard');
31
+ const unique = [...new Set(tools)];
32
+ return unique.length;
33
+ }
34
+
35
+ // --- Defense Layers ---
36
+ // Counted from the pre-deploy gates in src/pre-deploy.js (the canonical list).
37
+ function countLayers() {
38
+ // Count from pre-deploy.js GATES array — no git needed.
39
+ try {
40
+ const src = fs.readFileSync(path.join(ROOT, 'src', 'pre-deploy.js'), 'utf8');
41
+ const match = src.match(/const GATES\s*=\s*\[([\s\S]*?)\]/);
42
+ if (match) {
43
+ const ids = match[1].match(/id:\s*'[^']+'/g);
44
+ if (ids) return ids.length;
45
+ }
46
+ } catch {}
47
+ return 13;
48
+ }
49
+
50
+ function getCounts() {
51
+ return {
52
+ rules: countRules(),
53
+ mcpTools: countMcpTools(),
54
+ layers: countLayers(),
55
+ };
56
+ }
57
+
58
+ // --- README update ---
59
+ function updateReadme(counts) {
60
+ const readmePath = path.join(ROOT, 'README.md');
61
+ let content = fs.readFileSync(readmePath, 'utf8');
62
+ const startMarker = '<!-- COUNTS:START -->';
63
+ const endMarker = '<!-- COUNTS:END -->';
64
+
65
+ const block = [
66
+ startMarker,
67
+ `<!-- Auto-generated by scripts/counts.js — do not edit manually -->`,
68
+ `<!-- Rules: ${counts.rules} | MCP Tools: ${counts.mcpTools} | Defense Layers: ${counts.layers} -->`,
69
+ endMarker,
70
+ ].join('\n');
71
+
72
+ const startIdx = content.indexOf(startMarker);
73
+ const endIdx = content.indexOf(endMarker);
74
+
75
+ if (startIdx !== -1 && endIdx !== -1) {
76
+ content = content.slice(0, startIdx) + block + content.slice(endIdx + endMarker.length);
77
+ } else {
78
+ // No markers yet — append before the closing </div> at the end.
79
+ content = content.trimEnd() + '\n\n' + block + '\n';
80
+ }
81
+
82
+ fs.writeFileSync(readmePath, content);
83
+ }
84
+
85
+ // --- CLI ---
86
+ const args = process.argv.slice(2);
87
+ const counts = getCounts();
88
+
89
+ if (args.includes('--update-readme')) {
90
+ updateReadme(counts);
91
+ console.error('Updated README.md with counts block.');
92
+ }
93
+
94
+ console.log(JSON.stringify(counts, null, 2));
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ // scripts/gen-integrity.js — regenerate src/integrity.json with fresh SHA-256
4
+ // hashes of the critical security modules. Run before publish (wired into
5
+ // prepublishOnly) so the shipped package can self-verify it wasn't tampered.
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { computeManifest } = require('../src/integrity');
10
+
11
+ const srcDir = path.join(__dirname, '..', 'src');
12
+ const manifest = computeManifest(srcDir);
13
+ const out = path.join(srcDir, 'integrity.json');
14
+ fs.writeFileSync(out, JSON.stringify(manifest, null, 2) + '\n');
15
+ process.stdout.write(`integrity.json written: ${Object.keys(manifest.hashes).length} modules hashed.\n`);
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* Live MCP handshake test: speaks the MCP JSON-RPC protocol over stdio,
4
+ * exactly like Claude Code / Cursor / any MCP client would. */
5
+ const { spawn } = require('child_process');
6
+ const path = require('path');
7
+
8
+ const serverPath = path.join(__dirname, '..', 'src', 'mcp-server.js');
9
+ const child = spawn(process.execPath, [serverPath], {
10
+ cwd: path.join(__dirname, '..'),
11
+ env: { ...process.env, PATH: process.env.PATH },
12
+ stdio: ['pipe', 'pipe', 'pipe'],
13
+ });
14
+
15
+ // Surface spawn/exit failures instead of dying silently (as the OS pipes do).
16
+ child.on('error', (e) => {
17
+ console.error('FATAL: could not spawn MCP server —', e.message);
18
+ for (const p of pending.values()) p.rej(e);
19
+ pending.clear();
20
+ process.exitCode = 1;
21
+ });
22
+ child.on('exit', (code) => {
23
+ if (pending.size > 0) {
24
+ console.error('FATAL: MCP server exited early (code=' + code + ') with requests pending.');
25
+ for (const p of pending.values()) p.rej(new Error('server exited'));
26
+ pending.clear();
27
+ process.exitCode = 1;
28
+ }
29
+ });
30
+
31
+ let buf = '';
32
+ const pending = new Map();
33
+ let idc = 0;
34
+
35
+ function send(method, params) {
36
+ const id = ++idc;
37
+ const msg = JSON.stringify({ jsonrpc: '2.0', id, method, params });
38
+ child.stdin.write(msg + '\n');
39
+ return new Promise((res, rej) => pending.set(id, { res, rej }));
40
+ }
41
+
42
+ child.stdout.on('data', (d) => {
43
+ process.stderr.write('[raw-out] ' + d.toString().slice(0, 300) + '\n');
44
+ buf += d.toString();
45
+ let idx;
46
+ while ((idx = buf.indexOf('\n')) !== -1) {
47
+ const line = buf.slice(0, idx).trim();
48
+ buf = buf.slice(idx + 1);
49
+ if (!line) continue;
50
+ let msg;
51
+ try { msg = JSON.parse(line); } catch { continue; }
52
+ if (msg.id && pending.has(msg.id)) {
53
+ const p = pending.get(msg.id);
54
+ pending.delete(msg.id);
55
+ msg.error ? p.rej(new Error(JSON.stringify(msg.error))) : p.res(msg.result);
56
+ } else if (msg.method === 'notifications/initialized') {
57
+ // ignore
58
+ }
59
+ }
60
+ });
61
+
62
+ let stderr = '';
63
+ child.stderr.on('data', (d) => { stderr += d.toString(); });
64
+
65
+ (async () => {
66
+ try {
67
+ const t0 = Date.now();
68
+ const init = await send('initialize', {
69
+ protocolVersion: '2024-11-05',
70
+ capabilities: {},
71
+ clientInfo: { name: 'hermes-livecheck', version: '1.0.0' },
72
+ });
73
+ console.log('[1] initialize OK in', Date.now() - t0 + 'ms');
74
+ console.log(' serverInfo:', JSON.stringify(init.serverInfo));
75
+ console.log(' protocolVersion:', init.protocolVersion);
76
+ console.log(' capabilities:', JSON.stringify(init.capabilities));
77
+
78
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
79
+
80
+ const tools = await send('tools/list', {});
81
+ console.log('[2] tools/list OK —', tools.tools.length, 'tools');
82
+ const names = tools.tools.map((t) => t.name);
83
+ console.log(' sample:', names.slice(0, 8).join(', '), '…');
84
+
85
+ // Verify every tool has a name + description + inputSchema (agents need these).
86
+ const missing = tools.tools.filter((t) => !t.name || !t.description || !t.inputSchema);
87
+ console.log('[3] tools missing name/desc/schema:', missing.length);
88
+ const noDesc = tools.tools.filter((t) => !t.description || t.description.length < 10);
89
+ if (noDesc.length) console.log(' weak descriptions:', noDesc.map((t) => t.name).join(', '));
90
+
91
+ // Actually call the flagship tool against this repo.
92
+ const res = await send('tools/call', {
93
+ name: 'scan_project',
94
+ arguments: { dir: path.join(__dirname, '..', 'test', 'fixtures') },
95
+ });
96
+ if (res.isError) throw new Error('scan_project failed: ' + JSON.stringify(res).slice(0, 300));
97
+ const text = (res.content || []).map((c) => c.text || '').join('');
98
+ console.log('[4] tools/call scan_project OK —', text.slice(0, 90).replace(/\n/g, ' '));
99
+ if (!/Grade [A-F]/.test(text)) throw new Error('scan_project result missing grade: ' + text.slice(0, 200));
100
+
101
+ // check_code is the inline-snippet tool agents use most.
102
+ const res2 = await send('tools/call', {
103
+ name: 'check_code',
104
+ arguments: { code: 'const fs=require("fs");\nconst data = fs.readFileSync(req.query.file, "utf8");\nres.send(data);', language: 'javascript' },
105
+ });
106
+ if (res2.isError) throw new Error('check_code failed: ' + JSON.stringify(res2).slice(0, 300));
107
+ const text2 = (res2.content || []).map((c) => c.text || '').join('');
108
+ console.log('[5] tools/call check_code OK — finds:', /critical|high|medium|low|path-traversal|injection/i.test(text2) ? 'findings present' : 'no findings?');
109
+
110
+ // Unknown tool must name the tool, not "undefined" — agents rely on this error.
111
+ const bad = await send('tools/call', { name: 'definitely_not_a_tool', arguments: {} });
112
+ if (!bad.isError) throw new Error('unknown tool should have errored');
113
+ const badText = (bad.content || []).map((c) => c.text || '').join('');
114
+ if (!badText.includes('definitely_not_a_tool')) throw new Error('unknown-tool error does not name the tool: ' + badText);
115
+ console.log('[6] unknown tool error names the tool OK —', badText.slice(0, 60));
116
+
117
+ console.log('ALL MCP HANDSHAKE CHECKS PASSED');
118
+ } catch (e) {
119
+ console.error('MCP HANDSHAKE FAILED:', e.message);
120
+ if (stderr) console.error('server stderr:', stderr.slice(0, 800));
121
+ process.exitCode = 1;
122
+ } finally {
123
+ child.kill();
124
+ // Let stdout flush naturally — process.exit() truncates piped output.
125
+ }
126
+ })();
127
+
128
+ // Global watchdog: if the server never answers, fail loudly instead of hanging.
129
+ setTimeout(() => {
130
+ if (pending.size > 0) {
131
+ console.error('MCP HANDSHAKE TIMED OUT — server never responded. stderr:');
132
+ console.error(stderr.slice(0, 1200) || '(no stderr)');
133
+ process.exitCode = 1;
134
+ child.kill();
135
+ }
136
+ }, 20000).unref();
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env node
2
+ /* Deep MCP tool audit: boots the server, enumerates every tool, calls each one
3
+ * with minimal/valid args, and classifies the result:
4
+ * PASS — returned a result
5
+ * graceful-err — returned an isError result with a clean validation message
6
+ * BUG — crash, "Unknown tool", TypeError, or empty/undefined result
7
+ * Usage: node scripts/mcp-audit-tools.js [--json]
8
+ */
9
+ 'use strict';
10
+ const { spawn } = require('child_process');
11
+ const path = require('path');
12
+
13
+ const serverPath = path.join(__dirname, '..', 'src', 'mcp-server.js');
14
+ const child = spawn(process.execPath, [serverPath], {
15
+ cwd: path.join(__dirname, '..'),
16
+ env: { ...process.env, PATH: process.env.PATH },
17
+ stdio: ['pipe', 'pipe', 'pipe'],
18
+ });
19
+
20
+ let buf = '';
21
+ const pending = new Map();
22
+ let idc = 0;
23
+
24
+ child.stdout.on('data', (d) => {
25
+ buf += d.toString('utf8');
26
+ let idx;
27
+ while ((idx = buf.indexOf('\n')) !== -1) {
28
+ const line = buf.slice(0, idx).trim();
29
+ buf = buf.slice(idx + 1);
30
+ if (!line) continue;
31
+ let msg;
32
+ try { msg = JSON.parse(line); } catch { continue; }
33
+ if (msg.id && pending.has(msg.id)) {
34
+ const { resolve } = pending.get(msg.id);
35
+ pending.delete(msg.id);
36
+ resolve(msg);
37
+ }
38
+ }
39
+ });
40
+ child.stderr.on('data', () => { /* banner etc — ignore */ });
41
+
42
+ function send(method, params, timeoutMs = 30000) {
43
+ const id = ++idc;
44
+ const msg = JSON.stringify({ jsonrpc: '2.0', id, method, params });
45
+ return new Promise((resolve, reject) => {
46
+ const t = setTimeout(() => { pending.delete(id); reject(new Error(`timeout ${method}`)); }, timeoutMs);
47
+ pending.set(id, { resolve: (m) => { clearTimeout(t); resolve(m); } });
48
+ child.stdin.write(msg + '\n');
49
+ });
50
+ }
51
+
52
+ // Build a minimal valid arg set from a JSON Schema (string props get samples).
53
+ function sampleArgs(schema) {
54
+ const props = (schema && schema.properties) || {};
55
+ const args = {};
56
+ const required = (schema && schema.required) || [];
57
+ const isDir = (k) => /dir|root|folder|directory/i.test(k);
58
+ const isFile = (k) => /^file$|filename|^path$/.test(k);
59
+ const isRule = (k) => /^rule|rule_id|ruleid/i.test(k);
60
+ for (const [k, v] of Object.entries(props)) {
61
+ if (!required.includes(k) && v.default === undefined) continue;
62
+ let val;
63
+ if (v.default !== undefined) val = v.default;
64
+ else if (isDir(k)) val = 'src'; // real dir in the repo
65
+ else if (isFile(k)) val = 'src/scanner.js'; // real file
66
+ else if (isRule(k)) val = 'ast.command-injection'; // real rule id
67
+ else if (v.type === 'string') {
68
+ val = k === 'preset' ? 'react' // real preset
69
+ : k === 'command' ? 'ls -la'
70
+ : 'test';
71
+ } else {
72
+ const S = { integer: 1, number: 1, boolean: true, array: ['test'], object: {} };
73
+ val = v.enum ? v.enum[0] : S[v.type] !== undefined ? S[v.type] : 'test';
74
+ }
75
+ args[k] = val;
76
+ }
77
+ // For dir-scoped tools, point scans at the repo 'src' so they complete fast.
78
+ if (Object.entries(args).length === 0) args.dir = 'src';
79
+ return args;
80
+ }
81
+
82
+ function flatten(text) {
83
+ return String(text).replace(/\s+/g, ' ').trim().slice(0, 140);
84
+ }
85
+
86
+ async function main() {
87
+ const out = { pass: [], graceful: [], bugs: [] };
88
+ try {
89
+ await send('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'audit', version: '1' } });
90
+ const list = await send('tools/list', {});
91
+ const tools = (list.result && list.result.tools) || [];
92
+ for (const t of tools) {
93
+ let res;
94
+ try {
95
+ res = await send('tools/call', { name: t.name, arguments: sampleArgs(t.inputSchema) });
96
+ } catch (e) {
97
+ out.bugs.push({ tool: t.name, why: 'call crashed: ' + e.message });
98
+ continue;
99
+ }
100
+ const r = res.result;
101
+ if (!r) { out.bugs.push({ tool: t.name, why: 'empty result' }); continue; }
102
+ if (r.isError) {
103
+ const text = flatten(Array.isArray(r.content) ? r.content.map((c) => c.text || '').join(' ') : JSON.stringify(r));
104
+ // Graceful validation errors name the missing arg / bad input; bugs crash.
105
+ if (/unknown tool|typeerror|internal error|cannot read|is not a function|undefined is not/i.test(text) && !/required/i.test(text)) {
106
+ out.bugs.push({ tool: t.name, why: text });
107
+ } else {
108
+ out.graceful.push({ tool: t.name, why: text });
109
+ }
110
+ } else {
111
+ out.pass.push(t.name);
112
+ }
113
+ }
114
+ } finally {
115
+ child.stdin.end();
116
+ child.kill();
117
+ }
118
+ const json = process.argv.includes('--json');
119
+ if (json) { console.log(JSON.stringify(out, null, 2)); return; }
120
+ console.log(`tools audited: ${out.pass.length + out.graceful.length + out.bugs.length}`);
121
+ console.log(`PASS : ${out.pass.length}`);
122
+ console.log(`graceful-err : ${out.graceful.length} (expected: missing-arg / not-found)`);
123
+ for (const g of out.graceful) console.log(` ~ ${g.tool}: ${g.why}`);
124
+ console.log(`BUGS : ${out.bugs.length}`);
125
+ for (const b of out.bugs) console.log(` ! ${b.tool}: ${b.why}`);
126
+ process.exitCode = out.bugs.length ? 1 : 0;
127
+ }
128
+
129
+ main().catch((e) => { console.error('audit failed:', e.message); process.exitCode = 2; });
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ // scripts/postinstall.js — runs after npm install.
4
+ // Prints a one-line suggestion. NEVER modifies shell profiles or any file
5
+ // outside the installed package. A security tool that silently edits user
6
+ // files is doing the thing it warns about.
7
+
8
+ try {
9
+ // Opt-out + CI quiet: a security tool should not add install-time noise or
10
+ // surprise. VIBEGUARD_NO_POSTINSTALL=1 silences this entirely.
11
+ if (process.env.VIBEGUARD_NO_POSTINSTALL === '1' || process.env.CI) {
12
+ process.exit(0);
13
+ }
14
+
15
+ const path = require('path');
16
+ const fs = require('fs');
17
+
18
+ const cliPath = path.join(__dirname, '..', 'bin', 'cli.js');
19
+ if (!fs.existsSync(cliPath)) {
20
+ process.exit(0);
21
+ }
22
+
23
+ process.stderr.write('\n VibeGuard installed. Run "vibeguard auto" to enable layered protection.\n\n');
24
+ process.exit(0);
25
+ } catch {
26
+ process.exit(0);
27
+ }