@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,656 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Safe Runtime Wrappers
|
|
4
|
+
*
|
|
5
|
+
* These functions are injected into the AgentScript sandbox to provide
|
|
6
|
+
* safe implementations of tool calls, loops, and other operations.
|
|
7
|
+
*
|
|
8
|
+
* @packageDocumentation
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.createSafeRuntime = createSafeRuntime;
|
|
12
|
+
exports.serializeSafeRuntime = serializeSafeRuntime;
|
|
13
|
+
const value_sanitizer_1 = require("./value-sanitizer");
|
|
14
|
+
const safe_error_1 = require("./safe-error");
|
|
15
|
+
const reference_resolver_1 = require("./sidecar/reference-resolver");
|
|
16
|
+
const reference_config_1 = require("./sidecar/reference-config");
|
|
17
|
+
const secure_proxy_1 = require("./secure-proxy");
|
|
18
|
+
const memory_proxy_1 = require("./memory-proxy");
|
|
19
|
+
/**
|
|
20
|
+
* Create safe runtime context with all __safe_* functions
|
|
21
|
+
*
|
|
22
|
+
* @param context Execution context
|
|
23
|
+
* @param options Optional runtime options (sidecar, referenceConfig)
|
|
24
|
+
* @returns Object containing all safe runtime functions
|
|
25
|
+
*/
|
|
26
|
+
function createSafeRuntime(context, options) {
|
|
27
|
+
const { config, stats } = context;
|
|
28
|
+
const sidecar = options?.sidecar;
|
|
29
|
+
const referenceConfig = options?.referenceConfig;
|
|
30
|
+
const secureProxyConfig = options?.secureProxyConfig;
|
|
31
|
+
const memoryTracker = options?.memoryTracker;
|
|
32
|
+
const resolver = sidecar && referenceConfig ? new reference_resolver_1.ReferenceResolver(sidecar, referenceConfig) : undefined;
|
|
33
|
+
// Build proxy options from config for consistent usage
|
|
34
|
+
const proxyOptions = secureProxyConfig ? { levelConfig: secureProxyConfig } : {};
|
|
35
|
+
/**
|
|
36
|
+
* Safe callTool implementation
|
|
37
|
+
* - Tracks tool call count
|
|
38
|
+
* - Enforces max tool call limit
|
|
39
|
+
* - Resolves reference IDs before calling tool
|
|
40
|
+
* - Lifts large results back to sidecar
|
|
41
|
+
* - Delegates to user-provided tool handler
|
|
42
|
+
*/
|
|
43
|
+
async function __safe_callTool(toolName, args) {
|
|
44
|
+
// Check if aborted
|
|
45
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
46
|
+
if (context.aborted) {
|
|
47
|
+
throw (0, safe_error_1.createSafeError)('Execution aborted');
|
|
48
|
+
}
|
|
49
|
+
// Increment tool call count
|
|
50
|
+
stats.toolCallCount++;
|
|
51
|
+
// Check tool call limit
|
|
52
|
+
if (stats.toolCallCount > config.maxToolCalls) {
|
|
53
|
+
throw (0, safe_error_1.createSafeError)(`Maximum tool call limit exceeded (${config.maxToolCalls}). ` + `This limit prevents runaway script execution.`);
|
|
54
|
+
}
|
|
55
|
+
// Validate inputs
|
|
56
|
+
if (typeof toolName !== 'string' || !toolName) {
|
|
57
|
+
throw (0, safe_error_1.createSafeTypeError)('Tool name must be a non-empty string');
|
|
58
|
+
}
|
|
59
|
+
if (typeof args !== 'object' || args === null || Array.isArray(args)) {
|
|
60
|
+
throw (0, safe_error_1.createSafeTypeError)('Tool arguments must be an object');
|
|
61
|
+
}
|
|
62
|
+
// Check for tool handler
|
|
63
|
+
if (!context.toolHandler) {
|
|
64
|
+
throw (0, safe_error_1.createSafeError)('No tool handler configured. Cannot execute tool calls.');
|
|
65
|
+
}
|
|
66
|
+
// Resolve references if sidecar is available
|
|
67
|
+
let resolvedArgs = args;
|
|
68
|
+
if (resolver && resolver.containsReferences(args)) {
|
|
69
|
+
// Predictive check - fail fast before allocation
|
|
70
|
+
if (resolver.wouldExceedLimit(args)) {
|
|
71
|
+
throw (0, safe_error_1.createSafeError)(`Tool arguments would exceed maximum resolved size when references are expanded. ` +
|
|
72
|
+
`Reduce the amount of data being passed to the tool.`);
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
resolvedArgs = resolver.resolve(args);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (error instanceof reference_resolver_1.ResolutionLimitError) {
|
|
79
|
+
throw (0, safe_error_1.createSafeError)(`Failed to resolve references in tool arguments: ${error.message}`);
|
|
80
|
+
}
|
|
81
|
+
// SECURITY: Wrap unknown errors in safe error to prevent prototype chain escape
|
|
82
|
+
const err = error;
|
|
83
|
+
throw (0, safe_error_1.createSafeError)(`Reference resolution failed: ${err.message || 'Unknown error'}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Execute the tool call
|
|
87
|
+
try {
|
|
88
|
+
const result = await context.toolHandler(toolName, resolvedArgs);
|
|
89
|
+
// Sanitize the return value to prevent:
|
|
90
|
+
// - Function injection
|
|
91
|
+
// - Symbol injection
|
|
92
|
+
// - Prototype pollution (__proto__, constructor)
|
|
93
|
+
// - Deeply nested objects (DoS)
|
|
94
|
+
// - Large object graphs (DoS)
|
|
95
|
+
const sanitized = (0, value_sanitizer_1.sanitizeValue)(result, {
|
|
96
|
+
maxDepth: 20,
|
|
97
|
+
maxProperties: 10000,
|
|
98
|
+
allowDates: true,
|
|
99
|
+
allowErrors: true,
|
|
100
|
+
});
|
|
101
|
+
// Lift large string results to sidecar if configured
|
|
102
|
+
if (sidecar && referenceConfig && typeof sanitized === 'string') {
|
|
103
|
+
const size = Buffer.byteLength(sanitized, 'utf-8');
|
|
104
|
+
if (size >= referenceConfig.extractionThreshold) {
|
|
105
|
+
try {
|
|
106
|
+
const refId = sidecar.store(sanitized, 'tool-result', { origin: toolName });
|
|
107
|
+
return refId;
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// If storage fails (limits), return original value
|
|
111
|
+
return sanitized;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return sanitized;
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
// SECURITY: Re-throw with safe error to prevent prototype chain escape attacks
|
|
119
|
+
// This is critical - the original error from the tool handler could expose
|
|
120
|
+
// the host Function constructor via error.constructor.constructor
|
|
121
|
+
const err = error;
|
|
122
|
+
throw (0, safe_error_1.createSafeError)(`Tool call failed: ${toolName} - ${err.message || 'Unknown error'}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Safe for-of iterator
|
|
127
|
+
* - Enforces iteration limit per loop
|
|
128
|
+
* - Tracks total iteration count
|
|
129
|
+
*/
|
|
130
|
+
function* __safe_forOf(iterable) {
|
|
131
|
+
let iterations = 0;
|
|
132
|
+
for (const item of iterable) {
|
|
133
|
+
// Check if aborted
|
|
134
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
135
|
+
if (context.aborted) {
|
|
136
|
+
throw (0, safe_error_1.createSafeError)('Execution aborted');
|
|
137
|
+
}
|
|
138
|
+
// Increment iteration count
|
|
139
|
+
iterations++;
|
|
140
|
+
stats.iterationCount++;
|
|
141
|
+
// Check iteration limit
|
|
142
|
+
if (iterations > config.maxIterations) {
|
|
143
|
+
throw (0, safe_error_1.createSafeError)(`Maximum iteration limit exceeded (${config.maxIterations}). ` + `This limit prevents infinite loops.`);
|
|
144
|
+
}
|
|
145
|
+
yield item;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Safe for loop wrapper
|
|
150
|
+
* - Enforces iteration limit
|
|
151
|
+
* - Tracks iteration count
|
|
152
|
+
*/
|
|
153
|
+
function __safe_for(init, test, update, body) {
|
|
154
|
+
let iterations = 0;
|
|
155
|
+
// Execute init
|
|
156
|
+
init();
|
|
157
|
+
// Execute loop
|
|
158
|
+
while (test()) {
|
|
159
|
+
// Check if aborted
|
|
160
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
161
|
+
if (context.aborted) {
|
|
162
|
+
throw (0, safe_error_1.createSafeError)('Execution aborted');
|
|
163
|
+
}
|
|
164
|
+
// Increment iteration count
|
|
165
|
+
iterations++;
|
|
166
|
+
stats.iterationCount++;
|
|
167
|
+
// Check iteration limit
|
|
168
|
+
if (iterations > config.maxIterations) {
|
|
169
|
+
throw (0, safe_error_1.createSafeError)(`Maximum iteration limit exceeded (${config.maxIterations}). ` + `This limit prevents infinite loops.`);
|
|
170
|
+
}
|
|
171
|
+
// Execute body
|
|
172
|
+
body();
|
|
173
|
+
// Execute update
|
|
174
|
+
update();
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Safe while loop wrapper
|
|
179
|
+
* - Enforces iteration limit
|
|
180
|
+
* - Tracks iteration count
|
|
181
|
+
*/
|
|
182
|
+
function __safe_while(test, body) {
|
|
183
|
+
let iterations = 0;
|
|
184
|
+
while (test()) {
|
|
185
|
+
// Check if aborted
|
|
186
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
187
|
+
if (context.aborted) {
|
|
188
|
+
throw (0, safe_error_1.createSafeError)('Execution aborted');
|
|
189
|
+
}
|
|
190
|
+
// Increment iteration count
|
|
191
|
+
iterations++;
|
|
192
|
+
stats.iterationCount++;
|
|
193
|
+
// Check iteration limit
|
|
194
|
+
if (iterations > config.maxIterations) {
|
|
195
|
+
throw (0, safe_error_1.createSafeError)(`Maximum iteration limit exceeded (${config.maxIterations}). ` + `This limit prevents infinite loops.`);
|
|
196
|
+
}
|
|
197
|
+
// Execute body
|
|
198
|
+
body();
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Safe addition/concatenation operator
|
|
203
|
+
*
|
|
204
|
+
* Replaces the `+` operator to support:
|
|
205
|
+
* 1. Numeric addition when both operands are numbers
|
|
206
|
+
* 2. String concatenation with memory tracking
|
|
207
|
+
* 3. Reference ID handling for sidecar support
|
|
208
|
+
*
|
|
209
|
+
* Follows JavaScript's ToPrimitive algorithm for objects.
|
|
210
|
+
*/
|
|
211
|
+
function __safe_concat(left, right) {
|
|
212
|
+
// Fast path: both are numbers - do numeric addition
|
|
213
|
+
if (typeof left === 'number' && typeof right === 'number') {
|
|
214
|
+
return left + right;
|
|
215
|
+
}
|
|
216
|
+
// Fast path: both are strings - do string concatenation with memory tracking
|
|
217
|
+
if (typeof left === 'string' && typeof right === 'string') {
|
|
218
|
+
// Store length BEFORE isReferenceId calls (TypeScript type guard causes narrowing issues)
|
|
219
|
+
const rightLen = right.length;
|
|
220
|
+
const leftIsRef = (0, reference_config_1.isReferenceId)(left);
|
|
221
|
+
const rightIsRef = (0, reference_config_1.isReferenceId)(right);
|
|
222
|
+
if (!leftIsRef && !rightIsRef) {
|
|
223
|
+
// Both are regular strings - concatenate and track
|
|
224
|
+
if (memoryTracker) {
|
|
225
|
+
const growthBytes = rightLen * 2; // UTF-16
|
|
226
|
+
memoryTracker.track(growthBytes);
|
|
227
|
+
}
|
|
228
|
+
return left + right;
|
|
229
|
+
}
|
|
230
|
+
// References detected
|
|
231
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
232
|
+
if (!resolver) {
|
|
233
|
+
throw (0, safe_error_1.createSafeError)('Cannot concatenate reference IDs: reference system not configured. ' +
|
|
234
|
+
'Pass references directly to callTool arguments instead.');
|
|
235
|
+
}
|
|
236
|
+
return resolver.createComposite([left, right]);
|
|
237
|
+
}
|
|
238
|
+
// For mixed types (one string, one non-string), use native + for ToPrimitive
|
|
239
|
+
// but check for references in string operands first
|
|
240
|
+
if (typeof left === 'string' || typeof right === 'string') {
|
|
241
|
+
// Check if the string operand(s) are references BEFORE coercion
|
|
242
|
+
const leftIsRef = typeof left === 'string' && (0, reference_config_1.isReferenceId)(left);
|
|
243
|
+
const rightIsRef = typeof right === 'string' && (0, reference_config_1.isReferenceId)(right);
|
|
244
|
+
if (leftIsRef || rightIsRef) {
|
|
245
|
+
// Reference detected - need special handling
|
|
246
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
247
|
+
if (!resolver) {
|
|
248
|
+
throw (0, safe_error_1.createSafeError)('Cannot concatenate reference IDs: reference system not configured. ' +
|
|
249
|
+
'Pass references directly to callTool arguments instead.');
|
|
250
|
+
}
|
|
251
|
+
// Convert both to strings for composite
|
|
252
|
+
const leftStr = String(left);
|
|
253
|
+
const rightStr = String(right);
|
|
254
|
+
return resolver.createComposite([leftStr, rightStr]);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
// For all other cases (objects, booleans, null, undefined, or strings without refs),
|
|
258
|
+
// use JavaScript's default + behavior which will call ToPrimitive correctly
|
|
259
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
260
|
+
const result = left + right;
|
|
261
|
+
// Track if result is a string (string concatenation occurred)
|
|
262
|
+
if (typeof result === 'string' && memoryTracker) {
|
|
263
|
+
// Estimate the growth - we track the full result since we don't know original sizes
|
|
264
|
+
memoryTracker.track(result.length * 2); // UTF-16
|
|
265
|
+
}
|
|
266
|
+
return result;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Safe template literal interpolation
|
|
270
|
+
*
|
|
271
|
+
* Handles template literals with expressions like `Hello ${name}!`
|
|
272
|
+
* Detects reference IDs and creates composite handles when allowed.
|
|
273
|
+
*
|
|
274
|
+
* Also tracks memory allocation when memoryTracker is provided.
|
|
275
|
+
*
|
|
276
|
+
* @param quasis - The static string parts
|
|
277
|
+
* @param values - The interpolated values
|
|
278
|
+
*/
|
|
279
|
+
function __safe_template(quasis, ...values) {
|
|
280
|
+
// Convert all values to strings
|
|
281
|
+
const stringValues = values.map((v) => String(v));
|
|
282
|
+
// Check if any values are references
|
|
283
|
+
const hasReferences = stringValues.some((v) => (0, reference_config_1.isReferenceId)(v));
|
|
284
|
+
// If no references, just join normally
|
|
285
|
+
if (!hasReferences) {
|
|
286
|
+
let result = quasis[0];
|
|
287
|
+
for (let i = 0; i < stringValues.length; i++) {
|
|
288
|
+
result += stringValues[i] + quasis[i + 1];
|
|
289
|
+
}
|
|
290
|
+
// Track memory allocation for the resulting string
|
|
291
|
+
if (memoryTracker) {
|
|
292
|
+
const resultBytes = result.length * 2; // UTF-16
|
|
293
|
+
memoryTracker.track(resultBytes);
|
|
294
|
+
}
|
|
295
|
+
return result;
|
|
296
|
+
}
|
|
297
|
+
// References detected - need resolver
|
|
298
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
299
|
+
if (!resolver) {
|
|
300
|
+
throw (0, safe_error_1.createSafeError)('Cannot interpolate reference IDs in template literals: reference system not configured. ' +
|
|
301
|
+
'Pass references directly to callTool arguments instead.');
|
|
302
|
+
}
|
|
303
|
+
// Build parts array for composite
|
|
304
|
+
const parts = [];
|
|
305
|
+
for (let i = 0; i < quasis.length; i++) {
|
|
306
|
+
if (quasis[i]) {
|
|
307
|
+
parts.push(quasis[i]);
|
|
308
|
+
}
|
|
309
|
+
if (i < stringValues.length) {
|
|
310
|
+
parts.push(stringValues[i]);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
// Use resolver to create composite (will throw if not allowed)
|
|
314
|
+
return resolver.createComposite(parts);
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Safe parallel execution wrapper
|
|
318
|
+
*
|
|
319
|
+
* Executes multiple async functions in parallel while:
|
|
320
|
+
* - Respecting the shared tool call limit (all parallel calls share the limit)
|
|
321
|
+
* - Enforcing a maximum concurrency limit to prevent resource exhaustion
|
|
322
|
+
* - Handling timeouts and cancellation properly
|
|
323
|
+
*
|
|
324
|
+
* @param fns - Array of async functions to execute in parallel
|
|
325
|
+
* @param options - Optional configuration { maxConcurrency?: number }
|
|
326
|
+
* @returns Array of results in the same order as inputs
|
|
327
|
+
*/
|
|
328
|
+
async function __safe_parallel(fns, options) {
|
|
329
|
+
// Check if aborted
|
|
330
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
331
|
+
if (context.aborted) {
|
|
332
|
+
throw (0, safe_error_1.createSafeError)('Execution aborted');
|
|
333
|
+
}
|
|
334
|
+
// Validate inputs
|
|
335
|
+
if (!Array.isArray(fns)) {
|
|
336
|
+
throw (0, safe_error_1.createSafeTypeError)('__safe_parallel requires an array of functions');
|
|
337
|
+
}
|
|
338
|
+
if (fns.length === 0) {
|
|
339
|
+
return [];
|
|
340
|
+
}
|
|
341
|
+
// Enforce maximum array size to prevent DoS
|
|
342
|
+
const MAX_PARALLEL_ITEMS = 100;
|
|
343
|
+
if (fns.length > MAX_PARALLEL_ITEMS) {
|
|
344
|
+
throw (0, safe_error_1.createSafeError)(`Cannot execute more than ${MAX_PARALLEL_ITEMS} operations in parallel. ` + `Split into smaller batches.`);
|
|
345
|
+
}
|
|
346
|
+
// Validate all items are functions
|
|
347
|
+
for (let i = 0; i < fns.length; i++) {
|
|
348
|
+
if (typeof fns[i] !== 'function') {
|
|
349
|
+
throw (0, safe_error_1.createSafeTypeError)(`Item at index ${i} is not a function`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
// Get concurrency limit (default: 10, max: 20)
|
|
353
|
+
const MAX_CONCURRENCY = 20;
|
|
354
|
+
const concurrency = Math.min(Math.max(1, options?.maxConcurrency ?? 10), MAX_CONCURRENCY);
|
|
355
|
+
// Track results in original order
|
|
356
|
+
const results = new Array(fns.length);
|
|
357
|
+
const errors = [];
|
|
358
|
+
// Process in batches with concurrency limit
|
|
359
|
+
let currentIndex = 0;
|
|
360
|
+
async function runNext() {
|
|
361
|
+
while (currentIndex < fns.length) {
|
|
362
|
+
// Check if aborted before starting new work
|
|
363
|
+
if (context.aborted) {
|
|
364
|
+
throw (0, safe_error_1.createSafeError)('Execution aborted');
|
|
365
|
+
}
|
|
366
|
+
const index = currentIndex++;
|
|
367
|
+
const fn = fns[index];
|
|
368
|
+
try {
|
|
369
|
+
const result = await fn();
|
|
370
|
+
results[index] = result;
|
|
371
|
+
}
|
|
372
|
+
catch (error) {
|
|
373
|
+
// SECURITY: Wrap caught errors in safe error to prevent prototype chain escape
|
|
374
|
+
const errMsg = error && typeof error === 'object'
|
|
375
|
+
? typeof error.message === 'string'
|
|
376
|
+
? error.message
|
|
377
|
+
: Object.prototype.toString.call(error)
|
|
378
|
+
: String(error);
|
|
379
|
+
errors.push({
|
|
380
|
+
index,
|
|
381
|
+
error: (0, safe_error_1.createSafeError)(errMsg),
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
// Start workers up to concurrency limit
|
|
387
|
+
const workers = Array.from({ length: Math.min(concurrency, fns.length) }, () => runNext());
|
|
388
|
+
// Wait for all workers to complete
|
|
389
|
+
await Promise.all(workers);
|
|
390
|
+
// If any errors occurred, throw an aggregate error
|
|
391
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
392
|
+
if (errors.length > 0) {
|
|
393
|
+
const errorMessages = errors.map((e) => `[${e.index}]: ${e.error.message}`).join('\n');
|
|
394
|
+
throw (0, safe_error_1.createSafeError)(`${errors.length} of ${fns.length} parallel operations failed:\n${errorMessages}`);
|
|
395
|
+
}
|
|
396
|
+
return results;
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Safe do-while loop wrapper
|
|
400
|
+
* - Enforces iteration limit
|
|
401
|
+
* - Tracks iteration count
|
|
402
|
+
*/
|
|
403
|
+
function __safe_doWhile(body, test) {
|
|
404
|
+
let iterations = 0;
|
|
405
|
+
do {
|
|
406
|
+
// Check if aborted
|
|
407
|
+
// SECURITY: Use createSafeError to prevent prototype chain escape attacks
|
|
408
|
+
if (context.aborted) {
|
|
409
|
+
throw (0, safe_error_1.createSafeError)('Execution aborted');
|
|
410
|
+
}
|
|
411
|
+
// Increment iteration count
|
|
412
|
+
iterations++;
|
|
413
|
+
stats.iterationCount++;
|
|
414
|
+
// Check iteration limit
|
|
415
|
+
if (iterations > config.maxIterations) {
|
|
416
|
+
throw (0, safe_error_1.createSafeError)(`Maximum iteration limit exceeded (${config.maxIterations}). ` + `This limit prevents infinite loops.`);
|
|
417
|
+
}
|
|
418
|
+
// Execute body
|
|
419
|
+
body();
|
|
420
|
+
} while (test());
|
|
421
|
+
}
|
|
422
|
+
// Prepare custom globals with __safe_ prefix
|
|
423
|
+
// Wrap all custom globals with secure proxies to block constructor access
|
|
424
|
+
const customGlobalsWithPrefix = {};
|
|
425
|
+
if (config.globals) {
|
|
426
|
+
const wrappedCustomGlobals = (0, secure_proxy_1.wrapGlobalsWithSecureProxy)(config.globals, proxyOptions);
|
|
427
|
+
for (const [key, value] of Object.entries(wrappedCustomGlobals)) {
|
|
428
|
+
customGlobalsWithPrefix[`__safe_${key}`] = value;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
// Create secure proxies for standard library objects
|
|
432
|
+
// This blocks access to dangerous properties like 'constructor', '__proto__'
|
|
433
|
+
// even when accessed via computed property names like obj['const'+'ructor']
|
|
434
|
+
//
|
|
435
|
+
// When memory tracking is enabled, use tracked versions of String/Array
|
|
436
|
+
// that monitor allocations and enforce memory limits
|
|
437
|
+
const StringConstructor = memoryTracker ? (0, memory_proxy_1.createTrackedString)(memoryTracker) : String;
|
|
438
|
+
const ArrayConstructor = memoryTracker ? (0, memory_proxy_1.createTrackedArray)(memoryTracker) : Array;
|
|
439
|
+
const secureStdLib = (0, secure_proxy_1.wrapGlobalsWithSecureProxy)({
|
|
440
|
+
Math,
|
|
441
|
+
JSON,
|
|
442
|
+
Array: ArrayConstructor,
|
|
443
|
+
Object,
|
|
444
|
+
String: StringConstructor,
|
|
445
|
+
Number,
|
|
446
|
+
Date,
|
|
447
|
+
}, proxyOptions);
|
|
448
|
+
// Wrap the safe runtime functions themselves with secure proxies
|
|
449
|
+
// This prevents attacks like: callTool['const'+'ructor']
|
|
450
|
+
const safeCallToolProxy = (0, secure_proxy_1.createSecureProxy)(__safe_callTool, proxyOptions);
|
|
451
|
+
const safeForOfProxy = (0, secure_proxy_1.createSecureProxy)(__safe_forOf, proxyOptions);
|
|
452
|
+
const safeForProxy = (0, secure_proxy_1.createSecureProxy)(__safe_for, proxyOptions);
|
|
453
|
+
const safeWhileProxy = (0, secure_proxy_1.createSecureProxy)(__safe_while, proxyOptions);
|
|
454
|
+
const safeDoWhileProxy = (0, secure_proxy_1.createSecureProxy)(__safe_doWhile, proxyOptions);
|
|
455
|
+
const safeConcatProxy = (0, secure_proxy_1.createSecureProxy)(__safe_concat, proxyOptions);
|
|
456
|
+
const safeTemplateProxy = (0, secure_proxy_1.createSecureProxy)(__safe_template, proxyOptions);
|
|
457
|
+
const safeParallelProxy = (0, secure_proxy_1.createSecureProxy)(__safe_parallel, proxyOptions);
|
|
458
|
+
// Return safe runtime object with all values protected by secure proxies
|
|
459
|
+
return {
|
|
460
|
+
// Safe runtime functions (proxied to block constructor access)
|
|
461
|
+
__safe_callTool: safeCallToolProxy,
|
|
462
|
+
__safe_forOf: safeForOfProxy,
|
|
463
|
+
__safe_for: safeForProxy,
|
|
464
|
+
__safe_while: safeWhileProxy,
|
|
465
|
+
__safe_doWhile: safeDoWhileProxy,
|
|
466
|
+
__safe_concat: safeConcatProxy,
|
|
467
|
+
__safe_template: safeTemplateProxy,
|
|
468
|
+
__safe_parallel: safeParallelProxy,
|
|
469
|
+
// Iteration limit for loop transformation (used by injected counter checks)
|
|
470
|
+
__maxIterations: config.maxIterations,
|
|
471
|
+
// Whitelisted safe globals (proxied to block constructor access)
|
|
472
|
+
...secureStdLib,
|
|
473
|
+
// Primitives don't need proxying
|
|
474
|
+
NaN: NaN,
|
|
475
|
+
Infinity: Infinity,
|
|
476
|
+
undefined: undefined,
|
|
477
|
+
isNaN: isNaN,
|
|
478
|
+
isFinite: isFinite,
|
|
479
|
+
parseInt: parseInt,
|
|
480
|
+
parseFloat: parseFloat,
|
|
481
|
+
// Custom globals (with __safe_ prefix, already proxied)
|
|
482
|
+
...customGlobalsWithPrefix,
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Serialize safe runtime code as a string for injection
|
|
487
|
+
* This is used by sandbox adapters that need to inject the runtime as code
|
|
488
|
+
*
|
|
489
|
+
* @returns JavaScript code string containing the safe runtime
|
|
490
|
+
*/
|
|
491
|
+
function serializeSafeRuntime() {
|
|
492
|
+
return `
|
|
493
|
+
// Safe callTool implementation
|
|
494
|
+
async function __safe_callTool(toolName, args) {
|
|
495
|
+
if (typeof toolName !== 'string' || !toolName) {
|
|
496
|
+
throw new TypeError('Tool name must be a non-empty string');
|
|
497
|
+
}
|
|
498
|
+
if (typeof args !== 'object' || args === null || Array.isArray(args)) {
|
|
499
|
+
throw new TypeError('Tool arguments must be an object');
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// This will be replaced by the sandbox adapter with actual implementation
|
|
503
|
+
if (typeof __internal_callTool === 'function') {
|
|
504
|
+
return await __internal_callTool(toolName, args);
|
|
505
|
+
}
|
|
506
|
+
throw new Error('Tool handler not available');
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// Safe for-of iterator
|
|
510
|
+
function* __safe_forOf(iterable) {
|
|
511
|
+
let iterations = 0;
|
|
512
|
+
const maxIterations = __internal_maxIterations || 10000;
|
|
513
|
+
|
|
514
|
+
for (const item of iterable) {
|
|
515
|
+
iterations++;
|
|
516
|
+
if (iterations > maxIterations) {
|
|
517
|
+
throw new Error('Maximum iteration limit exceeded (' + maxIterations + ')');
|
|
518
|
+
}
|
|
519
|
+
yield item;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// Safe for loop
|
|
524
|
+
function __safe_for(init, test, update, body) {
|
|
525
|
+
let iterations = 0;
|
|
526
|
+
const maxIterations = __internal_maxIterations || 10000;
|
|
527
|
+
|
|
528
|
+
init();
|
|
529
|
+
while (test()) {
|
|
530
|
+
iterations++;
|
|
531
|
+
if (iterations > maxIterations) {
|
|
532
|
+
throw new Error('Maximum iteration limit exceeded (' + maxIterations + ')');
|
|
533
|
+
}
|
|
534
|
+
body();
|
|
535
|
+
update();
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// Safe while loop
|
|
540
|
+
function __safe_while(test, body) {
|
|
541
|
+
let iterations = 0;
|
|
542
|
+
const maxIterations = __internal_maxIterations || 10000;
|
|
543
|
+
|
|
544
|
+
while (test()) {
|
|
545
|
+
iterations++;
|
|
546
|
+
if (iterations > maxIterations) {
|
|
547
|
+
throw new Error('Maximum iteration limit exceeded (' + maxIterations + ')');
|
|
548
|
+
}
|
|
549
|
+
body();
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// Safe string concatenation
|
|
554
|
+
// Detects reference IDs and throws or creates composite handles
|
|
555
|
+
function __safe_concat(left, right) {
|
|
556
|
+
const leftStr = String(left);
|
|
557
|
+
const rightStr = String(right);
|
|
558
|
+
|
|
559
|
+
// Reference detection pattern: __REF_[uuid]__
|
|
560
|
+
const refPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
|
|
561
|
+
const leftIsRef = refPattern.test(leftStr);
|
|
562
|
+
const rightIsRef = refPattern.test(rightStr);
|
|
563
|
+
|
|
564
|
+
if (!leftIsRef && !rightIsRef) {
|
|
565
|
+
return leftStr + rightStr;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// References detected - use internal handler if available
|
|
569
|
+
if (typeof __internal_handleConcat === 'function') {
|
|
570
|
+
return __internal_handleConcat(leftStr, rightStr);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
throw new Error('Cannot concatenate reference IDs: reference system not configured.');
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// Safe template literal interpolation
|
|
577
|
+
function __safe_template(quasis, ...values) {
|
|
578
|
+
const stringValues = values.map(v => String(v));
|
|
579
|
+
const refPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
|
|
580
|
+
const hasReferences = stringValues.some(v => refPattern.test(v));
|
|
581
|
+
|
|
582
|
+
if (!hasReferences) {
|
|
583
|
+
let result = quasis[0];
|
|
584
|
+
for (let i = 0; i < stringValues.length; i++) {
|
|
585
|
+
result += stringValues[i] + quasis[i + 1];
|
|
586
|
+
}
|
|
587
|
+
return result;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// References detected - use internal handler if available
|
|
591
|
+
if (typeof __internal_handleTemplate === 'function') {
|
|
592
|
+
return __internal_handleTemplate(quasis, stringValues);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
throw new Error('Cannot interpolate reference IDs in template literals: reference system not configured.');
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// Safe parallel execution
|
|
599
|
+
async function __safe_parallel(fns, options) {
|
|
600
|
+
if (!Array.isArray(fns)) {
|
|
601
|
+
throw new TypeError('__safe_parallel requires an array of functions');
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
if (fns.length === 0) {
|
|
605
|
+
return [];
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
const MAX_PARALLEL_ITEMS = 100;
|
|
609
|
+
if (fns.length > MAX_PARALLEL_ITEMS) {
|
|
610
|
+
throw new Error('Cannot execute more than ' + MAX_PARALLEL_ITEMS + ' operations in parallel.');
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
for (let i = 0; i < fns.length; i++) {
|
|
614
|
+
if (typeof fns[i] !== 'function') {
|
|
615
|
+
throw new TypeError('Item at index ' + i + ' is not a function');
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const MAX_CONCURRENCY = 20;
|
|
620
|
+
const concurrency = Math.min(Math.max(1, (options && options.maxConcurrency) || 10), MAX_CONCURRENCY);
|
|
621
|
+
|
|
622
|
+
const results = new Array(fns.length);
|
|
623
|
+
const errors = [];
|
|
624
|
+
let currentIndex = 0;
|
|
625
|
+
|
|
626
|
+
async function runNext() {
|
|
627
|
+
while (currentIndex < fns.length) {
|
|
628
|
+
const index = currentIndex++;
|
|
629
|
+
try {
|
|
630
|
+
results[index] = await fns[index]();
|
|
631
|
+
} catch (error) {
|
|
632
|
+
errors.push({ index: index, error: error });
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const workers = [];
|
|
638
|
+
for (let i = 0; i < Math.min(concurrency, fns.length); i++) {
|
|
639
|
+
workers.push(runNext());
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
await Promise.all(workers);
|
|
643
|
+
|
|
644
|
+
if (errors.length > 0) {
|
|
645
|
+
const msgs = errors.map(function(e) { return '[' + e.index + ']: ' + (e.error && e.error.message || e.error); }).join('\\n');
|
|
646
|
+
throw new Error(errors.length + ' of ' + fns.length + ' parallel operations failed:\\n' + msgs);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
return results;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// Whitelisted globals (already available)
|
|
653
|
+
// Math, JSON, Array, Object, String, Number, Date, etc.
|
|
654
|
+
`.trim();
|
|
655
|
+
}
|
|
656
|
+
//# sourceMappingURL=safe-runtime.js.map
|