@enclave-vm/core 0.0.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.
- package/LICENSE +201 -0
- package/README.md +732 -0
- package/SECURITY-AUDIT.md +916 -0
- package/package.json +59 -0
- package/src/adapters/vm-adapter.d.ts +32 -0
- package/src/adapters/vm-adapter.js +1140 -0
- package/src/adapters/vm-adapter.js.map +1 -0
- package/src/adapters/worker-pool/config.d.ts +149 -0
- package/src/adapters/worker-pool/config.js +129 -0
- package/src/adapters/worker-pool/config.js.map +1 -0
- package/src/adapters/worker-pool/errors.d.ts +109 -0
- package/src/adapters/worker-pool/errors.js +181 -0
- package/src/adapters/worker-pool/errors.js.map +1 -0
- package/src/adapters/worker-pool/execution-queue.d.ts +85 -0
- package/src/adapters/worker-pool/execution-queue.js +179 -0
- package/src/adapters/worker-pool/execution-queue.js.map +1 -0
- package/src/adapters/worker-pool/index.d.ts +48 -0
- package/src/adapters/worker-pool/index.js +73 -0
- package/src/adapters/worker-pool/index.js.map +1 -0
- package/src/adapters/worker-pool/memory-monitor.d.ts +106 -0
- package/src/adapters/worker-pool/memory-monitor.js +184 -0
- package/src/adapters/worker-pool/memory-monitor.js.map +1 -0
- package/src/adapters/worker-pool/protocol.d.ts +314 -0
- package/src/adapters/worker-pool/protocol.js +143 -0
- package/src/adapters/worker-pool/protocol.js.map +1 -0
- package/src/adapters/worker-pool/rate-limiter.d.ts +60 -0
- package/src/adapters/worker-pool/rate-limiter.js +101 -0
- package/src/adapters/worker-pool/rate-limiter.js.map +1 -0
- package/src/adapters/worker-pool/safe-deserialize.d.ts +50 -0
- package/src/adapters/worker-pool/safe-deserialize.js +141 -0
- package/src/adapters/worker-pool/safe-deserialize.js.map +1 -0
- package/src/adapters/worker-pool/worker-pool-adapter.d.ts +84 -0
- package/src/adapters/worker-pool/worker-pool-adapter.js +506 -0
- package/src/adapters/worker-pool/worker-pool-adapter.js.map +1 -0
- package/src/adapters/worker-pool/worker-script.d.ts +12 -0
- package/src/adapters/worker-pool/worker-script.js +770 -0
- package/src/adapters/worker-pool/worker-script.js.map +1 -0
- package/src/adapters/worker-pool/worker-slot.d.ts +116 -0
- package/src/adapters/worker-pool/worker-slot.js +301 -0
- package/src/adapters/worker-pool/worker-slot.js.map +1 -0
- package/src/babel/babel-wrapper.d.ts +118 -0
- package/src/babel/babel-wrapper.js +395 -0
- package/src/babel/babel-wrapper.js.map +1 -0
- package/src/babel/index.d.ts +9 -0
- package/src/babel/index.js +17 -0
- package/src/babel/index.js.map +1 -0
- package/src/babel/multi-file-transform.d.ts +122 -0
- package/src/babel/multi-file-transform.js +344 -0
- package/src/babel/multi-file-transform.js.map +1 -0
- package/src/double-vm/double-vm-wrapper.d.ts +65 -0
- package/src/double-vm/double-vm-wrapper.js +523 -0
- package/src/double-vm/double-vm-wrapper.js.map +1 -0
- package/src/double-vm/index.d.ts +31 -0
- package/src/double-vm/index.js +34 -0
- package/src/double-vm/index.js.map +1 -0
- package/src/double-vm/parent-vm-bootstrap.d.ts +63 -0
- package/src/double-vm/parent-vm-bootstrap.js +1695 -0
- package/src/double-vm/parent-vm-bootstrap.js.map +1 -0
- package/src/double-vm/suspicious-patterns.d.ts +57 -0
- package/src/double-vm/suspicious-patterns.js +304 -0
- package/src/double-vm/suspicious-patterns.js.map +1 -0
- package/src/double-vm/types.d.ts +178 -0
- package/src/double-vm/types.js +11 -0
- package/src/double-vm/types.js.map +1 -0
- package/src/double-vm/wrap-adapter.d.ts +36 -0
- package/src/double-vm/wrap-adapter.js +59 -0
- package/src/double-vm/wrap-adapter.js.map +1 -0
- package/src/enclave.d.ts +159 -0
- package/src/enclave.js +671 -0
- package/src/enclave.js.map +1 -0
- package/src/globals-validator.d.ts +80 -0
- package/src/globals-validator.js +206 -0
- package/src/globals-validator.js.map +1 -0
- package/src/index.d.ts +29 -0
- package/src/index.js +130 -0
- package/src/index.js.map +1 -0
- package/src/memory-proxy.d.ts +69 -0
- package/src/memory-proxy.js +310 -0
- package/src/memory-proxy.js.map +1 -0
- package/src/memory-tracker.d.ts +170 -0
- package/src/memory-tracker.js +230 -0
- package/src/memory-tracker.js.map +1 -0
- package/src/safe-error.d.ts +18 -0
- package/src/safe-error.js +76 -0
- package/src/safe-error.js.map +1 -0
- package/src/safe-runtime.d.ts +72 -0
- package/src/safe-runtime.js +656 -0
- package/src/safe-runtime.js.map +1 -0
- package/src/scoring/cache.d.ts +68 -0
- package/src/scoring/cache.js +158 -0
- package/src/scoring/cache.js.map +1 -0
- package/src/scoring/feature-extractor.d.ts +61 -0
- package/src/scoring/feature-extractor.js +366 -0
- package/src/scoring/feature-extractor.js.map +1 -0
- package/src/scoring/index.d.ts +33 -0
- package/src/scoring/index.js +53 -0
- package/src/scoring/index.js.map +1 -0
- package/src/scoring/scorer.interface.d.ts +65 -0
- package/src/scoring/scorer.interface.js +49 -0
- package/src/scoring/scorer.interface.js.map +1 -0
- package/src/scoring/scorers/disabled.scorer.d.ts +19 -0
- package/src/scoring/scorers/disabled.scorer.js +34 -0
- package/src/scoring/scorers/disabled.scorer.js.map +1 -0
- package/src/scoring/scorers/external-api.scorer.d.ts +29 -0
- package/src/scoring/scorers/external-api.scorer.js +141 -0
- package/src/scoring/scorers/external-api.scorer.js.map +1 -0
- package/src/scoring/scorers/index.d.ts +10 -0
- package/src/scoring/scorers/index.js +22 -0
- package/src/scoring/scorers/index.js.map +1 -0
- package/src/scoring/scorers/local-llm.scorer.d.ts +116 -0
- package/src/scoring/scorers/local-llm.scorer.js +474 -0
- package/src/scoring/scorers/local-llm.scorer.js.map +1 -0
- package/src/scoring/scorers/progressive.scorer.d.ts +77 -0
- package/src/scoring/scorers/progressive.scorer.js +199 -0
- package/src/scoring/scorers/progressive.scorer.js.map +1 -0
- package/src/scoring/scorers/rule-based.scorer.d.ts +66 -0
- package/src/scoring/scorers/rule-based.scorer.js +316 -0
- package/src/scoring/scorers/rule-based.scorer.js.map +1 -0
- package/src/scoring/scoring-gate.d.ts +76 -0
- package/src/scoring/scoring-gate.js +246 -0
- package/src/scoring/scoring-gate.js.map +1 -0
- package/src/scoring/types.d.ts +690 -0
- package/src/scoring/types.js +107 -0
- package/src/scoring/types.js.map +1 -0
- package/src/secure-proxy.d.ts +157 -0
- package/src/secure-proxy.js +609 -0
- package/src/secure-proxy.js.map +1 -0
- package/src/session/channels/embedded-channel.d.ts +76 -0
- package/src/session/channels/embedded-channel.js +130 -0
- package/src/session/channels/embedded-channel.js.map +1 -0
- package/src/session/channels/index.d.ts +9 -0
- package/src/session/channels/index.js +14 -0
- package/src/session/channels/index.js.map +1 -0
- package/src/session/index.d.ts +15 -0
- package/src/session/index.js +27 -0
- package/src/session/index.js.map +1 -0
- package/src/session/session-emitter.d.ts +119 -0
- package/src/session/session-emitter.js +253 -0
- package/src/session/session-emitter.js.map +1 -0
- package/src/session/session-state-machine.d.ts +108 -0
- package/src/session/session-state-machine.js +182 -0
- package/src/session/session-state-machine.js.map +1 -0
- package/src/session/session.d.ts +135 -0
- package/src/session/session.js +398 -0
- package/src/session/session.js.map +1 -0
- package/src/session-types.d.ts +313 -0
- package/src/session-types.js +39 -0
- package/src/session-types.js.map +1 -0
- package/src/sidecar/index.d.ts +12 -0
- package/src/sidecar/index.js +31 -0
- package/src/sidecar/index.js.map +1 -0
- package/src/sidecar/reference-config.d.ts +81 -0
- package/src/sidecar/reference-config.js +118 -0
- package/src/sidecar/reference-config.js.map +1 -0
- package/src/sidecar/reference-resolver.d.ts +115 -0
- package/src/sidecar/reference-resolver.js +262 -0
- package/src/sidecar/reference-resolver.js.map +1 -0
- package/src/sidecar/reference-sidecar.d.ts +161 -0
- package/src/sidecar/reference-sidecar.js +226 -0
- package/src/sidecar/reference-sidecar.js.map +1 -0
- package/src/tool-bridge.d.ts +4 -0
- package/src/tool-bridge.js +306 -0
- package/src/tool-bridge.js.map +1 -0
- package/src/types.d.ts +775 -0
- package/src/types.js +187 -0
- package/src/types.js.map +1 -0
- package/src/value-sanitizer.d.ts +133 -0
- package/src/value-sanitizer.js +421 -0
- package/src/value-sanitizer.js.map +1 -0
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Double VM Wrapper
|
|
4
|
+
*
|
|
5
|
+
* Wraps a base sandbox adapter with a double VM layer for enhanced security.
|
|
6
|
+
* User code runs in an Inner VM which is isolated inside a Parent VM,
|
|
7
|
+
* providing defense-in-depth against VM escape attacks.
|
|
8
|
+
*
|
|
9
|
+
* @packageDocumentation
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.DoubleVmWrapper = void 0;
|
|
13
|
+
const tslib_1 = require("tslib");
|
|
14
|
+
const vm = tslib_1.__importStar(require("vm"));
|
|
15
|
+
const value_sanitizer_1 = require("../value-sanitizer");
|
|
16
|
+
const secure_proxy_1 = require("../secure-proxy");
|
|
17
|
+
const safe_error_1 = require("../safe-error");
|
|
18
|
+
const reference_resolver_1 = require("../sidecar/reference-resolver");
|
|
19
|
+
const memory_tracker_1 = require("../memory-tracker");
|
|
20
|
+
const tool_bridge_1 = require("../tool-bridge");
|
|
21
|
+
const parent_vm_bootstrap_1 = require("./parent-vm-bootstrap");
|
|
22
|
+
const suspicious_patterns_1 = require("./suspicious-patterns");
|
|
23
|
+
/**
|
|
24
|
+
* Sensitive patterns to redact from stack traces
|
|
25
|
+
* (Same as vm-adapter for consistency)
|
|
26
|
+
*/
|
|
27
|
+
const SENSITIVE_STACK_PATTERNS = [
|
|
28
|
+
/\/Users\/[^/]+\/[^\s):]*/gi,
|
|
29
|
+
/\/home\/[^/]+\/[^\s):]*/gi,
|
|
30
|
+
/\/var\/[^\s):]*/gi,
|
|
31
|
+
/node_modules\/[^\s):]+/gi,
|
|
32
|
+
];
|
|
33
|
+
/**
|
|
34
|
+
* Sanitize stack trace by removing host file system paths
|
|
35
|
+
*
|
|
36
|
+
* Uses line-by-line processing with pre-checks to prevent ReDoS attacks.
|
|
37
|
+
* The vulnerable pattern /at\s+(\S+)\s+\([^)]*:\d+:\d+\)/g can cause polynomial
|
|
38
|
+
* backtracking on malicious input like "at ! (at ! (at ! (...".
|
|
39
|
+
*/
|
|
40
|
+
function sanitizeStackTrace(stack, sanitize = true) {
|
|
41
|
+
if (!stack || !sanitize)
|
|
42
|
+
return stack;
|
|
43
|
+
let sanitized = stack;
|
|
44
|
+
for (const pattern of SENSITIVE_STACK_PATTERNS) {
|
|
45
|
+
pattern.lastIndex = 0;
|
|
46
|
+
sanitized = sanitized.replace(pattern, '[REDACTED]');
|
|
47
|
+
}
|
|
48
|
+
// Remove line/column numbers - process line by line with pre-checks to prevent ReDoS
|
|
49
|
+
// Pre-checking the ending pattern before applying full regex avoids polynomial backtracking
|
|
50
|
+
const lines = sanitized.split('\n');
|
|
51
|
+
for (let i = 0; i < lines.length; i++) {
|
|
52
|
+
const line = lines[i];
|
|
53
|
+
// Defense-in-depth: skip very long lines
|
|
54
|
+
if (line.length > 1000)
|
|
55
|
+
continue;
|
|
56
|
+
// Pattern 1: "at functionName (path:line:column)" format
|
|
57
|
+
// Quick check: does line contain ":digits:digits)" pattern?
|
|
58
|
+
if (/:\d+:\d+\)/.test(line)) {
|
|
59
|
+
// Extract function name using indexOf to avoid regex backtracking
|
|
60
|
+
const atIdx = line.indexOf('at ');
|
|
61
|
+
if (atIdx !== -1) {
|
|
62
|
+
const afterAt = line.substring(atIdx + 3).trimStart();
|
|
63
|
+
const spaceIdx = afterAt.indexOf(' ');
|
|
64
|
+
if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === '(') {
|
|
65
|
+
const funcName = afterAt.substring(0, spaceIdx);
|
|
66
|
+
lines[i] = line.substring(0, atIdx) + 'at ' + funcName + ' ([REDACTED])';
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// Pattern 2: "at path:line:column" format (no parentheses)
|
|
72
|
+
if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
|
|
73
|
+
lines[i] = line.replace(/:\d+:\d+$/, '') + '[REDACTED]';
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return lines.join('\n');
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Double VM Wrapper
|
|
80
|
+
*
|
|
81
|
+
* Creates a nested VM structure:
|
|
82
|
+
* - Parent VM: Security barrier with enhanced validation
|
|
83
|
+
* - Inner VM: Where user code actually executes
|
|
84
|
+
*/
|
|
85
|
+
class DoubleVmWrapper {
|
|
86
|
+
config;
|
|
87
|
+
securityLevel;
|
|
88
|
+
parentContext;
|
|
89
|
+
constructor(config, securityLevel) {
|
|
90
|
+
this.config = config;
|
|
91
|
+
this.securityLevel = securityLevel;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Execute code in the double VM structure
|
|
95
|
+
*/
|
|
96
|
+
async execute(code, executionContext) {
|
|
97
|
+
const { stats, config } = executionContext;
|
|
98
|
+
const startTime = Date.now();
|
|
99
|
+
const isStrictOrSecure = this.securityLevel === 'STRICT' || this.securityLevel === 'SECURE';
|
|
100
|
+
const policyViolation = {};
|
|
101
|
+
// Create memory tracker if memory limit is configured
|
|
102
|
+
const memoryTracker = config.memoryLimit && config.memoryLimit > 0
|
|
103
|
+
? new memory_tracker_1.MemoryTracker({
|
|
104
|
+
memoryLimit: config.memoryLimit,
|
|
105
|
+
trackStrings: true,
|
|
106
|
+
trackArrays: true,
|
|
107
|
+
trackObjects: false,
|
|
108
|
+
})
|
|
109
|
+
: undefined;
|
|
110
|
+
// Start tracking before execution
|
|
111
|
+
memoryTracker?.start();
|
|
112
|
+
try {
|
|
113
|
+
// Create parent VM context with memory tracker
|
|
114
|
+
const parentContext = this.createParentContext(executionContext, memoryTracker, (type) => {
|
|
115
|
+
if (!policyViolation.type)
|
|
116
|
+
policyViolation.type = String(type);
|
|
117
|
+
});
|
|
118
|
+
this.parentContext = parentContext;
|
|
119
|
+
// Generate the parent VM bootstrap script
|
|
120
|
+
const parentScript = this.buildParentScript(code, executionContext);
|
|
121
|
+
// Compile and execute in parent VM
|
|
122
|
+
const script = new vm.Script(parentScript, {
|
|
123
|
+
filename: 'parent-vm.js',
|
|
124
|
+
});
|
|
125
|
+
// Parent VM timeout = inner VM timeout + buffer
|
|
126
|
+
const parentTimeout = config.timeout + this.config.parentTimeoutBuffer;
|
|
127
|
+
const resultPromise = script.runInContext(parentContext, {
|
|
128
|
+
timeout: parentTimeout,
|
|
129
|
+
breakOnSigint: true,
|
|
130
|
+
});
|
|
131
|
+
// Wait for result
|
|
132
|
+
const value = await resultPromise;
|
|
133
|
+
// Update stats
|
|
134
|
+
stats.duration = Date.now() - startTime;
|
|
135
|
+
stats.endTime = Date.now();
|
|
136
|
+
// Report memory usage if tracking was enabled
|
|
137
|
+
if (memoryTracker) {
|
|
138
|
+
const memSnapshot = memoryTracker.getSnapshot();
|
|
139
|
+
stats.memoryUsage = memSnapshot.peakTrackedBytes;
|
|
140
|
+
}
|
|
141
|
+
// STRICT/SECURE: Fail closed on recorded policy violations even if user code caught them.
|
|
142
|
+
if (isStrictOrSecure && policyViolation.type) {
|
|
143
|
+
return {
|
|
144
|
+
success: false,
|
|
145
|
+
error: {
|
|
146
|
+
name: 'SecurityViolationError',
|
|
147
|
+
message: 'Blocked operation: security policy violation',
|
|
148
|
+
code: 'SECURITY_VIOLATION',
|
|
149
|
+
data: { type: policyViolation.type },
|
|
150
|
+
},
|
|
151
|
+
stats,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
// SECURITY FIX (Vector 340): Check serialized size of return value BEFORE returning.
|
|
155
|
+
// Attacks can create structures with many references to the same large string that
|
|
156
|
+
// appear small in memory (strings are shared by reference) but explode during
|
|
157
|
+
// JSON serialization when each reference becomes a full copy.
|
|
158
|
+
// Example: 500 refs × 5 copies × 10KB = 25MB serialized from ~20KB in-memory
|
|
159
|
+
if (config.memoryLimit && config.memoryLimit > 0 && value !== undefined) {
|
|
160
|
+
// Use memory limit as serialization limit (or a reasonable cap)
|
|
161
|
+
// This prevents the serialization size from exceeding what we'd allow in memory
|
|
162
|
+
const maxSerializedBytes = Math.min(config.memoryLimit, 50 * 1024 * 1024); // Cap at 50MB
|
|
163
|
+
const sizeCheck = (0, value_sanitizer_1.checkSerializedSize)(value, maxSerializedBytes);
|
|
164
|
+
if (!sizeCheck.ok) {
|
|
165
|
+
return {
|
|
166
|
+
success: false,
|
|
167
|
+
error: {
|
|
168
|
+
name: 'MemoryLimitError',
|
|
169
|
+
message: `Return value serialization would exceed memory limit: ${sizeCheck.error}`,
|
|
170
|
+
code: 'SERIALIZATION_LIMIT_EXCEEDED',
|
|
171
|
+
},
|
|
172
|
+
stats,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
// Sanitize the return value to convert Error objects to { name, message } format
|
|
177
|
+
// This prevents Error objects from serializing to {} and provides useful error info
|
|
178
|
+
const sanitizedValue = (0, value_sanitizer_1.sanitizeValue)(value, {
|
|
179
|
+
maxDepth: config.maxSanitizeDepth,
|
|
180
|
+
maxProperties: config.maxSanitizeProperties,
|
|
181
|
+
allowDates: true,
|
|
182
|
+
allowErrors: true,
|
|
183
|
+
});
|
|
184
|
+
return {
|
|
185
|
+
success: true,
|
|
186
|
+
value: sanitizedValue,
|
|
187
|
+
stats,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
// Update stats
|
|
192
|
+
stats.duration = Date.now() - startTime;
|
|
193
|
+
stats.endTime = Date.now();
|
|
194
|
+
// Report memory usage if tracking was enabled
|
|
195
|
+
let memSnapshot;
|
|
196
|
+
if (memoryTracker) {
|
|
197
|
+
memSnapshot = memoryTracker.getSnapshot();
|
|
198
|
+
stats.memoryUsage = memSnapshot.peakTrackedBytes;
|
|
199
|
+
}
|
|
200
|
+
// Handle memory limit errors specially (host Error or sandbox-safe payload)
|
|
201
|
+
if (error instanceof memory_tracker_1.MemoryLimitError ||
|
|
202
|
+
(error && typeof error === 'object' && error.code === 'MEMORY_LIMIT_EXCEEDED')) {
|
|
203
|
+
const payload = error;
|
|
204
|
+
const usedBytes = typeof payload.usedBytes === 'number' ? payload.usedBytes : (memSnapshot?.trackedBytes ?? 0);
|
|
205
|
+
const limitBytes = typeof payload.limitBytes === 'number' ? payload.limitBytes : (config.memoryLimit ?? 0);
|
|
206
|
+
return {
|
|
207
|
+
success: false,
|
|
208
|
+
error: {
|
|
209
|
+
name: 'MemoryLimitError',
|
|
210
|
+
message: typeof payload.message === 'string' ? payload.message : 'Memory limit exceeded',
|
|
211
|
+
code: 'MEMORY_LIMIT_EXCEEDED',
|
|
212
|
+
data: { usedBytes, limitBytes },
|
|
213
|
+
},
|
|
214
|
+
stats,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
// Determine whether to sanitize stack traces
|
|
218
|
+
const shouldSanitize = config.sanitizeStackTraces ?? true;
|
|
219
|
+
// Handle thrown strings (e.g., iteration limit exceeded throws a string literal)
|
|
220
|
+
if (typeof error === 'string') {
|
|
221
|
+
return {
|
|
222
|
+
success: false,
|
|
223
|
+
error: {
|
|
224
|
+
name: 'DoubleVMExecutionError',
|
|
225
|
+
message: error,
|
|
226
|
+
code: 'DOUBLE_VM_EXECUTION_ERROR',
|
|
227
|
+
},
|
|
228
|
+
stats,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
const err = error;
|
|
232
|
+
return {
|
|
233
|
+
success: false,
|
|
234
|
+
error: {
|
|
235
|
+
name: err.name || 'DoubleVMExecutionError',
|
|
236
|
+
message: err.message || 'Unknown double VM execution error',
|
|
237
|
+
stack: sanitizeStackTrace(err.stack, shouldSanitize),
|
|
238
|
+
code: 'DOUBLE_VM_EXECUTION_ERROR',
|
|
239
|
+
},
|
|
240
|
+
stats,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Create the parent VM context
|
|
246
|
+
*
|
|
247
|
+
* The parent VM gets controlled access to:
|
|
248
|
+
* - The vm module (to create inner VM)
|
|
249
|
+
* - A tool call proxy to the host
|
|
250
|
+
* - Stats and config references
|
|
251
|
+
* - Memory tracking callback (when memoryLimit is set)
|
|
252
|
+
*/
|
|
253
|
+
createParentContext(executionContext, memoryTracker, reportViolation) {
|
|
254
|
+
const { stats, config } = executionContext;
|
|
255
|
+
// Create isolated context for parent VM
|
|
256
|
+
// codeGeneration.strings=false disables new Function() and eval() from strings
|
|
257
|
+
// This prevents sandbox escape via constructor chain in both parent and inner VMs
|
|
258
|
+
const parentContext = vm.createContext({}, {
|
|
259
|
+
codeGeneration: { strings: false, wasm: false },
|
|
260
|
+
});
|
|
261
|
+
// Inject controlled vm module access
|
|
262
|
+
// CRITICAL: Only expose createContext and Script, nothing else
|
|
263
|
+
// NOTE: configurable: true allows parent-vm-bootstrap.ts to delete this
|
|
264
|
+
// reference after use, preventing access if child VM escapes to parent context
|
|
265
|
+
const safeVm = {
|
|
266
|
+
createContext: vm.createContext.bind(vm),
|
|
267
|
+
Script: vm.Script,
|
|
268
|
+
};
|
|
269
|
+
Object.defineProperty(parentContext, '__host_vm_module__', {
|
|
270
|
+
value: safeVm,
|
|
271
|
+
writable: false,
|
|
272
|
+
configurable: true, // Allow deletion after use for defense-in-depth
|
|
273
|
+
});
|
|
274
|
+
// Inject tool call proxy to host
|
|
275
|
+
const toolBridgeMode = config.toolBridge?.mode ?? 'string';
|
|
276
|
+
const hostCallTool = toolBridgeMode === 'string'
|
|
277
|
+
? (0, tool_bridge_1.createHostToolBridge)(executionContext, { updateStats: false })
|
|
278
|
+
: this.createHostCallToolProxy(executionContext);
|
|
279
|
+
Object.defineProperty(parentContext, '__host_callTool__', {
|
|
280
|
+
value: hostCallTool,
|
|
281
|
+
writable: false,
|
|
282
|
+
configurable: true, // Allow deletion after capture for defense-in-depth
|
|
283
|
+
});
|
|
284
|
+
// Inject mutable stats reference so parent can update counts
|
|
285
|
+
Object.defineProperty(parentContext, '__host_stats__', {
|
|
286
|
+
value: stats,
|
|
287
|
+
writable: false,
|
|
288
|
+
configurable: true, // Allow deletion after capture for defense-in-depth
|
|
289
|
+
});
|
|
290
|
+
// Inject abort check function
|
|
291
|
+
Object.defineProperty(parentContext, '__host_abort_check__', {
|
|
292
|
+
value: () => executionContext.aborted,
|
|
293
|
+
writable: false,
|
|
294
|
+
configurable: true, // Allow deletion after capture for defense-in-depth
|
|
295
|
+
});
|
|
296
|
+
// Inject policy-violation reporter (used for STRICT/SECURE fail-closed behavior)
|
|
297
|
+
Object.defineProperty(parentContext, '__host_reportViolation__', {
|
|
298
|
+
value: reportViolation,
|
|
299
|
+
writable: false,
|
|
300
|
+
configurable: true, // Allow deletion after capture for defense-in-depth
|
|
301
|
+
});
|
|
302
|
+
// Inject config (for globals, console limits, and memory limit)
|
|
303
|
+
Object.defineProperty(parentContext, '__host_config__', {
|
|
304
|
+
value: {
|
|
305
|
+
globals: config.globals,
|
|
306
|
+
maxConsoleOutputBytes: config.maxConsoleOutputBytes,
|
|
307
|
+
maxConsoleCalls: config.maxConsoleCalls,
|
|
308
|
+
memoryLimit: config.memoryLimit, // Required for pre-allocation checks in inner VM
|
|
309
|
+
},
|
|
310
|
+
writable: false,
|
|
311
|
+
configurable: true, // Allow deletion after capture for defense-in-depth
|
|
312
|
+
});
|
|
313
|
+
// Inject memory tracking callback (when memoryLimit is set)
|
|
314
|
+
// This is called by innerConcat to track string allocation memory
|
|
315
|
+
if (memoryTracker) {
|
|
316
|
+
Object.defineProperty(parentContext, '__host_memory_track__', {
|
|
317
|
+
value: (bytes) => {
|
|
318
|
+
try {
|
|
319
|
+
memoryTracker.track(bytes);
|
|
320
|
+
}
|
|
321
|
+
catch (err) {
|
|
322
|
+
// SECURITY: Never throw host Error instances into the sandbox realm.
|
|
323
|
+
// Always convert errors into a null-prototype payload that cannot be
|
|
324
|
+
// used for prototype chain escape attacks (and never includes host stack).
|
|
325
|
+
if (err instanceof memory_tracker_1.MemoryLimitError) {
|
|
326
|
+
const safeError = Object.freeze(Object.assign(Object.create(null), {
|
|
327
|
+
name: 'MemoryLimitError',
|
|
328
|
+
message: err.message,
|
|
329
|
+
code: err.code,
|
|
330
|
+
usedBytes: err.usedBytes,
|
|
331
|
+
limitBytes: err.limitBytes,
|
|
332
|
+
}));
|
|
333
|
+
throw safeError;
|
|
334
|
+
}
|
|
335
|
+
const code = err && typeof err === 'object' && typeof err.code !== 'undefined'
|
|
336
|
+
? err.code
|
|
337
|
+
: undefined;
|
|
338
|
+
const safeError = Object.freeze(Object.assign(Object.create(null), {
|
|
339
|
+
name: err instanceof Error ? err.name : 'Error',
|
|
340
|
+
message: err instanceof Error ? err.message : typeof err === 'string' ? err : 'Memory tracking failed',
|
|
341
|
+
...(typeof code === 'string' || typeof code === 'number' ? { code } : {}),
|
|
342
|
+
}));
|
|
343
|
+
throw safeError;
|
|
344
|
+
}
|
|
345
|
+
},
|
|
346
|
+
writable: false,
|
|
347
|
+
configurable: false,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
else {
|
|
351
|
+
// No-op when memory tracking is disabled
|
|
352
|
+
Object.defineProperty(parentContext, '__host_memory_track__', {
|
|
353
|
+
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
|
354
|
+
value: () => { },
|
|
355
|
+
writable: false,
|
|
356
|
+
configurable: false,
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
// Add console for parent VM (for debugging only, not a security risk since
|
|
360
|
+
// user code runs in the inner VM, not the parent VM)
|
|
361
|
+
Object.defineProperty(parentContext, 'console', {
|
|
362
|
+
value: console,
|
|
363
|
+
writable: false,
|
|
364
|
+
configurable: false,
|
|
365
|
+
});
|
|
366
|
+
return parentContext;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Create the tool call proxy function that runs in the HOST
|
|
370
|
+
*
|
|
371
|
+
* This is called BY the parent VM's innerCallTool function
|
|
372
|
+
* when it wants to forward a validated call to the actual host.
|
|
373
|
+
*
|
|
374
|
+
* The proxy handles:
|
|
375
|
+
* - Sidecar reference resolution (args with __REF_...__ are resolved)
|
|
376
|
+
* - Large result lifting (strings > threshold are stored in sidecar)
|
|
377
|
+
* - Value sanitization
|
|
378
|
+
*/
|
|
379
|
+
createHostCallToolProxy(executionContext) {
|
|
380
|
+
const { config, toolHandler, sidecar, referenceConfig } = executionContext;
|
|
381
|
+
// Create resolver for sidecar references if available
|
|
382
|
+
const resolver = sidecar && referenceConfig ? new reference_resolver_1.ReferenceResolver(sidecar, referenceConfig) : undefined;
|
|
383
|
+
return async (toolName, args) => {
|
|
384
|
+
// Double check abort status
|
|
385
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
386
|
+
if (executionContext.aborted) {
|
|
387
|
+
throw (0, safe_error_1.createSafeError)('Execution aborted');
|
|
388
|
+
}
|
|
389
|
+
// Check for tool handler
|
|
390
|
+
if (!toolHandler) {
|
|
391
|
+
throw (0, safe_error_1.createSafeError)('No tool handler configured. Cannot execute tool calls.');
|
|
392
|
+
}
|
|
393
|
+
// Resolve sidecar references if present
|
|
394
|
+
let resolvedArgs = args;
|
|
395
|
+
if (resolver && resolver.containsReferences(args)) {
|
|
396
|
+
// Predictive check - fail fast before allocation
|
|
397
|
+
if (resolver.wouldExceedLimit(args)) {
|
|
398
|
+
throw (0, safe_error_1.createSafeError)(`Arguments would exceed maximum resolved size when references are expanded. ` +
|
|
399
|
+
`Pass large data directly to tool arguments instead of constructing them.`);
|
|
400
|
+
}
|
|
401
|
+
// Resolve all references to actual data
|
|
402
|
+
resolvedArgs = resolver.resolve(args);
|
|
403
|
+
}
|
|
404
|
+
// Execute the tool call
|
|
405
|
+
try {
|
|
406
|
+
const result = await toolHandler(toolName, resolvedArgs);
|
|
407
|
+
// Sanitize the return value using configured limits from security level
|
|
408
|
+
const sanitized = (0, value_sanitizer_1.sanitizeValue)(result, {
|
|
409
|
+
maxDepth: config.maxSanitizeDepth,
|
|
410
|
+
maxProperties: config.maxSanitizeProperties,
|
|
411
|
+
allowDates: true,
|
|
412
|
+
allowErrors: true,
|
|
413
|
+
});
|
|
414
|
+
// Lift large string results to sidecar if configured
|
|
415
|
+
if (sidecar && referenceConfig && typeof sanitized === 'string') {
|
|
416
|
+
const size = Buffer.byteLength(sanitized, 'utf-8');
|
|
417
|
+
if (size >= referenceConfig.extractionThreshold) {
|
|
418
|
+
try {
|
|
419
|
+
const refId = sidecar.store(sanitized, 'tool-result', { origin: toolName });
|
|
420
|
+
return refId;
|
|
421
|
+
}
|
|
422
|
+
catch (storageError) {
|
|
423
|
+
// If storage fails (e.g., sidecar limits reached), log and return original value
|
|
424
|
+
if (process.env['NODE_ENV'] !== 'production') {
|
|
425
|
+
console.debug(`[DoubleVmWrapper] Sidecar storage failed for tool "${toolName}": ${storageError.message}`);
|
|
426
|
+
}
|
|
427
|
+
return sanitized;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return sanitized;
|
|
432
|
+
}
|
|
433
|
+
catch (error) {
|
|
434
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
435
|
+
// This is critical - the original error from the tool handler could expose
|
|
436
|
+
// the host Function constructor via error.constructor.constructor
|
|
437
|
+
const err = error;
|
|
438
|
+
throw (0, safe_error_1.createSafeError)(`Tool call failed: ${toolName} - ${err.message || 'Unknown error'}`);
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Build the parent VM script with embedded user code
|
|
444
|
+
*/
|
|
445
|
+
buildParentScript(code, executionContext) {
|
|
446
|
+
const { config, secureProxyConfig, referenceConfig } = executionContext;
|
|
447
|
+
// Serialize validation config for passing to parent VM
|
|
448
|
+
const serializableConfig = this.serializeValidationConfig();
|
|
449
|
+
// Get all suspicious patterns (defaults + custom)
|
|
450
|
+
const allPatterns = [...suspicious_patterns_1.DEFAULT_SUSPICIOUS_PATTERNS, ...(this.config.parentValidation.suspiciousPatterns || [])];
|
|
451
|
+
const serializedPatterns = (0, suspicious_patterns_1.serializePatterns)(allPatterns);
|
|
452
|
+
// Get blocked properties for secure proxy
|
|
453
|
+
// Use explicit secureProxyConfig override if available, otherwise use security level defaults
|
|
454
|
+
let blockedPropertiesSet;
|
|
455
|
+
let throwOnBlocked;
|
|
456
|
+
if (secureProxyConfig) {
|
|
457
|
+
blockedPropertiesSet = (0, secure_proxy_1.buildBlockedPropertiesFromConfig)(secureProxyConfig);
|
|
458
|
+
throwOnBlocked = secureProxyConfig.throwOnBlocked ?? true;
|
|
459
|
+
}
|
|
460
|
+
else {
|
|
461
|
+
blockedPropertiesSet = (0, secure_proxy_1.getBlockedPropertiesForLevel)(this.securityLevel);
|
|
462
|
+
// Get throwOnBlocked from security level config
|
|
463
|
+
// Import the security level configs to get the throwOnBlocked setting
|
|
464
|
+
const SECURITY_LEVEL_CONFIGS = {
|
|
465
|
+
STRICT: { throwOnBlocked: true },
|
|
466
|
+
SECURE: { throwOnBlocked: true },
|
|
467
|
+
STANDARD: { throwOnBlocked: true },
|
|
468
|
+
PERMISSIVE: { throwOnBlocked: false },
|
|
469
|
+
};
|
|
470
|
+
throwOnBlocked = SECURITY_LEVEL_CONFIGS[this.securityLevel]?.throwOnBlocked ?? true;
|
|
471
|
+
}
|
|
472
|
+
const blockedProperties = Array.from(blockedPropertiesSet);
|
|
473
|
+
// Whether composite reference handles are allowed
|
|
474
|
+
const allowComposites = referenceConfig?.allowComposites ?? false;
|
|
475
|
+
const toolBridgeMode = config.toolBridge?.mode ?? 'string';
|
|
476
|
+
const toolBridgeMaxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
|
|
477
|
+
return (0, parent_vm_bootstrap_1.generateParentVmBootstrap)({
|
|
478
|
+
userCode: code,
|
|
479
|
+
innerTimeout: config.timeout,
|
|
480
|
+
maxIterations: config.maxIterations,
|
|
481
|
+
maxToolCalls: config.maxToolCalls,
|
|
482
|
+
sanitizeStackTraces: config.sanitizeStackTraces ?? true,
|
|
483
|
+
securityLevel: this.securityLevel,
|
|
484
|
+
validationConfig: serializableConfig,
|
|
485
|
+
suspiciousPatterns: serializedPatterns,
|
|
486
|
+
blockedProperties,
|
|
487
|
+
allowComposites,
|
|
488
|
+
memoryLimit: config.memoryLimit,
|
|
489
|
+
throwOnBlocked,
|
|
490
|
+
toolBridgeMode,
|
|
491
|
+
toolBridgeMaxPayloadBytes,
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Serialize validation config for passing to parent VM
|
|
496
|
+
*
|
|
497
|
+
* RegExp objects cannot be passed across VM boundaries,
|
|
498
|
+
* so we extract their source and flags.
|
|
499
|
+
*/
|
|
500
|
+
serializeValidationConfig() {
|
|
501
|
+
const pv = this.config.parentValidation;
|
|
502
|
+
return {
|
|
503
|
+
validateOperationNames: pv.validateOperationNames,
|
|
504
|
+
allowedOperationPatternSource: pv.allowedOperationPattern?.source,
|
|
505
|
+
allowedOperationPatternFlags: pv.allowedOperationPattern?.flags,
|
|
506
|
+
blockedOperationPatternSources: pv.blockedOperationPatterns?.map((p) => p.source),
|
|
507
|
+
blockedOperationPatternFlags: pv.blockedOperationPatterns?.map((p) => p.flags),
|
|
508
|
+
maxOperationsPerSecond: pv.maxOperationsPerSecond,
|
|
509
|
+
blockSuspiciousSequences: pv.blockSuspiciousSequences,
|
|
510
|
+
rapidEnumerationThreshold: pv.rapidEnumerationThreshold,
|
|
511
|
+
rapidEnumerationOverrides: pv.rapidEnumerationOverrides,
|
|
512
|
+
suspiciousPatterns: [], // Will be populated separately
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Dispose resources
|
|
517
|
+
*/
|
|
518
|
+
dispose() {
|
|
519
|
+
this.parentContext = undefined;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
exports.DoubleVmWrapper = DoubleVmWrapper;
|
|
523
|
+
//# sourceMappingURL=double-vm-wrapper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,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C,sBAAsB;YACjD,wBAAwB,EAAE,EAAE,CAAC,wBAAwB;YACrD,yBAAyB,EAAE,EAAE,CAAC,yBAAyB;YACvD,yBAAyB,EAAE,EAAE,CAAC,yBAAyB;YACvD,kBAAkB,EAAE,EAAE,EAAE,+BAA+B;SACxD,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,OAAO;QACL,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC;IACjC,CAAC;CACF;AAvfD,0CAufC","sourcesContent":["/**\n * Double VM Wrapper\n *\n * Wraps a base sandbox adapter with a double VM layer for enhanced security.\n * User code runs in an Inner VM which is isolated inside a Parent VM,\n * providing defense-in-depth against VM escape attacks.\n *\n * @packageDocumentation\n */\n\nimport * as vm from 'vm';\nimport type { SandboxAdapter, ExecutionContext, ExecutionResult, SecurityLevel } from '../types';\nimport { sanitizeValue, checkSerializedSize } from '../value-sanitizer';\nimport { getBlockedPropertiesForLevel, buildBlockedPropertiesFromConfig } from '../secure-proxy';\nimport { createSafeError } from '../safe-error';\nimport { ReferenceResolver } from '../sidecar/reference-resolver';\nimport { MemoryTracker, MemoryLimitError } from '../memory-tracker';\nimport { createHostToolBridge } from '../tool-bridge';\nimport type { DoubleVmConfig, SerializableParentValidationConfig } from './types';\nimport { generateParentVmBootstrap } from './parent-vm-bootstrap';\nimport { serializePatterns, DEFAULT_SUSPICIOUS_PATTERNS } from './suspicious-patterns';\n\n/**\n * Sensitive patterns to redact from stack traces\n * (Same as vm-adapter for consistency)\n */\nconst SENSITIVE_STACK_PATTERNS = [\n /\\/Users\\/[^/]+\\/[^\\s):]*/gi,\n /\\/home\\/[^/]+\\/[^\\s):]*/gi,\n /\\/var\\/[^\\s):]*/gi,\n /node_modules\\/[^\\s):]+/gi,\n];\n\n/**\n * Sanitize stack trace by removing host file system paths\n *\n * Uses line-by-line processing with pre-checks to prevent ReDoS attacks.\n * The vulnerable pattern /at\\s+(\\S+)\\s+\\([^)]*:\\d+:\\d+\\)/g can cause polynomial\n * backtracking on malicious input like \"at ! (at ! (at ! (...\".\n */\nfunction sanitizeStackTrace(stack: string | undefined, sanitize = true): string | undefined {\n if (!stack || !sanitize) return stack;\n\n let sanitized = stack;\n for (const pattern of SENSITIVE_STACK_PATTERNS) {\n pattern.lastIndex = 0;\n sanitized = sanitized.replace(pattern, '[REDACTED]');\n }\n\n // Remove line/column numbers - process line by line with pre-checks to prevent ReDoS\n // Pre-checking the ending pattern before applying full regex avoids polynomial backtracking\n const lines = sanitized.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Defense-in-depth: skip very long lines\n if (line.length > 1000) continue;\n\n // Pattern 1: \"at functionName (path:line:column)\" format\n // Quick check: does line contain \":digits:digits)\" pattern?\n if (/:\\d+:\\d+\\)/.test(line)) {\n // Extract function name using indexOf to avoid regex backtracking\n const atIdx = line.indexOf('at ');\n if (atIdx !== -1) {\n const afterAt = line.substring(atIdx + 3).trimStart();\n const spaceIdx = afterAt.indexOf(' ');\n if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === '(') {\n const funcName = afterAt.substring(0, spaceIdx);\n lines[i] = line.substring(0, atIdx) + 'at ' + funcName + ' ([REDACTED])';\n continue;\n }\n }\n }\n\n // Pattern 2: \"at path:line:column\" format (no parentheses)\n if (/:\\d+:\\d+$/.test(line) && /^\\s*at\\s/.test(line)) {\n lines[i] = line.replace(/:\\d+:\\d+$/, '') + '[REDACTED]';\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Double VM Wrapper\n *\n * Creates a nested VM structure:\n * - Parent VM: Security barrier with enhanced validation\n * - Inner VM: Where user code actually executes\n */\nexport class DoubleVmWrapper implements SandboxAdapter {\n private parentContext?: vm.Context;\n\n constructor(\n private readonly config: DoubleVmConfig,\n private readonly securityLevel: SecurityLevel,\n ) {}\n\n /**\n * Execute code in the double VM structure\n */\n async execute<T = unknown>(code: string, executionContext: ExecutionContext): Promise<ExecutionResult<T>> {\n const { stats, config } = executionContext;\n const startTime = Date.now();\n const isStrictOrSecure = this.securityLevel === 'STRICT' || this.securityLevel === 'SECURE';\n const policyViolation: { type?: string } = {};\n\n // Create memory tracker if memory limit is configured\n const memoryTracker =\n config.memoryLimit && config.memoryLimit > 0\n ? new MemoryTracker({\n memoryLimit: config.memoryLimit,\n trackStrings: true,\n trackArrays: true,\n trackObjects: false,\n })\n : undefined;\n\n // Start tracking before execution\n memoryTracker?.start();\n\n try {\n // Create parent VM context with memory tracker\n const parentContext = this.createParentContext(executionContext, memoryTracker, (type: string) => {\n if (!policyViolation.type) policyViolation.type = String(type);\n });\n this.parentContext = parentContext;\n\n // Generate the parent VM bootstrap script\n const parentScript = this.buildParentScript(code, executionContext);\n\n // Compile and execute in parent VM\n const script = new vm.Script(parentScript, {\n filename: 'parent-vm.js',\n });\n\n // Parent VM timeout = inner VM timeout + buffer\n const parentTimeout = config.timeout + this.config.parentTimeoutBuffer;\n\n const resultPromise = script.runInContext(parentContext, {\n timeout: parentTimeout,\n breakOnSigint: true,\n });\n\n // Wait for result\n const value = await resultPromise;\n\n // Update stats\n stats.duration = Date.now() - startTime;\n stats.endTime = Date.now();\n\n // Report memory usage if tracking was enabled\n if (memoryTracker) {\n const memSnapshot = memoryTracker.getSnapshot();\n stats.memoryUsage = memSnapshot.peakTrackedBytes;\n }\n\n // STRICT/SECURE: Fail closed on recorded policy violations even if user code caught them.\n if (isStrictOrSecure && policyViolation.type) {\n return {\n success: false,\n error: {\n name: 'SecurityViolationError',\n message: 'Blocked operation: security policy violation',\n code: 'SECURITY_VIOLATION',\n data: { type: policyViolation.type },\n },\n stats,\n };\n }\n\n // SECURITY FIX (Vector 340): Check serialized size of return value BEFORE returning.\n // Attacks can create structures with many references to the same large string that\n // appear small in memory (strings are shared by reference) but explode during\n // JSON serialization when each reference becomes a full copy.\n // Example: 500 refs × 5 copies × 10KB = 25MB serialized from ~20KB in-memory\n if (config.memoryLimit && config.memoryLimit > 0 && value !== undefined) {\n // Use memory limit as serialization limit (or a reasonable cap)\n // This prevents the serialization size from exceeding what we'd allow in memory\n const maxSerializedBytes = Math.min(config.memoryLimit, 50 * 1024 * 1024); // Cap at 50MB\n const sizeCheck = checkSerializedSize(value, maxSerializedBytes);\n\n if (!sizeCheck.ok) {\n return {\n success: false,\n error: {\n name: 'MemoryLimitError',\n message: `Return value serialization would exceed memory limit: ${sizeCheck.error}`,\n code: 'SERIALIZATION_LIMIT_EXCEEDED',\n },\n stats,\n };\n }\n }\n\n // Sanitize the return value to convert Error objects to { name, message } format\n // This prevents Error objects from serializing to {} and provides useful error info\n const sanitizedValue = sanitizeValue(value, {\n maxDepth: config.maxSanitizeDepth,\n maxProperties: config.maxSanitizeProperties,\n allowDates: true,\n allowErrors: true,\n });\n\n return {\n success: true,\n value: sanitizedValue as T,\n stats,\n };\n } catch (error: unknown) {\n // Update stats\n stats.duration = Date.now() - startTime;\n stats.endTime = Date.now();\n\n // Report memory usage if tracking was enabled\n let memSnapshot: ReturnType<MemoryTracker['getSnapshot']> | undefined;\n if (memoryTracker) {\n memSnapshot = memoryTracker.getSnapshot();\n stats.memoryUsage = memSnapshot.peakTrackedBytes;\n }\n\n // Handle memory limit errors specially (host Error or sandbox-safe payload)\n if (\n error instanceof MemoryLimitError ||\n (error && typeof error === 'object' && (error as any).code === 'MEMORY_LIMIT_EXCEEDED')\n ) {\n const payload = error as { message?: unknown; usedBytes?: unknown; limitBytes?: unknown };\n const usedBytes = typeof payload.usedBytes === 'number' ? payload.usedBytes : (memSnapshot?.trackedBytes ?? 0);\n const limitBytes = typeof payload.limitBytes === 'number' ? payload.limitBytes : (config.memoryLimit ?? 0);\n\n return {\n success: false,\n error: {\n name: 'MemoryLimitError',\n message: typeof payload.message === 'string' ? payload.message : 'Memory limit exceeded',\n code: 'MEMORY_LIMIT_EXCEEDED',\n data: { usedBytes, limitBytes },\n },\n stats,\n };\n }\n\n // Determine whether to sanitize stack traces\n const shouldSanitize = config.sanitizeStackTraces ?? true;\n\n // Handle thrown strings (e.g., iteration limit exceeded throws a string literal)\n if (typeof error === 'string') {\n return {\n success: false,\n error: {\n name: 'DoubleVMExecutionError',\n message: error,\n code: 'DOUBLE_VM_EXECUTION_ERROR',\n },\n stats,\n };\n }\n\n const err = error as Error;\n return {\n success: false,\n error: {\n name: err.name || 'DoubleVMExecutionError',\n message: err.message || 'Unknown double VM execution error',\n stack: sanitizeStackTrace(err.stack, shouldSanitize),\n code: 'DOUBLE_VM_EXECUTION_ERROR',\n },\n stats,\n };\n }\n }\n\n /**\n * Create the parent VM context\n *\n * The parent VM gets controlled access to:\n * - The vm module (to create inner VM)\n * - A tool call proxy to the host\n * - Stats and config references\n * - Memory tracking callback (when memoryLimit is set)\n */\n private createParentContext(\n executionContext: ExecutionContext,\n memoryTracker: MemoryTracker | undefined,\n reportViolation: (type: string) => void,\n ): vm.Context {\n const { stats, config } = executionContext;\n\n // Create isolated context for parent VM\n // codeGeneration.strings=false disables new Function() and eval() from strings\n // This prevents sandbox escape via constructor chain in both parent and inner VMs\n const parentContext = vm.createContext(\n {},\n {\n codeGeneration: { strings: false, wasm: false },\n },\n );\n\n // Inject controlled vm module access\n // CRITICAL: Only expose createContext and Script, nothing else\n // NOTE: configurable: true allows parent-vm-bootstrap.ts to delete this\n // reference after use, preventing access if child VM escapes to parent context\n const safeVm = {\n createContext: vm.createContext.bind(vm),\n Script: vm.Script,\n };\n\n Object.defineProperty(parentContext, '__host_vm_module__', {\n value: safeVm,\n writable: false,\n configurable: true, // Allow deletion after use for defense-in-depth\n });\n\n // Inject tool call proxy to host\n const toolBridgeMode = config.toolBridge?.mode ?? 'string';\n const hostCallTool =\n toolBridgeMode === 'string'\n ? createHostToolBridge(executionContext, { updateStats: false })\n : this.createHostCallToolProxy(executionContext);\n Object.defineProperty(parentContext, '__host_callTool__', {\n value: hostCallTool,\n writable: false,\n configurable: true, // Allow deletion after capture for defense-in-depth\n });\n\n // Inject mutable stats reference so parent can update counts\n Object.defineProperty(parentContext, '__host_stats__', {\n value: stats,\n writable: false,\n configurable: true, // Allow deletion after capture for defense-in-depth\n });\n\n // Inject abort check function\n Object.defineProperty(parentContext, '__host_abort_check__', {\n value: () => executionContext.aborted,\n writable: false,\n configurable: true, // Allow deletion after capture for defense-in-depth\n });\n\n // Inject policy-violation reporter (used for STRICT/SECURE fail-closed behavior)\n Object.defineProperty(parentContext, '__host_reportViolation__', {\n value: reportViolation,\n writable: false,\n configurable: true, // Allow deletion after capture for defense-in-depth\n });\n\n // Inject config (for globals, console limits, and memory limit)\n Object.defineProperty(parentContext, '__host_config__', {\n value: {\n globals: config.globals,\n maxConsoleOutputBytes: config.maxConsoleOutputBytes,\n maxConsoleCalls: config.maxConsoleCalls,\n memoryLimit: config.memoryLimit, // Required for pre-allocation checks in inner VM\n },\n writable: false,\n configurable: true, // Allow deletion after capture for defense-in-depth\n });\n\n // Inject memory tracking callback (when memoryLimit is set)\n // This is called by innerConcat to track string allocation memory\n if (memoryTracker) {\n Object.defineProperty(parentContext, '__host_memory_track__', {\n value: (bytes: number) => {\n try {\n memoryTracker.track(bytes);\n } catch (err: unknown) {\n // SECURITY: Never throw host Error instances into the sandbox realm.\n // Always convert errors into a null-prototype payload that cannot be\n // used for prototype chain escape attacks (and never includes host stack).\n if (err instanceof MemoryLimitError) {\n const safeError = Object.freeze(\n Object.assign(Object.create(null), {\n name: 'MemoryLimitError',\n message: err.message,\n code: err.code,\n usedBytes: err.usedBytes,\n limitBytes: err.limitBytes,\n }),\n );\n throw safeError;\n }\n\n const code =\n err && typeof err === 'object' && typeof (err as { code?: unknown }).code !== 'undefined'\n ? (err as { code?: unknown }).code\n : undefined;\n\n const safeError = Object.freeze(\n Object.assign(Object.create(null), {\n name: err instanceof Error ? err.name : 'Error',\n message: err instanceof Error ? err.message : typeof err === 'string' ? err : 'Memory tracking failed',\n ...(typeof code === 'string' || typeof code === 'number' ? { code } : {}),\n }),\n );\n throw safeError;\n }\n },\n writable: false,\n configurable: false,\n });\n } else {\n // No-op when memory tracking is disabled\n Object.defineProperty(parentContext, '__host_memory_track__', {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n value: () => {},\n writable: false,\n configurable: false,\n });\n }\n\n // Add console for parent VM (for debugging only, not a security risk since\n // user code runs in the inner VM, not the parent VM)\n Object.defineProperty(parentContext, 'console', {\n value: console,\n writable: false,\n configurable: false,\n });\n\n return parentContext;\n }\n\n /**\n * Create the tool call proxy function that runs in the HOST\n *\n * This is called BY the parent VM's innerCallTool function\n * when it wants to forward a validated call to the actual host.\n *\n * The proxy handles:\n * - Sidecar reference resolution (args with __REF_...__ are resolved)\n * - Large result lifting (strings > threshold are stored in sidecar)\n * - Value sanitization\n */\n private createHostCallToolProxy(executionContext: ExecutionContext) {\n const { config, toolHandler, sidecar, referenceConfig } = executionContext;\n\n // Create resolver for sidecar references if available\n const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : undefined;\n\n return async (toolName: string, args: Record<string, unknown>): Promise<unknown> => {\n // Double check abort status\n // SECURITY: Use createSafeError to prevent prototype chain escape attacks\n if (executionContext.aborted) {\n throw createSafeError('Execution aborted');\n }\n\n // Check for tool handler\n if (!toolHandler) {\n throw createSafeError('No tool handler configured. Cannot execute tool calls.');\n }\n\n // Resolve sidecar references if present\n let resolvedArgs = args;\n if (resolver && resolver.containsReferences(args)) {\n // Predictive check - fail fast before allocation\n if (resolver.wouldExceedLimit(args)) {\n throw createSafeError(\n `Arguments would exceed maximum resolved size when references are expanded. ` +\n `Pass large data directly to tool arguments instead of constructing them.`,\n );\n }\n // Resolve all references to actual data\n resolvedArgs = resolver.resolve(args) as Record<string, unknown>;\n }\n\n // Execute the tool call\n try {\n const result = await toolHandler(toolName, resolvedArgs);\n\n // Sanitize the return value using configured limits from security level\n const sanitized = sanitizeValue(result, {\n maxDepth: config.maxSanitizeDepth,\n maxProperties: config.maxSanitizeProperties,\n allowDates: true,\n allowErrors: true,\n });\n\n // Lift large string results to sidecar if configured\n if (sidecar && referenceConfig && typeof sanitized === 'string') {\n const size = Buffer.byteLength(sanitized, 'utf-8');\n if (size >= referenceConfig.extractionThreshold) {\n try {\n const refId = sidecar.store(sanitized, 'tool-result', { origin: toolName });\n return refId;\n } catch (storageError) {\n // If storage fails (e.g., sidecar limits reached), log and return original value\n if (process.env['NODE_ENV'] !== 'production') {\n console.debug(\n `[DoubleVmWrapper] Sidecar storage failed for tool \"${toolName}\": ${(storageError as Error).message}`,\n );\n }\n return sanitized;\n }\n }\n }\n\n return sanitized;\n } catch (error: unknown) {\n // SECURITY: Use createSafeError to prevent prototype chain escape attacks\n // This is critical - the original error from the tool handler could expose\n // the host Function constructor via error.constructor.constructor\n const err = error as Error;\n throw createSafeError(`Tool call failed: ${toolName} - ${err.message || 'Unknown error'}`);\n }\n };\n }\n\n /**\n * Build the parent VM script with embedded user code\n */\n private buildParentScript(code: string, executionContext: ExecutionContext): string {\n const { config, secureProxyConfig, referenceConfig } = executionContext;\n\n // Serialize validation config for passing to parent VM\n const serializableConfig = this.serializeValidationConfig();\n\n // Get all suspicious patterns (defaults + custom)\n const allPatterns = [...DEFAULT_SUSPICIOUS_PATTERNS, ...(this.config.parentValidation.suspiciousPatterns || [])];\n const serializedPatterns = serializePatterns(allPatterns);\n\n // Get blocked properties for secure proxy\n // Use explicit secureProxyConfig override if available, otherwise use security level defaults\n let blockedPropertiesSet: Set<string>;\n let throwOnBlocked: boolean;\n if (secureProxyConfig) {\n blockedPropertiesSet = buildBlockedPropertiesFromConfig(secureProxyConfig);\n throwOnBlocked = secureProxyConfig.throwOnBlocked ?? true;\n } else {\n blockedPropertiesSet = getBlockedPropertiesForLevel(this.securityLevel);\n // Get throwOnBlocked from security level config\n // Import the security level configs to get the throwOnBlocked setting\n const SECURITY_LEVEL_CONFIGS: Record<string, { throwOnBlocked: boolean }> = {\n STRICT: { throwOnBlocked: true },\n SECURE: { throwOnBlocked: true },\n STANDARD: { throwOnBlocked: true },\n PERMISSIVE: { throwOnBlocked: false },\n };\n throwOnBlocked = SECURITY_LEVEL_CONFIGS[this.securityLevel]?.throwOnBlocked ?? true;\n }\n const blockedProperties = Array.from(blockedPropertiesSet);\n\n // Whether composite reference handles are allowed\n const allowComposites = referenceConfig?.allowComposites ?? false;\n\n const toolBridgeMode = config.toolBridge?.mode ?? 'string';\n const toolBridgeMaxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;\n\n return generateParentVmBootstrap({\n userCode: code,\n innerTimeout: config.timeout,\n maxIterations: config.maxIterations,\n maxToolCalls: config.maxToolCalls,\n sanitizeStackTraces: config.sanitizeStackTraces ?? true,\n securityLevel: this.securityLevel,\n validationConfig: serializableConfig,\n suspiciousPatterns: serializedPatterns,\n blockedProperties,\n allowComposites,\n memoryLimit: config.memoryLimit,\n throwOnBlocked,\n toolBridgeMode,\n toolBridgeMaxPayloadBytes,\n });\n }\n\n /**\n * Serialize validation config for passing to parent VM\n *\n * RegExp objects cannot be passed across VM boundaries,\n * so we extract their source and flags.\n */\n private serializeValidationConfig(): SerializableParentValidationConfig {\n const pv = this.config.parentValidation;\n\n return {\n validateOperationNames: pv.validateOperationNames,\n allowedOperationPatternSource: pv.allowedOperationPattern?.source,\n allowedOperationPatternFlags: pv.allowedOperationPattern?.flags,\n blockedOperationPatternSources: pv.blockedOperationPatterns?.map((p) => p.source),\n blockedOperationPatternFlags: pv.blockedOperationPatterns?.map((p) => p.flags),\n maxOperationsPerSecond: pv.maxOperationsPerSecond,\n blockSuspiciousSequences: pv.blockSuspiciousSequences,\n rapidEnumerationThreshold: pv.rapidEnumerationThreshold,\n rapidEnumerationOverrides: pv.rapidEnumerationOverrides,\n suspiciousPatterns: [], // Will be populated separately\n };\n }\n\n /**\n * Dispose resources\n */\n dispose(): void {\n this.parentContext = undefined;\n }\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Double VM Module
|
|
3
|
+
*
|
|
4
|
+
* Provides enhanced security isolation through nested VM architecture.
|
|
5
|
+
*
|
|
6
|
+
* @packageDocumentation
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Type exports for double VM configuration and runtime
|
|
10
|
+
*/
|
|
11
|
+
export type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig, SuspiciousPattern, SerializableSuspiciousPattern, SerializableParentValidationConfig, OperationHistory, DoubleVmStats, } from './types';
|
|
12
|
+
/**
|
|
13
|
+
* Core wrapper class for double VM execution
|
|
14
|
+
*/
|
|
15
|
+
export { DoubleVmWrapper } from './double-vm-wrapper';
|
|
16
|
+
/**
|
|
17
|
+
* Utility functions for adapter wrapping
|
|
18
|
+
*/
|
|
19
|
+
export { wrapWithDoubleVm, isDoubleVmEnabled } from './wrap-adapter';
|
|
20
|
+
/**
|
|
21
|
+
* Suspicious pattern detection exports
|
|
22
|
+
*/
|
|
23
|
+
export { DEFAULT_SUSPICIOUS_PATTERNS, serializePattern, serializePatterns } from './suspicious-patterns';
|
|
24
|
+
/**
|
|
25
|
+
* Bootstrap generation for parent VM (primarily for testing)
|
|
26
|
+
*/
|
|
27
|
+
export { generateParentVmBootstrap } from './parent-vm-bootstrap';
|
|
28
|
+
/**
|
|
29
|
+
* Bootstrap options type
|
|
30
|
+
*/
|
|
31
|
+
export type { ParentVmBootstrapOptions } from './parent-vm-bootstrap';
|