@enclave-vm/core 0.0.1 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/esm/index.mjs +11172 -0
  2. package/esm/package.json +6 -0
  3. package/index.js +11268 -0
  4. package/package.json +11 -10
  5. package/src/adapters/vm-adapter.js +0 -1140
  6. package/src/adapters/vm-adapter.js.map +0 -1
  7. package/src/adapters/worker-pool/config.js +0 -129
  8. package/src/adapters/worker-pool/config.js.map +0 -1
  9. package/src/adapters/worker-pool/errors.js +0 -181
  10. package/src/adapters/worker-pool/errors.js.map +0 -1
  11. package/src/adapters/worker-pool/execution-queue.js +0 -179
  12. package/src/adapters/worker-pool/execution-queue.js.map +0 -1
  13. package/src/adapters/worker-pool/index.js +0 -73
  14. package/src/adapters/worker-pool/index.js.map +0 -1
  15. package/src/adapters/worker-pool/memory-monitor.js +0 -184
  16. package/src/adapters/worker-pool/memory-monitor.js.map +0 -1
  17. package/src/adapters/worker-pool/protocol.js +0 -143
  18. package/src/adapters/worker-pool/protocol.js.map +0 -1
  19. package/src/adapters/worker-pool/rate-limiter.js +0 -101
  20. package/src/adapters/worker-pool/rate-limiter.js.map +0 -1
  21. package/src/adapters/worker-pool/safe-deserialize.js +0 -141
  22. package/src/adapters/worker-pool/safe-deserialize.js.map +0 -1
  23. package/src/adapters/worker-pool/worker-pool-adapter.js +0 -506
  24. package/src/adapters/worker-pool/worker-pool-adapter.js.map +0 -1
  25. package/src/adapters/worker-pool/worker-script.js +0 -770
  26. package/src/adapters/worker-pool/worker-script.js.map +0 -1
  27. package/src/adapters/worker-pool/worker-slot.js +0 -301
  28. package/src/adapters/worker-pool/worker-slot.js.map +0 -1
  29. package/src/babel/babel-wrapper.js +0 -395
  30. package/src/babel/babel-wrapper.js.map +0 -1
  31. package/src/babel/index.js +0 -17
  32. package/src/babel/index.js.map +0 -1
  33. package/src/babel/multi-file-transform.js +0 -344
  34. package/src/babel/multi-file-transform.js.map +0 -1
  35. package/src/double-vm/double-vm-wrapper.js +0 -523
  36. package/src/double-vm/double-vm-wrapper.js.map +0 -1
  37. package/src/double-vm/index.js +0 -34
  38. package/src/double-vm/index.js.map +0 -1
  39. package/src/double-vm/parent-vm-bootstrap.js +0 -1695
  40. package/src/double-vm/parent-vm-bootstrap.js.map +0 -1
  41. package/src/double-vm/suspicious-patterns.js +0 -304
  42. package/src/double-vm/suspicious-patterns.js.map +0 -1
  43. package/src/double-vm/types.js +0 -11
  44. package/src/double-vm/types.js.map +0 -1
  45. package/src/double-vm/wrap-adapter.js +0 -59
  46. package/src/double-vm/wrap-adapter.js.map +0 -1
  47. package/src/enclave.js +0 -671
  48. package/src/enclave.js.map +0 -1
  49. package/src/globals-validator.js +0 -206
  50. package/src/globals-validator.js.map +0 -1
  51. package/src/index.js +0 -130
  52. package/src/index.js.map +0 -1
  53. package/src/memory-proxy.js +0 -310
  54. package/src/memory-proxy.js.map +0 -1
  55. package/src/memory-tracker.js +0 -230
  56. package/src/memory-tracker.js.map +0 -1
  57. package/src/safe-error.js +0 -76
  58. package/src/safe-error.js.map +0 -1
  59. package/src/safe-runtime.js +0 -656
  60. package/src/safe-runtime.js.map +0 -1
  61. package/src/scoring/cache.js +0 -158
  62. package/src/scoring/cache.js.map +0 -1
  63. package/src/scoring/feature-extractor.js +0 -366
  64. package/src/scoring/feature-extractor.js.map +0 -1
  65. package/src/scoring/index.js +0 -53
  66. package/src/scoring/index.js.map +0 -1
  67. package/src/scoring/scorer.interface.js +0 -49
  68. package/src/scoring/scorer.interface.js.map +0 -1
  69. package/src/scoring/scorers/disabled.scorer.js +0 -34
  70. package/src/scoring/scorers/disabled.scorer.js.map +0 -1
  71. package/src/scoring/scorers/external-api.scorer.js +0 -141
  72. package/src/scoring/scorers/external-api.scorer.js.map +0 -1
  73. package/src/scoring/scorers/index.js +0 -22
  74. package/src/scoring/scorers/index.js.map +0 -1
  75. package/src/scoring/scorers/local-llm.scorer.js +0 -474
  76. package/src/scoring/scorers/local-llm.scorer.js.map +0 -1
  77. package/src/scoring/scorers/progressive.scorer.js +0 -199
  78. package/src/scoring/scorers/progressive.scorer.js.map +0 -1
  79. package/src/scoring/scorers/rule-based.scorer.js +0 -316
  80. package/src/scoring/scorers/rule-based.scorer.js.map +0 -1
  81. package/src/scoring/scoring-gate.js +0 -246
  82. package/src/scoring/scoring-gate.js.map +0 -1
  83. package/src/scoring/types.js +0 -107
  84. package/src/scoring/types.js.map +0 -1
  85. package/src/secure-proxy.js +0 -609
  86. package/src/secure-proxy.js.map +0 -1
  87. package/src/session/channels/embedded-channel.js +0 -130
  88. package/src/session/channels/embedded-channel.js.map +0 -1
  89. package/src/session/channels/index.js +0 -14
  90. package/src/session/channels/index.js.map +0 -1
  91. package/src/session/index.js +0 -27
  92. package/src/session/index.js.map +0 -1
  93. package/src/session/session-emitter.js +0 -253
  94. package/src/session/session-emitter.js.map +0 -1
  95. package/src/session/session-state-machine.js +0 -182
  96. package/src/session/session-state-machine.js.map +0 -1
  97. package/src/session/session.js +0 -398
  98. package/src/session/session.js.map +0 -1
  99. package/src/session-types.js +0 -39
  100. package/src/session-types.js.map +0 -1
  101. package/src/sidecar/index.js +0 -31
  102. package/src/sidecar/index.js.map +0 -1
  103. package/src/sidecar/reference-config.js +0 -118
  104. package/src/sidecar/reference-config.js.map +0 -1
  105. package/src/sidecar/reference-resolver.js +0 -262
  106. package/src/sidecar/reference-resolver.js.map +0 -1
  107. package/src/sidecar/reference-sidecar.js +0 -226
  108. package/src/sidecar/reference-sidecar.js.map +0 -1
  109. package/src/tool-bridge.js +0 -306
  110. package/src/tool-bridge.js.map +0 -1
  111. package/src/types.js +0 -187
  112. package/src/types.js.map +0 -1
  113. package/src/value-sanitizer.js +0 -421
  114. package/src/value-sanitizer.js.map +0 -1
  115. /package/{src/adapters → adapters}/vm-adapter.d.ts +0 -0
  116. /package/{src/adapters → adapters}/worker-pool/config.d.ts +0 -0
  117. /package/{src/adapters → adapters}/worker-pool/errors.d.ts +0 -0
  118. /package/{src/adapters → adapters}/worker-pool/execution-queue.d.ts +0 -0
  119. /package/{src/adapters → adapters}/worker-pool/index.d.ts +0 -0
  120. /package/{src/adapters → adapters}/worker-pool/memory-monitor.d.ts +0 -0
  121. /package/{src/adapters → adapters}/worker-pool/protocol.d.ts +0 -0
  122. /package/{src/adapters → adapters}/worker-pool/rate-limiter.d.ts +0 -0
  123. /package/{src/adapters → adapters}/worker-pool/safe-deserialize.d.ts +0 -0
  124. /package/{src/adapters → adapters}/worker-pool/worker-pool-adapter.d.ts +0 -0
  125. /package/{src/adapters → adapters}/worker-pool/worker-script.d.ts +0 -0
  126. /package/{src/adapters → adapters}/worker-pool/worker-slot.d.ts +0 -0
  127. /package/{src/babel → babel}/babel-wrapper.d.ts +0 -0
  128. /package/{src/babel → babel}/index.d.ts +0 -0
  129. /package/{src/babel → babel}/multi-file-transform.d.ts +0 -0
  130. /package/{src/double-vm → double-vm}/double-vm-wrapper.d.ts +0 -0
  131. /package/{src/double-vm → double-vm}/index.d.ts +0 -0
  132. /package/{src/double-vm → double-vm}/parent-vm-bootstrap.d.ts +0 -0
  133. /package/{src/double-vm → double-vm}/suspicious-patterns.d.ts +0 -0
  134. /package/{src/double-vm → double-vm}/types.d.ts +0 -0
  135. /package/{src/double-vm → double-vm}/wrap-adapter.d.ts +0 -0
  136. /package/{src/enclave.d.ts → enclave.d.ts} +0 -0
  137. /package/{src/globals-validator.d.ts → globals-validator.d.ts} +0 -0
  138. /package/{src/index.d.ts → index.d.ts} +0 -0
  139. /package/{src/memory-proxy.d.ts → memory-proxy.d.ts} +0 -0
  140. /package/{src/memory-tracker.d.ts → memory-tracker.d.ts} +0 -0
  141. /package/{src/safe-error.d.ts → safe-error.d.ts} +0 -0
  142. /package/{src/safe-runtime.d.ts → safe-runtime.d.ts} +0 -0
  143. /package/{src/scoring → scoring}/cache.d.ts +0 -0
  144. /package/{src/scoring → scoring}/feature-extractor.d.ts +0 -0
  145. /package/{src/scoring → scoring}/index.d.ts +0 -0
  146. /package/{src/scoring → scoring}/scorer.interface.d.ts +0 -0
  147. /package/{src/scoring → scoring}/scorers/disabled.scorer.d.ts +0 -0
  148. /package/{src/scoring → scoring}/scorers/external-api.scorer.d.ts +0 -0
  149. /package/{src/scoring → scoring}/scorers/index.d.ts +0 -0
  150. /package/{src/scoring → scoring}/scorers/local-llm.scorer.d.ts +0 -0
  151. /package/{src/scoring → scoring}/scorers/progressive.scorer.d.ts +0 -0
  152. /package/{src/scoring → scoring}/scorers/rule-based.scorer.d.ts +0 -0
  153. /package/{src/scoring → scoring}/scoring-gate.d.ts +0 -0
  154. /package/{src/scoring → scoring}/types.d.ts +0 -0
  155. /package/{src/secure-proxy.d.ts → secure-proxy.d.ts} +0 -0
  156. /package/{src/session → session}/channels/embedded-channel.d.ts +0 -0
  157. /package/{src/session → session}/channels/index.d.ts +0 -0
  158. /package/{src/session → session}/index.d.ts +0 -0
  159. /package/{src/session → session}/session-emitter.d.ts +0 -0
  160. /package/{src/session → session}/session-state-machine.d.ts +0 -0
  161. /package/{src/session → session}/session.d.ts +0 -0
  162. /package/{src/session-types.d.ts → session-types.d.ts} +0 -0
  163. /package/{src/sidecar → sidecar}/index.d.ts +0 -0
  164. /package/{src/sidecar → sidecar}/reference-config.d.ts +0 -0
  165. /package/{src/sidecar → sidecar}/reference-resolver.d.ts +0 -0
  166. /package/{src/sidecar → sidecar}/reference-sidecar.d.ts +0 -0
  167. /package/{src/tool-bridge.d.ts → tool-bridge.d.ts} +0 -0
  168. /package/{src/types.d.ts → types.d.ts} +0 -0
  169. /package/{src/value-sanitizer.d.ts → value-sanitizer.d.ts} +0 -0
@@ -1,1695 +0,0 @@
1
- "use strict";
2
- /**
3
- * Parent VM Bootstrap Script Generator
4
- *
5
- * Generates the JavaScript code that runs inside the Parent VM.
6
- * The Parent VM is responsible for:
7
- * - Creating and managing the Inner VM where user code runs
8
- * - Intercepting and validating all tool calls from the Inner VM
9
- * - Applying enhanced security validation (rate limiting, pattern detection)
10
- * - Proxying validated tool calls to the host
11
- *
12
- * @packageDocumentation
13
- */
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.generateParentVmBootstrap = generateParentVmBootstrap;
16
- /**
17
- * Node.js 24 dangerous globals that should be removed per security level
18
- * (Same as in vm-adapter.ts)
19
- *
20
- * Defense-in-depth: Even though codeGeneration.strings=false blocks
21
- * new Function() from strings, removing Function entirely eliminates
22
- * any potential bypass vectors discovered in the future.
23
- *
24
- * ATK-RECON-01 identified these accessible globals as attack surface:
25
- * Function, eval, Proxy, Reflect, WeakRef, FinalizationRegistry,
26
- * SharedArrayBuffer, Atomics, gc, WebAssembly, globalThis
27
- */
28
- const NODEJS_24_DANGEROUS_GLOBALS = {
29
- STRICT: [
30
- // Code execution - CRITICAL
31
- 'Function', // Constructor for functions - primary escape vector
32
- 'eval', // Direct code execution
33
- 'globalThis', // Indirect access to all globals
34
- // Metaprogramming - sandbox escape vectors
35
- 'Proxy', // Can intercept all operations
36
- 'Reflect', // Metaprogramming primitive
37
- // Memory/timing attacks
38
- 'SharedArrayBuffer', // Spectre/timing attacks
39
- 'Atomics', // Shared memory operations
40
- 'gc', // Force garbage collection (shouldn't be exposed)
41
- // Future/experimental APIs
42
- 'Iterator', // Iterator helpers
43
- 'AsyncIterator', // Async iterator helpers
44
- 'ShadowRealm', // New realm creation (major escape risk)
45
- 'WeakRef', // Can observe GC behavior
46
- 'FinalizationRegistry', // Can observe GC behavior
47
- 'performance', // Timing information
48
- 'Temporal', // New date/time API
49
- ],
50
- SECURE: [
51
- // Code execution - CRITICAL
52
- 'Function',
53
- 'eval',
54
- 'globalThis',
55
- // Most dangerous metaprogramming
56
- 'Proxy',
57
- // Memory/timing attacks
58
- 'SharedArrayBuffer',
59
- 'Atomics',
60
- 'gc',
61
- // Future APIs
62
- 'Iterator',
63
- 'AsyncIterator',
64
- 'ShadowRealm',
65
- 'WeakRef',
66
- 'FinalizationRegistry',
67
- ],
68
- STANDARD: [
69
- // Code execution - always block these
70
- 'Function',
71
- 'eval',
72
- // Memory/timing attacks
73
- 'SharedArrayBuffer',
74
- 'Atomics',
75
- 'gc',
76
- // Definitely dangerous
77
- 'ShadowRealm',
78
- 'WeakRef',
79
- 'FinalizationRegistry',
80
- ],
81
- PERMISSIVE: [
82
- // Even PERMISSIVE should block the most dangerous
83
- 'ShadowRealm', // Too dangerous to allow
84
- 'gc', // Shouldn't be exposed at all
85
- 'SharedArrayBuffer', // Spectre risk
86
- 'Atomics', // Goes with SharedArrayBuffer
87
- ],
88
- };
89
- /**
90
- * Generate code to sanitize the inner VM context
91
- */
92
- function generateSanitizeContextCode(securityLevel) {
93
- const globalsToRemove = NODEJS_24_DANGEROUS_GLOBALS[securityLevel];
94
- return globalsToRemove
95
- .map((g) => `
96
- if ('${g}' in innerContext) {
97
- try { delete innerContext['${g}']; } catch (e) {
98
- try { innerContext['${g}'] = undefined; } catch (e2) {}
99
- }
100
- }`)
101
- .join('\n');
102
- }
103
- /**
104
- * Generate code for pattern detectors
105
- */
106
- function generatePatternDetectorsCode(patterns) {
107
- const patternDefs = patterns
108
- .map((p) => `{
109
- id: ${JSON.stringify(p.id)},
110
- description: ${JSON.stringify(p.description)},
111
- detect: function(operationName, args, history) {
112
- ${p.detectBody}
113
- }
114
- }`)
115
- .join(',\n ');
116
- return `[
117
- ${patternDefs}
118
- ]`;
119
- }
120
- /**
121
- * Generate the parent VM bootstrap script
122
- *
123
- * This returns JavaScript code as a string that will be executed
124
- * inside the parent VM context.
125
- */
126
- function generateParentVmBootstrap(options) {
127
- const { userCode, innerTimeout, maxIterations, maxToolCalls, toolBridgeMode = 'string', toolBridgeMaxPayloadBytes = 5 * 1024 * 1024, sanitizeStackTraces, securityLevel, validationConfig, suspiciousPatterns, blockedProperties, allowComposites = false, memoryLimit = 0, throwOnBlocked = true, } = options;
128
- const sanitizeContextCode = generateSanitizeContextCode(securityLevel);
129
- const patternDetectorsCode = generatePatternDetectorsCode(suspiciousPatterns);
130
- // Patch code executed inside VM realms to prevent leaking host stack traces via error.stack.
131
- // We avoid including any file names/paths/line numbers in the formatted stack.
132
- const stackTraceHardeningCode = `
133
- (function() {
134
- function __ag_redactStackString(stackStr) {
135
- try {
136
- if (typeof stackStr !== 'string' || !stackStr) return 'Error';
137
- var lines = String(stackStr).split('\\n');
138
- var header = lines[0] ? String(lines[0]) : 'Error';
139
- var frameCount = (lines.length > 1) ? (lines.length - 1) : 0;
140
- var max = frameCount;
141
- if (max > 25) max = 25;
142
- var out = [header];
143
- for (var i = 0; i < max; i++) out.push(' at [REDACTED]');
144
- if (frameCount > max) out.push(' at [REDACTED]');
145
- return out.join('\\n');
146
- } catch (e) {
147
- return 'Error';
148
- }
149
- }
150
-
151
- function __ag_prepareStackTrace(err, stack) {
152
- try {
153
- var name = (err && err.name) ? String(err.name) : 'Error';
154
- var message = (err && err.message) ? String(err.message) : '';
155
- var header = message ? (name + ': ' + message) : name;
156
- if (!stack || !stack.length) return header;
157
- var lines = [header];
158
- var max = stack.length;
159
- if (max > 25) max = 25;
160
- for (var i = 0; i < max; i++) {
161
- lines.push(' at [REDACTED]');
162
- }
163
- if (stack.length > max) {
164
- lines.push(' at [REDACTED]');
165
- }
166
- return lines.join('\\n');
167
- } catch (e) {
168
- return 'Error';
169
- }
170
- }
171
-
172
- function __ag_lockStackGetter(proto) {
173
- if (!proto) return;
174
- try {
175
- var desc = Object.getOwnPropertyDescriptor(proto, 'stack');
176
- if (!desc || typeof desc.get !== 'function') return;
177
- var origGet = desc.get;
178
- var origSet = desc.set;
179
- Object.defineProperty(proto, 'stack', {
180
- get: function() {
181
- try {
182
- return __ag_redactStackString(origGet.call(this));
183
- } catch (e) {
184
- return 'Error';
185
- }
186
- },
187
- set: function(v) {
188
- try {
189
- if (typeof origSet === 'function') return origSet.call(this, v);
190
- } catch (e) {}
191
- },
192
- configurable: false,
193
- enumerable: false
194
- });
195
- } catch (e) {}
196
- }
197
-
198
- function __ag_lockPrepareStackTrace(ErrCtor) {
199
- if (!ErrCtor) return;
200
- try {
201
- Object.defineProperty(ErrCtor, 'prepareStackTrace', {
202
- value: __ag_prepareStackTrace,
203
- writable: false,
204
- configurable: false,
205
- enumerable: false
206
- });
207
- } catch (e) {}
208
- try {
209
- Object.defineProperty(ErrCtor, 'stackTraceLimit', {
210
- value: 25,
211
- writable: false,
212
- configurable: false,
213
- enumerable: false
214
- });
215
- } catch (e) {}
216
- }
217
-
218
- __ag_lockStackGetter(Error && Error.prototype);
219
- __ag_lockPrepareStackTrace(Error);
220
- __ag_lockPrepareStackTrace(EvalError);
221
- __ag_lockPrepareStackTrace(RangeError);
222
- __ag_lockPrepareStackTrace(ReferenceError);
223
- __ag_lockPrepareStackTrace(SyntaxError);
224
- __ag_lockPrepareStackTrace(TypeError);
225
- __ag_lockPrepareStackTrace(URIError);
226
- try {
227
- if (typeof AggregateError !== 'undefined') __ag_lockPrepareStackTrace(AggregateError);
228
- } catch (e) {}
229
- })();
230
- `.trim();
231
- const stackTraceHardeningCodeJson = JSON.stringify(stackTraceHardeningCode);
232
- // Detect and report code-generation attempts (Function/eval) even if user code catches the thrown error.
233
- // Used to fail closed in STRICT/SECURE modes.
234
- const codeGenViolationDetectorCode = `
235
- (function() {
236
- var __ag_report = (typeof __ag_reportViolation__ === 'function') ? __ag_reportViolation__ : null;
237
- function __ag_reportOnce(kind) {
238
- try {
239
- if (__ag_report) __ag_report(kind);
240
- } catch (e) {}
241
- }
242
-
243
- var __ag_Reflect = (typeof Reflect !== 'undefined') ? Reflect : null;
244
- var __ag_Proxy = (typeof Proxy !== 'undefined') ? Proxy : null;
245
- var __ag_Object = (typeof Object !== 'undefined') ? Object : null;
246
-
247
- function __ag_wrapCtor(Ctor, kind) {
248
- if (!Ctor || !__ag_Proxy || !__ag_Reflect || !__ag_Object) return;
249
- try {
250
- var proxy = new __ag_Proxy(Ctor, {
251
- apply: function(target, thisArg, args) {
252
- __ag_reportOnce(kind);
253
- return __ag_Reflect.apply(target, thisArg, args);
254
- },
255
- construct: function(target, args, newTarget) {
256
- __ag_reportOnce(kind);
257
- return __ag_Reflect.construct(target, args, newTarget);
258
- }
259
- });
260
-
261
- try {
262
- if (Ctor.prototype) {
263
- __ag_Object.defineProperty(Ctor.prototype, 'constructor', {
264
- value: proxy,
265
- writable: false,
266
- configurable: false,
267
- enumerable: false
268
- });
269
- }
270
- } catch (e) {}
271
- } catch (e) {}
272
- }
273
-
274
- try { __ag_wrapCtor(Function, 'CODE_GENERATION'); } catch (e) {}
275
- try { __ag_wrapCtor((async function(){}).constructor, 'CODE_GENERATION'); } catch (e) {}
276
- try { __ag_wrapCtor((function*(){}).constructor, 'CODE_GENERATION'); } catch (e) {}
277
- try { __ag_wrapCtor((async function*(){}).constructor, 'CODE_GENERATION'); } catch (e) {}
278
- })();
279
- `.trim();
280
- const codeGenViolationDetectorCodeJson = JSON.stringify(codeGenViolationDetectorCode);
281
- // Define __safe_concat/__safe_template inside the INNER VM realm.
282
- //
283
- // Why: when `__safe_concat` is a host/parent-realm function (injected into the inner context),
284
- // stack-overflow errors can span multiple realms and Node/V8 may bypass Error.prepareStackTrace
285
- // formatting entirely, leaking internal filenames like "parent-vm.js" into user-accessible stacks.
286
- //
287
- // By defining these helpers inside the inner realm, stack overflows stay within the inner realm
288
- // and our stack-trace hardening can reliably redact frames.
289
- const innerRealmSafeConcatAndTemplateCode = `
290
- (function() {
291
- ${stackTraceHardeningCode}
292
- })();
293
-
294
- (function() {
295
- var __ag_Object = Object;
296
- var __ag_Reflect = (typeof Reflect !== 'undefined') ? Reflect : null;
297
- var __ag_Proxy = (typeof Proxy !== 'undefined') ? Proxy : null;
298
- var __ag_WeakMap = (typeof WeakMap !== 'undefined') ? WeakMap : null;
299
- var __ag_proxyCache = __ag_WeakMap ? new __ag_WeakMap() : null;
300
-
301
- // Capture intrinsics before any later global sanitization/proxying.
302
- var __ag_String = String;
303
- var __ag_ArrayProto = __ag_Object.getPrototypeOf([]);
304
- var __ag_refIdPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
305
- var __ag_allowComposites = ${allowComposites};
306
- var __ag_memoryLimit = ${memoryLimit};
307
- var __ag_track = (typeof __host_memory_track__ === 'function') ? __host_memory_track__ : null;
308
-
309
- // Best-effort secure proxy to block dangerous property access on these runtime helpers.
310
- // This mirrors the "constructor/__proto__/prototype" defense-in-depth used elsewhere.
311
- var __ag_blocked = new Set(${JSON.stringify(blockedProperties)});
312
- function __ag_createSecureProxy(obj, depth) {
313
- if (depth === undefined) depth = 0;
314
- if (!__ag_Proxy || !__ag_Reflect) return obj;
315
- if (depth > 10) return obj;
316
- if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) return obj;
317
-
318
- if (__ag_proxyCache) {
319
- try {
320
- var cached = __ag_proxyCache.get(obj);
321
- if (cached) return cached;
322
- } catch (e) {}
323
- }
324
-
325
- var proxy = new __ag_Proxy(obj, {
326
- get: function(target, property, receiver) {
327
- var propName = __ag_String(property);
328
- if (__ag_blocked.has(propName)) {
329
- throw new Error(
330
- "Security violation: Access to '" + propName + "' is blocked. " +
331
- "This property can be used for sandbox escape attacks."
332
- );
333
- }
334
- var value = __ag_Reflect.get(target, property, receiver);
335
- if (typeof value === 'function') {
336
- // Bind methods to preserve internal slots when relevant.
337
- try { value = value.bind(target); } catch (e) {}
338
- }
339
- return __ag_createSecureProxy(value, depth + 1);
340
- },
341
- apply: function(target, thisArg, args) {
342
- return __ag_Reflect.apply(target, thisArg, args);
343
- },
344
- construct: function(target, args, newTarget) {
345
- return __ag_Reflect.construct(target, args, newTarget);
346
- }
347
- });
348
-
349
- if (__ag_proxyCache) {
350
- try {
351
- __ag_proxyCache.set(obj, proxy);
352
- } catch (e) {}
353
- }
354
-
355
- return proxy;
356
- }
357
-
358
- function __ag_createSafeError(message, name) {
359
- if (name === undefined) name = 'Error';
360
- var error = new Error(message);
361
- // NOTE: Use __ag_Object.defineProperty instead of direct assignment because
362
- // Error.prototype.name is frozen, and in strict mode direct assignment fails.
363
- try {
364
- __ag_Object.defineProperty(error, 'name', {
365
- value: name,
366
- writable: true,
367
- enumerable: false,
368
- configurable: true
369
- });
370
- } catch (e) {}
371
- try {
372
- var SafeConstructor = __ag_Object.create(null);
373
- __ag_Object.defineProperties(SafeConstructor, {
374
- constructor: { value: SafeConstructor, writable: false, enumerable: false, configurable: false },
375
- prototype: { value: null, writable: false, enumerable: false, configurable: false },
376
- name: { value: 'SafeError', writable: false, enumerable: false, configurable: false }
377
- });
378
- __ag_Object.freeze(SafeConstructor);
379
- __ag_Object.defineProperty(error, 'constructor', {
380
- value: SafeConstructor,
381
- writable: false,
382
- enumerable: false,
383
- configurable: false
384
- });
385
- } catch (e) {}
386
- try {
387
- __ag_Object.defineProperty(error, '__proto__', {
388
- value: null,
389
- writable: false,
390
- enumerable: false,
391
- configurable: false
392
- });
393
- } catch (e) {}
394
- try {
395
- __ag_Object.defineProperty(error, 'stack', {
396
- value: undefined,
397
- writable: false,
398
- enumerable: false,
399
- configurable: false
400
- });
401
- } catch (e) {}
402
- try { __ag_Object.freeze(error); } catch (e) {}
403
- return error;
404
- }
405
-
406
- function __ag_innerConcat(left, right) {
407
- if (typeof left === 'number' && typeof right === 'number') {
408
- return left + right;
409
- }
410
-
411
- if (typeof left === 'string' && typeof right === 'string') {
412
- var leftLen = left.length;
413
- var rightLen = right.length;
414
-
415
- var leftIsRef = __ag_refIdPattern.test(left);
416
- var rightIsRef = __ag_refIdPattern.test(right);
417
-
418
- if (!leftIsRef && !rightIsRef) {
419
- if (__ag_track && __ag_memoryLimit > 0) {
420
- __ag_track(rightLen * 2);
421
- }
422
- return left + right;
423
- }
424
-
425
- if (!__ag_allowComposites) {
426
- throw __ag_createSafeError(
427
- 'Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +
428
- 'Composite handles are disabled in the current security configuration.'
429
- );
430
- }
431
-
432
- return {
433
- __type: 'composite',
434
- __operation: 'concat',
435
- __parts: [left, right],
436
- __estimatedSize: 0
437
- };
438
- }
439
-
440
- if (typeof left === 'string' || typeof right === 'string') {
441
- var leftIsRef2 = typeof left === 'string' && __ag_refIdPattern.test(left);
442
- var rightIsRef2 = typeof right === 'string' && __ag_refIdPattern.test(right);
443
-
444
- if (leftIsRef2 || rightIsRef2) {
445
- if (!__ag_allowComposites) {
446
- throw __ag_createSafeError(
447
- 'Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +
448
- 'Composite handles are disabled in the current security configuration.'
449
- );
450
- }
451
-
452
- var leftStr = __ag_String(left);
453
- var rightStr = __ag_String(right);
454
- return {
455
- __type: 'composite',
456
- __operation: 'concat',
457
- __parts: [leftStr, rightStr],
458
- __estimatedSize: 0
459
- };
460
- }
461
- }
462
-
463
- var result = left + right;
464
- if (typeof result === 'string' && __ag_track && __ag_memoryLimit > 0) {
465
- __ag_track(result.length * 2);
466
- }
467
- return result;
468
- }
469
-
470
- function __ag_innerTemplate(quasis) {
471
- var values = __ag_ArrayProto.slice.call(arguments, 1);
472
- var parts = [];
473
- var hasReferences = false;
474
-
475
- for (var i = 0; i < quasis.length; i++) {
476
- parts.push(quasis[i]);
477
- if (i < values.length) {
478
- var valueStr = __ag_String(values[i]);
479
- parts.push(valueStr);
480
- if (__ag_refIdPattern.test(valueStr)) {
481
- hasReferences = true;
482
- }
483
- }
484
- }
485
-
486
- if (!hasReferences) {
487
- var joined = parts.join('');
488
- if (typeof joined === 'string' && __ag_track && __ag_memoryLimit > 0) {
489
- __ag_track(joined.length * 2);
490
- }
491
- return joined;
492
- }
493
-
494
- if (!__ag_allowComposites) {
495
- throw __ag_createSafeError(
496
- 'Cannot concatenate reference IDs in template literals. Pass references directly to callTool arguments. ' +
497
- 'Composite handles are disabled in the current security configuration.'
498
- );
499
- }
500
-
501
- return {
502
- __type: 'composite',
503
- __operation: 'concat',
504
- __parts: parts,
505
- __estimatedSize: 0
506
- };
507
- }
508
-
509
- try {
510
- __ag_Object.defineProperty(globalThis, '__safe_concat', {
511
- value: __ag_createSecureProxy(__ag_innerConcat, 0),
512
- writable: false,
513
- configurable: false,
514
- enumerable: false
515
- });
516
- } catch (e) {}
517
-
518
- try {
519
- __ag_Object.defineProperty(globalThis, '__safe_template', {
520
- value: __ag_createSecureProxy(__ag_innerTemplate, 0),
521
- writable: false,
522
- configurable: false,
523
- enumerable: false
524
- });
525
- } catch (e) {}
526
- })();
527
- `.trim();
528
- const innerRealmSafeConcatAndTemplateCodeJson = JSON.stringify(innerRealmSafeConcatAndTemplateCode);
529
- // Generate allowed/blocked pattern reconstruction code
530
- let patternReconstructCode = '';
531
- if (validationConfig.allowedOperationPatternSource) {
532
- patternReconstructCode += `
533
- const allowedOperationPattern = new RegExp(${JSON.stringify(validationConfig.allowedOperationPatternSource)}, ${JSON.stringify(validationConfig.allowedOperationPatternFlags || '')});
534
- `;
535
- }
536
- if (validationConfig.blockedOperationPatternSources && validationConfig.blockedOperationPatternSources.length > 0) {
537
- const blockedPatterns = validationConfig.blockedOperationPatternSources
538
- .map((src, i) => `new RegExp(${JSON.stringify(src)}, ${JSON.stringify(validationConfig.blockedOperationPatternFlags?.[i] || '')})`)
539
- .join(', ');
540
- patternReconstructCode += `
541
- const blockedOperationPatterns = [${blockedPatterns}];
542
- `;
543
- }
544
- return `
545
- 'use strict';
546
-
547
- // Parent VM Bootstrap Script
548
- // This code runs inside the Parent VM and creates/manages the Inner VM
549
-
550
- (async function parentVmMain() {
551
- // Get injected references from host
552
- const vm = __host_vm_module__;
553
- const hostCallTool = __host_callTool__;
554
- const hostStats = __host_stats__;
555
- const hostAbortCheck = __host_abort_check__;
556
- const hostReportViolation = __host_reportViolation__;
557
- const hostConfig = __host_config__;
558
- const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
559
- const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
560
-
561
- // Defense-in-depth: remove direct access to host bridge references after capture.
562
- // If the inner VM escapes to the parent global, these names should not be discoverable.
563
- try { delete globalThis.__host_callTool__; } catch (e) { /* ignore */ }
564
- try { delete globalThis.__host_vm_module__; } catch (e) { /* ignore */ }
565
- try { delete globalThis.__host_stats__; } catch (e) { /* ignore */ }
566
- try { delete globalThis.__host_abort_check__; } catch (e) { /* ignore */ }
567
- try { delete globalThis.__host_reportViolation__; } catch (e) { /* ignore */ }
568
- try { delete globalThis.__host_config__; } catch (e) { /* ignore */ }
569
-
570
- // Policy violation reporter (best-effort; host decides how to handle based on security level)
571
- function __ag_reportViolation(kind) {
572
- try {
573
- if (typeof hostReportViolation === 'function') hostReportViolation(kind);
574
- } catch (e) { /* ignore */ }
575
- }
576
-
577
- // SECURITY HARDENING: prevent leaking host stack traces via error.stack inside the sandbox.
578
- const sanitizeStackTraces = ${sanitizeStackTraces};
579
- if (sanitizeStackTraces) {
580
- try {
581
- // Patch the PARENT VM realm (errors thrown from safe runtime functions).
582
- // Note: we execute code directly here, and separately apply the same patch to the INNER VM.
583
- ${stackTraceHardeningCode}
584
- } catch (e) { /* ignore */ }
585
- }
586
-
587
- /**
588
- * Creates a "safe" error object that cannot be used to escape the sandbox.
589
- *
590
- * SECURITY: This function creates error objects with a severed prototype chain
591
- * to prevent attacks that climb the prototype chain to reach the host Function constructor.
592
- * It also removes the stack trace to prevent information leakage (Vector 1230).
593
- *
594
- * Attack vectors blocked:
595
- * - err.constructor.constructor('return process.env.SECRET')()
596
- * - err.__proto__.constructor.constructor('malicious code')()
597
- * - err.stack leaking internal function frames and file paths (Vector 1230)
598
- */
599
- // Unique symbol-like marker for identifying safe errors (not a real Symbol to avoid sandbox escape)
600
- var SAFE_ERROR_MARKER = '__enclave_safe_error_' + Math.random().toString(36).slice(2);
601
-
602
- function createSafeError(message, name) {
603
- if (name === undefined) name = 'Error';
604
-
605
- // Create the real error
606
- var error = new Error(message);
607
- // NOTE: Use Object.defineProperty instead of direct assignment because
608
- // Error.prototype.name is frozen, and in strict mode direct assignment fails.
609
- Object.defineProperty(error, 'name', {
610
- value: name,
611
- writable: true,
612
- enumerable: false,
613
- configurable: true
614
- });
615
-
616
- // CRITICAL: sever the *actual* prototype chain (native getters / Object.getPrototypeOf).
617
- // A shadowing __proto__ data property is not sufficient.
618
- Object.setPrototypeOf(error, null);
619
-
620
- // Create a null-prototype object to use as a safe "constructor"
621
- // This object has no prototype chain to climb
622
- var SafeConstructor = Object.create(null);
623
- Object.defineProperties(SafeConstructor, {
624
- // Make constructor point to itself to break the chain
625
- constructor: {
626
- value: SafeConstructor,
627
- writable: false,
628
- enumerable: false,
629
- configurable: false
630
- },
631
- // Block prototype access
632
- prototype: {
633
- value: null,
634
- writable: false,
635
- enumerable: false,
636
- configurable: false
637
- },
638
- // Add name for debugging
639
- name: {
640
- value: 'SafeError',
641
- writable: false,
642
- enumerable: false,
643
- configurable: false
644
- }
645
- });
646
- Object.freeze(SafeConstructor);
647
-
648
- // Override the constructor property on the error instance
649
- // This breaks the prototype chain: err.constructor.constructor no longer reaches Function
650
- Object.defineProperty(error, 'constructor', {
651
- value: SafeConstructor,
652
- writable: false,
653
- enumerable: false,
654
- configurable: false
655
- });
656
-
657
- // SECURITY: Override __proto__ on the error instance to prevent prototype chain escape
658
- // Attack vector blocked: err.__proto__.constructor.constructor('malicious code')()
659
- Object.defineProperty(error, '__proto__', {
660
- value: null,
661
- writable: false,
662
- enumerable: false,
663
- configurable: false
664
- });
665
-
666
- // SECURITY: Remove the stack property to prevent information leakage (Vector 1230)
667
- // The stack trace can reveal internal implementation details like function names,
668
- // file paths, and line numbers which can be used for reconnaissance attacks.
669
- Object.defineProperty(error, 'stack', {
670
- value: undefined,
671
- writable: false,
672
- enumerable: false,
673
- configurable: false
674
- });
675
-
676
- // Add a unique marker to identify this as a safe error from our runtime
677
- // This is used by suspicious pattern detection to distinguish our errors from user errors
678
- Object.defineProperty(error, SAFE_ERROR_MARKER, {
679
- value: true,
680
- writable: false,
681
- enumerable: false,
682
- configurable: false
683
- });
684
-
685
- // Freeze the error to prevent modifications
686
- Object.freeze(error);
687
-
688
- return error;
689
- }
690
-
691
- // Helper to check if an error is a safe error from our runtime
692
- function isSafeError(e) {
693
- return e && e[SAFE_ERROR_MARKER] === true;
694
- }
695
-
696
- // Validation configuration
697
- const validationConfig = ${JSON.stringify({
698
- validateOperationNames: validationConfig.validateOperationNames,
699
- maxOperationsPerSecond: validationConfig.maxOperationsPerSecond,
700
- blockSuspiciousSequences: validationConfig.blockSuspiciousSequences,
701
- rapidEnumerationThreshold: validationConfig.rapidEnumerationThreshold,
702
- rapidEnumerationOverrides: validationConfig.rapidEnumerationOverrides,
703
- })};
704
- ${patternReconstructCode}
705
-
706
- // Suspicious pattern detectors
707
- const suspiciousPatterns = ${patternDetectorsCode};
708
-
709
- // Operation history for pattern detection
710
- const operationHistory = [];
711
-
712
- // Tool call stats for rate limiting
713
- let toolCallCount = 0;
714
-
715
- // Blocked properties for secure proxy (from security level)
716
- const blockedPropertiesSet = new Set(${JSON.stringify(blockedProperties)});
717
-
718
- // Whether to throw errors instead of returning undefined for blocked properties
719
- const throwOnBlocked = ${throwOnBlocked};
720
-
721
- // Whether composite reference handles are allowed (for string concatenation)
722
- const allowComposites = ${allowComposites};
723
-
724
- // Memory limit in bytes (0 = unlimited)
725
- const memoryLimit = ${memoryLimit};
726
-
727
- // Reference ID pattern for detecting sidecar references
728
- const refIdPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
729
-
730
- // Proxy cache to avoid infinite recursion and duplicate wrapping
731
- const proxyCache = new WeakMap();
732
-
733
- /**
734
- * Create a secure proxy that blocks access to dangerous properties
735
- * Defense-in-depth against attacks like: callTool['const' + 'ructor']
736
- *
737
- * IMPORTANT: Must respect JavaScript proxy invariants:
738
- * - Non-configurable properties must return their actual value
739
- * - Non-configurable non-writable properties cannot be hidden
740
- */
741
- function createSecureProxy(obj, depth) {
742
- if (depth === undefined) depth = 0;
743
- if (depth > 10) return obj; // Max depth to prevent infinite recursion
744
-
745
- // Skip primitives and null
746
- if (obj === null || typeof obj !== 'object' && typeof obj !== 'function') {
747
- return obj;
748
- }
749
-
750
- // Check cache
751
- if (proxyCache.has(obj)) {
752
- return proxyCache.get(obj);
753
- }
754
-
755
- var proxy = new Proxy(obj, {
756
- get: function(target, property, receiver) {
757
- var propName = String(property);
758
-
759
- // Check if property is non-configurable (proxy invariant requires returning actual value)
760
- var descriptor = Object.getOwnPropertyDescriptor(target, property);
761
- var isNonConfigurable = descriptor && !descriptor.configurable;
762
-
763
- // Proxy invariant: if the target has a non-configurable, non-writable data property,
764
- // the proxy must return the exact same value (cannot wrap/bind/proxy it).
765
- // This matters for hardened properties like Error.prepareStackTrace.
766
- if (descriptor && isNonConfigurable && 'value' in descriptor && descriptor.writable === false) {
767
- return descriptor.value;
768
- }
769
-
770
- // Block dangerous properties - but respect proxy invariants
771
- if (blockedPropertiesSet.has(propName)) {
772
- // For non-configurable properties, we MUST return the actual value
773
- // (JavaScript proxy invariant - can't hide non-configurable properties)
774
- if (isNonConfigurable) {
775
- return Reflect.get(target, property, receiver);
776
- }
777
- if (throwOnBlocked) {
778
- throw createSafeError(
779
- "Security violation: Access to '" + propName + "' is blocked. " +
780
- "This property can be used for sandbox escape attacks."
781
- );
782
- }
783
- return undefined;
784
- }
785
-
786
- var value = Reflect.get(target, property, receiver);
787
-
788
- // For function values, bind to target first (preserves internal slot access for Promises, etc.)
789
- // Then recursively proxy the bound function to block constructor access
790
- if (typeof value === 'function') {
791
- var boundMethod = value.bind(target);
792
- return createSecureProxy(boundMethod, depth + 1);
793
- }
794
-
795
- // Recursively proxy nested objects to maintain security barrier
796
- // This prevents attacks like: process.env.__proto__.constructor
797
- if (value !== null && typeof value === 'object') {
798
- return createSecureProxy(value, depth + 1);
799
- }
800
-
801
- return value;
802
- },
803
- set: function(target, property, value, receiver) {
804
- var propName = String(property);
805
- if (blockedPropertiesSet.has(propName)) {
806
- if (throwOnBlocked) {
807
- throw createSafeError(
808
- "Security violation: Setting '" + propName + "' is blocked. " +
809
- "This property can be used for sandbox escape attacks."
810
- );
811
- }
812
- return false;
813
- }
814
- return Reflect.set(target, property, value, receiver);
815
- },
816
- defineProperty: function(target, property, descriptor) {
817
- var propName = String(property);
818
- if (blockedPropertiesSet.has(propName)) {
819
- if (throwOnBlocked) {
820
- throw createSafeError(
821
- "Security violation: Defining '" + propName + "' is blocked. " +
822
- "This property can be used for sandbox escape attacks."
823
- );
824
- }
825
- return false;
826
- }
827
- return Reflect.defineProperty(target, property, descriptor);
828
- },
829
- getOwnPropertyDescriptor: function(target, property) {
830
- var propName = String(property);
831
- var descriptor = Reflect.getOwnPropertyDescriptor(target, property);
832
-
833
- // Must return actual descriptor for non-configurable properties (proxy invariant)
834
- if (descriptor && !descriptor.configurable) {
835
- return descriptor;
836
- }
837
-
838
- // Block configurable dangerous properties
839
- if (blockedPropertiesSet.has(propName)) {
840
- if (throwOnBlocked) {
841
- throw createSafeError(
842
- "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
843
- "This property can be used for sandbox escape attacks."
844
- );
845
- }
846
- return undefined;
847
- }
848
- return descriptor;
849
- },
850
- ownKeys: function(target) {
851
- var keys = Reflect.ownKeys(target);
852
- return keys.filter(function(key) {
853
- var keyStr = String(key);
854
- // Keep non-blocked properties
855
- if (!blockedPropertiesSet.has(keyStr)) {
856
- return true;
857
- }
858
- // Must keep non-configurable properties (proxy invariant)
859
- var descriptor = Object.getOwnPropertyDescriptor(target, key);
860
- if (descriptor && !descriptor.configurable) {
861
- return true;
862
- }
863
- // Filter out blocked configurable properties
864
- return false;
865
- });
866
- },
867
- getPrototypeOf: function(target) {
868
- // Return null to hide prototype chain
869
- return null;
870
- }
871
- });
872
-
873
- proxyCache.set(obj, proxy);
874
- return proxy;
875
- }
876
-
877
- /**
878
- * Validate an operation before forwarding to host
879
- */
880
- function validateOperation(operationName, args) {
881
- // Rate limiting check with sliding window cleanup
882
- const now = Date.now();
883
- // Clean up old entries to prevent unbounded growth (keep only last 2 seconds)
884
- while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {
885
- operationHistory.shift();
886
- }
887
- const recentOperations = operationHistory.filter(function(h) { return now - h.timestamp < 1000; });
888
- if (recentOperations.length >= validationConfig.maxOperationsPerSecond) {
889
- throw createSafeError('Operation rate limit exceeded (' + validationConfig.maxOperationsPerSecond + ' operations/second)');
890
- }
891
-
892
- // Operation name format validation
893
- if (typeof operationName !== 'string' || !operationName) {
894
- throw createSafeError('Operation name must be a non-empty string', 'TypeError');
895
- }
896
-
897
- // Operation name pattern validation (whitelist)
898
- if (validationConfig.validateOperationNames && typeof allowedOperationPattern !== 'undefined') {
899
- if (!allowedOperationPattern.test(operationName)) {
900
- throw createSafeError('Operation "' + operationName + '" does not match allowed pattern');
901
- }
902
- }
903
-
904
- // Operation name pattern validation (blacklist)
905
- if (typeof blockedOperationPatterns !== 'undefined') {
906
- for (var i = 0; i < blockedOperationPatterns.length; i++) {
907
- if (blockedOperationPatterns[i].test(operationName)) {
908
- throw createSafeError('Operation "' + operationName + '" matches blocked pattern');
909
- }
910
- }
911
- }
912
-
913
- // Suspicious sequence detection
914
- // NOTE: User-provided pattern functions can throw; those errors are intentionally ignored to avoid
915
- // breaking the sandbox due to a buggy detector. If a detector returns true, we always fail closed.
916
- if (validationConfig.blockSuspiciousSequences) {
917
- for (var j = 0; j < suspiciousPatterns.length; j++) {
918
- var pattern = suspiciousPatterns[j];
919
- var detected = false;
920
- try {
921
- detected = !!pattern.detect(operationName, args, operationHistory);
922
- } catch (e) {
923
- detected = false;
924
- }
925
- if (detected) {
926
- throw createSafeError('Suspicious pattern detected: ' + pattern.description + ' [' + pattern.id + ']');
927
- }
928
- }
929
- }
930
- }
931
-
932
- /**
933
- * Inner VM's callTool function
934
- * Proxies through parent VM with validation
935
- */
936
- function innerCallTool(toolName, args) {
937
- // Check if aborted
938
- if (hostAbortCheck()) {
939
- throw createSafeError('Execution aborted');
940
- }
941
-
942
- // Increment count and check limit
943
- toolCallCount++;
944
- if (toolCallCount > ${maxToolCalls}) {
945
- throw createSafeError('Maximum tool call limit exceeded (${maxToolCalls}). This limit prevents runaway script execution.');
946
- }
947
-
948
- // Validate args
949
- if (typeof args !== 'object' || args === null || Array.isArray(args)) {
950
- throw createSafeError('Tool arguments must be an object', 'TypeError');
951
- }
952
-
953
- // Double sanitization (defense in depth)
954
- var sanitizedArgs;
955
- try {
956
- sanitizedArgs = JSON.parse(JSON.stringify(args));
957
- } catch (e) {
958
- throw createSafeError('Tool arguments must be JSON-serializable');
959
- }
960
-
961
- // Enhanced validation
962
- validateOperation(toolName, sanitizedArgs);
963
-
964
- // Record in history
965
- operationHistory.push({
966
- operationName: toolName,
967
- timestamp: Date.now(),
968
- argKeys: Object.keys(sanitizedArgs)
969
- });
970
-
971
- // Update host stats
972
- hostStats.toolCallCount = toolCallCount;
973
-
974
- // Forward to host and wrap the Promise + result in secure proxies
975
- // This prevents access to Promise.constructor and result object constructors
976
- var promise;
977
- if (toolBridgeMode === 'string') {
978
- var requestJson;
979
- try {
980
- requestJson = JSON.stringify({ v: 1, tool: toolName, args: sanitizedArgs });
981
- } catch (e) {
982
- throw createSafeError('Tool request must be JSON-serializable');
983
- }
984
-
985
- // Conservative byte estimate: UTF-8 is at most 4 bytes per code unit.
986
- if (requestJson && (requestJson.length * 4) > toolBridgeMaxPayloadBytes) {
987
- throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
988
- }
989
-
990
- promise = hostCallTool(requestJson).then(function(responseJson) {
991
- if (typeof responseJson !== 'string') {
992
- throw createSafeError('Tool bridge returned non-string response');
993
- }
994
-
995
- if ((responseJson.length * 4) > toolBridgeMaxPayloadBytes) {
996
- throw createSafeError('Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
997
- }
998
-
999
- var response;
1000
- try {
1001
- response = JSON.parse(responseJson);
1002
- } catch (e) {
1003
- throw createSafeError('Tool bridge returned invalid JSON');
1004
- }
1005
-
1006
- if (!response || typeof response !== 'object' || Array.isArray(response)) {
1007
- throw createSafeError('Tool bridge returned invalid response');
1008
- }
1009
-
1010
- if (response.v !== 1) {
1011
- throw createSafeError('Tool bridge protocol version mismatch');
1012
- }
1013
-
1014
- if (response.ok === true) {
1015
- if (Object.prototype.hasOwnProperty.call(response, 'value')) {
1016
- return response.value;
1017
- }
1018
- return undefined;
1019
- }
1020
-
1021
- if (response.ok === false) {
1022
- var err = response.error;
1023
- var msg = (err && typeof err.message === 'string') ? err.message : 'Tool call failed';
1024
- var name = (err && typeof err.name === 'string') ? err.name : 'Error';
1025
- throw createSafeError(msg, name);
1026
- }
1027
-
1028
- throw createSafeError('Tool bridge returned invalid response');
1029
- });
1030
- } else {
1031
- promise = hostCallTool(toolName, sanitizedArgs);
1032
- }
1033
-
1034
- // Create a secure promise that wraps both the promise object and its result
1035
- // Note: We can't just wrap the promise because Promise.then/catch/finally must work
1036
- // Instead, we chain the promise to wrap the result
1037
- return createSecureProxy(promise.then(function(result) {
1038
- return createSecureProxy(result);
1039
- }));
1040
- }
1041
-
1042
- /**
1043
- * Safe for-of iterator for inner VM
1044
- */
1045
- function* innerForOf(iterable) {
1046
- var iterations = 0;
1047
- for (var item of iterable) {
1048
- if (hostAbortCheck()) {
1049
- throw createSafeError('Execution aborted');
1050
- }
1051
- iterations++;
1052
- hostStats.iterationCount++;
1053
- if (iterations > ${maxIterations}) {
1054
- throw createSafeError('Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.');
1055
- }
1056
- yield item;
1057
- }
1058
- }
1059
-
1060
- /**
1061
- * Safe for loop wrapper for inner VM
1062
- */
1063
- function innerFor(init, test, update, body) {
1064
- var iterations = 0;
1065
- init();
1066
- while (test()) {
1067
- if (hostAbortCheck()) {
1068
- throw createSafeError('Execution aborted');
1069
- }
1070
- iterations++;
1071
- hostStats.iterationCount++;
1072
- if (iterations > ${maxIterations}) {
1073
- throw createSafeError('Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.');
1074
- }
1075
- body();
1076
- update();
1077
- }
1078
- }
1079
-
1080
- /**
1081
- * Safe while loop wrapper for inner VM
1082
- */
1083
- function innerWhile(test, body) {
1084
- var iterations = 0;
1085
- while (test()) {
1086
- if (hostAbortCheck()) {
1087
- throw createSafeError('Execution aborted');
1088
- }
1089
- iterations++;
1090
- hostStats.iterationCount++;
1091
- if (iterations > ${maxIterations}) {
1092
- throw createSafeError('Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.');
1093
- }
1094
- body();
1095
- }
1096
- }
1097
-
1098
- /**
1099
- * Safe do-while loop wrapper for inner VM
1100
- */
1101
- function innerDoWhile(test, body) {
1102
- var iterations = 0;
1103
- do {
1104
- if (hostAbortCheck()) {
1105
- throw createSafeError('Execution aborted');
1106
- }
1107
- iterations++;
1108
- hostStats.iterationCount++;
1109
- if (iterations > ${maxIterations}) {
1110
- throw createSafeError('Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.');
1111
- }
1112
- body();
1113
- } while (test());
1114
- }
1115
-
1116
- /**
1117
- * Safe addition/concatenation for inner VM
1118
- * Supports numeric addition, string concatenation, and reference ID handling.
1119
- * Also tracks memory allocation when memoryLimit is set.
1120
- */
1121
- function innerConcat(left, right) {
1122
- // Fast path: both are numbers - do numeric addition (JavaScript + semantics)
1123
- if (typeof left === 'number' && typeof right === 'number') {
1124
- return left + right;
1125
- }
1126
-
1127
- // Fast path: both are strings
1128
- if (typeof left === 'string' && typeof right === 'string') {
1129
- var leftLen = left.length;
1130
- var rightLen = right.length;
1131
-
1132
- var leftIsRef = refIdPattern.test(left);
1133
- var rightIsRef = refIdPattern.test(right);
1134
-
1135
- if (!leftIsRef && !rightIsRef) {
1136
- // Track memory if enabled
1137
- if (memoryLimit > 0) {
1138
- __host_memory_track__(rightLen * 2); // UTF-16 encoding
1139
- }
1140
- return left + right;
1141
- }
1142
-
1143
- // References detected - check if composites are allowed
1144
- if (!allowComposites) {
1145
- throw createSafeError(
1146
- 'Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +
1147
- 'Composite handles are disabled in the current security configuration.'
1148
- );
1149
- }
1150
-
1151
- return {
1152
- __type: 'composite',
1153
- __operation: 'concat',
1154
- __parts: [left, right],
1155
- __estimatedSize: 0
1156
- };
1157
- }
1158
-
1159
- // For mixed types (one string, one non-string), check for references first
1160
- // then use native + for proper ToPrimitive handling
1161
- if (typeof left === 'string' || typeof right === 'string') {
1162
- // Check if the string operand(s) are references BEFORE coercion
1163
- var leftIsRef = typeof left === 'string' && refIdPattern.test(left);
1164
- var rightIsRef = typeof right === 'string' && refIdPattern.test(right);
1165
-
1166
- if (leftIsRef || rightIsRef) {
1167
- // Reference detected - check if composites are allowed
1168
- if (!allowComposites) {
1169
- throw createSafeError(
1170
- 'Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +
1171
- 'Composite handles are disabled in the current security configuration.'
1172
- );
1173
- }
1174
-
1175
- // Convert both to strings for composite
1176
- var leftStr = String(left);
1177
- var rightStr = String(right);
1178
- return {
1179
- __type: 'composite',
1180
- __operation: 'concat',
1181
- __parts: [leftStr, rightStr],
1182
- __estimatedSize: 0
1183
- };
1184
- }
1185
- }
1186
-
1187
- // For all other cases (objects, booleans, null, undefined, or strings without refs),
1188
- // use JavaScript's default + behavior which correctly handles ToPrimitive
1189
- var result = left + right;
1190
-
1191
- // Track if result is a string
1192
- if (typeof result === 'string' && memoryLimit > 0) {
1193
- __host_memory_track__(result.length * 2);
1194
- }
1195
-
1196
- return result;
1197
- }
1198
-
1199
- /**
1200
- * Safe template literal for inner VM
1201
- * Detects reference IDs and handles them according to allowComposites config
1202
- */
1203
- function innerTemplate(quasis) {
1204
- var values = Array.prototype.slice.call(arguments, 1);
1205
- var parts = [];
1206
- var hasReferences = false;
1207
-
1208
- for (var i = 0; i < quasis.length; i++) {
1209
- parts.push(quasis[i]);
1210
- if (i < values.length) {
1211
- var valueStr = String(values[i]);
1212
- parts.push(valueStr);
1213
- if (refIdPattern.test(valueStr)) {
1214
- hasReferences = true;
1215
- }
1216
- }
1217
- }
1218
-
1219
- // If no references, just concatenate normally
1220
- if (!hasReferences) {
1221
- return parts.join('');
1222
- }
1223
-
1224
- // References detected - check if composites are allowed
1225
- if (!allowComposites) {
1226
- throw createSafeError(
1227
- 'Cannot concatenate reference IDs in template literals. Pass references directly to callTool arguments. ' +
1228
- 'Composite handles are disabled in the current security configuration.'
1229
- );
1230
- }
1231
-
1232
- // Create a composite handle for lazy resolution at callTool boundary
1233
- return {
1234
- __type: 'composite',
1235
- __operation: 'concat',
1236
- __parts: parts,
1237
- __estimatedSize: 0
1238
- };
1239
- }
1240
-
1241
- /**
1242
- * Safe parallel execution for inner VM
1243
- */
1244
- async function innerParallel(items, fn) {
1245
- if (!Array.isArray(items)) {
1246
- throw createSafeError('parallel() requires an array', 'TypeError');
1247
- }
1248
- if (typeof fn !== 'function') {
1249
- throw createSafeError('parallel() requires a callback function as second argument', 'TypeError');
1250
- }
1251
- if (items.length > 100) {
1252
- throw createSafeError('parallel() is limited to 100 items');
1253
- }
1254
- return await Promise.all(items.map(fn));
1255
- }
1256
-
1257
- /**
1258
- * Rate-limited console for inner VM
1259
- */
1260
- var consoleStats = { totalBytes: 0, callCount: 0 };
1261
- var maxConsoleBytes = hostConfig.maxConsoleOutputBytes || 65536;
1262
- var maxConsoleCalls = hostConfig.maxConsoleCalls || 100;
1263
-
1264
- function createSafeConsoleMethod(method) {
1265
- return function() {
1266
- consoleStats.callCount++;
1267
- if (consoleStats.callCount > maxConsoleCalls) {
1268
- throw createSafeError('Console call limit exceeded (max: ' + maxConsoleCalls + '). This limit prevents I/O flood attacks.');
1269
- }
1270
- var output = Array.prototype.map.call(arguments, function(a) {
1271
- if (a === undefined) return 'undefined';
1272
- if (a === null) return 'null';
1273
- if (typeof a === 'object') {
1274
- try { return JSON.stringify(a); } catch (e) { return String(a); }
1275
- }
1276
- return String(a);
1277
- }).join(' ');
1278
- consoleStats.totalBytes += output.length;
1279
- if (consoleStats.totalBytes > maxConsoleBytes) {
1280
- throw createSafeError('Console output size limit exceeded (max: ' + maxConsoleBytes + ' bytes). This limit prevents I/O flood attacks.');
1281
- }
1282
- method.apply(console, arguments);
1283
- };
1284
- }
1285
-
1286
- var innerConsole = {
1287
- log: createSafeConsoleMethod(console.log.bind(console)),
1288
- error: createSafeConsoleMethod(console.error.bind(console)),
1289
- warn: createSafeConsoleMethod(console.warn.bind(console)),
1290
- info: createSafeConsoleMethod(console.info.bind(console))
1291
- };
1292
-
1293
- // ============================================================
1294
- // Create Inner VM
1295
- // ============================================================
1296
-
1297
- // Create completely isolated context
1298
- // codeGeneration.strings=false disables new Function() and eval() from strings
1299
- // This prevents sandbox escape via constructor chain: [][c][c]('malicious code')
1300
- var innerContext = vm.createContext({}, {
1301
- codeGeneration: { strings: false, wasm: false }
1302
- });
1303
-
1304
- // STRICT/SECURE: record code-generation attempts (Function/eval) even if user code catches them.
1305
- if (${securityLevel === 'STRICT' || securityLevel === 'SECURE'}) {
1306
- try {
1307
- Object.defineProperty(innerContext, '__ag_reportViolation__', {
1308
- value: __ag_reportViolation,
1309
- writable: false,
1310
- configurable: false,
1311
- enumerable: false
1312
- });
1313
- var codeGenPatchScript = new vm.Script(${codeGenViolationDetectorCodeJson});
1314
- codeGenPatchScript.runInContext(innerContext);
1315
- } catch (e) { /* ignore */ }
1316
- }
1317
-
1318
- // Apply stack trace hardening to INNER VM realm (prevents error.stack leakage to user code).
1319
- if (sanitizeStackTraces) {
1320
- try {
1321
- var stackPatchScript = new vm.Script(${stackTraceHardeningCodeJson});
1322
- stackPatchScript.runInContext(innerContext);
1323
- } catch (e) { /* ignore */ }
1324
- }
1325
-
1326
- // CRITICAL: Inject memory-safe prototype methods BEFORE sanitization
1327
- // This must happen FIRST because sanitization may remove globals needed for patching.
1328
- // The patch needs the intrinsic Object.getPrototypeOf to access the VM's actual
1329
- // String.prototype and Array.prototype (not the global realm's).
1330
- // Security: Prevents ATK-JSON-03 (Parser Bomb) and similar attacks
1331
- // These checks happen BEFORE allocation, not after
1332
- //
1333
- // SECURITY FIX (Vector 320): Track CUMULATIVE memory usage across all allocations
1334
- // Previously only checked if single allocation exceeded limit, allowing attackers
1335
- // to create many smaller allocations that together exceed the limit.
1336
- // We use __host_memory_track__ to track cumulative memory in the host's MemoryTracker.
1337
- (function() {
1338
- var memoryLimit = hostConfig.memoryLimit || 0;
1339
- if (memoryLimit > 0) {
1340
- // First, inject the host memory tracking callback into innerContext
1341
- // This allows the patched methods to track cumulative memory
1342
- Object.defineProperty(innerContext, '__host_memory_track__', {
1343
- value: __host_memory_track__,
1344
- writable: false,
1345
- configurable: false,
1346
- enumerable: false
1347
- });
1348
-
1349
- // Run the patching code in innerContext
1350
- var patchCode = '(function() {' +
1351
- 'var memoryLimit = ' + memoryLimit + ';' +
1352
- 'var trackMemory = __host_memory_track__;' +
1353
- // Get the ACTUAL prototype used by literals in this realm
1354
- 'var stringProto = Object.getPrototypeOf("");' +
1355
- 'var arrayProto = Object.getPrototypeOf([]);' +
1356
- // Patch string repeat
1357
- 'var originalRepeat = stringProto.repeat;' +
1358
- 'stringProto.repeat = function(count) {' +
1359
- ' var estimatedSize = this.length * count * 2;' +
1360
- ' if (estimatedSize > memoryLimit) {' +
1361
- ' throw new RangeError("String.repeat would exceed memory limit: " +' +
1362
- ' Math.round(estimatedSize / 1024 / 1024) + "MB > " +' +
1363
- ' Math.round(memoryLimit / 1024 / 1024) + "MB");' +
1364
- ' }' +
1365
- ' trackMemory(estimatedSize);' +
1366
- ' return originalRepeat.call(this, count);' +
1367
- '};' +
1368
- // Patch array join
1369
- 'var originalJoin = arrayProto.join;' +
1370
- 'arrayProto.join = function(separator) {' +
1371
- ' var sep = separator === undefined ? "," : String(separator);' +
1372
- ' var estimatedSize = 0;' +
1373
- ' for (var i = 0; i < this.length; i++) {' +
1374
- ' var item = this[i];' +
1375
- ' estimatedSize += (item === null || item === undefined) ? 0 : String(item).length;' +
1376
- ' if (i > 0) estimatedSize += sep.length;' +
1377
- ' }' +
1378
- ' estimatedSize *= 2;' +
1379
- ' if (estimatedSize > memoryLimit) {' +
1380
- ' throw new RangeError("Array.join would exceed memory limit: " +' +
1381
- ' Math.round(estimatedSize / 1024 / 1024) + "MB > " +' +
1382
- ' Math.round(memoryLimit / 1024 / 1024) + "MB");' +
1383
- ' }' +
1384
- ' trackMemory(estimatedSize);' +
1385
- ' return originalJoin.call(this, separator);' +
1386
- '};' +
1387
- // Patch string padStart/padEnd
1388
- 'var originalPadStart = stringProto.padStart;' +
1389
- 'var originalPadEnd = stringProto.padEnd;' +
1390
- 'stringProto.padStart = function(targetLength, padString) {' +
1391
- ' var estimatedSize = Math.max(this.length, targetLength) * 2;' +
1392
- ' if (estimatedSize > memoryLimit) {' +
1393
- ' throw new RangeError("String.padStart would exceed memory limit");' +
1394
- ' }' +
1395
- ' trackMemory(estimatedSize);' +
1396
- ' return originalPadStart.call(this, targetLength, padString);' +
1397
- '};' +
1398
- 'stringProto.padEnd = function(targetLength, padString) {' +
1399
- ' var estimatedSize = Math.max(this.length, targetLength) * 2;' +
1400
- ' if (estimatedSize > memoryLimit) {' +
1401
- ' throw new RangeError("String.padEnd would exceed memory limit");' +
1402
- ' }' +
1403
- ' trackMemory(estimatedSize);' +
1404
- ' return originalPadEnd.call(this, targetLength, padString);' +
1405
- '};' +
1406
- // Patch array fill - converts sparse arrays to dense (allocates memory)
1407
- // Vector 1110/1170: Array(dynamicSize).fill() can exhaust memory
1408
- 'var originalFill = arrayProto.fill;' +
1409
- 'arrayProto.fill = function(value, start, end) {' +
1410
- ' var len = this.length >>> 0;' +
1411
- ' var relativeStart = start === undefined ? 0 : (start >> 0);' +
1412
- ' var relativeEnd = end === undefined ? len : (end >> 0);' +
1413
- ' var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len);' +
1414
- ' var finalEnd = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len);' +
1415
- ' var fillCount = Math.max(0, finalEnd - k);' +
1416
- ' var estimatedSize = fillCount * 8;' +
1417
- ' if (estimatedSize > memoryLimit) {' +
1418
- ' throw new RangeError("Array.fill would exceed memory limit: " +' +
1419
- ' Math.round(estimatedSize / 1024 / 1024) + "MB > " +' +
1420
- ' Math.round(memoryLimit / 1024 / 1024) + "MB");' +
1421
- ' }' +
1422
- ' trackMemory(estimatedSize);' +
1423
- ' return originalFill.call(this, value, start, end);' +
1424
- '};' +
1425
- '})();';
1426
- var patchScript = new vm.Script(patchCode);
1427
- patchScript.runInContext(innerContext);
1428
- }
1429
- })();
1430
-
1431
- // Remove dangerous globals from inner VM (AFTER memory patching)
1432
- ${sanitizeContextCode}
1433
-
1434
- // Freeze built-in prototypes to prevent prototype pollution
1435
- // and cut off constructor chain access for sandbox escape prevention
1436
- //
1437
- // We freeze prototypes in TWO places:
1438
- // 1. PARENT VM prototypes - because SafeObject.prototype = Object.prototype uses parent's prototype
1439
- // and user code accessing Object.prototype gets SafeObject.prototype
1440
- // 2. INNER VM prototypes - for string/array literals which use intrinsic prototypes
1441
- //
1442
- // This provides defense-in-depth against prototype pollution attacks.
1443
-
1444
- // Freeze PARENT VM prototypes (used by SafeObject and other safe globals)
1445
- Object.freeze(Object.prototype);
1446
- Object.freeze(Array.prototype);
1447
- Object.freeze(Function.prototype);
1448
- Object.freeze(String.prototype);
1449
- Object.freeze(Number.prototype);
1450
- Object.freeze(Boolean.prototype);
1451
- Object.freeze(Date.prototype);
1452
- Object.freeze(Error.prototype);
1453
- Object.freeze(TypeError.prototype);
1454
- Object.freeze(RangeError.prototype);
1455
- Object.freeze(SyntaxError.prototype);
1456
- Object.freeze(ReferenceError.prototype);
1457
- Object.freeze(Promise.prototype);
1458
-
1459
- // Freeze INNER VM prototypes (used by literals like '', [], etc.)
1460
- (function() {
1461
- var freezeCode =
1462
- 'Object.freeze(Object.prototype);' +
1463
- 'Object.freeze(Array.prototype);' +
1464
- 'Object.freeze(Function.prototype);' +
1465
- 'Object.freeze(String.prototype);' +
1466
- 'Object.freeze(Number.prototype);' +
1467
- 'Object.freeze(Boolean.prototype);' +
1468
- 'Object.freeze(Date.prototype);' +
1469
- 'Object.freeze(Error.prototype);' +
1470
- 'Object.freeze(TypeError.prototype);' +
1471
- 'Object.freeze(RangeError.prototype);' +
1472
- 'Object.freeze(SyntaxError.prototype);' +
1473
- 'Object.freeze(ReferenceError.prototype);' +
1474
- 'Object.freeze(Promise.prototype);';
1475
- var freezeScript = new vm.Script(freezeCode);
1476
- freezeScript.runInContext(innerContext);
1477
- })();
1478
-
1479
- // Inject safe runtime functions (non-writable, non-configurable)
1480
- // Wrap with secure proxy to block dangerous property access
1481
- var safeRuntime = {
1482
- __safe_callTool: createSecureProxy(innerCallTool),
1483
- __safe_forOf: createSecureProxy(innerForOf),
1484
- __safe_for: createSecureProxy(innerFor),
1485
- __safe_while: createSecureProxy(innerWhile),
1486
- __safe_doWhile: createSecureProxy(innerDoWhile),
1487
- __safe_parallel: createSecureProxy(innerParallel),
1488
- __safe_console: createSecureProxy(innerConsole),
1489
- callTool: createSecureProxy(innerCallTool),
1490
- parallel: createSecureProxy(innerParallel),
1491
- // Loop transformation runtime support
1492
- __maxIterations: ${maxIterations}
1493
- };
1494
-
1495
- // SECURITY FIX (Vector 640): Use enumerable: false to prevent valueOf context-hijack
1496
- // Attack uses arrow functions in valueOf hooks where "this" refers to global scope.
1497
- // Object.values(this) would enumerate all enumerable properties including internal
1498
- // functions, leaking their source code. Non-enumerable prevents this information leak.
1499
- for (var key in safeRuntime) {
1500
- if (safeRuntime.hasOwnProperty(key)) {
1501
- Object.defineProperty(innerContext, key, {
1502
- value: safeRuntime[key],
1503
- writable: false,
1504
- configurable: false,
1505
- enumerable: false
1506
- });
1507
- }
1508
- }
1509
-
1510
- // Define __safe_concat and __safe_template in the INNER realm to avoid cross-realm stacks.
1511
- // (See innerRealmSafeConcatAndTemplateCode for rationale.)
1512
- try {
1513
- var innerRuntimeScript = new vm.Script(${innerRealmSafeConcatAndTemplateCodeJson}, { filename: 'inner-runtime.js' });
1514
- innerRuntimeScript.runInContext(innerContext);
1515
- } catch (e) { /* ignore */ }
1516
-
1517
- // Create a safe Object that blocks dangerous STATIC methods
1518
- // Prevents ATK-DATA-02 (Serialization Hijack via defineProperty)
1519
- // Note: __defineGetter__ etc. are on Object.prototype (instance methods), not static
1520
- var DANGEROUS_OBJECT_STATIC_METHODS = [
1521
- 'defineProperty',
1522
- 'defineProperties',
1523
- 'setPrototypeOf',
1524
- 'getOwnPropertyDescriptor',
1525
- 'getOwnPropertyDescriptors'
1526
- ];
1527
-
1528
- var SafeObject = function(value) {
1529
- if (value === null || value === undefined) return {};
1530
- return Object(value);
1531
- };
1532
-
1533
- // Copy safe static methods
1534
- var safeObjectMethods = [
1535
- 'keys', 'values', 'entries', 'fromEntries', 'assign', 'is', 'hasOwn',
1536
- 'freeze', 'isFrozen', 'seal', 'isSealed', 'preventExtensions', 'isExtensible',
1537
- 'getOwnPropertyNames', 'getOwnPropertySymbols', 'getPrototypeOf'
1538
- ];
1539
- for (var i = 0; i < safeObjectMethods.length; i++) {
1540
- var m = safeObjectMethods[i];
1541
- if (m in Object) SafeObject[m] = Object[m];
1542
- }
1543
-
1544
- // Safe Object.create without property descriptors
1545
- SafeObject.create = function(proto, props) {
1546
- if (props !== undefined) {
1547
- throw createSafeError('Object.create with property descriptors is not allowed (security restriction)');
1548
- }
1549
- return Object.create(proto);
1550
- };
1551
-
1552
- SafeObject.prototype = Object.prototype;
1553
-
1554
- // Block dangerous methods with helpful errors
1555
- for (var i = 0; i < DANGEROUS_OBJECT_STATIC_METHODS.length; i++) {
1556
- (function(method) {
1557
- SafeObject[method] = function() {
1558
- throw createSafeError('Object.' + method + ' is not allowed (security restriction: prevents property manipulation attacks)');
1559
- };
1560
- })(DANGEROUS_OBJECT_STATIC_METHODS[i]);
1561
- }
1562
-
1563
- // Get INNER context's intrinsic constructors
1564
- // CRITICAL: We must use the inner context's Array/String/etc constructors
1565
- // so that objects created with new Array() use the patched prototypes.
1566
- // Using parent VM constructors would bypass our memory-safe prototype patches.
1567
- var innerIntrinsics = (function() {
1568
- var getIntrinsicsCode =
1569
- '({ ' +
1570
- ' Array: Array, ' +
1571
- ' String: String, ' +
1572
- ' Number: Number, ' +
1573
- ' Boolean: Boolean, ' +
1574
- ' Date: Date, ' +
1575
- ' RegExp: RegExp, ' +
1576
- ' Error: Error, ' +
1577
- ' TypeError: TypeError, ' +
1578
- ' RangeError: RangeError, ' +
1579
- ' Promise: Promise, ' +
1580
- ' Math: Math, ' +
1581
- ' JSON: JSON ' +
1582
- '})';
1583
- var script = new vm.Script(getIntrinsicsCode);
1584
- return script.runInContext(innerContext);
1585
- })();
1586
-
1587
- // Add safe standard globals wrapped with secure proxy
1588
- // Use inner context intrinsics for constructors to ensure patched prototypes are used
1589
- var safeGlobals = {
1590
- Math: createSecureProxy(innerIntrinsics.Math),
1591
- JSON: createSecureProxy(innerIntrinsics.JSON),
1592
- Array: createSecureProxy(innerIntrinsics.Array),
1593
- Object: createSecureProxy(SafeObject),
1594
- String: createSecureProxy(innerIntrinsics.String),
1595
- Number: createSecureProxy(innerIntrinsics.Number),
1596
- Date: createSecureProxy(innerIntrinsics.Date),
1597
- Boolean: createSecureProxy(innerIntrinsics.Boolean),
1598
- RegExp: createSecureProxy(innerIntrinsics.RegExp),
1599
- Error: createSecureProxy(innerIntrinsics.Error),
1600
- TypeError: createSecureProxy(innerIntrinsics.TypeError),
1601
- RangeError: createSecureProxy(innerIntrinsics.RangeError),
1602
- Promise: createSecureProxy(innerIntrinsics.Promise),
1603
- undefined: undefined,
1604
- NaN: NaN,
1605
- Infinity: Infinity,
1606
- isNaN: isNaN,
1607
- isFinite: isFinite,
1608
- parseInt: parseInt,
1609
- parseFloat: parseFloat,
1610
- encodeURI: encodeURI,
1611
- decodeURI: decodeURI,
1612
- encodeURIComponent: encodeURIComponent,
1613
- decodeURIComponent: decodeURIComponent
1614
- };
1615
-
1616
- // SECURITY FIX (Vector 640): Use enumerable: false for defense-in-depth
1617
- // While standard globals (Math, JSON, etc.) are less sensitive than internal functions,
1618
- // making them non-enumerable prevents Object.values(this) from revealing sandbox structure.
1619
- // Skip globals that the user is providing their own version of
1620
- for (var gKey in safeGlobals) {
1621
- if (safeGlobals.hasOwnProperty(gKey)) {
1622
- // If user provides this global, skip so their version takes precedence
1623
- if (hostConfig.globals && hostConfig.globals.hasOwnProperty(gKey)) {
1624
- continue;
1625
- }
1626
- Object.defineProperty(innerContext, gKey, {
1627
- value: safeGlobals[gKey],
1628
- writable: false,
1629
- configurable: false,
1630
- enumerable: false
1631
- });
1632
- }
1633
- }
1634
-
1635
- // Add user-provided globals if any (also wrapped with secure proxy and non-writable)
1636
- // SECURITY: Use enumerable: false to prevent Object.assign({}, this) from copying globals
1637
- // This blocks Vector 380 (Bridge-Serialized State Reflection) attack
1638
- if (hostConfig.globals) {
1639
- for (var uKey in hostConfig.globals) {
1640
- if (hostConfig.globals.hasOwnProperty(uKey)) {
1641
- var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey]);
1642
- Object.defineProperty(innerContext, uKey, {
1643
- value: wrappedGlobal,
1644
- writable: false,
1645
- configurable: false,
1646
- enumerable: false
1647
- });
1648
- // Also add __safe_ prefixed version
1649
- Object.defineProperty(innerContext, '__safe_' + uKey, {
1650
- value: wrappedGlobal,
1651
- writable: false,
1652
- configurable: false,
1653
- enumerable: false
1654
- });
1655
- }
1656
- }
1657
- }
1658
-
1659
- // ============================================================
1660
- // Execute User Code
1661
- // ============================================================
1662
-
1663
- var userCode = ${JSON.stringify(userCode)};
1664
- // IMPORTANT: For stack overflow errors (RangeError: Maximum call stack size exceeded),
1665
- // Node/V8 may ignore Error.prepareStackTrace when it was installed by a different Script
1666
- // than the one that triggered the overflow. To make stack sanitization reliable,
1667
- // we also prepend the hardening code into the same Script that executes user code.
1668
- var __ag_stackHardenPrefix = sanitizeStackTraces ? (${stackTraceHardeningCodeJson} + '\\n') : '';
1669
- var wrappedCode =
1670
- '(async function() { ' +
1671
- __ag_stackHardenPrefix +
1672
- userCode +
1673
- ' return typeof __ag_main === "function" ? await __ag_main() : undefined; })()';
1674
-
1675
- var script = new vm.Script(wrappedCode, { filename: 'inner-agentscript.js' });
1676
-
1677
- // SECURITY HARDENING: Disable vm module before running user code
1678
- // This prevents access to vm module even if user code escapes to parent context
1679
- // We null out the vm object's methods since we can't delete globals in strict mode
1680
- try {
1681
- vm.createContext = null;
1682
- vm.Script = null;
1683
- } catch (e) { /* ignore if properties are non-writable */ }
1684
-
1685
- // Note: codeGeneration is set in createContext(), not runInContext()
1686
- var result = await script.runInContext(innerContext, {
1687
- timeout: ${innerTimeout},
1688
- breakOnSigint: true
1689
- });
1690
-
1691
- return result;
1692
- })();
1693
- `.trim();
1694
- }
1695
- //# sourceMappingURL=parent-vm-bootstrap.js.map