@yagyeshvyas/vibeguard 1.11.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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 };