@yagyeshvyas/vibeguard 1.3.0 → 1.11.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.
Files changed (167) hide show
  1. package/.vibeguard-mcp.example.json +51 -0
  2. package/CHANGELOG.md +604 -216
  3. package/MCP-FIREWALL.md +296 -0
  4. package/README.md +355 -31
  5. package/bin/cli.js +355 -27
  6. package/bin/cmd-agent-monitor.js +45 -0
  7. package/bin/cmd-agent-risk.js +64 -0
  8. package/bin/cmd-gif.js +62 -0
  9. package/bin/cmd-git-scan.js +74 -0
  10. package/bin/cmd-llm-proxy.js +164 -0
  11. package/bin/cmd-mcp-firewall.js +191 -0
  12. package/bin/cmd-pentest.js +103 -0
  13. package/bin/cmd-platform.js +137 -0
  14. package/bin/cmd-pr-scan.js +135 -0
  15. package/bin/cmd-sbom-diff.js +38 -0
  16. package/bin/cmd-skill-scan.js +35 -0
  17. package/docs/AISVS.md +25 -0
  18. package/docs/ARCHITECTURE.md +81 -0
  19. package/docs/INSTALLATION.md +139 -0
  20. package/docs/WINDOWS.md +74 -0
  21. package/docs/security-policy.strict.example.json +134 -0
  22. package/docs/security-policy.strict.example.pub.pem +3 -0
  23. package/package.json +45 -7
  24. package/src/.vibeguard/cache/file-hashes.json +60 -0
  25. package/src/.vibeguard/latest-snapshot.json +36 -0
  26. package/src/.vibeguard/mcp-pins.json +1 -0
  27. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +428 -0
  28. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +344 -0
  29. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +279 -0
  30. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +297 -0
  31. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +151 -0
  32. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +299 -0
  33. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +65 -0
  34. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +2051 -0
  35. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +168 -0
  36. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +362 -0
  37. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +150 -0
  38. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +1611 -0
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +164 -0
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +292 -0
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +144 -0
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +220 -0
  43. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +428 -0
  44. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +344 -0
  45. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +297 -0
  46. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +299 -0
  47. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +37 -0
  48. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +2055 -0
  49. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +168 -0
  50. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +362 -0
  51. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +220 -0
  52. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +428 -0
  53. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +344 -0
  54. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +279 -0
  55. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +297 -0
  56. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +151 -0
  57. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +299 -0
  58. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +65 -0
  59. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +2055 -0
  60. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +168 -0
  61. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +362 -0
  62. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +150 -0
  63. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +1611 -0
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +164 -0
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +292 -0
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +144 -0
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +220 -0
  68. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +428 -0
  69. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +344 -0
  70. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +279 -0
  71. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +297 -0
  72. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +151 -0
  73. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +299 -0
  74. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +65 -0
  75. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +2054 -0
  76. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +168 -0
  77. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +362 -0
  78. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +150 -0
  79. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +1611 -0
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +164 -0
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +292 -0
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +144 -0
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +220 -0
  84. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +428 -0
  85. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +344 -0
  86. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +297 -0
  87. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +299 -0
  88. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +37 -0
  89. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +2055 -0
  90. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +168 -0
  91. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +362 -0
  92. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +220 -0
  93. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +428 -0
  94. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +344 -0
  95. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +297 -0
  96. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +33 -0
  97. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +2055 -0
  98. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +1611 -0
  99. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +292 -0
  100. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +220 -0
  101. package/src/.vibeguard-baseline.json +5226 -0
  102. package/src/action-guard.js +84 -6
  103. package/src/agent-monitor.js +262 -0
  104. package/src/agent-policy.js +642 -0
  105. package/src/agent-risk.js +271 -0
  106. package/src/agentic.js +1513 -0
  107. package/src/ast.js +165 -7
  108. package/src/audit-trail.js +212 -67
  109. package/src/auto.js +427 -427
  110. package/src/autofix.js +11 -4
  111. package/src/bundles.js +198 -0
  112. package/src/daemon.js +343 -343
  113. package/src/dashboard.js +278 -278
  114. package/src/engine.js +3 -0
  115. package/src/entropy.js +187 -0
  116. package/src/firewall.js +19 -3
  117. package/src/gif.js +134 -0
  118. package/src/gitscan.js +282 -0
  119. package/src/hook.js +151 -151
  120. package/src/injection-decode.js +136 -0
  121. package/src/install.js +298 -280
  122. package/src/integrity.js +16 -1
  123. package/src/integrity.json +43 -13
  124. package/src/interceptor.js +12 -9
  125. package/src/llm-proxy.js +986 -0
  126. package/src/mcp-audit.js +61 -5
  127. package/src/mcp-firewall.js +971 -0
  128. package/src/mcp-server.js +2500 -2047
  129. package/src/obfuscation.js +315 -0
  130. package/src/owasp-agentic.js +314 -0
  131. package/src/pentest.js +589 -0
  132. package/src/pii.js +4 -0
  133. package/src/platform/aisvs.js +38 -0
  134. package/src/platform/approval.js +187 -0
  135. package/src/platform/canonical.js +73 -0
  136. package/src/platform/contracts.js +158 -0
  137. package/src/platform/delegation.js +73 -0
  138. package/src/platform/http-gateway.js +177 -0
  139. package/src/platform/identity.js +253 -0
  140. package/src/platform/jwt.js +86 -0
  141. package/src/platform/mcp-http-bridge.js +199 -0
  142. package/src/platform/memory-guard.js +64 -0
  143. package/src/platform/os-sandbox.js +144 -0
  144. package/src/platform/policy.js +332 -0
  145. package/src/platform/sandbox-manager.js +92 -0
  146. package/src/platform/signed-audit.js +357 -0
  147. package/src/platform/ssrf.js +129 -0
  148. package/src/plugin.js +182 -168
  149. package/src/pre-deploy.js +170 -55
  150. package/src/privacy-audit.js +272 -272
  151. package/src/repl.js +150 -150
  152. package/src/report.js +7 -1
  153. package/src/routes.js +1210 -0
  154. package/src/rules-2026.js +1407 -0
  155. package/src/rules-pack.js +3068 -3019
  156. package/src/rules.js +376 -60
  157. package/src/sandbox.js +200 -10
  158. package/src/sbom.js +193 -164
  159. package/src/scanner.js +189 -33
  160. package/src/shell-guard.js +11 -0
  161. package/src/skill-scan.js +477 -0
  162. package/src/slopsquat.js +144 -144
  163. package/src/surface.js +408 -0
  164. package/src/taint-ast.js +204 -37
  165. package/src/taint.js +15 -3
  166. package/src/tokenlean.js +579 -0
  167. package/src/trace.js +220 -220
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/platform/os-sandbox.js — Linux OS-namespace execution backend.
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.
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const os = require('os');
15
+ const path = require('path');
16
+ const net = require('net');
17
+ const { spawn, spawnSync } = require('child_process');
18
+ const { ISOLATION } = require('./contracts');
19
+ const { HARNESS_SOURCE } = require('../sandbox');
20
+
21
+ const DEFAULT_TIMEOUT = 5000;
22
+
23
+ function which(name) {
24
+ const cmd = process.platform === 'win32' ? 'where' : 'which';
25
+ try {
26
+ const r = spawnSync(cmd, [name], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
27
+ return r.status === 0 ? String(r.stdout).trim().split(/\r?\n/)[0] : null;
28
+ } catch { return null; }
29
+ }
30
+
31
+ class LinuxNamespaceSandbox {
32
+ constructor(opts = {}) {
33
+ this.id = 'linux-namespace';
34
+ this.isolationClass = ISOLATION.OS;
35
+ this.verified = false;
36
+ this.verification = 'unverified';
37
+ this.limitations = ['filesystem is not isolated from the host', 'requires util-linux unshare and user namespaces'];
38
+ this.nodePath = opts.nodePath || process.execPath;
39
+ this.unshare = opts.unshare || which('unshare');
40
+ }
41
+
42
+ available() {
43
+ return process.platform === 'linux' && Boolean(this.unshare);
44
+ }
45
+
46
+ _baseArgs() {
47
+ return ['-Urn', '--pid', '--fork', '--mount-proc'];
48
+ }
49
+
50
+ run(code, opts = {}) {
51
+ const started = Date.now();
52
+ const timeout = opts.timeout || DEFAULT_TIMEOUT;
53
+ 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,
62
+ limitations: this.limitations.slice(),
63
+ };
64
+ if (!this.available()) {
65
+ result.error = 'Linux namespace backend unavailable (requires Linux + unshare + user namespaces)';
66
+ result.duration = Date.now() - started;
67
+ return Promise.resolve(result);
68
+ }
69
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-osns-'));
70
+ fs.writeFileSync(path.join(dir, 'user.js'), String(code), 'utf8');
71
+ fs.writeFileSync(path.join(dir, 'harness.js'), HARNESS_SOURCE, 'utf8');
72
+ return new Promise((resolve) => {
73
+ const child = spawn(this.unshare, [...this._baseArgs(), this.nodePath, path.join(dir, 'harness.js')], {
74
+ cwd: dir,
75
+ env: { PATH: process.env.PATH || '/usr/bin:/bin', HOME: dir },
76
+ stdio: ['ignore', 'pipe', 'pipe'],
77
+ windowsHide: true,
78
+ shell: false,
79
+ });
80
+ let stdout = '';
81
+ let stderr = '';
82
+ const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* ignore */ } }, timeout);
83
+ child.stdout.on('data', (c) => { stdout += c.toString('utf8'); if (stdout.length > 1024 * 1024) stdout = stdout.slice(0, 1024 * 1024); });
84
+ child.stderr.on('data', (c) => { stderr += c.toString('utf8').slice(0, 1024 * 1024); });
85
+ child.once('error', (err) => { clearTimeout(timer); result.error = err.message; result.duration = Date.now() - started; resolve(result); });
86
+ child.once('exit', (code, signal) => {
87
+ 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
+ }
99
+ result.duration = Date.now() - started;
100
+ resolve(result);
101
+ });
102
+ });
103
+ }
104
+
105
+ 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));
133
+ this.verified = ok;
134
+ this.verification = ok ? 'network-namespace-verified' : 'verification-failed';
135
+ if (ok) this.limitations = ['filesystem is not isolated from the host', 'network/PID namespaces verified by local probe'];
136
+ return ok;
137
+ }
138
+ }
139
+
140
+ function getLinuxBackend(opts) {
141
+ return new LinuxNamespaceSandbox(opts);
142
+ }
143
+
144
+ module.exports = { LinuxNamespaceSandbox, getLinuxBackend };
@@ -0,0 +1,332 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/platform/policy.js — strict, signed policy v2 for the security gateway.
5
+ *
6
+ * This module is deliberately pure: no network, no filesystem reads inside the
7
+ * evaluator, no clock unless injected. It implements the subset of
8
+ * research/10-security-policy-schema.md needed for the strict foundation:
9
+ *
10
+ * - default deny and deny-overrides
11
+ * - capability + principal checks
12
+ * - per-tool and per-resource allow/deny/approval rules
13
+ * - canonical path checks
14
+ * - URL/host egress checks (including URLs embedded in shell commands)
15
+ * - secret/PII/entropy inspection
16
+ * - signed policy documents (Ed25519 over canonical body)
17
+ *
18
+ * It is additive; the legacy agent-policy module remains for compatibility.
19
+ */
20
+
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const crypto = require('crypto');
24
+ const { DECISION, CAPABILITIES, ERROR_CODES, VibeGuardError, assertPrincipal } = require('./contracts');
25
+ const { sha256Hex, actionDigest } = require('./canonical');
26
+ const { loadPrivateKey, loadPublicKey } = require('./identity');
27
+ const { checkCommand } = require('../shell-guard');
28
+ const { scanForLeaksDeep, isExternalHost, hostOf } = require('../action-guard');
29
+
30
+ function matchesGlob(value, glob) {
31
+ const v = String(value == null ? '' : value);
32
+ const g = String(glob == null ? '' : glob);
33
+ if (g === '*') return true;
34
+ if (!/[?*]/.test(g)) return v === g;
35
+ const re = new RegExp('^' + g.split('').map((c) => {
36
+ if (c === '*') return '.*';
37
+ if (c === '?') return '.';
38
+ return c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
39
+ }).join('') + '$', 'i');
40
+ return re.test(v);
41
+ }
42
+
43
+ function matchesAny(value, globs) {
44
+ return Array.isArray(globs) && globs.some((g) => matchesGlob(value, g));
45
+ }
46
+
47
+ function canonicalPath(root, value) {
48
+ const expanded = String(value).replace(/^~(?=$|[\\/])/, require('os').homedir());
49
+ const resolved = path.isAbsolute(expanded) ? path.resolve(expanded) : path.resolve(root, expanded);
50
+ let existing = resolved;
51
+ const suffix = [];
52
+ for (let i = 0; i < 32; i++) {
53
+ try {
54
+ const real = fs.realpathSync.native(existing);
55
+ return path.join(real, ...suffix.reverse());
56
+ } catch {
57
+ const parent = path.dirname(existing);
58
+ if (parent === existing) break;
59
+ suffix.push(path.basename(existing));
60
+ existing = parent;
61
+ }
62
+ }
63
+ return resolved;
64
+ }
65
+
66
+ function canonicalRoot(root) {
67
+ try { return fs.realpathSync.native(root); } catch { return path.resolve(root); }
68
+ }
69
+
70
+ function inside(root, candidate) {
71
+ const rel = path.relative(root, candidate);
72
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
73
+ }
74
+
75
+ function walkStrings(value, key, out) {
76
+ if (value == null) return;
77
+ if (typeof value === 'string') { out.push({ key: key || '', value }); return; }
78
+ if (Array.isArray(value)) { value.forEach((v) => walkStrings(v, key, out)); return; }
79
+ if (typeof value === 'object') for (const [k, v] of Object.entries(value)) walkStrings(v, k, out);
80
+ }
81
+
82
+ const PATH_KEY = /path|file|dir|folder|root|cwd|target|source|dest|destination|location/i;
83
+ const COMMAND_KEY = /command|cmd|script|shell|code|expression|eval|query|sql|input|args/i;
84
+
85
+ function conditionMatches(cond, ctx) {
86
+ if (!cond) return true;
87
+ if (typeof cond !== 'object') return false;
88
+ const op = cond.op;
89
+ if (op === 'and') return (cond.args || []).every((c) => conditionMatches(c, ctx));
90
+ if (op === 'or') return (cond.args || []).some((c) => conditionMatches(c, ctx));
91
+ if (op === 'not') return !conditionMatches((cond.args || [])[0], ctx);
92
+ const value = getPath(ctx, cond.path);
93
+ switch (op) {
94
+ case 'eq': return value === cond.value;
95
+ case 'neq': return value !== cond.value;
96
+ case 'in': return Array.isArray(cond.value) && cond.value.includes(value);
97
+ case 'notIn': return Array.isArray(cond.value) && !cond.value.includes(value);
98
+ case 'contains': return String(value == null ? '' : value).includes(String(cond.value));
99
+ case 'startsWith': return String(value == null ? '' : value).startsWith(String(cond.value));
100
+ case 'endsWith': return String(value == null ? '' : value).endsWith(String(cond.value));
101
+ case 'within': return typeof value === 'string' && matchesGlob(value, cond.value);
102
+ case 'labelIn': return Array.isArray(ctx.labels) && cond.value.every((x) => ctx.labels.includes(x));
103
+ default: return false;
104
+ }
105
+ }
106
+
107
+ function getPath(obj, expr) {
108
+ if (!expr || expr === '$') return obj;
109
+ const parts = String(expr).replace(/^\$\.?/, '').split('.').filter(Boolean);
110
+ let cur = obj;
111
+ for (const p of parts) {
112
+ if (cur == null) return undefined;
113
+ cur = cur[p];
114
+ }
115
+ return cur;
116
+ }
117
+
118
+ function ruleMatches(rule, req, ctx) {
119
+ const m = rule.match || {};
120
+ if (m.principal && !matchesGlob(req.principal, m.principal)) return false;
121
+ if (m.server && !matchesGlob(req.server, m.server)) return false;
122
+ if (m.tool && !matchesGlob(req.tool, m.tool)) return false;
123
+ if (m.capability) {
124
+ const caps = Array.isArray(m.capability) ? m.capability : [m.capability];
125
+ if (!caps.includes(req.capability)) return false;
126
+ }
127
+ if (rule.resources) {
128
+ if (Array.isArray(rule.resources.paths) && rule.resources.paths.length) {
129
+ if (!ctx.paths.some((p) => matchesAny(p.value, rule.resources.paths) || matchesAny(p.rel, rule.resources.paths) || matchesAny(p.resolved, rule.resources.paths))) return false;
130
+ }
131
+ if (Array.isArray(rule.resources.hosts) && rule.resources.hosts.length) {
132
+ if (!ctx.hosts.some((h) => matchesAny(h, rule.resources.hosts))) return false;
133
+ }
134
+ }
135
+ if (rule.conditions && !conditionMatches(rule.conditions, ctx)) return false;
136
+ return true;
137
+ }
138
+
139
+ class StrictPolicyEngine {
140
+ constructor(policy, opts = {}) {
141
+ if (!policy || policy.schemaVersion !== '2.0') {
142
+ throw new VibeGuardError(ERROR_CODES.POLICY_INVALID, 'policy schemaVersion must be 2.0');
143
+ }
144
+ if (!['strict', 'monitor', 'legacy'].includes(policy.mode)) {
145
+ throw new VibeGuardError(ERROR_CODES.POLICY_INVALID, 'invalid policy mode');
146
+ }
147
+ if (policy.mode === 'strict' && (!policy.defaults || policy.defaults.decision !== 'deny')) {
148
+ throw new VibeGuardError(ERROR_CODES.POLICY_INVALID, 'strict policy must default to deny');
149
+ }
150
+ this.policy = policy;
151
+ this.root = path.resolve(opts.root || process.cwd());
152
+ this.clock = opts.clock || (() => new Date());
153
+ const now = this.clock();
154
+ const issued = policy.issuedAt ? new Date(policy.issuedAt) : null;
155
+ const expires = policy.expiresAt ? new Date(policy.expiresAt) : null;
156
+ if (issued && Number.isFinite(issued.getTime()) && issued.getTime() > now.getTime() + 300000) {
157
+ throw new VibeGuardError(ERROR_CODES.POLICY_INVALID, 'policy is not valid yet');
158
+ }
159
+ if (expires && Number.isFinite(expires.getTime()) && expires.getTime() <= now.getTime()) {
160
+ throw new VibeGuardError(ERROR_CODES.POLICY_INVALID, 'policy has expired');
161
+ }
162
+ this.principalCapabilities = new Map();
163
+ for (const subj of policy.subjects || []) {
164
+ if (subj && subj.principal) this.principalCapabilities.set(subj.principal, subj.capabilities || []);
165
+ }
166
+ this.rootCanonical = canonicalRoot(this.root);
167
+ }
168
+
169
+ evaluate(request = {}) {
170
+ const req = {
171
+ principal: request.principal,
172
+ server: request.server || '',
173
+ tool: request.tool || '',
174
+ capability: request.capability || '',
175
+ args: request.arguments || request.args || {},
176
+ labels: Array.isArray(request.labels) ? request.labels : [],
177
+ sessionId: request.sessionId || null,
178
+ };
179
+ try {
180
+ assertPrincipal(req.principal);
181
+ if (!CAPABILITIES.includes(req.capability)) return deny('VG_AUTHORIZATION_DENIED', 'unknown capability');
182
+ const declared = this.principalCapabilities.get(req.principal);
183
+ if (!declared) return deny('VG_AUTHORIZATION_DENIED', 'principal is not declared in policy');
184
+ if (!declared.includes(req.capability)) return deny('VG_AUTHORIZATION_DENIED', `principal lacks capability ${req.capability}`);
185
+
186
+ const strings = [];
187
+ walkStrings(req.args, '', strings);
188
+ const actions = this._inspectArguments(req, strings);
189
+ if (actions.deny) return actions.deny;
190
+
191
+ const ctx = { principal: req.principal, server: req.server, tool: req.tool, args: req.args, labels: req.labels, paths: actions.paths || [], hosts: actions.hosts || [], resource: actions };
192
+ const rules = [...(this.policy.tools || []), ...(this.policy.resources || [])];
193
+ const matched = rules.filter((r) => ruleMatches(r, req, ctx));
194
+ const denyRule = matched.find((r) => r.effect === 'deny');
195
+ if (denyRule) return deny('VG_AUTHORIZATION_DENIED', denyRule.reason || 'denied by policy', denyRule.id);
196
+ const quarantine = matched.find((r) => r.effect === 'quarantine');
197
+ if (quarantine) return { decision: DECISION.QUARANTINE, reasonCode: 'VG_AUTHORIZATION_DENIED', matchedRules: [quarantine.id || 'quarantine'] };
198
+ const approval = matched.find((r) => r.effect === 'approval_required');
199
+ if (approval) {
200
+ return {
201
+ decision: DECISION.APPROVAL_REQUIRED,
202
+ reasonCode: ERROR_CODES.APPROVAL_REQUIRED,
203
+ matchedRules: [approval.id || 'approval'],
204
+ approval: approval.approval || {},
205
+ actionDigest: actionDigest({ server: req.server, tool: req.tool, capability: req.capability, arguments: req.args }),
206
+ };
207
+ }
208
+ const allow = matched.find((r) => r.effect === 'allow');
209
+ if (allow) {
210
+ return { decision: DECISION.ALLOW, reasonCode: 'OK', matchedRules: [allow.id || 'allow'] };
211
+ }
212
+ return deny('VG_AUTHORIZATION_DENIED', 'no allow rule matched (default deny)');
213
+ } catch (err) {
214
+ if (err instanceof VibeGuardError) return deny(err.code, err.message);
215
+ return deny(ERROR_CODES.POLICY_EVALUATION_ERROR, 'policy evaluation failed');
216
+ }
217
+ }
218
+
219
+ _inspectArguments(req, strings) {
220
+ const blob = strings.map((s) => s.value).join('\n') + '\n' + strings.map((s) => s.value).join('');
221
+ const leaks = scanForLeaksDeep(blob);
222
+ if (leaks.secrets.length || leaks.entropy.length) {
223
+ return { deny: deny('VG_AUTHORIZATION_DENIED', 'secret/high-entropy credential material in arguments') };
224
+ }
225
+ if (leaks.pii.length && this.policy.data && this.policy.data.pii && this.policy.data.pii.action === 'block') {
226
+ return { deny: deny('VG_AUTHORIZATION_DENIED', 'PII in arguments is blocked by policy') };
227
+ }
228
+ const paths = [];
229
+ const hosts = [];
230
+ for (const { key, value } of strings) {
231
+ if (PATH_KEY.test(key) && !/^https?:\/\//i.test(value)) {
232
+ const resolved = canonicalPath(this.root, value);
233
+ const rel = path.relative(this.rootCanonical, resolved).replace(/\\/g, '/');
234
+ paths.push({ value, resolved, rel });
235
+ const denyPaths = [];
236
+ for (const rule of this.policy.resources || []) {
237
+ if (rule.effect === 'deny' && rule.resources && rule.resources.paths) denyPaths.push(...rule.resources.paths);
238
+ }
239
+ if (denyPaths.length && (matchesAny(value, denyPaths) || matchesAny(rel, denyPaths) || matchesAny(resolved, denyPaths))) {
240
+ return { deny: deny('VG_AUTHORIZATION_DENIED', 'path matches a denied resource') };
241
+ }
242
+ const allowPaths = [];
243
+ for (const rule of this.policy.resources || []) {
244
+ if (rule.effect === 'allow' && rule.resources && rule.resources.paths) allowPaths.push(...rule.resources.paths);
245
+ }
246
+ if (!inside(this.rootCanonical, resolved) && !matchesAny(value, allowPaths) && !matchesAny(rel, allowPaths)) {
247
+ return { deny: deny('VG_AUTHORIZATION_DENIED', 'path is outside the project and not explicitly allowed') };
248
+ }
249
+ if (this.policy.sandbox && this.policy.sandbox.filesystem && Array.isArray(this.policy.sandbox.filesystem.deny)) {
250
+ if (matchesAny(value, this.policy.sandbox.filesystem.deny) || matchesAny(rel, this.policy.sandbox.filesystem.deny)) {
251
+ return { deny: deny('VG_AUTHORIZATION_DENIED', 'path matches a denied sandbox mount') };
252
+ }
253
+ }
254
+ }
255
+ if (COMMAND_KEY.test(key)) {
256
+ const cmd = checkCommand(value);
257
+ if (cmd.blocked) return { deny: deny('VG_AUTHORIZATION_DENIED', cmd.reason || 'dangerous command') };
258
+ for (const m of value.matchAll(/\bhttps?:\/\/[^\s"'<>]+/gi)) {
259
+ const host = hostOf(m[0]) || m[0].toLowerCase();
260
+ hosts.push(host);
261
+ const allowed = this.policy.data && this.policy.data.dlp && this.policy.data.dlp.destinations && this.policy.data.dlp.destinations.allow;
262
+ if (isExternalHost(host) && Array.isArray(allowed) && !matchesAny(host, allowed)) {
263
+ return { deny: deny('VG_AUTHORIZATION_DENIED', `egress host not allowlisted: ${host}`) };
264
+ }
265
+ }
266
+ }
267
+ }
268
+ return { paths, hosts };
269
+ }
270
+ }
271
+
272
+ function deny(code, explanation, ruleId) {
273
+ return {
274
+ decision: DECISION.DENY,
275
+ reasonCode: code || 'VG_AUTHORIZATION_DENIED',
276
+ matchedRules: ruleId ? [ruleId] : [],
277
+ obligations: [],
278
+ explanation,
279
+ };
280
+ }
281
+
282
+ function signPolicy(policy, opts = {}) {
283
+ if (!opts.privateKey) throw new Error('signPolicy requires privateKey');
284
+ const body = JSON.parse(JSON.stringify(policy));
285
+ delete body.signature;
286
+ const bodyHash = 'sha256:' + sha256Hex(body);
287
+ const sig = crypto.sign(null, Buffer.from(bodyHash, 'utf8'), loadPrivateKey(opts.privateKey)).toString('base64url');
288
+ return { ...body, signature: { alg: 'Ed25519', keyId: opts.keyId || 'policy-key', bodyHash, sig } };
289
+ }
290
+
291
+ function verifyPolicy(policy, opts = {}) {
292
+ if (!policy || policy.schemaVersion !== '2.0') return { valid: false, reason: 'schemaVersion must be 2.0' };
293
+ const now = opts.now ? new Date(opts.now) : new Date();
294
+ if (policy.issuedAt && new Date(policy.issuedAt).getTime() > now.getTime() + 300000) return { valid: false, reason: 'policy is not valid yet' };
295
+ if (policy.expiresAt && new Date(policy.expiresAt).getTime() <= now.getTime()) return { valid: false, reason: 'policy has expired' };
296
+ const sig = policy.signature;
297
+ if (!sig || sig.alg !== 'Ed25519' || !sig.bodyHash || !sig.sig) return { valid: false, reason: 'missing/unsupported signature' };
298
+ if (!opts.publicKey) return { valid: false, reason: 'no public key' };
299
+ const body = { ...policy };
300
+ delete body.signature;
301
+ const hash = 'sha256:' + sha256Hex(body);
302
+ if (hash !== sig.bodyHash) return { valid: false, reason: 'policy body hash mismatch' };
303
+ try {
304
+ const ok = crypto.verify(null, Buffer.from(hash, 'utf8'), loadPublicKey(opts.publicKey), Buffer.from(sig.sig, 'base64url'));
305
+ if (!ok) return { valid: false, reason: 'policy signature invalid' };
306
+ } catch {
307
+ return { valid: false, reason: 'policy signature verification error' };
308
+ }
309
+ return { valid: true };
310
+ }
311
+
312
+ function loadPolicyFile(file, opts = {}) {
313
+ let policy;
314
+ try { policy = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (err) {
315
+ throw new VibeGuardError(ERROR_CODES.POLICY_INVALID, `cannot load policy: ${err.message}`);
316
+ }
317
+ if (policy.mode === 'strict' && !opts.allowUnsigned) {
318
+ const v = verifyPolicy(policy, { publicKey: opts.publicKey });
319
+ if (!v.valid) throw new VibeGuardError(ERROR_CODES.POLICY_INVALID, `strict policy is not authentic: ${v.reason}`);
320
+ }
321
+ return new StrictPolicyEngine(policy, opts);
322
+ }
323
+
324
+ module.exports = {
325
+ StrictPolicyEngine,
326
+ signPolicy,
327
+ verifyPolicy,
328
+ loadPolicyFile,
329
+ matchesGlob,
330
+ canonicalPath,
331
+ conditionMatches,
332
+ };
@@ -0,0 +1,92 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/platform/sandbox-manager.js — isolation backend registry and selection.
5
+ *
6
+ * This build ships only an unverified process backend and a legacy vm backend.
7
+ * Selection is fail-closed: a policy that requires an OS/container/microVM
8
+ * class cannot run untrusted code until a backend passes its verification
9
+ * suite. This prevents "sandbox" claims from exceeding the actual isolation.
10
+ */
11
+
12
+ const { ERROR_CODES, ISOLATION, VibeGuardError } = require('./contracts');
13
+
14
+ const RANK = {
15
+ [ISOLATION.NONE]: 0,
16
+ [ISOLATION.PROCESS]: 1,
17
+ [ISOLATION.OS]: 2,
18
+ [ISOLATION.CONTAINER]: 3,
19
+ [ISOLATION.MICROVM]: 4,
20
+ [ISOLATION.HARDWARE_VM]: 5,
21
+ };
22
+
23
+ class SandboxManager {
24
+ constructor() {
25
+ this.backends = new Map();
26
+ }
27
+
28
+ register(backend) {
29
+ if (!backend || !backend.id) throw new Error('sandbox backend needs an id');
30
+ if (!Object.prototype.hasOwnProperty.call(RANK, backend.isolationClass)) {
31
+ throw new Error(`unknown isolation class: ${backend.isolationClass}`);
32
+ }
33
+ this.backends.set(backend.id, backend);
34
+ return this;
35
+ }
36
+
37
+ list() {
38
+ return [...this.backends.values()].map((b) => ({
39
+ id: b.id,
40
+ isolationClass: b.isolationClass,
41
+ verified: b.verified === true,
42
+ verification: b.verification || 'unverified',
43
+ limitations: b.limitations || [],
44
+ }));
45
+ }
46
+
47
+ select(requestedClass = ISOLATION.CONTAINER, opts = {}) {
48
+ const required = RANK[requestedClass];
49
+ if (required === undefined) throw new VibeGuardError(ERROR_CODES.SANDBOX_UNAVAILABLE, `unknown isolation class ${requestedClass}`);
50
+ const candidates = [...this.backends.values()].filter((b) => {
51
+ if (RANK[b.isolationClass] < required) return false;
52
+ return opts.allowUnverified === true || b.verified === true;
53
+ });
54
+ candidates.sort((a, b) => RANK[b.isolationClass] - RANK[a.isolationClass]);
55
+ if (!candidates.length) {
56
+ throw new VibeGuardError(
57
+ ERROR_CODES.SANDBOX_UNAVAILABLE,
58
+ opts.allowUnverified
59
+ ? `no backend provides ${requestedClass}`
60
+ : `no VERIFIED backend provides ${requestedClass}; refusing to claim isolation`,
61
+ { status: 503 }
62
+ );
63
+ }
64
+ return candidates[0];
65
+ }
66
+ }
67
+
68
+ function defaultManager() {
69
+ const manager = new SandboxManager();
70
+ try {
71
+ const { getLinuxBackend } = require('./os-sandbox');
72
+ const linux = getLinuxBackend();
73
+ if (linux.available()) manager.register(linux);
74
+ } catch { /* optional platform backend */ }
75
+ manager.register({
76
+ id: 'process',
77
+ isolationClass: ISOLATION.PROCESS,
78
+ verified: false,
79
+ verification: 'unverified',
80
+ limitations: ['same OS user', 'Node permission model is not a kernel sandbox', 'network is not blocked at the OS layer'],
81
+ });
82
+ manager.register({
83
+ id: 'legacy-vm',
84
+ isolationClass: ISOLATION.NONE,
85
+ verified: false,
86
+ verification: 'unverified',
87
+ limitations: ['compatibility runner only', 'host-realm escape was the original audit finding', 'not for untrusted code'],
88
+ });
89
+ return manager;
90
+ }
91
+
92
+ module.exports = { SandboxManager, defaultManager, RANK };