@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,1140 +0,0 @@
1
- "use strict";
2
- /**
3
- * VM Adapter - Node.js vm module implementation
4
- *
5
- * Uses Node.js built-in vm module for sandboxed code execution.
6
- * Provides isolated execution context with controlled globals.
7
- *
8
- * @packageDocumentation
9
- */
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.VmAdapter = void 0;
12
- const tslib_1 = require("tslib");
13
- const vm = tslib_1.__importStar(require("vm"));
14
- const safe_runtime_1 = require("../safe-runtime");
15
- const secure_proxy_1 = require("../secure-proxy");
16
- const safe_error_1 = require("../safe-error");
17
- const memory_tracker_1 = require("../memory-tracker");
18
- const tool_bridge_1 = require("../tool-bridge");
19
- const value_sanitizer_1 = require("../value-sanitizer");
20
- /**
21
- * Sensitive patterns to redact from stack traces
22
- * Security: Prevents information leakage about host environment
23
- *
24
- * Categories covered:
25
- * - File system paths (Unix, Windows, UNC)
26
- * - Cloud environment variables and metadata
27
- * - Container/orchestration paths
28
- * - CI/CD system paths
29
- * - User home directories
30
- * - Secret/credential patterns
31
- * - Internal hostnames and IPs
32
- * - Package manager cache paths
33
- */
34
- const SENSITIVE_STACK_PATTERNS = [
35
- // Unix file system paths
36
- /\/Users\/[^/]+\/[^\s):]*/gi, // macOS home directories
37
- /\/home\/[^/]+\/[^\s):]*/gi, // Linux home directories
38
- /\/var\/[^\s):]*/gi, // System var directories
39
- /\/opt\/[^\s):]*/gi, // Optional software
40
- /\/tmp\/[^\s):]*/gi, // Temporary files
41
- /\/etc\/[^\s):]*/gi, // System configuration
42
- /\/root\/[^\s):]*/gi, // Root home directory
43
- /\/mnt\/[^\s):]*/gi, // Mount points
44
- /\/srv\/[^\s):]*/gi, // Service data
45
- /\/data\/[^\s):]*/gi, // Data directories
46
- /\/app\/[^\s):]*/gi, // Application directories
47
- /\/proc\/[^\s):]*/gi, // Process information
48
- /\/sys\/[^\s):]*/gi, // System files
49
- // Windows paths
50
- /\\\\[^\s):]*/g, // UNC paths
51
- /[A-Z]:\\[^\s):]+/gi, // Windows drive paths
52
- // URL-based paths
53
- /file:\/\/[^\s):]+/gi, // File URLs
54
- /webpack:\/\/[^\s):]+/gi, // Webpack paths
55
- /%2F[^\s):]+/gi, // URL-encoded paths
56
- // Package managers and node
57
- /node_modules\/[^\s):]+/gi, // Node modules paths
58
- /\/nix\/store\/[^\s):]*/gi, // Nix store paths
59
- /\.npm\/[^\s):]*/gi, // NPM cache
60
- /\.yarn\/[^\s):]*/gi, // Yarn cache
61
- /\.pnpm\/[^\s):]*/gi, // PNPM cache
62
- // Container and orchestration
63
- /\/run\/secrets\/[^\s):]*/gi, // Docker/K8s secrets
64
- /\/var\/run\/[^\s):]*/gi, // Runtime directories
65
- /\/docker\/[^\s):]*/gi, // Docker paths
66
- /\/containers\/[^\s):]*/gi, // Container paths
67
- /\/kubelet\/[^\s):]*/gi, // Kubernetes kubelet
68
- // CI/CD systems
69
- /\/github\/workspace\/[^\s):]*/gi, // GitHub Actions
70
- /\/runner\/[^\s):]*/gi, // GitHub/GitLab runner
71
- /\/builds\/[^\s):]*/gi, // CI builds
72
- /\/workspace\/[^\s):]*/gi, // Generic workspace
73
- /\/pipeline\/[^\s):]*/gi, // CI pipelines
74
- /\/jenkins\/[^\s):]*/gi, // Jenkins
75
- /\/bamboo\/[^\s):]*/gi, // Bamboo
76
- /\/teamcity\/[^\s):]*/gi, // TeamCity
77
- /\/circleci\/[^\s):]*/gi, // CircleCI
78
- // Cloud providers
79
- /\/aws\/[^\s):]*/gi, // AWS paths
80
- /\/gcloud\/[^\s):]*/gi, // Google Cloud
81
- /\/azure\/[^\s):]*/gi, // Azure paths
82
- /s3:\/\/[^\s):]+/gi, // S3 URIs
83
- /gs:\/\/[^\s):]+/gi, // GCS URIs
84
- // Secrets and credentials (patterns that might appear in paths or errors)
85
- /[A-Z0-9]{20,}/g, // AWS-style access keys (20+ uppercase chars)
86
- /sk-[a-zA-Z0-9]{32,}/g, // OpenAI/Stripe-style secret keys
87
- /ghp_[a-zA-Z0-9]{36,}/g, // GitHub personal access tokens
88
- /gho_[a-zA-Z0-9]{36,}/g, // GitHub OAuth tokens
89
- /github_pat_[a-zA-Z0-9_]{22,}/g, // GitHub fine-grained tokens
90
- /xox[baprs]-[a-zA-Z0-9-]+/g, // Slack tokens
91
- /Bearer\s+[a-zA-Z0-9._-]+/gi, // Bearer tokens
92
- /Basic\s+[a-zA-Z0-9+/=]+/gi, // Basic auth
93
- // Internal network info
94
- /(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g, // Private IPs
95
- /[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi, // Internal hostnames
96
- /localhost:\d+/gi, // Localhost with port
97
- /127\.0\.0\.1:\d+/gi, // Loopback with port
98
- // User information
99
- /\/u\/[^/]+\//gi, // User subdirectories
100
- /~[a-z_][a-z0-9_-]*/gi, // Unix user home shorthand
101
- ];
102
- /**
103
- * Sanitize stack trace by removing host file system paths
104
- * Security: Prevents information leakage about host environment
105
- *
106
- * When enabled (sanitize=true):
107
- * - Removes file paths from all supported platforms
108
- * - Redacts potential secrets and credentials
109
- * - Strips internal hostnames and IPs
110
- * - Removes line/column numbers for full anonymization
111
- *
112
- * Uses line-by-line processing with pre-checks to prevent ReDoS attacks.
113
- * The vulnerable pattern /at\s+(\S+)\s+\([^)]*:\d+:\d+\)/g can cause polynomial
114
- * backtracking on malicious input like "at ! (at ! (at ! (...".
115
- *
116
- * @param stack Original stack trace
117
- * @param sanitize Whether to sanitize (defaults to true)
118
- * @returns Sanitized stack trace (or original if sanitize=false)
119
- */
120
- function sanitizeStackTrace(stack, sanitize = true) {
121
- if (!stack)
122
- return stack;
123
- // Return unsanitized stack if disabled
124
- if (!sanitize)
125
- return stack;
126
- let sanitized = stack;
127
- // Apply all sensitive patterns
128
- for (const pattern of SENSITIVE_STACK_PATTERNS) {
129
- // Reset lastIndex for global patterns to ensure consistent behavior
130
- pattern.lastIndex = 0;
131
- sanitized = sanitized.replace(pattern, '[REDACTED]');
132
- }
133
- // Remove line/column numbers - process line by line with pre-checks to prevent ReDoS
134
- // Pre-checking the ending pattern before applying full regex avoids polynomial backtracking
135
- const lines = sanitized.split('\n');
136
- for (let i = 0; i < lines.length; i++) {
137
- const line = lines[i];
138
- // Defense-in-depth: skip very long lines
139
- if (line.length > 1000)
140
- continue;
141
- // Pattern 1: "at functionName (path:line:column)" format
142
- // Quick check: does line contain ":digits:digits)" pattern?
143
- if (/:\d+:\d+\)/.test(line)) {
144
- // Extract function name using indexOf to avoid regex backtracking
145
- const atIdx = line.indexOf('at ');
146
- if (atIdx !== -1) {
147
- const afterAt = line.substring(atIdx + 3).trimStart();
148
- const spaceIdx = afterAt.indexOf(' ');
149
- if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === '(') {
150
- const funcName = afterAt.substring(0, spaceIdx);
151
- lines[i] = line.substring(0, atIdx) + 'at ' + funcName + ' ([REDACTED])';
152
- continue;
153
- }
154
- }
155
- }
156
- // Pattern 2: "at path:line:column" format (no parentheses)
157
- if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
158
- lines[i] = line.replace(/:\d+:\d+$/, '') + '[REDACTED]';
159
- }
160
- }
161
- return lines.join('\n');
162
- }
163
- /**
164
- * Patch code executed inside the sandbox realm to prevent leaking host stack traces via `error.stack`.
165
- *
166
- * Note: This is intentionally conservative: it avoids emitting any file names/paths/line numbers
167
- * and also locks `Error.prepareStackTrace` to prevent CallSite-based exfiltration.
168
- */
169
- const STACK_TRACE_HARDENING_CODE = `
170
- (function() {
171
- function __ag_redactStackString(stackStr) {
172
- try {
173
- if (typeof stackStr !== 'string' || !stackStr) return 'Error';
174
- var lines = String(stackStr).split('\\n');
175
- var header = lines[0] ? String(lines[0]) : 'Error';
176
- var frameCount = (lines.length > 1) ? (lines.length - 1) : 0;
177
- var max = frameCount;
178
- if (max > 25) max = 25;
179
- var out = [header];
180
- for (var i = 0; i < max; i++) out.push(' at [REDACTED]');
181
- if (frameCount > max) out.push(' at [REDACTED]');
182
- return out.join('\\n');
183
- } catch (e) {
184
- return 'Error';
185
- }
186
- }
187
-
188
- function __ag_prepareStackTrace(err, stack) {
189
- try {
190
- var name = (err && err.name) ? String(err.name) : 'Error';
191
- var message = (err && err.message) ? String(err.message) : '';
192
- var header = message ? (name + ': ' + message) : name;
193
- if (!stack || !stack.length) return header;
194
- var lines = [header];
195
- var max = stack.length;
196
- if (max > 25) max = 25;
197
- for (var i = 0; i < max; i++) {
198
- lines.push(' at [REDACTED]');
199
- }
200
- if (stack.length > max) {
201
- lines.push(' at [REDACTED]');
202
- }
203
- return lines.join('\\n');
204
- } catch (e) {
205
- return 'Error';
206
- }
207
- }
208
-
209
- function __ag_lockStackGetter(proto) {
210
- if (!proto) return;
211
- try {
212
- var desc = Object.getOwnPropertyDescriptor(proto, 'stack');
213
- if (!desc || typeof desc.get !== 'function') return;
214
- var origGet = desc.get;
215
- var origSet = desc.set;
216
- Object.defineProperty(proto, 'stack', {
217
- get: function() {
218
- try {
219
- return __ag_redactStackString(origGet.call(this));
220
- } catch (e) {
221
- return 'Error';
222
- }
223
- },
224
- set: function(v) {
225
- try {
226
- if (typeof origSet === 'function') return origSet.call(this, v);
227
- } catch (e) {}
228
- },
229
- configurable: false,
230
- enumerable: false
231
- });
232
- } catch (e) {}
233
- }
234
-
235
- function __ag_lockPrepareStackTrace(ErrCtor) {
236
- if (!ErrCtor) return;
237
- try {
238
- Object.defineProperty(ErrCtor, 'prepareStackTrace', {
239
- value: __ag_prepareStackTrace,
240
- writable: false,
241
- configurable: false,
242
- enumerable: false
243
- });
244
- } catch (e) {}
245
- try {
246
- Object.defineProperty(ErrCtor, 'stackTraceLimit', {
247
- value: 25,
248
- writable: false,
249
- configurable: false,
250
- enumerable: false
251
- });
252
- } catch (e) {}
253
- }
254
-
255
- __ag_lockStackGetter(Error && Error.prototype);
256
- __ag_lockPrepareStackTrace(Error);
257
- __ag_lockPrepareStackTrace(EvalError);
258
- __ag_lockPrepareStackTrace(RangeError);
259
- __ag_lockPrepareStackTrace(ReferenceError);
260
- __ag_lockPrepareStackTrace(SyntaxError);
261
- __ag_lockPrepareStackTrace(TypeError);
262
- __ag_lockPrepareStackTrace(URIError);
263
- try {
264
- if (typeof AggregateError !== 'undefined') __ag_lockPrepareStackTrace(AggregateError);
265
- } catch (e) {}
266
- })();
267
- `.trim();
268
- const STACK_TRACE_HARDENING_SCRIPT = new vm.Script(STACK_TRACE_HARDENING_CODE);
269
- /**
270
- * Detect and report code-generation attempts (Function/eval) even if user code catches the thrown error.
271
- *
272
- * In STRICT/SECURE mode we treat these as policy violations and fail the execution after it returns.
273
- */
274
- const CODE_GENERATION_VIOLATION_DETECTOR_CODE = `
275
- (function() {
276
- var __ag_report = (typeof __ag_reportViolation__ === 'function') ? __ag_reportViolation__ : null;
277
- function __ag_reportOnce(kind) {
278
- try {
279
- if (__ag_report) __ag_report(kind);
280
- } catch (e) {}
281
- }
282
-
283
- // Capture intrinsics BEFORE any sanitization mutates globals like Reflect.
284
- var __ag_Reflect = (typeof Reflect !== 'undefined') ? Reflect : null;
285
- var __ag_Proxy = (typeof Proxy !== 'undefined') ? Proxy : null;
286
- var __ag_Object = (typeof Object !== 'undefined') ? Object : null;
287
-
288
- function __ag_wrapCtor(Ctor, kind) {
289
- if (!Ctor || !__ag_Proxy || !__ag_Reflect || !__ag_Object) return;
290
- try {
291
- var proxy = new __ag_Proxy(Ctor, {
292
- apply: function(target, thisArg, args) {
293
- __ag_reportOnce(kind);
294
- return __ag_Reflect.apply(target, thisArg, args);
295
- },
296
- construct: function(target, args, newTarget) {
297
- __ag_reportOnce(kind);
298
- return __ag_Reflect.construct(target, args, newTarget);
299
- }
300
- });
301
-
302
- // Ensure constructor-chain escapes (x.constructor.constructor) hit the proxy.
303
- try {
304
- if (Ctor.prototype) {
305
- __ag_Object.defineProperty(Ctor.prototype, 'constructor', {
306
- value: proxy,
307
- writable: false,
308
- configurable: false,
309
- enumerable: false
310
- });
311
- }
312
- } catch (e) {}
313
- } catch (e) {}
314
- }
315
-
316
- try { __ag_wrapCtor(Function, 'CODE_GENERATION'); } catch (e) {}
317
- try { __ag_wrapCtor((async function(){}).constructor, 'CODE_GENERATION'); } catch (e) {}
318
- try { __ag_wrapCtor((function*(){}).constructor, 'CODE_GENERATION'); } catch (e) {}
319
- try { __ag_wrapCtor((async function*(){}).constructor, 'CODE_GENERATION'); } catch (e) {}
320
- })();
321
- `.trim();
322
- const CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new vm.Script(CODE_GENERATION_VIOLATION_DETECTOR_CODE);
323
- /**
324
- * Protected identifier prefixes that cannot be modified from sandbox code
325
- * Security: Prevents runtime override attacks on safe functions
326
- */
327
- const PROTECTED_PREFIXES = ['__safe_', '__ag_'];
328
- /**
329
- * Create a rate-limited console wrapper
330
- * Security: Prevents I/O flood attacks via excessive console.log output
331
- *
332
- * @param config Configuration with maxConsoleOutputBytes and maxConsoleCalls
333
- * @param stats Mutable stats object to track output across all console methods
334
- * @returns Safe console object with rate limiting
335
- */
336
- function createSafeConsole(config, stats) {
337
- const wrap = (method) => (...args) => {
338
- // Check call count limit BEFORE doing any work
339
- stats.callCount++;
340
- if (stats.callCount > config.maxConsoleCalls) {
341
- throw (0, safe_error_1.createSafeError)(`Console call limit exceeded (max: ${config.maxConsoleCalls}). ` + `This limit prevents I/O flood attacks.`, 'SecurityError');
342
- }
343
- // Calculate output size
344
- const output = args
345
- .map((a) => {
346
- if (a === undefined)
347
- return 'undefined';
348
- if (a === null)
349
- return 'null';
350
- if (typeof a === 'object') {
351
- try {
352
- return JSON.stringify(a);
353
- }
354
- catch {
355
- return String(a);
356
- }
357
- }
358
- return String(a);
359
- })
360
- .join(' ');
361
- // Check output size limit
362
- stats.totalBytes += output.length;
363
- if (stats.totalBytes > config.maxConsoleOutputBytes) {
364
- throw (0, safe_error_1.createSafeError)(`Console output size limit exceeded (max: ${config.maxConsoleOutputBytes} bytes). ` +
365
- `This limit prevents I/O flood attacks.`, 'SecurityError');
366
- }
367
- // Safe to call the real console method
368
- method(...args);
369
- };
370
- return {
371
- log: wrap(console.log.bind(console)),
372
- error: wrap(console.error.bind(console)),
373
- warn: wrap(console.warn.bind(console)),
374
- info: wrap(console.info.bind(console)),
375
- };
376
- }
377
- /**
378
- * Check if an identifier is protected
379
- */
380
- function isProtectedIdentifier(prop) {
381
- if (typeof prop !== 'string')
382
- return false;
383
- return PROTECTED_PREFIXES.some((prefix) => prop.startsWith(prefix));
384
- }
385
- /**
386
- * Create a protected sandbox context using Proxy
387
- * Security: Prevents runtime reassignment of __safe_* and __ag_* functions
388
- *
389
- * @param sandbox The original VM context sandbox
390
- * @returns A proxy that protects reserved identifiers from modification
391
- */
392
- function createProtectedSandbox(sandbox) {
393
- return new Proxy(sandbox, {
394
- set(target, prop, value) {
395
- if (isProtectedIdentifier(prop)) {
396
- throw (0, safe_error_1.createSafeError)(`Cannot modify protected identifier "${String(prop)}". ` +
397
- `Identifiers starting with ${PROTECTED_PREFIXES.map((p) => `"${p}"`).join(', ')} are protected runtime functions.`, 'SecurityError');
398
- }
399
- return Reflect.set(target, prop, value);
400
- },
401
- defineProperty(target, prop, descriptor) {
402
- if (isProtectedIdentifier(prop)) {
403
- throw (0, safe_error_1.createSafeError)(`Cannot define protected identifier "${String(prop)}". ` +
404
- `Identifiers starting with ${PROTECTED_PREFIXES.map((p) => `"${p}"`).join(', ')} are protected runtime functions.`, 'SecurityError');
405
- }
406
- return Reflect.defineProperty(target, prop, descriptor);
407
- },
408
- deleteProperty(target, prop) {
409
- if (isProtectedIdentifier(prop)) {
410
- throw (0, safe_error_1.createSafeError)(`Cannot delete protected identifier "${String(prop)}". ` +
411
- `Identifiers starting with ${PROTECTED_PREFIXES.map((p) => `"${p}"`).join(', ')} are protected runtime functions.`, 'SecurityError');
412
- }
413
- return Reflect.deleteProperty(target, prop);
414
- },
415
- });
416
- }
417
- /**
418
- * Dangerous Object STATIC methods that allow property manipulation attacks
419
- * These methods can be used for:
420
- * - Serialization hijacking (defineProperty with toJSON)
421
- * - Prototype pollution (setPrototypeOf)
422
- * - Getter/setter injection (defineProperty, defineProperties)
423
- *
424
- * Note: __defineGetter__ etc. are on Object.prototype (instance methods),
425
- * not static methods on Object constructor. Those are blocked separately
426
- * on Object.prototype if needed.
427
- */
428
- const DANGEROUS_OBJECT_STATIC_METHODS = [
429
- 'defineProperty',
430
- 'defineProperties',
431
- 'setPrototypeOf',
432
- 'getOwnPropertyDescriptor', // Can retrieve defineProperty reference
433
- 'getOwnPropertyDescriptors', // Same
434
- ];
435
- /**
436
- * Create a safe Object global that removes dangerous methods
437
- * Prevents attacks like:
438
- * - ATK-DATA-02: Serialization Hijack via defineProperty('toJSON')
439
- * - Prototype pollution via setPrototypeOf
440
- * - Getter/setter injection
441
- *
442
- * @param originalObject The original Object constructor from VM context
443
- * @returns Safe Object with dangerous methods removed
444
- */
445
- function createSafeObject(originalObject) {
446
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
447
- const SafeObject = function (value) {
448
- // Support both Object() and new Object() calls
449
- if (value === null || value === undefined) {
450
- return {};
451
- }
452
- return Object(value);
453
- };
454
- // Copy all safe static methods from original Object
455
- const safeStaticMethods = [
456
- 'keys',
457
- 'values',
458
- 'entries',
459
- 'fromEntries',
460
- 'assign',
461
- 'is',
462
- 'hasOwn',
463
- 'freeze',
464
- 'isFrozen',
465
- 'seal',
466
- 'isSealed',
467
- 'preventExtensions',
468
- 'isExtensible',
469
- 'getOwnPropertyNames',
470
- 'getOwnPropertySymbols',
471
- 'getPrototypeOf', // Read-only, safe
472
- ];
473
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
474
- const origObj = originalObject;
475
- for (const method of safeStaticMethods) {
476
- if (method in origObj) {
477
- SafeObject[method] = origObj[method];
478
- }
479
- }
480
- // Provide a safe Object.create that only allows null or object as prototype
481
- // and does NOT allow property descriptors (second argument)
482
- SafeObject.create = function (proto, propertiesObject) {
483
- if (propertiesObject !== undefined) {
484
- throw (0, safe_error_1.createSafeError)('Object.create with property descriptors is not allowed (security restriction)', 'SecurityError');
485
- }
486
- return Object.create(proto);
487
- };
488
- // Copy prototype reference
489
- SafeObject.prototype = origObj.prototype;
490
- // Add blocked methods that throw helpful errors
491
- for (const method of DANGEROUS_OBJECT_STATIC_METHODS) {
492
- SafeObject[method] = function () {
493
- throw (0, safe_error_1.createSafeError)(`Object.${method} is not allowed (security restriction: prevents property manipulation attacks)`, 'SecurityError');
494
- };
495
- }
496
- return SafeObject;
497
- }
498
- /**
499
- * Node.js 24 dangerous globals that should be removed per security level
500
- * These globals can be used for various escape/attack vectors
501
- *
502
- * Defense-in-depth: Even though codeGeneration.strings=false blocks
503
- * new Function() from strings, removing Function entirely eliminates
504
- * any potential bypass vectors discovered in the future.
505
- *
506
- * ATK-RECON-01 identified these accessible globals as attack surface:
507
- * Function, eval, Proxy, Reflect, WeakRef, FinalizationRegistry,
508
- * SharedArrayBuffer, Atomics, gc, WebAssembly, globalThis
509
- */
510
- const NODEJS_24_DANGEROUS_GLOBALS = {
511
- STRICT: [
512
- // Code execution - CRITICAL
513
- 'Function', // Constructor for functions - primary escape vector
514
- 'eval', // Direct code execution
515
- 'globalThis', // Indirect access to all globals
516
- // Metaprogramming - sandbox escape vectors
517
- 'Proxy', // Can intercept all operations
518
- 'Reflect', // Metaprogramming primitive
519
- // Memory/timing attacks
520
- 'SharedArrayBuffer', // Spectre/timing attacks
521
- 'Atomics', // Shared memory operations
522
- 'gc', // Force garbage collection (shouldn't be exposed)
523
- // Future/experimental APIs
524
- 'Iterator', // Iterator helpers
525
- 'AsyncIterator', // Async iterator helpers
526
- 'ShadowRealm', // New realm creation (major escape risk)
527
- 'WeakRef', // Can observe GC behavior
528
- 'FinalizationRegistry', // Can observe GC behavior
529
- 'performance', // Timing information
530
- 'Temporal', // New date/time API
531
- ],
532
- SECURE: [
533
- // Code execution - CRITICAL
534
- 'Function',
535
- 'eval',
536
- 'globalThis',
537
- // Most dangerous metaprogramming
538
- 'Proxy',
539
- // Memory/timing attacks
540
- 'SharedArrayBuffer',
541
- 'Atomics',
542
- 'gc',
543
- // Future APIs
544
- 'Iterator',
545
- 'AsyncIterator',
546
- 'ShadowRealm',
547
- 'WeakRef',
548
- 'FinalizationRegistry',
549
- ],
550
- STANDARD: [
551
- // Code execution - always block these
552
- 'Function',
553
- 'eval',
554
- // Memory/timing attacks
555
- 'SharedArrayBuffer',
556
- 'Atomics',
557
- 'gc',
558
- // Definitely dangerous
559
- 'ShadowRealm',
560
- 'WeakRef',
561
- 'FinalizationRegistry',
562
- ],
563
- PERMISSIVE: [
564
- // Even PERMISSIVE should block the most dangerous
565
- 'ShadowRealm', // Too dangerous to allow
566
- 'gc', // Shouldn't be exposed at all
567
- 'SharedArrayBuffer', // Spectre risk
568
- 'Atomics', // Goes with SharedArrayBuffer
569
- ],
570
- };
571
- /**
572
- * Sanitize VM context by removing dangerous Node.js 24 globals
573
- * Security: Prevents escape via new APIs like Iterator helpers, ShadowRealm, etc.
574
- *
575
- * @param context The VM context to sanitize
576
- * @param securityLevel The security level to determine which globals to remove
577
- */
578
- function sanitizeVmContext(context, securityLevel) {
579
- const globalsToRemove = NODEJS_24_DANGEROUS_GLOBALS[securityLevel];
580
- for (const global of globalsToRemove) {
581
- // Delete the global if it exists in the context
582
- if (global in context) {
583
- try {
584
- delete context[global];
585
- }
586
- catch {
587
- // Some globals may be non-configurable, set to undefined instead
588
- try {
589
- context[global] = undefined;
590
- }
591
- catch {
592
- // Ignore if we can't modify it
593
- }
594
- }
595
- }
596
- }
597
- // For security levels that allow Reflect, provide a safe version
598
- if (securityLevel !== 'STRICT') {
599
- const safeReflect = (0, secure_proxy_1.createSafeReflect)(securityLevel);
600
- if (safeReflect) {
601
- Object.defineProperty(context, 'Reflect', {
602
- value: safeReflect,
603
- writable: false,
604
- configurable: false,
605
- enumerable: true,
606
- });
607
- }
608
- }
609
- // Add safe Object to the context that blocks dangerous methods
610
- // Security: Prevents ATK-DATA-02 (Serialization Hijack via defineProperty)
611
- // Note: We use the global Object to create SafeObject, then add it to context
612
- // This shadows the internal V8 Object global with our safe version
613
- const safeObject = createSafeObject(Object);
614
- Object.defineProperty(context, 'Object', {
615
- value: safeObject,
616
- writable: false,
617
- configurable: false,
618
- enumerable: true,
619
- });
620
- }
621
- /**
622
- * VM-based sandbox adapter
623
- *
624
- * Uses Node.js vm module to execute AgentScript code in an isolated context.
625
- * Injects safe runtime wrappers and controls available globals.
626
- */
627
- class VmAdapter {
628
- context;
629
- securityLevel;
630
- constructor(securityLevel = 'STANDARD') {
631
- this.securityLevel = securityLevel;
632
- }
633
- /**
634
- * Execute code in the VM sandbox
635
- *
636
- * @param code Transformed AgentScript code to execute
637
- * @param executionContext Execution context with config and handlers
638
- * @returns Execution result
639
- */
640
- async execute(code, executionContext) {
641
- const { stats, config } = executionContext;
642
- const startTime = Date.now();
643
- // Create memory tracker if memory limit is configured
644
- // This tracks string/array allocations and enforces the limit
645
- const memoryTracker = config.memoryLimit && config.memoryLimit > 0
646
- ? new memory_tracker_1.MemoryTracker({
647
- memoryLimit: config.memoryLimit,
648
- trackStrings: true,
649
- trackArrays: true,
650
- trackObjects: false, // Object tracking has higher overhead, skip for now
651
- })
652
- : undefined;
653
- // Start tracking before execution
654
- memoryTracker?.start();
655
- try {
656
- // Create safe runtime context with optional sidecar support and proxy config
657
- const safeRuntime = (0, safe_runtime_1.createSafeRuntime)(executionContext, {
658
- sidecar: executionContext.sidecar,
659
- referenceConfig: executionContext.referenceConfig,
660
- secureProxyConfig: executionContext.secureProxyConfig,
661
- memoryTracker, // Pass tracker for allocation monitoring
662
- });
663
- // Create sandbox context with safe globals only
664
- // IMPORTANT: Use empty object to get NEW isolated prototypes
665
- // codeGeneration.strings=false disables new Function() and eval() from strings
666
- // This prevents sandbox escape via constructor chain: [][c][c]('malicious code')
667
- const baseSandbox = vm.createContext({}, {
668
- codeGeneration: { strings: false, wasm: false },
669
- });
670
- // CRITICAL: Inject memory-safe prototype methods BEFORE sanitizeVmContext
671
- // This must happen FIRST because sanitizeVmContext replaces the intrinsic Object
672
- // with SafeObject. The patch needs the intrinsic Object.getPrototypeOf to access
673
- // the VM's actual String.prototype and Array.prototype (not the global realm's).
674
- // Security: Prevents ATK-JSON-03 (Parser Bomb) and similar attacks
675
- // that use repeat()/join() to allocate massive strings before we can track them
676
- // The check happens BEFORE allocation, not after
677
- //
678
- // SECURITY FIX (Vector 320): Track CUMULATIVE memory usage across all allocations
679
- // Previously only checked if single allocation exceeded limit, allowing attackers
680
- // to create many smaller allocations that together exceed the limit.
681
- if (memoryTracker && config.memoryLimit && config.memoryLimit > 0) {
682
- // Inject memory tracking callback into the sandbox
683
- // This allows the patched methods to track cumulative memory in the host
684
- Object.defineProperty(baseSandbox, '__host_memory_track__', {
685
- value: (bytes) => {
686
- memoryTracker.track(bytes);
687
- },
688
- writable: false,
689
- configurable: false,
690
- enumerable: false,
691
- });
692
- const patchScript = new vm.Script(`
693
- (function() {
694
- var memoryLimit = ${config.memoryLimit};
695
- var trackMemory = __host_memory_track__;
696
-
697
- // Get the ACTUAL prototype used by string literals in this realm
698
- // Using Object.getPrototypeOf('') gets the intrinsic String.prototype
699
- var stringProto = Object.getPrototypeOf('');
700
- var arrayProto = Object.getPrototypeOf([]);
701
-
702
- // Patch string repeat - primary attack vector for string bombs
703
- var originalRepeat = stringProto.repeat;
704
- stringProto.repeat = function(count) {
705
- // Pre-check: estimate size BEFORE allocation
706
- var estimatedSize = this.length * count * 2; // 2 bytes per char (UTF-16)
707
- // Check single allocation limit
708
- if (estimatedSize > memoryLimit) {
709
- throw new RangeError('String.repeat would exceed memory limit: ' +
710
- Math.round(estimatedSize / 1024 / 1024) + 'MB > ' +
711
- Math.round(memoryLimit / 1024 / 1024) + 'MB');
712
- }
713
- // Track cumulative memory BEFORE allocation (throws if limit exceeded)
714
- trackMemory(estimatedSize);
715
- return originalRepeat.call(this, count);
716
- };
717
-
718
- // Patch array join - can create huge strings from large arrays
719
- var originalJoin = arrayProto.join;
720
- arrayProto.join = function(separator) {
721
- // Estimate: separator between each element + element string lengths
722
- var sep = separator === undefined ? ',' : String(separator);
723
- var estimatedSize = 0;
724
- for (var i = 0; i < this.length; i++) {
725
- var item = this[i];
726
- estimatedSize += (item === null || item === undefined) ? 0 : String(item).length;
727
- if (i > 0) estimatedSize += sep.length;
728
- }
729
- estimatedSize *= 2; // UTF-16
730
-
731
- // Check single allocation limit
732
- if (estimatedSize > memoryLimit) {
733
- throw new RangeError('Array.join would exceed memory limit: ' +
734
- Math.round(estimatedSize / 1024 / 1024) + 'MB > ' +
735
- Math.round(memoryLimit / 1024 / 1024) + 'MB');
736
- }
737
- // Track cumulative memory BEFORE allocation (throws if limit exceeded)
738
- trackMemory(estimatedSize);
739
- return originalJoin.call(this, separator);
740
- };
741
-
742
- // Patch string padStart/padEnd - can pad to huge sizes
743
- var originalPadStart = stringProto.padStart;
744
- var originalPadEnd = stringProto.padEnd;
745
-
746
- stringProto.padStart = function(targetLength, padString) {
747
- var estimatedSize = Math.max(this.length, targetLength) * 2;
748
- if (estimatedSize > memoryLimit) {
749
- throw new RangeError('String.padStart would exceed memory limit');
750
- }
751
- // Track cumulative memory BEFORE allocation (throws if limit exceeded)
752
- trackMemory(estimatedSize);
753
- return originalPadStart.call(this, targetLength, padString);
754
- };
755
-
756
- stringProto.padEnd = function(targetLength, padString) {
757
- var estimatedSize = Math.max(this.length, targetLength) * 2;
758
- if (estimatedSize > memoryLimit) {
759
- throw new RangeError('String.padEnd would exceed memory limit');
760
- }
761
- // Track cumulative memory BEFORE allocation (throws if limit exceeded)
762
- trackMemory(estimatedSize);
763
- return originalPadEnd.call(this, targetLength, padString);
764
- };
765
-
766
- // Patch array fill - converts sparse arrays to dense (allocates memory)
767
- // Vector 1110/1170: Array(dynamicSize).fill() can exhaust memory
768
- // Estimate: each element uses ~8 bytes (pointer) for objects/primitives
769
- var originalFill = arrayProto.fill;
770
- arrayProto.fill = function(value, start, end) {
771
- // Calculate actual fill range
772
- var len = this.length >>> 0;
773
- var relativeStart = start === undefined ? 0 : (start >> 0);
774
- var relativeEnd = end === undefined ? len : (end >> 0);
775
- var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len);
776
- var finalEnd = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len);
777
- var fillCount = Math.max(0, finalEnd - k);
778
-
779
- // Estimate memory: 8 bytes per element (pointer size)
780
- // For objects/arrays as fill value, each creates a reference
781
- var estimatedSize = fillCount * 8;
782
-
783
- // Check single allocation limit
784
- if (estimatedSize > memoryLimit) {
785
- throw new RangeError('Array.fill would exceed memory limit: ' +
786
- Math.round(estimatedSize / 1024 / 1024) + 'MB > ' +
787
- Math.round(memoryLimit / 1024 / 1024) + 'MB');
788
- }
789
- // Track cumulative memory BEFORE allocation (throws if limit exceeded)
790
- trackMemory(estimatedSize);
791
- return originalFill.call(this, value, start, end);
792
- };
793
- })();
794
- `);
795
- patchScript.runInContext(baseSandbox);
796
- }
797
- // SECURITY HARDENING: prevent leaking host stack traces via error.stack inside the sandbox.
798
- // Must run BEFORE sanitizeVmContext() replaces Object with SafeObject (which blocks defineProperty).
799
- const shouldHardenStacks = config.sanitizeStackTraces ?? true;
800
- if (shouldHardenStacks) {
801
- try {
802
- STACK_TRACE_HARDENING_SCRIPT.runInContext(baseSandbox);
803
- }
804
- catch {
805
- // Ignore if the environment forbids patching (defense-in-depth only)
806
- }
807
- }
808
- // STRICT/SECURE: record code-generation attempts (Function/eval) even if caught.
809
- // This prevents reconnaissance loops that probe blocked primitives and then "return success".
810
- const isStrictOrSecure = this.securityLevel === 'STRICT' || this.securityLevel === 'SECURE';
811
- const policyViolation = {};
812
- if (isStrictOrSecure) {
813
- Object.defineProperty(baseSandbox, '__ag_reportViolation__', {
814
- value: (type) => {
815
- if (!policyViolation.type)
816
- policyViolation.type = String(type);
817
- },
818
- writable: false,
819
- configurable: false,
820
- enumerable: false,
821
- });
822
- try {
823
- CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT.runInContext(baseSandbox);
824
- }
825
- catch {
826
- // Best-effort only; codeGeneration.strings=false still blocks execution.
827
- }
828
- }
829
- // Sanitize the VM context by removing dangerous Node.js 24 globals
830
- // Security: Prevents escape via Iterator helpers, ShadowRealm, etc.
831
- sanitizeVmContext(baseSandbox, this.securityLevel);
832
- // TOOL BRIDGE (string mode): define __safe_callTool inside the VM realm and
833
- // communicate with the host tool handler via JSON string envelopes.
834
- if (config.toolBridge?.mode === 'string') {
835
- const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
836
- const hostToolBridge = (0, tool_bridge_1.createHostToolBridge)(executionContext, { updateStats: true });
837
- Object.defineProperty(baseSandbox, '__host_callToolBridge__', {
838
- value: hostToolBridge,
839
- writable: false,
840
- configurable: true, // allow deletion after capture
841
- enumerable: false,
842
- });
843
- const bridgeInitScript = new vm.Script(`
844
- (function() {
845
- var bridge = __host_callToolBridge__;
846
- var stringify = JSON.stringify;
847
- var parse = JSON.parse;
848
- var hasOwn = Object.prototype.hasOwnProperty;
849
- var maxBytes = ${maxPayloadBytes};
850
-
851
- // Remove global handle after capture (defense-in-depth)
852
- try { delete globalThis.__host_callToolBridge__; } catch (e) { /* ignore */ }
853
-
854
- function estimateBytes(str) {
855
- // Conservative: UTF-8 can be up to 4 bytes per code unit.
856
- return str.length * 4;
857
- }
858
-
859
- function makeError(message, name) {
860
- var err = new Error(message);
861
- if (name) err.name = name;
862
- return err;
863
- }
864
-
865
- return async function __safe_callTool(toolName, args) {
866
- if (typeof toolName !== 'string' || !toolName) {
867
- throw makeError('Tool name must be a non-empty string', 'TypeError');
868
- }
869
- if (typeof args !== 'object' || args === null || Array.isArray(args)) {
870
- throw makeError('Tool arguments must be an object', 'TypeError');
871
- }
872
- if (typeof bridge !== 'function') {
873
- throw makeError('Tool bridge is not available', 'Error');
874
- }
875
-
876
- // Defense-in-depth: ensure JSON-serializable input.
877
- var sanitizedArgs;
878
- try {
879
- sanitizedArgs = parse(stringify(args));
880
- } catch (e) {
881
- throw makeError('Tool arguments must be JSON-serializable', 'TypeError');
882
- }
883
-
884
- var requestJson;
885
- try {
886
- requestJson = stringify({ v: 1, tool: toolName, args: sanitizedArgs });
887
- } catch (e) {
888
- throw makeError('Tool request must be JSON-serializable', 'TypeError');
889
- }
890
-
891
- if (estimateBytes(requestJson) > maxBytes) {
892
- throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
893
- }
894
-
895
- var responseJson = await bridge(requestJson);
896
- if (typeof responseJson !== 'string') {
897
- throw makeError('Tool bridge returned invalid response', 'Error');
898
- }
899
- if (estimateBytes(responseJson) > maxBytes) {
900
- throw makeError('Tool response exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
901
- }
902
-
903
- var response;
904
- try {
905
- response = parse(responseJson);
906
- } catch (e) {
907
- throw makeError('Tool bridge returned invalid JSON', 'Error');
908
- }
909
-
910
- if (!response || typeof response !== 'object' || Array.isArray(response) || response.v !== 1) {
911
- throw makeError('Tool bridge returned invalid response', 'Error');
912
- }
913
-
914
- if (response.ok === true) {
915
- if (hasOwn.call(response, 'value')) return response.value;
916
- return undefined;
917
- }
918
-
919
- if (response.ok === false && response.error) {
920
- var msg = (typeof response.error.message === 'string') ? response.error.message : 'Tool call failed';
921
- var name = (typeof response.error.name === 'string') ? response.error.name : 'Error';
922
- throw makeError(msg, name);
923
- }
924
-
925
- throw makeError('Tool bridge returned invalid response', 'Error');
926
- };
927
- })()
928
- `);
929
- const vmSafeCallTool = bridgeInitScript.runInContext(baseSandbox);
930
- const proxiedVmSafeCallTool = (0, secure_proxy_1.createSecureProxy)(vmSafeCallTool, {
931
- levelConfig: executionContext.secureProxyConfig,
932
- });
933
- Object.defineProperty(baseSandbox, '__safe_callTool', {
934
- value: proxiedVmSafeCallTool,
935
- writable: false,
936
- configurable: false,
937
- enumerable: true,
938
- });
939
- // Best-effort cleanup if init script couldn't delete it for any reason.
940
- try {
941
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
942
- delete baseSandbox.__host_callToolBridge__;
943
- }
944
- catch {
945
- // ignore
946
- }
947
- }
948
- // Add safe runtime functions to the isolated context as non-writable, non-configurable
949
- // Security: Prevents runtime override attacks on __safe_* functions
950
- // Note: Skip 'Object' if already added by sanitizeVmContext (with SafeObject)
951
- for (const [key, value] of Object.entries(safeRuntime)) {
952
- // Skip if property is already defined (e.g., Object was added by sanitizeVmContext)
953
- if (key in baseSandbox)
954
- continue;
955
- Object.defineProperty(baseSandbox, key, {
956
- value: value,
957
- writable: false,
958
- configurable: false,
959
- enumerable: true,
960
- });
961
- }
962
- // Add user-provided globals (if any)
963
- // Security: Wrap ALL custom globals with secure proxy to prevent prototype chain attacks
964
- // This blocks access to __proto__, constructor, and other dangerous properties
965
- // SECURITY: Use enumerable: false to prevent Object.assign({}, this) from copying globals
966
- // This blocks Vector 380 (Bridge-Serialized State Reflection) attack
967
- if (config.globals) {
968
- for (const [key, value] of Object.entries(config.globals)) {
969
- // Only proxy objects, primitives are safe as-is
970
- const wrappedValue = value !== null && typeof value === 'object'
971
- ? (0, secure_proxy_1.createSecureProxy)(value, {
972
- levelConfig: executionContext.secureProxyConfig,
973
- })
974
- : value;
975
- Object.defineProperty(baseSandbox, key, {
976
- value: wrappedValue,
977
- writable: false,
978
- configurable: false,
979
- enumerable: false,
980
- });
981
- }
982
- }
983
- // Add __safe_console with rate limiting to prevent I/O flood attacks
984
- // Security: Limits total output bytes and call count
985
- // Note: The agentscript transformer converts `console` → `__safe_console` in whitelist mode
986
- // Skip if user already provided console via globals (already added with __safe_ prefix by safeRuntime)
987
- if (!('__safe_console' in safeRuntime)) {
988
- const consoleStats = { totalBytes: 0, callCount: 0 };
989
- Object.defineProperty(baseSandbox, '__safe_console', {
990
- value: createSafeConsole({
991
- maxConsoleOutputBytes: config.maxConsoleOutputBytes,
992
- maxConsoleCalls: config.maxConsoleCalls,
993
- }, consoleStats),
994
- writable: false,
995
- configurable: false,
996
- enumerable: true,
997
- });
998
- }
999
- // Wrap sandbox in protective Proxy to catch dynamic assignment attempts
1000
- // Security: Prevents dynamic assignment like `this['__safe_callTool'] = malicious`
1001
- // Note: Cannot use the Proxy as vm.runInContext requires the actual vm.Context
1002
- // The Proxy protection is applied but the underlying context is still used for execution
1003
- const _protectedSandbox = createProtectedSandbox(baseSandbox);
1004
- // Store context reference for disposal
1005
- // Note: Each execute() call creates a fresh context for isolation
1006
- // The stored reference is only used by dispose() for cleanup
1007
- this.context = baseSandbox;
1008
- // Wrap code in async IIFE to handle top-level await
1009
- const wrappedCode = `
1010
- (async () => {
1011
- ${code}
1012
- return typeof __ag_main === 'function' ? await __ag_main() : undefined;
1013
- })();
1014
- `;
1015
- // Compile script
1016
- const script = new vm.Script(wrappedCode, {
1017
- filename: 'agentscript.js',
1018
- });
1019
- // Execute script with timeout
1020
- // Note: codeGeneration is set in createContext(), not runInContext()
1021
- const resultPromise = script.runInContext(this.context, {
1022
- timeout: config.timeout,
1023
- breakOnSigint: true,
1024
- });
1025
- // Wait for result
1026
- const value = await resultPromise;
1027
- // Update stats
1028
- stats.duration = Date.now() - startTime;
1029
- stats.endTime = Date.now();
1030
- // Capture memory usage if tracking was enabled
1031
- if (memoryTracker) {
1032
- const memSnapshot = memoryTracker.getSnapshot();
1033
- stats.memoryUsage = memSnapshot.peakTrackedBytes;
1034
- }
1035
- // STRICT/SECURE: Fail closed on recorded policy violations even if user code caught them.
1036
- if (isStrictOrSecure && policyViolation.type) {
1037
- return {
1038
- success: false,
1039
- error: {
1040
- name: 'SecurityViolationError',
1041
- message: 'Blocked operation: security policy violation',
1042
- code: 'SECURITY_VIOLATION',
1043
- data: { type: policyViolation.type },
1044
- },
1045
- stats,
1046
- };
1047
- }
1048
- // SECURITY FIX (Vector 340): Check serialized size of return value BEFORE returning.
1049
- // Attacks can create structures with many references to the same large string that
1050
- // appear small in memory (strings are shared by reference) but explode during
1051
- // JSON serialization when each reference becomes a full copy.
1052
- // Example: 500 refs × 5 copies × 10KB = 25MB serialized from ~20KB in-memory
1053
- if (config.memoryLimit && config.memoryLimit > 0 && value !== undefined) {
1054
- // Use memory limit as serialization limit (or a reasonable cap)
1055
- // This prevents the serialization size from exceeding what we'd allow in memory
1056
- const maxSerializedBytes = Math.min(config.memoryLimit, 50 * 1024 * 1024); // Cap at 50MB
1057
- const sizeCheck = (0, value_sanitizer_1.checkSerializedSize)(value, maxSerializedBytes);
1058
- if (!sizeCheck.ok) {
1059
- return {
1060
- success: false,
1061
- error: {
1062
- name: 'MemoryLimitError',
1063
- message: `Return value serialization would exceed memory limit: ${sizeCheck.error}`,
1064
- code: 'SERIALIZATION_LIMIT_EXCEEDED',
1065
- },
1066
- stats,
1067
- };
1068
- }
1069
- }
1070
- // Sanitize the return value to convert Error objects to { name, message } format
1071
- // This prevents Error objects from serializing to {} and provides useful error info
1072
- // Use security-config-backed values, clamped to allowed ranges (depth: 5-50, properties: 50-1000)
1073
- // Apply sane defaults first to avoid NaN when config values are undefined
1074
- const depthDefaulted = config.maxSanitizeDepth ?? 20;
1075
- const propsDefaulted = config.maxSanitizeProperties ?? 100;
1076
- const clampedDepth = Math.max(5, Math.min(50, depthDefaulted));
1077
- const clampedProperties = Math.max(50, Math.min(1000, propsDefaulted));
1078
- const sanitizedValue = (0, value_sanitizer_1.sanitizeValue)(value, {
1079
- maxDepth: clampedDepth,
1080
- maxProperties: clampedProperties,
1081
- allowDates: true,
1082
- allowErrors: true,
1083
- });
1084
- return {
1085
- success: true,
1086
- value: sanitizedValue,
1087
- stats,
1088
- };
1089
- }
1090
- catch (error) {
1091
- const err = error;
1092
- // Update stats
1093
- stats.duration = Date.now() - startTime;
1094
- stats.endTime = Date.now();
1095
- // Capture memory usage even on error
1096
- if (memoryTracker) {
1097
- const memSnapshot = memoryTracker.getSnapshot();
1098
- stats.memoryUsage = memSnapshot.peakTrackedBytes;
1099
- }
1100
- // Handle memory limit errors specially
1101
- if (err instanceof memory_tracker_1.MemoryLimitError) {
1102
- return {
1103
- success: false,
1104
- error: {
1105
- name: 'MemoryLimitError',
1106
- message: err.message,
1107
- code: 'MEMORY_LIMIT_EXCEEDED',
1108
- data: {
1109
- usedBytes: err.usedBytes,
1110
- limitBytes: err.limitBytes,
1111
- },
1112
- },
1113
- stats,
1114
- };
1115
- }
1116
- // Determine whether to sanitize stack traces based on config
1117
- // Default to true for backwards compatibility if not explicitly set
1118
- const shouldSanitize = config.sanitizeStackTraces ?? true;
1119
- return {
1120
- success: false,
1121
- error: {
1122
- name: err.name || 'VMExecutionError',
1123
- message: err.message || 'Unknown VM execution error',
1124
- stack: sanitizeStackTrace(err.stack, shouldSanitize),
1125
- code: 'VM_EXECUTION_ERROR',
1126
- },
1127
- stats,
1128
- };
1129
- }
1130
- }
1131
- /**
1132
- * Dispose the VM context and cleanup resources
1133
- */
1134
- dispose() {
1135
- // VM contexts are garbage collected automatically
1136
- this.context = undefined;
1137
- }
1138
- }
1139
- exports.VmAdapter = VmAdapter;
1140
- //# sourceMappingURL=vm-adapter.js.map