@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.
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * scripts/security-bench.js — reproducible local performance measurements for
5
+ * the v2 security primitives. No network. Results are environment-specific;
6
+ * the report records hardware/Node so numbers are not comparable across
7
+ * machines without context.
8
+ */
9
+
10
+ const os = require('os');
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const { performance } = require('perf_hooks');
14
+ const { IdentityAuthority } = require('../src/platform/identity');
15
+ const { StrictPolicyEngine } = require('../src/platform/policy');
16
+ const { SignedAuditLog } = require('../src/platform/signed-audit');
17
+ const { scanTextForInjection } = require('../src/mcp-audit');
18
+ const { runInProcess } = require('../src/sandbox');
19
+ const { createEngine } = require('../src/mcp-firewall');
20
+
21
+ function nowMs() { return performance.now(); }
22
+ function bench(name, iterations, fn) {
23
+ const times = [];
24
+ const start = nowMs();
25
+ for (let i = 0; i < iterations; i++) {
26
+ const t0 = nowMs();
27
+ fn(i);
28
+ times.push(nowMs() - t0);
29
+ }
30
+ const total = nowMs() - start;
31
+ times.sort((a, b) => a - b);
32
+ return {
33
+ name,
34
+ iterations,
35
+ totalMs: Number(total.toFixed(2)),
36
+ opsPerSec: Number(((iterations / total) * 1000).toFixed(1)),
37
+ p50Ms: Number(times[Math.floor(times.length * 0.5)].toFixed(4)),
38
+ p95Ms: Number(times[Math.floor(times.length * 0.95)].toFixed(4)),
39
+ };
40
+ }
41
+
42
+ function main() {
43
+ const auth = new IdentityAuthority({ issuer: 'human:bench/security', tenant: 'bench' });
44
+ const roots = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-bench-'));
45
+ const policy = new StrictPolicyEngine({
46
+ schemaVersion: '2.0',
47
+ policyId: 'bench',
48
+ policyVersion: '1',
49
+ mode: 'strict',
50
+ defaults: { decision: 'deny' },
51
+ subjects: [{ principal: 'agent:bench/ci', capabilities: ['fs.read', 'mcp.tool.invoke'] }],
52
+ tools: [{ id: 'allow-read', effect: 'allow', match: { tool: 'read_file', capability: 'fs.read' }, resources: { paths: ['src/**'] } }],
53
+ }, { root: roots });
54
+ const text = 'normal developer documentation with no instruction at all. '.repeat(16);
55
+
56
+ const results = [];
57
+ results.push(bench('identity.issue+verify', 1000, () => {
58
+ const t = auth.issue({ principal: 'agent:bench/ci', capabilities: ['fs.read'], ttlSeconds: 300 });
59
+ auth.verify(t.token, { replay: false });
60
+ }));
61
+ results.push(bench('policy.evaluate', 5000, () => {
62
+ policy.evaluate({ principal: 'agent:bench/ci', server: 'files', tool: 'read_file', capability: 'fs.read', arguments: { path: 'src/index.js' } });
63
+ }));
64
+ results.push(bench('detect.injectionScan.1KB', 2000, () => scanTextForInjection(text)));
65
+
66
+ const auditFile = path.join(roots, 'audit.jsonl');
67
+ const audit = new SignedAuditLog({ file: auditFile, tenant: 'bench' });
68
+ const auditStart = nowMs();
69
+ for (let i = 0; i < 200; i++) audit.append('bench.event', { i }, { principal: 'agent:bench/ci', decision: 'allow' });
70
+ const auditMs = nowMs() - auditStart;
71
+ results.push({ name: 'audit.append+fsync', iterations: 200, totalMs: Number(auditMs.toFixed(2)), opsPerSec: Number(((200 / auditMs) * 1000).toFixed(1)) });
72
+ const vStart = nowMs();
73
+ const verification = SignedAuditLog.verifyFile(auditFile, { publicKey: audit.publicKey });
74
+ results.push({ name: 'audit.verify', iterations: 200, totalMs: Number((nowMs() - vStart).toFixed(2)), valid: verification.valid });
75
+
76
+ if (require('../src/sandbox').processIsolationSupported()) {
77
+ results.push(bench('sandbox.process.spawn+run', 5, () => runInProcess('const x = 1 + 2; x', { timeout: 2000 })));
78
+ }
79
+
80
+ const gateway = createEngine({ root: roots, policy: {}, logger: { log() {} } });
81
+ results.push(bench('mcp.engine.checkToolCall', 2000, () => gateway.checkToolCall('bench', 'read_file', { path: 'src/index.js' })));
82
+
83
+ const report = {
84
+ generatedAt: new Date().toISOString(),
85
+ node: process.version,
86
+ platform: `${os.platform()} ${os.release()} (${process.arch})`,
87
+ cpu: (os.cpus()[0] && os.cpus()[0].model) || 'unknown',
88
+ memoryBytes: os.totalmem(),
89
+ iterationsNote: 'Wall-clock measurements on this machine only; use the same environment for comparisons.',
90
+ results,
91
+ };
92
+ const outArg = process.argv.indexOf('--out');
93
+ if (outArg !== -1 && process.argv[outArg + 1]) {
94
+ fs.mkdirSync(path.dirname(path.resolve(process.argv[outArg + 1])), { recursive: true });
95
+ fs.writeFileSync(path.resolve(process.argv[outArg + 1]), JSON.stringify(report, null, 2) + '\n');
96
+ }
97
+ console.log(JSON.stringify(report, null, 2));
98
+ }
99
+
100
+ main();
package/src/integrity.js CHANGED
@@ -37,7 +37,7 @@ const CRITICAL_MODULES = [
37
37
  'platform/contracts.js', 'platform/canonical.js', 'platform/identity.js',
38
38
  'platform/approval.js', 'platform/signed-audit.js', 'platform/policy.js',
39
39
  'platform/jwt.js', 'platform/ssrf.js', 'platform/http-gateway.js',
40
- 'platform/sandbox-manager.js', 'platform/os-sandbox.js',
40
+ 'platform/sandbox-manager.js', 'platform/os-sandbox.js', 'platform/windows-sandbox.js',
41
41
  'platform/mcp-http-bridge.js', 'platform/memory-guard.js',
42
42
  'platform/delegation.js', 'platform/aisvs.js',
43
43
  ];
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "tool": "vibeguard",
3
- "generatedAt": "2026-11-22T18:57:17.069Z",
3
+ "generatedAt": "2026-11-22T19:31:04.837Z",
4
4
  "algo": "sha256",
5
5
  "hashes": {
6
6
  "action-guard.js": "764f02ee6d4a1dc95939642f120ac7c233f66aee2794dd71efa15f5690fc43b0",
@@ -25,7 +25,7 @@
25
25
  "bundles.js": "7c6535e4be4566edd2aec0d9d63c58e200813b621e503ad1d51a5a4840a1b359",
26
26
  "agentic.js": "4b7130e1e15f603df8ceb7ef8284db8d1784e8dd450a8ed332873271f7cec4ee",
27
27
  "suppress.js": "3c34ebbdabb0338fe3bf00d399aaa9ab04fb796067fe33a4a4b52884eb5c4fda",
28
- "mcp-firewall.js": "84c37c06bc82570d5e072cd7551704bd697be525ad49b598202564daf13f493d",
28
+ "mcp-firewall.js": "9ec7d5ec73b37b226027346e1eb81a68cfe200ba16561897e139cdd8f404c794",
29
29
  "agent-policy.js": "5735aca870b7ecfe55c3525f7a338e9f97e3c1ca000dbb16850c312db53eb9e9",
30
30
  "skill-scan.js": "b172529a94333f8fb07098df518ecce3be9cf93242830e140ade48c2742f50e0",
31
31
  "owasp-agentic.js": "7ca8dca83b633ae62607b2ab24696bdfbf34b4a7b96c3b26ba1035b9b05e9a99",
@@ -36,15 +36,16 @@
36
36
  "platform/contracts.js": "9c66ed174220e2f0b26adec8a222f2b370b4d1a7d55d272043f0154c958ad5ed",
37
37
  "platform/canonical.js": "a354597d9f81278ea14c76cbb726207ca228c2652876517838708769f70156e3",
38
38
  "platform/identity.js": "fc91495ef08c92b77dfaa0c6d11f4c837a0e309022fa683e7140803270606cc4",
39
- "platform/approval.js": "432b3abe8430084b2a3972ee39c86c797ac3e588be7e4fce3edaf35550d663df",
40
- "platform/signed-audit.js": "fd52a1631c63caa596c934e40823fee7b1cd1c31d9b6816fdaa9d1724c77d0cd",
39
+ "platform/approval.js": "a9d2e97ba80df37461e95aeff19eb4fd8bcba0d026e97c956158d1fce3f368da",
40
+ "platform/signed-audit.js": "46471ebb5765cb2725f3d1bccbef7bf1fef59f1f2e777f528e999fa96638621d",
41
41
  "platform/policy.js": "c54bca0290605ea74be72b9a7e06d6d3049ef53bf837e45e7d03330da5ecc1cc",
42
42
  "platform/jwt.js": "51c42b6f998b00c2a689194d9d60e6176df2f9b78406cd0e3b682cfcbba9a142",
43
43
  "platform/ssrf.js": "613e46a02c8930aed93b6d7227451167ae0349ab53b3d9ffefa997b2a5ba4e12",
44
- "platform/http-gateway.js": "7c47758a39923c17566c408aced7a18e1eba9488b99d7e830132a541ce878130",
45
- "platform/sandbox-manager.js": "290ff7df08bf5e901a112cb0a550f7e1830c3369dfd2d18a266fa133c692f301",
46
- "platform/os-sandbox.js": "ff57b36480a28b24b402228849b9bd0a433e20854da852d537c74f6d45fcdaf5",
47
- "platform/mcp-http-bridge.js": "7124c824c8ebfd9e20895dd728442c1b5f3a9bcea673a5d245f9aebbe6a76d2f",
44
+ "platform/http-gateway.js": "357749ea416bc242b20c2a5b5e92e179d99d7d6b41a62b84517b91f2147b5c8d",
45
+ "platform/sandbox-manager.js": "d882c114c4c640ca722dec11b351a4ec30b62c45254c2266706f0db617c32eb9",
46
+ "platform/os-sandbox.js": "b503f0e422c4005c57f11384fb1fbe474a94dd96c11340576da8e2e1d34a60d8",
47
+ "platform/windows-sandbox.js": "d3c5e5280aa81b740afd5fbbd31b9664d426e12154c4b199232932426aab3a08",
48
+ "platform/mcp-http-bridge.js": "21175c0fa187710e3af69b11b8b9017cdc321f6bb309aced4dd83a9789044a9a",
48
49
  "platform/memory-guard.js": "468da6d5483cb44ae2e2f3051b011afee44bbc0a900892950aabf9ac26ee3eae",
49
50
  "platform/delegation.js": "b7d4aa6c0885528f26de47c072b5e53e1b96bdc393a02fce3c6e8cbd780ad5cb",
50
51
  "platform/aisvs.js": "711fa398da46c8deb386b6397d0b104905cc761145656c8bdd1ce5e78d394a35"
@@ -186,7 +186,7 @@ function createEngine(opts = {}) {
186
186
  opts.signedAuditFile
187
187
  ? path.resolve(projectRoot, opts.signedAuditFile)
188
188
  : path.join(projectRoot, '.vibeguard', 'audit', 'mcp-firewall.signed.jsonl'),
189
- { projectRoot, auditKeyFile: opts.auditKeyFile, tenant: opts.tenant, keyId: 'gateway-audit' }
189
+ { projectRoot, auditKeyFile: opts.auditKeyFile, anchorFile: opts.anchorFile, tenant: opts.tenant, keyId: 'gateway-audit' }
190
190
  )
191
191
  : createLogger(opts.auditFile ? path.resolve(projectRoot, opts.auditFile) : null)
192
192
  );
@@ -693,6 +693,7 @@ function startProxy(opts = {}) {
693
693
  signedAudit: opts.signedAudit === true || (opts.strict === true && opts.signedAudit !== false),
694
694
  signedAuditFile: opts.signedAuditFile,
695
695
  auditKeyFile: opts.auditKeyFile,
696
+ anchorFile: opts.anchorFile,
696
697
  logger: opts.logger,
697
698
  strict: opts.strict === true,
698
699
  });
@@ -41,6 +41,11 @@ class ApprovalBroker {
41
41
  this.publicKey = publicKey;
42
42
  this.now = opts.now || (() => new Date());
43
43
  this.defaultTtlSeconds = opts.defaultTtlSeconds || 300;
44
+ this.approverKeys = new Map();
45
+ for (const [principal, key] of Object.entries(opts.approverKeys || {})) {
46
+ this.approverKeys.set(principal, loadPublicKey(key));
47
+ }
48
+ this.requireApproverProof = opts.requireApproverProof !== false;
44
49
  this.tickets = new Map();
45
50
  this.usedTokens = new Set();
46
51
  }
@@ -94,6 +99,19 @@ class ApprovalBroker {
94
99
  if (tenant(approver) !== this.tenant) throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'approver tenant mismatch');
95
100
  if (approver === ticket.principal) throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'self-approval is not allowed');
96
101
 
102
+ if (this.requireApproverProof) {
103
+ const key = this.approverKeys.get(approver);
104
+ if (!key) throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'approver has no registered verification key');
105
+ const proof = decision.proof;
106
+ if (!proof) throw new VibeGuardError(ERROR_CODES.AUTH_REQUIRED, 'signed approver proof is required', { status: 401 });
107
+ const decoded = verifyJws(proof, key);
108
+ const pp = decoded.payload;
109
+ if (decoded.header.typ !== 'VGAPPROVER' || decoded.header.alg !== 'EdDSA') throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'invalid approver proof type');
110
+ if (pp.aud !== 'vibeguard-approver-proof' || pp.sub !== approver) throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'approver proof identity mismatch');
111
+ if (pp.ticketId !== ticket.ticketId || pp.actionDigest !== ticket.actionDigest || pp.nonce !== ticket.nonce) throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'approver proof does not bind this ticket/action');
112
+ if (!Number.isInteger(pp.exp) || pp.exp <= Math.floor(this.now().getTime() / 1000)) throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'approver proof expired');
113
+ }
114
+
97
115
  if (decision.approve !== true) {
98
116
  ticket.status = 'denied';
99
117
  ticket.approver = approver;
@@ -122,6 +140,13 @@ class ApprovalBroker {
122
140
  return { status: 'approved', ticket: publicTicket(ticket), approvalToken: token };
123
141
  }
124
142
 
143
+ static signApproverProof({ ticketId, actionDigest: digest, nonce, approver, privateKey, ttlSeconds = 120, keyId = 'approver' } = {}) {
144
+ if (!ticketId || !digest || !nonce || !approver || !privateKey) throw new Error('approver proof requires ticketId, actionDigest, nonce, approver, privateKey');
145
+ const now = Math.floor(Date.now() / 1000);
146
+ const payload = { iss: approver, sub: approver, aud: 'vibeguard-approver-proof', iat: now, exp: now + Number(ttlSeconds), jti: crypto.randomBytes(12).toString('base64url'), typ: 'VGAPPROVER', ticketId, actionDigest: digest, nonce };
147
+ return signJws({ alg: 'EdDSA', typ: 'VGAPPROVER', kid: keyId }, payload, loadPrivateKey(privateKey));
148
+ }
149
+
125
150
  verify(ticketId, approvalToken, expectedActionDigest) {
126
151
  const ticket = this.tickets.get(ticketId);
127
152
  if (!ticket) throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'approval ticket not found');
@@ -175,6 +200,7 @@ function publicTicket(t) {
175
200
  ticketId: t.ticketId,
176
201
  principal: t.principal,
177
202
  actionDigest: t.actionDigest,
203
+ nonce: t.nonce,
178
204
  reason: t.reason,
179
205
  createdAt: t.createdAt,
180
206
  expiresAt: t.expiresAt,
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  const http = require('http');
13
+ const https = require('https');
13
14
  const { ERROR_CODES, VibeGuardError } = require('./contracts');
14
15
 
15
16
  const MAX_BODY = 1024 * 1024;
@@ -69,7 +70,11 @@ function createHttpGateway(opts = {}) {
69
70
  throw new VibeGuardError(ERROR_CODES.AUTH_INVALID, 'no authenticator configured', { status: 500 });
70
71
  }
71
72
 
72
- const server = http.createServer(async (req, res) => {
73
+ const server = opts.tls
74
+ ? https.createServer(opts.tls, async (req, res) => { gatewayHandler(req, res); })
75
+ : http.createServer(async (req, res) => { gatewayHandler(req, res); });
76
+
77
+ async function gatewayHandler(req, res) {
73
78
  try {
74
79
  if (req.method === 'GET' && req.url === '/health') {
75
80
  return json(res, 200, { status: 'ok', gateway: 'vibeguard', version: 1 });
@@ -154,7 +159,7 @@ function createHttpGateway(opts = {}) {
154
159
  }
155
160
  return json(res, 500, { jsonrpc: '2.0', id: null, error: { code: -32603, message: 'internal error' } });
156
161
  }
157
- });
162
+ }
158
163
 
159
164
  return new Promise((resolve, reject) => {
160
165
  server.once('error', reject);
@@ -162,9 +167,10 @@ function createHttpGateway(opts = {}) {
162
167
  const addr = server.address();
163
168
  resolve({
164
169
  server,
170
+ protocol: opts.tls ? 'https' : 'http',
165
171
  host: addr.address,
166
172
  port: addr.port,
167
- url: `http://${addr.address}:${addr.port}`,
173
+ url: `${opts.tls ? 'https' : 'http'}://${addr.address}:${addr.port}`,
168
174
  close: () => new Promise((res2) => {
169
175
  try { if (typeof server.closeAllConnections === 'function') server.closeAllConnections(); } catch { /* ignore */ }
170
176
  server.close(res2);
@@ -167,6 +167,7 @@ async function createMcpHttpBridge(opts = {}) {
167
167
  const gateway = await createHttpGateway({
168
168
  host: opts.host,
169
169
  port: opts.port,
170
+ tls: opts.tls,
170
171
  authority: opts.authority,
171
172
  jwt: opts.jwt,
172
173
  policy: opts.policy,
@@ -1,13 +1,16 @@
1
1
  'use strict';
2
2
 
3
3
  /*
4
- * src/platform/os-sandbox.js — Linux OS-namespace execution backend.
4
+ * src/platform/os-sandbox.js — Linux OS isolation backends.
5
5
  *
6
- * Uses util-linux `unshare` to create a user/network/PID namespace, then runs
7
- * the existing VibeGuard harness inside it. This provides real kernel-enforced
8
- * network and PID isolation on Linux, but the filesystem is still host-readable;
9
- * do not call it a general-purpose container or VM. Windows AppContainer/Job
10
- * Object/WFP and macOS VM backends are not implemented in this file.
6
+ * Two backends are provided:
7
+ * - LinuxBubblewrapSandbox: bubblewrap user/mount/net/PID namespace with a
8
+ * minimal read-only system root and isolated /tmp. This is the preferred
9
+ * Linux backend when bwrap is installed.
10
+ * - LinuxNamespaceSandbox: util-linux unshare network/PID namespace only;
11
+ * filesystem remains host-readable. Kept as a fallback, explicitly limited.
12
+ *
13
+ * Neither is a full container/VM. Verification is executable and reported.
11
14
  */
12
15
 
13
16
  const fs = require('fs');
@@ -28,6 +31,19 @@ function which(name) {
28
31
  } catch { return null; }
29
32
  }
30
33
 
34
+ function parseHarnessOutput(stdout, stderr, signal, code) {
35
+ const marker = stdout.split(/\r?\n/).find((l) => l.startsWith('__VG_RESULT__'));
36
+ const errorMarker = stdout.split(/\r?\n/).find((l) => l.startsWith('__VG_ERROR__'));
37
+ if (marker) {
38
+ try { const parsed = JSON.parse(marker.slice('__VG_RESULT__'.length)); return { success: true, output: parsed.result, error: null }; } catch { return { success: false, output: null, error: 'cannot parse harness result' }; }
39
+ }
40
+ if (errorMarker) {
41
+ try { return { success: false, output: null, error: JSON.parse(errorMarker.slice('__VG_ERROR__'.length)) }; } catch { return { success: false, output: null, error: 'sandbox error' }; }
42
+ }
43
+ if (signal === 'SIGKILL') return { success: false, output: null, error: 'VibeGuard OS sandbox: execution timed out' };
44
+ return { success: false, output: null, error: stderr.trim() || `sandbox exited with code ${code}` };
45
+ }
46
+
31
47
  class LinuxNamespaceSandbox {
32
48
  constructor(opts = {}) {
33
49
  this.id = 'linux-namespace';
@@ -51,14 +67,9 @@ class LinuxNamespaceSandbox {
51
67
  const started = Date.now();
52
68
  const timeout = opts.timeout || DEFAULT_TIMEOUT;
53
69
  const result = {
54
- success: false,
55
- output: null,
56
- error: null,
57
- duration: 0,
58
- isolation: 'os-linux-namespace',
59
- isolationClass: ISOLATION.OS,
60
- verified: this.verified,
61
- verification: this.verification,
70
+ success: false, output: null, error: null, duration: 0,
71
+ isolation: 'os-linux-namespace', isolationClass: ISOLATION.OS,
72
+ verified: this.verified, verification: this.verification,
62
73
  limitations: this.limitations.slice(),
63
74
  };
64
75
  if (!this.available()) {
@@ -73,9 +84,7 @@ class LinuxNamespaceSandbox {
73
84
  const child = spawn(this.unshare, [...this._baseArgs(), this.nodePath, path.join(dir, 'harness.js')], {
74
85
  cwd: dir,
75
86
  env: { PATH: process.env.PATH || '/usr/bin:/bin', HOME: dir },
76
- stdio: ['ignore', 'pipe', 'pipe'],
77
- windowsHide: true,
78
- shell: false,
87
+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, shell: false,
79
88
  });
80
89
  let stdout = '';
81
90
  let stderr = '';
@@ -85,17 +94,7 @@ class LinuxNamespaceSandbox {
85
94
  child.once('error', (err) => { clearTimeout(timer); result.error = err.message; result.duration = Date.now() - started; resolve(result); });
86
95
  child.once('exit', (code, signal) => {
87
96
  clearTimeout(timer);
88
- const marker = stdout.split(/\r?\n/).find((l) => l.startsWith('__VG_RESULT__'));
89
- const errorMarker = stdout.split(/\r?\n/).find((l) => l.startsWith('__VG_ERROR__'));
90
- if (marker) {
91
- try { const parsed = JSON.parse(marker.slice('__VG_RESULT__'.length)); result.success = true; result.output = parsed.result; } catch { result.error = 'cannot parse harness result'; }
92
- } else if (errorMarker) {
93
- try { result.error = JSON.parse(errorMarker.slice('__VG_ERROR__'.length)); } catch { result.error = 'sandbox error'; }
94
- } else if (signal === 'SIGKILL') {
95
- result.error = 'VibeGuard OS sandbox: execution timed out';
96
- } else {
97
- result.error = stderr.trim() || `sandbox exited with code ${code}`;
98
- }
97
+ Object.assign(result, parseHarnessOutput(stdout, stderr, signal, code));
99
98
  result.duration = Date.now() - started;
100
99
  resolve(result);
101
100
  });
@@ -103,33 +102,8 @@ class LinuxNamespaceSandbox {
103
102
  }
104
103
 
105
104
  async verify() {
106
- if (!this.available()) {
107
- this.verified = false;
108
- this.verification = 'unavailable';
109
- return false;
110
- }
111
- // Verify network isolation: a local TCP listener reachable on the host must
112
- // not be reachable from the new network namespace.
113
- const server = net.createServer();
114
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
115
- const port = server.address().port;
116
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-osns-verify-'));
117
- const probe = path.join(dir, 'probe.js');
118
- fs.writeFileSync(probe, `const net=require('net');const s=net.connect(${port},'127.0.0.1');s.on('connect',()=>{console.log('REACHABLE');process.exit(2)});s.on('error',()=>{console.log('BLOCKED');process.exit(0)});setTimeout(()=>{console.log('BLOCKED');process.exit(0)},1000);`);
119
- const ok = await new Promise((resolve) => {
120
- const child = spawn(this.unshare, [...this._baseArgs(), this.nodePath, probe], {
121
- cwd: dir,
122
- env: { PATH: process.env.PATH || '/usr/bin:/bin' },
123
- stdio: ['ignore', 'pipe', 'pipe'],
124
- shell: false,
125
- });
126
- let out = '';
127
- const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* ignore */ } resolve(false); }, 3000);
128
- child.stdout.on('data', (c) => { out += c.toString('utf8'); });
129
- child.once('error', () => { clearTimeout(timer); resolve(false); });
130
- child.once('exit', () => { clearTimeout(timer); resolve(out.includes('BLOCKED') && !out.includes('REACHABLE')); });
131
- });
132
- await new Promise((resolve) => server.close(resolve));
105
+ if (!this.available()) { this.verified = false; this.verification = 'unavailable'; return false; }
106
+ const ok = await verifyNetworkNamespace(this.unshare, this._baseArgs(), this.nodePath);
133
107
  this.verified = ok;
134
108
  this.verification = ok ? 'network-namespace-verified' : 'verification-failed';
135
109
  if (ok) this.limitations = ['filesystem is not isolated from the host', 'network/PID namespaces verified by local probe'];
@@ -137,8 +111,141 @@ class LinuxNamespaceSandbox {
137
111
  }
138
112
  }
139
113
 
140
- function getLinuxBackend(opts) {
114
+ class LinuxBubblewrapSandbox {
115
+ constructor(opts = {}) {
116
+ this.id = 'linux-bubblewrap';
117
+ this.isolationClass = ISOLATION.OS;
118
+ this.verified = false;
119
+ this.verification = 'unverified';
120
+ this.limitations = ['user/mount/net/PID namespaces; not a VM/hardware boundary'];
121
+ this.nodePath = opts.nodePath || process.execPath;
122
+ this.bwrap = opts.bwrap || which('bwrap');
123
+ }
124
+
125
+ available() {
126
+ return process.platform === 'linux' && Boolean(this.bwrap);
127
+ }
128
+
129
+ _args(dir) {
130
+ const nodeRoot = path.dirname(path.dirname(this.nodePath));
131
+ const nodeRel = path.relative(nodeRoot, this.nodePath);
132
+ const args = [
133
+ '--die-with-parent', '--new-session', '--unshare-all', '--clearenv',
134
+ '--setenv', 'PATH', '/usr/bin:/bin', '--setenv', 'HOME', '/tmp',
135
+ '--proc', '/proc', '--dev', '/dev',
136
+ '--tmpfs', '/tmp', '--tmpfs', '/home', '--tmpfs', '/root', '--tmpfs', '/var/tmp',
137
+ '--ro-bind', '/usr', '/usr', '--ro-bind', '/bin', '/bin',
138
+ '--ro-bind', '/lib', '/lib', '--ro-bind', '/lib64', '/lib64',
139
+ '--ro-bind', nodeRoot, '/node',
140
+ '--ro-bind', dir, '/work', '--chdir', '/work',
141
+ '/node/' + nodeRel, '/work/harness.js',
142
+ ];
143
+ return args;
144
+ }
145
+
146
+ run(code, opts = {}) {
147
+ const started = Date.now();
148
+ const timeout = opts.timeout || DEFAULT_TIMEOUT;
149
+ const result = {
150
+ success: false, output: null, error: null, duration: 0,
151
+ isolation: 'os-linux-bubblewrap', isolationClass: ISOLATION.OS,
152
+ verified: this.verified, verification: this.verification,
153
+ limitations: this.limitations.slice(),
154
+ };
155
+ if (!this.available()) {
156
+ result.error = 'bubblewrap backend unavailable';
157
+ result.duration = Date.now() - started;
158
+ return Promise.resolve(result);
159
+ }
160
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-bwrap-'));
161
+ fs.writeFileSync(path.join(dir, 'user.js'), String(code), 'utf8');
162
+ fs.writeFileSync(path.join(dir, 'harness.js'), HARNESS_SOURCE, 'utf8');
163
+ return new Promise((resolve) => {
164
+ const child = spawn(this.bwrap, this._args(dir), {
165
+ cwd: dir, env: { PATH: '/usr/bin:/bin' }, stdio: ['ignore', 'pipe', 'pipe'],
166
+ windowsHide: true, shell: false,
167
+ });
168
+ let stdout = '';
169
+ let stderr = '';
170
+ const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* ignore */ } }, timeout);
171
+ child.stdout.on('data', (c) => { stdout += c.toString('utf8'); if (stdout.length > 1024 * 1024) stdout = stdout.slice(0, 1024 * 1024); });
172
+ child.stderr.on('data', (c) => { stderr += c.toString('utf8').slice(0, 1024 * 1024); });
173
+ child.once('error', (err) => { clearTimeout(timer); result.error = err.message; result.duration = Date.now() - started; resolve(result); });
174
+ child.once('exit', (code, signal) => {
175
+ clearTimeout(timer);
176
+ Object.assign(result, parseHarnessOutput(stdout, stderr, signal, code));
177
+ result.duration = Date.now() - started;
178
+ resolve(result);
179
+ });
180
+ });
181
+ }
182
+
183
+ async verify() {
184
+ if (!this.available()) { this.verified = false; this.verification = 'unavailable'; return false; }
185
+ const nodeRoot = path.dirname(path.dirname(this.nodePath));
186
+ const nodeRel = path.relative(nodeRoot, this.nodePath);
187
+ const network = await verifyNetworkNamespace(this.bwrap, ['--die-with-parent', '--unshare-all', '--ro-bind', '/usr', '/usr', '--ro-bind', '/lib', '/lib', '--ro-bind', '/lib64', '/lib64', '--ro-bind', '/bin', '/bin', '--ro-bind', nodeRoot, '/node'], '/node/' + nodeRel);
188
+ const filesystem = await verifyFilesystemIsolation(this.bwrap, this.nodePath);
189
+ this.verified = network && filesystem;
190
+ this.verification = this.verified ? 'network-and-filesystem-isolation-verified' : `verification-failed(network=${network},filesystem=${filesystem})`;
191
+ if (this.verified) this.limitations = ['user/mount/net/PID namespaces; not a VM/hardware boundary', 'minimal read-only system root; /tmp isolated'];
192
+ return this.verified;
193
+ }
194
+ }
195
+
196
+ async function verifyNetworkNamespace(command, baseArgs, nodePath) {
197
+ const server = net.createServer();
198
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
199
+ const port = server.address().port;
200
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-osns-verify-'));
201
+ const probe = path.join(dir, 'probe.js');
202
+ fs.writeFileSync(probe, `const net=require('net');const s=net.connect(${port},'127.0.0.1');s.on('connect',()=>{console.log('REACHABLE');process.exit(2)});s.on('error',()=>{console.log('BLOCKED');process.exit(0)});setTimeout(()=>{console.log('BLOCKED');process.exit(0)},1000);`);
203
+ const ok = await new Promise((resolve) => {
204
+ const isBwrap = path.basename(command).includes('bwrap');
205
+ const argv = isBwrap ? [...baseArgs, '--ro-bind', dir, '/work', '--chdir', '/work', nodePath, '/work/probe.js'] : [...baseArgs, nodePath, probe];
206
+ const child = spawn(command, argv, {
207
+ cwd: dir, env: { PATH: '/usr/bin:/bin' }, stdio: ['ignore', 'pipe', 'pipe'], shell: false,
208
+ });
209
+ let out = '';
210
+ const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* ignore */ } resolve(false); }, 3000);
211
+ child.stdout.on('data', (c) => { out += c.toString('utf8'); });
212
+ child.once('error', () => { clearTimeout(timer); resolve(false); });
213
+ child.once('exit', () => { clearTimeout(timer); resolve(out.includes('BLOCKED') && !out.includes('REACHABLE')); });
214
+ });
215
+ await new Promise((resolve) => server.close(resolve));
216
+ return ok;
217
+ }
218
+
219
+ async function verifyFilesystemIsolation(bwrap, nodePath) {
220
+ const marker = path.join(os.tmpdir(), 'vg-host-marker-' + cryptoRandom());
221
+ fs.writeFileSync(marker, 'HOST-SECRET');
222
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-bwrap-verify-'));
223
+ const probe = path.join(dir, 'probe.js');
224
+ fs.writeFileSync(probe, `const fs=require('fs');try{fs.readFileSync(${JSON.stringify(marker)});console.log('VISIBLE')}catch(e){console.log('BLOCKED')}`);
225
+ const nodeRoot = path.dirname(path.dirname(nodePath));
226
+ const nodeRel = path.relative(nodeRoot, nodePath);
227
+ const args = ['--die-with-parent', '--unshare-all', '--clearenv', '--setenv', 'PATH', '/usr/bin:/bin',
228
+ '--ro-bind', '/usr', '/usr', '--ro-bind', '/bin', '/bin', '--ro-bind', '/lib', '/lib', '--ro-bind', '/lib64', '/lib64',
229
+ '--ro-bind', nodeRoot, '/node', '--ro-bind', dir, '/work', '--chdir', '/work',
230
+ '/node/' + nodeRel, '/work/probe.js'];
231
+ const ok = await new Promise((resolve) => {
232
+ const child = spawn(bwrap, args, { cwd: dir, env: { PATH: '/usr/bin:/bin' }, stdio: ['ignore', 'pipe', 'pipe'], shell: false });
233
+ let out = '';
234
+ const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* ignore */ } resolve(false); }, 3000);
235
+ child.stdout.on('data', (c) => { out += c.toString('utf8'); });
236
+ child.once('error', () => { clearTimeout(timer); resolve(false); });
237
+ child.once('exit', () => { clearTimeout(timer); resolve(out.includes('BLOCKED') && !out.includes('VISIBLE')); });
238
+ });
239
+ try { fs.unlinkSync(marker); } catch { /* ignore */ }
240
+ return ok;
241
+ }
242
+
243
+ function cryptoRandom() { return require('crypto').randomBytes(8).toString('hex'); }
244
+
245
+ function getLinuxBackend(opts = {}) {
246
+ const bwrap = new LinuxBubblewrapSandbox(opts);
247
+ if (bwrap.available()) return bwrap;
141
248
  return new LinuxNamespaceSandbox(opts);
142
249
  }
143
250
 
144
- module.exports = { LinuxNamespaceSandbox, getLinuxBackend };
251
+ module.exports = { LinuxNamespaceSandbox, LinuxBubblewrapSandbox, getLinuxBackend };
@@ -71,6 +71,11 @@ function defaultManager() {
71
71
  const { getLinuxBackend } = require('./os-sandbox');
72
72
  const linux = getLinuxBackend();
73
73
  if (linux.available()) manager.register(linux);
74
+ if (process.platform === 'win32') {
75
+ const { WindowsJobSandbox } = require('./windows-sandbox');
76
+ const win = new WindowsJobSandbox();
77
+ if (win.available()) manager.register(win);
78
+ }
74
79
  } catch { /* optional platform backend */ }
75
80
  manager.register({
76
81
  id: 'process',
@@ -83,12 +83,20 @@ class SignedAuditLog {
83
83
  this.clock = opts.clock || (() => new Date());
84
84
  this.tenant = opts.tenant || null;
85
85
  this.checkpointFile = opts.checkpointFile || `${this.file}.checkpoint.json`;
86
+ this.anchorFile = opts.anchorFile || null;
87
+ this.anchorLastHash = 'GENESIS';
86
88
  this.entries = [];
87
89
  this.lastHash = GENESIS;
88
90
  this._loadExisting(opts.verifyOnOpen !== false);
89
91
  }
90
92
 
91
93
  _loadExisting(verify) {
94
+ if (this.anchorFile && fs.existsSync(this.anchorFile)) {
95
+ const lines = fs.readFileSync(this.anchorFile, 'utf8').split(/\r?\n/).filter(Boolean);
96
+ if (lines.length) {
97
+ try { this.anchorLastHash = JSON.parse(lines[lines.length - 1]).hash || 'GENESIS'; } catch { throw new VibeGuardError(ERROR_CODES.AUDIT_INVALID, 'audit anchor is corrupt'); }
98
+ }
99
+ }
92
100
  if (!fs.existsSync(this.file)) return;
93
101
  const raw = fs.readFileSync(this.file, 'utf8');
94
102
  const lines = raw.split(/\r?\n/).filter(Boolean);
@@ -152,6 +160,13 @@ class SignedAuditLog {
152
160
  const cp = this.checkpoint();
153
161
  fs.writeFileSync(this.checkpointFile, JSON.stringify(cp) + '\n', { mode: 0o600 });
154
162
  try { fs.chmodSync(this.checkpointFile, 0o600); } catch { /* Windows/best effort */ }
163
+ if (this.anchorFile) {
164
+ const record = { schemaVersion: SCHEMA_VERSION, checkpoint: cp, previousAnchor: this.anchorLastHash, timestamp: iso(this.clock) };
165
+ record.hash = sha256Hex(record);
166
+ fs.mkdirSync(path.dirname(this.anchorFile), { recursive: true, mode: 0o700 });
167
+ fs.appendFileSync(this.anchorFile, JSON.stringify(record) + '\n', { mode: 0o600 });
168
+ this.anchorLastHash = record.hash;
169
+ }
155
170
  } catch (err) {
156
171
  throw new VibeGuardError(ERROR_CODES.AUDIT_INVALID, `audit checkpoint write failed: ${err.message}`);
157
172
  }
@@ -202,12 +217,26 @@ class SignedAuditLog {
202
217
  }
203
218
  const result = SignedAuditLog.verifyEntries(entries, { ...opts, requireEntries: opts.requireEntries !== false });
204
219
  let checkpoint;
220
+ let anchor;
205
221
  try {
206
222
  if (opts.checkpoint) checkpoint = opts.checkpoint;
207
223
  else if (opts.publicKey && fs.existsSync(`${path.resolve(file)}.checkpoint.json`)) {
208
224
  checkpoint = JSON.parse(fs.readFileSync(`${path.resolve(file)}.checkpoint.json`, 'utf8'));
209
225
  }
226
+ if (opts.anchorFile && fs.existsSync(opts.anchorFile)) {
227
+ const lines = fs.readFileSync(opts.anchorFile, 'utf8').split(/\r?\n/).filter(Boolean);
228
+ if (lines.length) anchor = JSON.parse(lines[lines.length - 1]);
229
+ }
210
230
  } catch { /* fall through to checkpoint failure below */ }
231
+ if (anchor && opts.publicKey) {
232
+ const cp = anchor.checkpoint;
233
+ if (!cp) { reasons.push('anchor has no checkpoint'); result.valid = false; }
234
+ else {
235
+ const av = SignedAuditLog.verifyCheckpoint(cp, opts.publicKey, entries);
236
+ if (!av.valid) { reasons.push(`external anchor: ${av.reason}`); result.valid = false; }
237
+ else if (cp.sequence !== entries.length) { reasons.push('external anchor sequence mismatch'); result.valid = false; }
238
+ }
239
+ }
211
240
  if (checkpoint && entries.length) {
212
241
  if (!opts.publicKey) {
213
242
  reasons.push('checkpoint present but no public key supplied; checkpoint signature not verified');