@yagyeshvyas/vibeguard 1.11.2 → 1.13.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,37 @@
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.13.0] - 2026-11-22
7
+
8
+ ### Added
9
+
10
+ - Linux bubblewrap filesystem/network/PID isolation and Windows Job Object containment (AppContainer/WFP still absent).
11
+ - macOS `sandbox-exec` backend (deprecated profile; not App Sandbox/VM).
12
+ - Hosted approval API with authenticated tickets/proofs, JSON persistence, key rotation and read-only dashboard.
13
+ - Local OAuth 2.1 authorization-code + PKCE server with JWKS and aud/scope validation.
14
+ - Runtime RSS monitor with `--max-rss` quarantine kill.
15
+ - External audit anchor and HTTPS/mTLS bridge options.
16
+
17
+ ### Breaking
18
+
19
+ - `ApprovalBroker.decide()` requires signed approver proof by default.
20
+
21
+ ## [1.12.0] - 2026-11-22
22
+
23
+ ### Added
24
+
25
+ - Linux bubblewrap backend with verified network, PID and filesystem isolation.
26
+ - Windows Job Object backend (process/memory containment; AppContainer/WFP still absent).
27
+ - External audit anchor file; `audit verify --anchor`.
28
+ - HTTPS/mTLS server options for the MCP HTTP bridge.
29
+ - Signed approver proof (`ApprovalBroker.signApproverProof`) and registered approver keys.
30
+
31
+ ### Changed — breaking approval behavior
32
+
33
+ - `ApprovalBroker.decide()` now requires a signed approver proof by default.
34
+ Register `approverKeys` and pass `proof` from the approver private key. Legacy
35
+ unauthenticated human strings are rejected.
36
+
6
37
  ## [1.11.2] - 2026-11-22
7
38
 
8
39
  ### 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-629%20passed-blue?style=flat-square" alt="629 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.2
69
+ ## 🆕 What's New — v1.13.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
+ - **629 tests, 0 failures** on Windows Node24/Node18 and Linux Node22; 35/35
85
85
  platform tests on Windows/Linux/macOS CI.
86
86
 
87
- Install note: v1.11.2 is distributed as `@yagyeshvyas/vibeguard@1.11.2`. If a
87
+ Install note: v1.13.0 is distributed as `@yagyeshvyas/vibeguard@1.13.0`. If a
88
88
  registry mirror still serves an older build, use the exact
89
- [v1.11.2 GitHub release tarball](https://github.com/yagyeshVyas/VibeGuard/releases/tag/v1.11.2).
89
+ [v1.13.0 GitHub release tarball](https://github.com/yagyeshVyas/VibeGuard/releases/tag/v1.13.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.2 status (internal testing)
149
+ ## Security baseline v2 — v1.13.0 status (internal testing)
150
150
 
151
- This repository contains the v1.11.2 security foundation. It is **not** a
151
+ This repository contains the v1.13.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,10 @@ 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 and
170
+ macOS `sandbox-exec` are available; AppContainer/WFP and macOS App Sandbox/VM
171
+ are still absent.
170
172
  - Memory provenance guard and signed multi-agent delegation library.
171
173
  - Labeled detection corpus runner and AISVS-style readiness mapping.
172
174
  - Target-controlled scanner plugins are **disabled by default**; code execution
@@ -179,19 +181,21 @@ Implemented and tested:
179
181
 
180
182
  Not implemented or not verified:
181
183
 
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.
184
+ - **Windows AppContainer/WFP and macOS VM backends are absent.** Windows Job
185
+ Object provides process/memory containment only; it does not isolate files or
186
+ network. Linux bubblewrap isolates network/PID/filesystem when installed, but
187
+ is not a VM/hardware boundary.
188
+ - **External audit anchor** and checkpoint sidecars are supported; legacy
189
+ non-strict gateway audit is still the legacy hash chain.
190
+ - **Approval service**: hosted API with authenticated tickets, signed approver
191
+ proofs, JSON persistence, key rotation and a read-only dashboard; no SSO/IdP.
192
+ - A **local OAuth 2.1 code+PKCE server** and TLS/mTLS bridge options exist;
193
+ multi-session persistence and a full remote IdP/lifecycle remain incomplete.
191
194
  - Persistent memory/multi-agent runtime; `MemoryGuard`/`DelegationGraph` are
192
195
  tested libraries only.
193
196
  - Independent penetration test, representative precision/recall corpus, macOS
194
- full-suite evidence and npm registry publication (NPM_TOKEN missing).
197
+ full-suite evidence. npm 1.13.0 is published; GitHub Actions still lacks the
198
+ NPM_TOKEN secret and skips its publish step.
195
199
  - Dashboard/SDK and full AISVS certification; AISVS is an internal mapping.
196
200
 
197
201
 
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', 'max-rss']);
27
27
 
28
28
  function parseArgs(argv) {
29
29
  const args = { _: [], flags: {} };
@@ -178,6 +178,7 @@ function cmdMcpFirewall(args, flags) {
178
178
  approvalTenant: flags['approval-tenant'],
179
179
  approvalKeyId: flags['approval-key-id'],
180
180
  maxBlocks: flags['max-blocks'] ? Number(flags['max-blocks']) : 0,
181
+ maxRssMb: flags['max-rss'] ? Number(flags['max-rss']) : 0,
181
182
  });
182
183
 
183
184
  proxy.child.once('spawn', () => {
@@ -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,18 @@ 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 if (process.platform === 'darwin') {
100
+ const { MacSandboxExecSandbox } = require('../src/platform/os-sandbox');
101
+ backend = new MacSandboxExecSandbox();
102
+ } else {
103
+ const { getLinuxBackend } = require('../src/platform/os-sandbox');
104
+ backend = getLinuxBackend();
105
+ }
106
+ if (!backend.available()) { process.stderr.write('OS backend unavailable on this host\n'); return 2; }
98
107
  const ok = await backend.verify();
99
108
  out(JSON.stringify({ backend: backend.id, verified: ok, verification: backend.verification, limitations: backend.limitations }, null, 2));
100
109
  return ok ? 0 : 1;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@yagyeshvyas/vibeguard",
3
- "version": "1.11.2",
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.13.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 + external anchor, hosted approvals with signed proofs, HTTP/SSE MCP bridge with OAuth/TLS, Linux bubblewrap isolation, Windows Job containment and macOS sandbox-exec. Zero telemetry.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
7
7
  "author": "Yagyesh Vyas <https://www.linkedin.com/in/yagyeshvyas/>",
package/src/integrity.js CHANGED
@@ -37,9 +37,10 @@ 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
+ 'platform/approval-service.js', 'platform/oauth-server.js', 'platform/runtime-monitor.js',
43
44
  ];
44
45
 
45
46
  function hashFile(p) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "tool": "vibeguard",
3
- "generatedAt": "2026-11-22T19:06:01.043Z",
3
+ "generatedAt": "2026-11-22T19:55:42.417Z",
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": "576cdbbf231c589dd10436f9053fbe43db18cf0ab14ea697b6bf419c7c49b70b",
29
29
  "agent-policy.js": "5735aca870b7ecfe55c3525f7a338e9f97e3c1ca000dbb16850c312db53eb9e9",
30
30
  "skill-scan.js": "b172529a94333f8fb07098df518ecce3be9cf93242830e140ade48c2742f50e0",
31
31
  "owasp-agentic.js": "7ca8dca83b633ae62607b2ab24696bdfbf34b4a7b96c3b26ba1035b9b05e9a99",
@@ -36,17 +36,21 @@
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": "f9f1a873b4a5eb17529d35d1aa5fde8c6a11016fa9db0f35ec0eafccadc9ec1b",
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": "b646cfbe80a2fcfc7ea7e942c9f38e19294d6bcfee83e2502abf567911118ff1",
46
+ "platform/os-sandbox.js": "126b7ddb1bb804c8a441e5fd7f339254ccede42d3428408158299183a0a50cc1",
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
- "platform/aisvs.js": "711fa398da46c8deb386b6397d0b104905cc761145656c8bdd1ce5e78d394a35"
51
+ "platform/aisvs.js": "711fa398da46c8deb386b6397d0b104905cc761145656c8bdd1ce5e78d394a35",
52
+ "platform/approval-service.js": "6c4cfc3b24e4a8dd53c343604adea55941fe8218b1232a71c56d5a03a06f1f3c",
53
+ "platform/oauth-server.js": "bc41bfd676a19766dde9399958e4db70d0512dc028ec37585d17267cabd5dc29",
54
+ "platform/runtime-monitor.js": "b3b18bc0164869ba32fd8bf1927f25aa376dbc72d5d1ae0de4b459b3f179737c"
51
55
  }
52
56
  }
@@ -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
  });
@@ -732,6 +733,16 @@ function startProxy(opts = {}) {
732
733
  setTimeout(() => process.exit(2), 10).unref();
733
734
  }
734
735
 
736
+ let resourceMonitor = null;
737
+ if (Number(opts.maxRssMb || 0) > 0 && child.pid) {
738
+ const { RuntimeMonitor } = require('./platform/runtime-monitor');
739
+ resourceMonitor = new RuntimeMonitor({
740
+ pid: child.pid,
741
+ maxRssBytes: Number(opts.maxRssMb) * 1024 * 1024,
742
+ onExceeded: (info) => quarantineKill(`RSS ${info.rss} exceeded ${info.maxRssBytes}`),
743
+ }).start();
744
+ }
745
+
735
746
  function forwardToServer(messages) {
736
747
  for (const message of messages) {
737
748
  if (message && typeof message === 'object' && message.method) {
@@ -832,6 +843,7 @@ function startProxy(opts = {}) {
832
843
  }
833
844
 
834
845
  child.on('exit', (code, signal) => {
846
+ if (resourceMonitor) resourceMonitor.stop();
835
847
  engine.logger.log('mcp_server_exit', { server: serverName, code, signal, stats: engine.getStats() });
836
848
  if (!closed) {
837
849
  closed = true;
@@ -0,0 +1,124 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/platform/approval-service.js — hosted approval API + read-only dashboard.
5
+ *
6
+ * Agents request approval with a VGAT token. Human approvers authenticate with a
7
+ * human VGAT token AND a signed VGApprover proof; the broker issues a single-use
8
+ * VGApproval token. Tickets are persisted atomically to a JSON store and the
9
+ * service supports approver key rotation.
10
+ *
11
+ * This is a local/loopback service slice, not a full IAM/SSO product.
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const http = require('http');
17
+ const { ApprovalBroker } = require('./approval');
18
+ const { ERROR_CODES, VibeGuardError } = require('./contracts');
19
+
20
+ class JsonApprovalStore {
21
+ constructor(file) {
22
+ this.file = file ? path.resolve(file) : null;
23
+ this.data = { tickets: [], usedTokens: [] };
24
+ if (this.file && fs.existsSync(this.file)) {
25
+ try { this.data = JSON.parse(fs.readFileSync(this.file, 'utf8')); } catch { throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'approval store is corrupt'); }
26
+ }
27
+ }
28
+ save(broker) {
29
+ const approverKeys = this.data.approverKeys || {};
30
+ this.data = { ...broker.exportState(), approverKeys };
31
+ if (!this.file) return;
32
+ fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
33
+ const tmp = this.file + '.tmp';
34
+ fs.writeFileSync(tmp, JSON.stringify(this.data, null, 2) + '\n', { mode: 0o600 });
35
+ fs.renameSync(tmp, this.file);
36
+ }
37
+ }
38
+
39
+ function json(res, status, body) {
40
+ const payload = JSON.stringify(body);
41
+ res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) });
42
+ res.end(payload);
43
+ }
44
+
45
+ function readBody(req) {
46
+ return new Promise((resolve, reject) => {
47
+ let s = '';
48
+ req.on('data', (c) => { s += c; if (s.length > 64 * 1024) { reject(new VibeGuardError(ERROR_CODES.LIMIT_EXCEEDED, 'request too large')); req.destroy(); } });
49
+ req.on('end', () => resolve(s));
50
+ req.on('error', reject);
51
+ });
52
+ }
53
+
54
+ function authenticate(req, authority) {
55
+ const h = req.headers.authorization || '';
56
+ const token = h.startsWith('Bearer ') ? h.slice(7) : '';
57
+ if (!token) throw new VibeGuardError(ERROR_CODES.AUTH_REQUIRED, 'bearer token required', { status: 401 });
58
+ return authority.verify(token).principal;
59
+ }
60
+
61
+ function dashboard(broker) {
62
+ const rows = [...broker.tickets.values()].map((t) => `<tr><td>${escapeHtml(t.ticketId)}</td><td>${escapeHtml(t.principal)}</td><td>${escapeHtml(t.action && t.action.tool)}</td><td>${escapeHtml(t.status)}</td><td>${escapeHtml(t.approver || '')}</td></tr>`).join('');
63
+ return `<!doctype html><html><head><meta charset="utf-8"><title>VibeGuard approvals</title><style>body{background:#070b12;color:#d6f6ff;font-family:monospace;padding:2rem}table{border-collapse:collapse;width:100%}td,th{border:1px solid #174455;padding:.5rem;text-align:left}</style></head><body><h1>VibeGuard approvals</h1><p>Read-only dashboard. Decisions require an authenticated human token and a signed approver proof via POST /approval/decision.</p><table><tr><th>Ticket</th><th>Agent</th><th>Tool</th><th>Status</th><th>Approver</th></tr>${rows}</table></body></html>`;
64
+ }
65
+
66
+ function escapeHtml(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])); }
67
+
68
+ function createApprovalService(opts = {}) {
69
+ if (!opts.broker) throw new Error('approval service requires a broker');
70
+ if (!opts.authority) throw new Error('approval service requires an identity authority');
71
+ const broker = opts.broker;
72
+ const store = new JsonApprovalStore(opts.storeFile);
73
+ if (store.data.tickets && store.data.tickets.length) broker.importState(store.data);
74
+ for (const [principal, key] of Object.entries(store.data.approverKeys || {})) broker.rotateApproverKey(principal, key);
75
+ const server = http.createServer(async (req, res) => {
76
+ try {
77
+ if (req.method === 'GET' && req.url === '/health') return json(res, 200, { status: 'ok', service: 'vibeguard-approval' });
78
+ if (req.method === 'GET' && req.url === '/approval') {
79
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
80
+ return res.end(dashboard(broker));
81
+ }
82
+ if (req.method === 'POST' && req.url === '/approval/request') {
83
+ const principal = authenticate(req, opts.authority);
84
+ if (!String(principal.principalId).startsWith('agent:')) throw new VibeGuardError(ERROR_CODES.AUTHORIZATION_DENIED, 'agent token required', { status: 403 });
85
+ const body = JSON.parse(await readBody(req) || '{}');
86
+ if (!body.action) throw new VibeGuardError(ERROR_CODES.SCHEMA_INVALID, 'action is required');
87
+ const t = broker.request({ principal: principal.principalId, action: body.action, reason: body.reason, ttlSeconds: body.ttlSeconds });
88
+ store.save(broker);
89
+ return json(res, 200, t);
90
+ }
91
+ if (req.method === 'POST' && req.url === '/approval/decision') {
92
+ const principal = authenticate(req, opts.authority);
93
+ if (!String(principal.principalId).startsWith('human:')) throw new VibeGuardError(ERROR_CODES.AUTHORIZATION_DENIED, 'human approver token required', { status: 403 });
94
+ const body = JSON.parse(await readBody(req) || '{}');
95
+ const d = broker.decide(body.ticketId, { approver: principal.principalId, approve: body.approve === true, proof: body.proof });
96
+ store.save(broker);
97
+ return json(res, 200, d);
98
+ }
99
+ if (req.method === 'POST' && req.url === '/approval/keys') {
100
+ const principal = authenticate(req, opts.authority);
101
+ if (!opts.adminPrincipals || !opts.adminPrincipals.includes(principal.principalId)) throw new VibeGuardError(ERROR_CODES.AUTHORIZATION_DENIED, 'admin principal required', { status: 403 });
102
+ const body = JSON.parse(await readBody(req) || '{}');
103
+ if (!body.principal || !body.publicKey) throw new VibeGuardError(ERROR_CODES.SCHEMA_INVALID, 'principal and publicKey are required');
104
+ const r = broker.rotateApproverKey(body.principal, body.publicKey);
105
+ store.data.approverKeys = store.data.approverKeys || {};
106
+ store.data.approverKeys[body.principal] = body.publicKey;
107
+ store.save(broker);
108
+ return json(res, 200, r);
109
+ }
110
+ return json(res, 404, { error: 'not found' });
111
+ } catch (err) {
112
+ return json(res, err.status || 400, { error: err.message, code: err.code || 'VG_APPROVAL_INVALID' });
113
+ }
114
+ });
115
+ return new Promise((resolve, reject) => {
116
+ server.once('error', reject);
117
+ server.listen(Number(opts.port || 0), opts.host || '127.0.0.1', () => {
118
+ const addr = server.address();
119
+ resolve({ server, host: addr.address, port: addr.port, url: `http://${addr.address}:${addr.port}`, broker, store, close: () => new Promise((r) => server.close(r)) });
120
+ });
121
+ });
122
+ }
123
+
124
+ module.exports = { createApprovalService, JsonApprovalStore };
@@ -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,29 @@ class ApprovalBroker {
122
140
  return { status: 'approved', ticket: publicTicket(ticket), approvalToken: token };
123
141
  }
124
142
 
143
+ exportState() {
144
+ return { tickets: [...this.tickets.values()], usedTokens: [...this.usedTokens] };
145
+ }
146
+
147
+ importState(state = {}) {
148
+ this.tickets = new Map((state.tickets || []).map((t) => [t.ticketId, t]));
149
+ this.usedTokens = new Set(state.usedTokens || []);
150
+ return this;
151
+ }
152
+
153
+ rotateApproverKey(principal, key) {
154
+ if (!String(principal).startsWith('human:')) throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'approver must be a human principal');
155
+ this.approverKeys.set(principal, loadPublicKey(key));
156
+ return { principal, rotatedAt: this.now().toISOString() };
157
+ }
158
+
159
+ static signApproverProof({ ticketId, actionDigest: digest, nonce, approver, privateKey, ttlSeconds = 120, keyId = 'approver' } = {}) {
160
+ if (!ticketId || !digest || !nonce || !approver || !privateKey) throw new Error('approver proof requires ticketId, actionDigest, nonce, approver, privateKey');
161
+ const now = Math.floor(Date.now() / 1000);
162
+ 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 };
163
+ return signJws({ alg: 'EdDSA', typ: 'VGAPPROVER', kid: keyId }, payload, loadPrivateKey(privateKey));
164
+ }
165
+
125
166
  verify(ticketId, approvalToken, expectedActionDigest) {
126
167
  const ticket = this.tickets.get(ticketId);
127
168
  if (!ticket) throw new VibeGuardError(ERROR_CODES.APPROVAL_INVALID, 'approval ticket not found');
@@ -175,6 +216,7 @@ function publicTicket(t) {
175
216
  ticketId: t.ticketId,
176
217
  principal: t.principal,
177
218
  actionDigest: t.actionDigest,
219
+ nonce: t.nonce,
178
220
  reason: t.reason,
179
221
  createdAt: t.createdAt,
180
222
  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,
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/platform/oauth-server.js — local OAuth 2.1 authorization-code + PKCE
5
+ * service for the MCP HTTP bridge. EdDSA access tokens, JWKS discovery, one-use
6
+ * authorization codes and client secrets. It is a loopback/library service, not
7
+ * an enterprise IdP.
8
+ */
9
+
10
+ const crypto = require('crypto');
11
+ const http = require('http');
12
+ const { signJws } = require('./identity');
13
+ const { ERROR_CODES, VibeGuardError } = require('./contracts');
14
+
15
+ function b64url(buf) { return Buffer.from(buf).toString('base64url'); }
16
+ function s256(verifier) { return b64url(crypto.createHash('sha256').update(verifier).digest()); }
17
+ function json(res, status, body) {
18
+ const payload = JSON.stringify(body);
19
+ res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload), 'cache-control': 'no-store' });
20
+ res.end(payload);
21
+ }
22
+ function readJson(req) {
23
+ return new Promise((resolve, reject) => {
24
+ let s = '';
25
+ req.on('data', (c) => { s += c; if (s.length > 64 * 1024) { reject(new Error('too large')); req.destroy(); } });
26
+ req.on('end', () => { try { resolve(JSON.parse(s || '{}')); } catch { reject(new Error('invalid JSON')); } });
27
+ req.on('error', reject);
28
+ });
29
+ }
30
+
31
+ function createOAuthServer(opts = {}) {
32
+ if (!opts.privateKey || !opts.publicKey) throw new Error('oauth server requires privateKey and publicKey');
33
+ const issuer = opts.issuer || 'https://vibeguard.local';
34
+ const audience = opts.audience || 'vibeguard-gateway';
35
+ const keyId = opts.keyId || 'oauth-key';
36
+ const clients = new Map(Object.entries(opts.clients || {}));
37
+ if (!clients.size) throw new Error('oauth server requires at least one client secret');
38
+ const codes = new Map();
39
+ const now = opts.now || (() => new Date());
40
+ const codeTtl = opts.codeTtlSeconds || 60;
41
+ const tokenTtl = opts.tokenTtlSeconds || 300;
42
+
43
+ const server = http.createServer(async (req, res) => {
44
+ try {
45
+ const u = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
46
+ if (req.method === 'GET' && u.pathname === '/.well-known/openid-configuration') {
47
+ return json(res, 200, { issuer, authorization_endpoint: `${issuer}/authorize`, token_endpoint: `${issuer}/token`, jwks_uri: `${issuer}/jwks`, response_types_supported: ['code'], grant_types_supported: ['authorization_code'], code_challenge_methods_supported: ['S256'] });
48
+ }
49
+ if (req.method === 'GET' && u.pathname === '/jwks') {
50
+ return json(res, 200, { keys: [require('./identity').publicKeyToJwk(opts.publicKey, keyId)] });
51
+ }
52
+ if (req.method === 'POST' && u.pathname === '/authorize') {
53
+ const body = await readJson(req);
54
+ const secret = req.headers['x-client-secret'];
55
+ if (!body.client_id || clients.get(body.client_id) !== secret) throw new VibeGuardError(ERROR_CODES.AUTH_INVALID, 'invalid client credentials', { status: 401 });
56
+ if (!body.redirect_uri || !body.code_challenge) throw new VibeGuardError(ERROR_CODES.SCHEMA_INVALID, 'redirect_uri and code_challenge are required');
57
+ const code = crypto.randomBytes(24).toString('base64url');
58
+ codes.set(code, { clientId: body.client_id, redirectUri: body.redirect_uri, challenge: body.code_challenge, scope: String(body.scope || ''), principal: String(body.principal || 'agent:oauth/user'), expiresAt: now().getTime() + codeTtl * 1000, used: false });
59
+ return json(res, 200, { code, expires_in: codeTtl });
60
+ }
61
+ if (req.method === 'POST' && u.pathname === '/token') {
62
+ const body = await readJson(req);
63
+ if (body.grant_type !== 'authorization_code') throw new VibeGuardError(ERROR_CODES.AUTH_INVALID, 'unsupported grant_type');
64
+ const code = codes.get(body.code);
65
+ if (!code || code.used || code.expiresAt <= now().getTime()) throw new VibeGuardError(ERROR_CODES.AUTH_INVALID, 'invalid or expired authorization code');
66
+ if (clients.get(code.clientId) !== (req.headers['x-client-secret'] || body.client_secret)) throw new VibeGuardError(ERROR_CODES.AUTH_INVALID, 'invalid client credentials');
67
+ if (code.redirectUri !== body.redirect_uri) throw new VibeGuardError(ERROR_CODES.AUTH_INVALID, 'redirect_uri mismatch');
68
+ if (!body.code_verifier || s256(body.code_verifier) !== code.challenge) throw new VibeGuardError(ERROR_CODES.AUTH_INVALID, 'PKCE verification failed');
69
+ code.used = true;
70
+ const iat = Math.floor(now().getTime() / 1000);
71
+ const payload = { iss: issuer, aud: audience, sub: code.principal, scope: code.scope, iat, exp: iat + tokenTtl, jti: crypto.randomBytes(12).toString('base64url') };
72
+ const token = signJws({ alg: 'EdDSA', typ: 'at+jwt', kid: keyId }, payload, opts.privateKey);
73
+ return json(res, 200, { access_token: token, token_type: 'Bearer', expires_in: tokenTtl, scope: code.scope });
74
+ }
75
+ return json(res, 404, { error: 'not found' });
76
+ } catch (err) {
77
+ return json(res, err.status || 400, { error: err.message, code: err.code || 'VG_AUTH_INVALID' });
78
+ }
79
+ });
80
+ return new Promise((resolve, reject) => {
81
+ server.once('error', reject);
82
+ server.listen(Number(opts.port || 0), opts.host || '127.0.0.1', () => {
83
+ const addr = server.address();
84
+ resolve({ server, url: `http://${addr.address}:${addr.port}`, issuer, audience, keyId, close: () => new Promise((r) => server.close(r)) });
85
+ });
86
+ });
87
+ }
88
+
89
+ module.exports = { createOAuthServer };
@@ -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,192 @@ 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
+
246
+ class MacSandboxExecSandbox {
247
+ constructor(opts = {}) {
248
+ this.id = 'macos-sandbox-exec';
249
+ this.isolationClass = ISOLATION.OS;
250
+ this.verified = false;
251
+ this.verification = 'unverified';
252
+ this.limitations = ['deprecated sandbox-exec profile; not an App Sandbox entitlement or VM', 'network and selected filesystem writes denied by profile'];
253
+ this.nodePath = opts.nodePath || process.execPath;
254
+ this.sandboxExec = opts.sandboxExec || (process.platform === 'darwin' ? '/usr/bin/sandbox-exec' : null);
255
+ }
256
+ available() { return process.platform === 'darwin' && Boolean(this.sandboxExec) && fs.existsSync(this.sandboxExec); }
257
+ _profile(dir) {
258
+ const nodeRoot = path.dirname(path.dirname(this.nodePath));
259
+ return [
260
+ '(version 1)', '(deny default)',
261
+ '(allow process*)',
262
+ '(allow sysctl-read)',
263
+ '(allow mach-lookup)',
264
+ '(allow file-read* (subpath "/usr") (subpath "/System") (subpath "/Library") (subpath "/bin") (subpath "/sbin") (subpath "/dev") (subpath "/private/etc") (subpath "/private/var/db"))',
265
+ '(allow file-read* (subpath ' + JSON.stringify(nodeRoot) + ') (subpath ' + JSON.stringify(dir) + '))',
266
+ '(allow file-write* (subpath "/tmp") (subpath "/private/tmp"))',
267
+ '(deny network*)',
268
+ ].join('\n');
269
+ }
270
+ run(code, opts = {}) {
271
+ const started = Date.now();
272
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-mac-'));
273
+ fs.writeFileSync(path.join(dir, 'user.js'), String(code), 'utf8');
274
+ fs.writeFileSync(path.join(dir, 'harness.js'), HARNESS_SOURCE, 'utf8');
275
+ const result = { success: false, output: null, error: null, duration: 0, isolation: this.id, isolationClass: ISOLATION.OS, verified: this.verified, verification: this.verification, limitations: this.limitations.slice() };
276
+ if (!this.available()) { result.error = 'macOS sandbox-exec backend unavailable'; return Promise.resolve(result); }
277
+ return new Promise((resolve) => {
278
+ const child = spawn(this.sandboxExec, ['-p', this._profile(dir), this.nodePath, path.join(dir, 'harness.js')], { cwd: dir, env: { PATH: '/usr/bin:/bin', HOME: '/tmp' }, stdio: ['ignore', 'pipe', 'pipe'], shell: false });
279
+ let stdout = ''; let stderr = '';
280
+ const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch {} }, opts.timeout || 5000);
281
+ child.stdout.on('data', (c) => { stdout += c.toString('utf8'); });
282
+ child.stderr.on('data', (c) => { stderr += c.toString('utf8').slice(0, 1024 * 1024); });
283
+ child.once('error', (err) => { clearTimeout(timer); result.error = err.message; result.duration = Date.now() - started; resolve(result); });
284
+ child.once('exit', (code, signal) => { clearTimeout(timer); Object.assign(result, parseHarnessOutput(stdout, stderr, signal, code)); result.duration = Date.now() - started; resolve(result); });
285
+ });
286
+ }
287
+ async verify() {
288
+ if (!this.available()) { this.verification = 'unavailable'; return false; }
289
+ const probe = await this.run('const x = 1 + 1; x', { timeout: 4000 });
290
+ this.verified = Boolean(probe.success);
291
+ this.verification = this.verified ? 'sandbox-exec-harness-verified' : 'verification-failed';
292
+ return this.verified;
293
+ }
294
+ }
295
+
296
+ function getLinuxBackend(opts = {}) {
297
+ const bwrap = new LinuxBubblewrapSandbox(opts);
298
+ if (bwrap.available()) return bwrap;
141
299
  return new LinuxNamespaceSandbox(opts);
142
300
  }
143
301
 
144
- module.exports = { LinuxNamespaceSandbox, getLinuxBackend };
302
+ module.exports = { LinuxNamespaceSandbox, LinuxBubblewrapSandbox, MacSandboxExecSandbox, getLinuxBackend };
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/platform/runtime-monitor.js — process-level runtime guard.
5
+ *
6
+ * Polls a child process RSS against a configured cap and invokes the configured
7
+ * quarantine callback once. This is not a filesystem or network monitor; those
8
+ * require OS-specific tracing/WFP/netns integrations.
9
+ */
10
+
11
+ const { execFileSync } = require('child_process');
12
+
13
+ function readRssBytes(pid, platform = process.platform) {
14
+ if (!pid) return null;
15
+ try {
16
+ if (platform === 'linux' || platform === 'darwin') {
17
+ const out = execFileSync('ps', ['-o', 'rss=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
18
+ const kb = Number(String(out).trim());
19
+ return Number.isFinite(kb) && kb >= 0 ? kb * 1024 : null;
20
+ }
21
+ if (platform === 'win32') {
22
+ const out = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-Process -Id ${Number(pid)} -ErrorAction Stop).WorkingSet64`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
23
+ const bytes = Number(String(out).trim());
24
+ return Number.isFinite(bytes) && bytes > 0 ? bytes : null;
25
+ }
26
+ } catch { /* process may have exited */ }
27
+ return null;
28
+ }
29
+
30
+ class RuntimeMonitor {
31
+ constructor(opts = {}) {
32
+ this.pid = opts.pid;
33
+ this.maxRssBytes = opts.maxRssBytes || 0;
34
+ this.intervalMs = opts.intervalMs || 2000;
35
+ this.onExceeded = opts.onExceeded || (() => {});
36
+ this.read = opts.read || ((pid) => readRssBytes(pid));
37
+ this.timer = null;
38
+ this.lastRss = null;
39
+ this.exceeded = false;
40
+ }
41
+
42
+ start() {
43
+ if (!this.pid || !this.maxRssBytes || this.timer) return this;
44
+ this.timer = setInterval(() => this.check(), this.intervalMs);
45
+ if (this.timer.unref) this.timer.unref();
46
+ return this;
47
+ }
48
+
49
+ check() {
50
+ if (this.exceeded) return { exceeded: true, rss: this.lastRss };
51
+ const rss = this.read(this.pid);
52
+ this.lastRss = rss;
53
+ if (rss != null && rss > this.maxRssBytes) {
54
+ this.exceeded = true;
55
+ this.stop();
56
+ try { this.onExceeded({ pid: this.pid, rss, maxRssBytes: this.maxRssBytes }); } catch { /* callback must not crash monitor */ }
57
+ return { exceeded: true, rss };
58
+ }
59
+ return { exceeded: false, rss };
60
+ }
61
+
62
+ stop() {
63
+ if (this.timer) clearInterval(this.timer);
64
+ this.timer = null;
65
+ return this;
66
+ }
67
+ }
68
+
69
+ module.exports = { RuntimeMonitor, readRssBytes };
@@ -71,6 +71,16 @@ 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
+ }
79
+ if (process.platform === 'darwin') {
80
+ const { MacSandboxExecSandbox } = require('./os-sandbox');
81
+ const mac = new MacSandboxExecSandbox();
82
+ if (mac.available()) manager.register(mac);
83
+ }
74
84
  } catch { /* optional platform backend */ }
75
85
  manager.register({
76
86
  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');
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/platform/windows-sandbox.js — Windows Job Object execution boundary.
5
+ *
6
+ * This is a real kernel Job Object (process/memory limits, kill-on-close), but
7
+ * it is NOT AppContainer and does not implement WFP network or filesystem
8
+ * isolation. Do not call it a full OS sandbox; the limitations are reported.
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+ const { spawn, spawnSync } = require('child_process');
15
+ const { ISOLATION } = require('./contracts');
16
+ const { HARNESS_SOURCE } = require('../sandbox');
17
+
18
+ const CS_SOURCE = [
19
+ 'using System;',
20
+ 'using System.Diagnostics;',
21
+ 'using System.Runtime.InteropServices;',
22
+ 'using System.Text;',
23
+ 'public static class VGJob {',
24
+ ' [StructLayout(LayoutKind.Sequential)] public struct IO_COUNTERS { public ulong ReadOperationCount; public ulong WriteOperationCount; public ulong OtherOperationCount; public ulong ReadTransferCount; public ulong WriteTransferCount; public ulong OtherTransferCount; }',
25
+ ' [StructLayout(LayoutKind.Sequential)] public struct JOBOBJECT_BASIC_LIMIT_INFORMATION { public long PerProcessUserTimeLimit; public long PerJobUserTimeLimit; public uint LimitFlags; public UIntPtr MinimumWorkingSetSize; public UIntPtr MaximumWorkingSetSize; public uint ActiveProcessLimit; public UIntPtr Affinity; public uint PriorityClass; public uint SchedulingClass; }',
26
+ ' [StructLayout(LayoutKind.Sequential)] public struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION { public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; public IO_COUNTERS IoInfo; public UIntPtr ProcessMemoryLimit; public UIntPtr JobMemoryLimit; public UIntPtr PeakProcessMemoryUsed; public UIntPtr PeakJobMemoryUsed; }',
27
+ ' [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr a, string name);',
28
+ ' [DllImport("kernel32.dll")] static extern bool SetInformationJobObject(IntPtr h, int info, IntPtr p, uint len);',
29
+ ' [DllImport("kernel32.dll")] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);',
30
+ ' [DllImport("kernel32.dll")] static extern bool TerminateJobObject(IntPtr job, uint code);',
31
+ ' [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);',
32
+ ' public static string Run(string exe, string args, int timeoutMs, int memoryMb) {',
33
+ ' IntPtr job = CreateJobObject(IntPtr.Zero, null);',
34
+ ' if (job == IntPtr.Zero) return "__VG_STDERR__failed to create job object";',
35
+ ' var ext = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();',
36
+ ' ext.BasicLimitInformation.LimitFlags = 0x2000 | 0x100 | 0x200;',
37
+ ' ext.ProcessMemoryLimit = (UIntPtr)(memoryMb * 1024L * 1024L);',
38
+ ' ext.JobMemoryLimit = (UIntPtr)(memoryMb * 2L * 1024L * 1024L);',
39
+ ' int len = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));',
40
+ ' IntPtr ptr = Marshal.AllocHGlobal(len);',
41
+ ' Marshal.StructureToPtr(ext, ptr, false);',
42
+ ' SetInformationJobObject(job, 9, ptr, (uint)len);',
43
+ ' Marshal.FreeHGlobal(ptr);',
44
+ ' var psi = new ProcessStartInfo(exe, args);',
45
+ ' psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true;',
46
+ ' var so = new StringBuilder(); var se = new StringBuilder();',
47
+ ' var p = new Process(); p.StartInfo = psi;',
48
+ ' p.OutputDataReceived += (s, e) => { if (e.Data != null) so.AppendLine(e.Data); };',
49
+ ' p.ErrorDataReceived += (s, e) => { if (e.Data != null) se.AppendLine(e.Data); };',
50
+ ' p.Start(); AssignProcessToJobObject(job, p.Handle);',
51
+ ' p.BeginOutputReadLine(); p.BeginErrorReadLine();',
52
+ ' bool exited = p.WaitForExit(timeoutMs);',
53
+ ' if (!exited) { TerminateJobObject(job, 1); p.WaitForExit(1000); }',
54
+ ' p.WaitForExit(); CloseHandle(job);',
55
+ ' return "__VG_STDOUT__" + so.ToString() + "__VG_STDERR__" + se.ToString() + "__VG_EXIT__" + (exited ? p.ExitCode : 124);',
56
+ ' }',
57
+ '}'
58
+ ].join('\n');
59
+
60
+ const PS_SOURCE = [
61
+ 'param()',
62
+ '$src = Get-Content -Raw -LiteralPath $env:VG_CS',
63
+ 'Add-Type -TypeDefinition $src -Language CSharp',
64
+ '$out = [VGJob]::Run($env:VG_NODE, $env:VG_ARGS, [int]$env:VG_TIMEOUT, [int]$env:VG_MEM)',
65
+ '[Console]::Out.Write($out)'
66
+ ].join('\r\n');
67
+
68
+ function parseOutput(raw) {
69
+ const o = raw.indexOf('__VG_STDOUT__');
70
+ const e = raw.indexOf('__VG_STDERR__');
71
+ const x = raw.indexOf('__VG_EXIT__');
72
+ if (o < 0 || e < 0 || x < 0) return { stdout: raw, stderr: '', exit: null };
73
+ return { stdout: raw.slice(o + 13, e), stderr: raw.slice(e + 13, x), exit: Number(raw.slice(x + 11).trim()) };
74
+ }
75
+
76
+ class WindowsJobSandbox {
77
+ constructor(opts = {}) {
78
+ this.id = 'windows-job';
79
+ this.isolationClass = ISOLATION.OS;
80
+ this.verified = false;
81
+ this.verification = 'unverified';
82
+ this.limitations = ['Job Object process/memory limits and kill-on-close', 'does not implement AppContainer, WFP network isolation or filesystem isolation'];
83
+ this.powershell = opts.powershell || (process.platform === 'win32' ? 'powershell.exe' : null);
84
+ this.nodePath = opts.nodePath || process.execPath;
85
+ this.memoryMb = opts.memoryMb || 256;
86
+ }
87
+
88
+ available() { return process.platform === 'win32' && Boolean(this.powershell); }
89
+
90
+ _runWithExe(exe, args, timeout) {
91
+ const started = Date.now();
92
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-winjob-'));
93
+ const cs = path.join(dir, 'VGJob.cs');
94
+ const ps = path.join(dir, 'run.ps1');
95
+ fs.writeFileSync(cs, CS_SOURCE, 'utf8');
96
+ fs.writeFileSync(ps, PS_SOURCE, 'utf8');
97
+ return new Promise((resolve) => {
98
+ const child = spawn(this.powershell, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', ps], {
99
+ cwd: dir,
100
+ env: { ...process.env, VG_CS: cs, VG_NODE: exe, VG_ARGS: args, VG_TIMEOUT: String(timeout), VG_MEM: String(this.memoryMb) },
101
+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, shell: false,
102
+ });
103
+ let raw = '';
104
+ let stderr = '';
105
+ const timer = setTimeout(() => { try { child.kill(); } catch { /* ignore */ } }, timeout + 4000);
106
+ child.stdout.on('data', (c) => { raw += c.toString('utf8'); });
107
+ child.stderr.on('data', (c) => { stderr += c.toString('utf8').slice(0, 64 * 1024); });
108
+ child.once('error', (err) => { clearTimeout(timer); resolve({ success: false, output: null, error: err.message, duration: Date.now() - started, isolation: this.id, isolationClass: ISOLATION.OS, verified: this.verified, verification: this.verification, limitations: this.limitations }); });
109
+ child.once('exit', () => {
110
+ clearTimeout(timer);
111
+ const parsed = parseOutput(raw);
112
+ const marker = parsed.stdout.split(/\r?\n/).find((l) => l.startsWith('__VG_RESULT__'));
113
+ const errorMarker = parsed.stdout.split(/\r?\n/).find((l) => l.startsWith('__VG_ERROR__'));
114
+ let success = false; let output = null; let error = null;
115
+ if (marker) { try { const p = JSON.parse(marker.slice(13)); success = true; output = p.result; } catch { error = 'cannot parse harness result'; } }
116
+ else if (errorMarker) { try { error = JSON.parse(errorMarker.slice(11)); } catch { error = 'sandbox error'; } }
117
+ else if (parsed.exit === 124) error = 'VibeGuard Windows Job sandbox: execution timed out';
118
+ else error = parsed.stderr.trim() || stderr.trim() || `sandbox exited with code ${parsed.exit}`;
119
+ resolve({ success, output, error, duration: Date.now() - started, isolation: this.id, isolationClass: ISOLATION.OS, verified: this.verified, verification: this.verification, limitations: this.limitations });
120
+ });
121
+ });
122
+ }
123
+
124
+ async run(code, opts = {}) {
125
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-winjob-prog-'));
126
+ fs.writeFileSync(path.join(dir, 'user.js'), String(code), 'utf8');
127
+ fs.writeFileSync(path.join(dir, 'harness.js'), HARNESS_SOURCE, 'utf8');
128
+ return this._runWithExe(this.nodePath, `"${path.join(dir, 'harness.js')}"`, opts.timeout || 5000);
129
+ }
130
+
131
+ async verify() {
132
+ if (!this.available()) { this.verification = 'unavailable'; return false; }
133
+ const safe = await this.run('const x = 1 + 1; x', { timeout: 5000 });
134
+ const timeout = await this.run('while (true) {}', { timeout: 1200 });
135
+ const killed = !timeout.success && /timed out|exit/i.test(String(timeout.error || ''));
136
+ this.verified = Boolean(safe.success && killed);
137
+ this.verification = this.verified ? 'job-object-process-containment-verified' : 'verification-failed';
138
+ return this.verified;
139
+ }
140
+ }
141
+
142
+ module.exports = { WindowsJobSandbox };