@enclave-vm/core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +732 -0
  3. package/SECURITY-AUDIT.md +916 -0
  4. package/package.json +59 -0
  5. package/src/adapters/vm-adapter.d.ts +32 -0
  6. package/src/adapters/vm-adapter.js +1140 -0
  7. package/src/adapters/vm-adapter.js.map +1 -0
  8. package/src/adapters/worker-pool/config.d.ts +149 -0
  9. package/src/adapters/worker-pool/config.js +129 -0
  10. package/src/adapters/worker-pool/config.js.map +1 -0
  11. package/src/adapters/worker-pool/errors.d.ts +109 -0
  12. package/src/adapters/worker-pool/errors.js +181 -0
  13. package/src/adapters/worker-pool/errors.js.map +1 -0
  14. package/src/adapters/worker-pool/execution-queue.d.ts +85 -0
  15. package/src/adapters/worker-pool/execution-queue.js +179 -0
  16. package/src/adapters/worker-pool/execution-queue.js.map +1 -0
  17. package/src/adapters/worker-pool/index.d.ts +48 -0
  18. package/src/adapters/worker-pool/index.js +73 -0
  19. package/src/adapters/worker-pool/index.js.map +1 -0
  20. package/src/adapters/worker-pool/memory-monitor.d.ts +106 -0
  21. package/src/adapters/worker-pool/memory-monitor.js +184 -0
  22. package/src/adapters/worker-pool/memory-monitor.js.map +1 -0
  23. package/src/adapters/worker-pool/protocol.d.ts +314 -0
  24. package/src/adapters/worker-pool/protocol.js +143 -0
  25. package/src/adapters/worker-pool/protocol.js.map +1 -0
  26. package/src/adapters/worker-pool/rate-limiter.d.ts +60 -0
  27. package/src/adapters/worker-pool/rate-limiter.js +101 -0
  28. package/src/adapters/worker-pool/rate-limiter.js.map +1 -0
  29. package/src/adapters/worker-pool/safe-deserialize.d.ts +50 -0
  30. package/src/adapters/worker-pool/safe-deserialize.js +141 -0
  31. package/src/adapters/worker-pool/safe-deserialize.js.map +1 -0
  32. package/src/adapters/worker-pool/worker-pool-adapter.d.ts +84 -0
  33. package/src/adapters/worker-pool/worker-pool-adapter.js +506 -0
  34. package/src/adapters/worker-pool/worker-pool-adapter.js.map +1 -0
  35. package/src/adapters/worker-pool/worker-script.d.ts +12 -0
  36. package/src/adapters/worker-pool/worker-script.js +770 -0
  37. package/src/adapters/worker-pool/worker-script.js.map +1 -0
  38. package/src/adapters/worker-pool/worker-slot.d.ts +116 -0
  39. package/src/adapters/worker-pool/worker-slot.js +301 -0
  40. package/src/adapters/worker-pool/worker-slot.js.map +1 -0
  41. package/src/babel/babel-wrapper.d.ts +118 -0
  42. package/src/babel/babel-wrapper.js +395 -0
  43. package/src/babel/babel-wrapper.js.map +1 -0
  44. package/src/babel/index.d.ts +9 -0
  45. package/src/babel/index.js +17 -0
  46. package/src/babel/index.js.map +1 -0
  47. package/src/babel/multi-file-transform.d.ts +122 -0
  48. package/src/babel/multi-file-transform.js +344 -0
  49. package/src/babel/multi-file-transform.js.map +1 -0
  50. package/src/double-vm/double-vm-wrapper.d.ts +65 -0
  51. package/src/double-vm/double-vm-wrapper.js +523 -0
  52. package/src/double-vm/double-vm-wrapper.js.map +1 -0
  53. package/src/double-vm/index.d.ts +31 -0
  54. package/src/double-vm/index.js +34 -0
  55. package/src/double-vm/index.js.map +1 -0
  56. package/src/double-vm/parent-vm-bootstrap.d.ts +63 -0
  57. package/src/double-vm/parent-vm-bootstrap.js +1695 -0
  58. package/src/double-vm/parent-vm-bootstrap.js.map +1 -0
  59. package/src/double-vm/suspicious-patterns.d.ts +57 -0
  60. package/src/double-vm/suspicious-patterns.js +304 -0
  61. package/src/double-vm/suspicious-patterns.js.map +1 -0
  62. package/src/double-vm/types.d.ts +178 -0
  63. package/src/double-vm/types.js +11 -0
  64. package/src/double-vm/types.js.map +1 -0
  65. package/src/double-vm/wrap-adapter.d.ts +36 -0
  66. package/src/double-vm/wrap-adapter.js +59 -0
  67. package/src/double-vm/wrap-adapter.js.map +1 -0
  68. package/src/enclave.d.ts +159 -0
  69. package/src/enclave.js +671 -0
  70. package/src/enclave.js.map +1 -0
  71. package/src/globals-validator.d.ts +80 -0
  72. package/src/globals-validator.js +206 -0
  73. package/src/globals-validator.js.map +1 -0
  74. package/src/index.d.ts +29 -0
  75. package/src/index.js +130 -0
  76. package/src/index.js.map +1 -0
  77. package/src/memory-proxy.d.ts +69 -0
  78. package/src/memory-proxy.js +310 -0
  79. package/src/memory-proxy.js.map +1 -0
  80. package/src/memory-tracker.d.ts +170 -0
  81. package/src/memory-tracker.js +230 -0
  82. package/src/memory-tracker.js.map +1 -0
  83. package/src/safe-error.d.ts +18 -0
  84. package/src/safe-error.js +76 -0
  85. package/src/safe-error.js.map +1 -0
  86. package/src/safe-runtime.d.ts +72 -0
  87. package/src/safe-runtime.js +656 -0
  88. package/src/safe-runtime.js.map +1 -0
  89. package/src/scoring/cache.d.ts +68 -0
  90. package/src/scoring/cache.js +158 -0
  91. package/src/scoring/cache.js.map +1 -0
  92. package/src/scoring/feature-extractor.d.ts +61 -0
  93. package/src/scoring/feature-extractor.js +366 -0
  94. package/src/scoring/feature-extractor.js.map +1 -0
  95. package/src/scoring/index.d.ts +33 -0
  96. package/src/scoring/index.js +53 -0
  97. package/src/scoring/index.js.map +1 -0
  98. package/src/scoring/scorer.interface.d.ts +65 -0
  99. package/src/scoring/scorer.interface.js +49 -0
  100. package/src/scoring/scorer.interface.js.map +1 -0
  101. package/src/scoring/scorers/disabled.scorer.d.ts +19 -0
  102. package/src/scoring/scorers/disabled.scorer.js +34 -0
  103. package/src/scoring/scorers/disabled.scorer.js.map +1 -0
  104. package/src/scoring/scorers/external-api.scorer.d.ts +29 -0
  105. package/src/scoring/scorers/external-api.scorer.js +141 -0
  106. package/src/scoring/scorers/external-api.scorer.js.map +1 -0
  107. package/src/scoring/scorers/index.d.ts +10 -0
  108. package/src/scoring/scorers/index.js +22 -0
  109. package/src/scoring/scorers/index.js.map +1 -0
  110. package/src/scoring/scorers/local-llm.scorer.d.ts +116 -0
  111. package/src/scoring/scorers/local-llm.scorer.js +474 -0
  112. package/src/scoring/scorers/local-llm.scorer.js.map +1 -0
  113. package/src/scoring/scorers/progressive.scorer.d.ts +77 -0
  114. package/src/scoring/scorers/progressive.scorer.js +199 -0
  115. package/src/scoring/scorers/progressive.scorer.js.map +1 -0
  116. package/src/scoring/scorers/rule-based.scorer.d.ts +66 -0
  117. package/src/scoring/scorers/rule-based.scorer.js +316 -0
  118. package/src/scoring/scorers/rule-based.scorer.js.map +1 -0
  119. package/src/scoring/scoring-gate.d.ts +76 -0
  120. package/src/scoring/scoring-gate.js +246 -0
  121. package/src/scoring/scoring-gate.js.map +1 -0
  122. package/src/scoring/types.d.ts +690 -0
  123. package/src/scoring/types.js +107 -0
  124. package/src/scoring/types.js.map +1 -0
  125. package/src/secure-proxy.d.ts +157 -0
  126. package/src/secure-proxy.js +609 -0
  127. package/src/secure-proxy.js.map +1 -0
  128. package/src/session/channels/embedded-channel.d.ts +76 -0
  129. package/src/session/channels/embedded-channel.js +130 -0
  130. package/src/session/channels/embedded-channel.js.map +1 -0
  131. package/src/session/channels/index.d.ts +9 -0
  132. package/src/session/channels/index.js +14 -0
  133. package/src/session/channels/index.js.map +1 -0
  134. package/src/session/index.d.ts +15 -0
  135. package/src/session/index.js +27 -0
  136. package/src/session/index.js.map +1 -0
  137. package/src/session/session-emitter.d.ts +119 -0
  138. package/src/session/session-emitter.js +253 -0
  139. package/src/session/session-emitter.js.map +1 -0
  140. package/src/session/session-state-machine.d.ts +108 -0
  141. package/src/session/session-state-machine.js +182 -0
  142. package/src/session/session-state-machine.js.map +1 -0
  143. package/src/session/session.d.ts +135 -0
  144. package/src/session/session.js +398 -0
  145. package/src/session/session.js.map +1 -0
  146. package/src/session-types.d.ts +313 -0
  147. package/src/session-types.js +39 -0
  148. package/src/session-types.js.map +1 -0
  149. package/src/sidecar/index.d.ts +12 -0
  150. package/src/sidecar/index.js +31 -0
  151. package/src/sidecar/index.js.map +1 -0
  152. package/src/sidecar/reference-config.d.ts +81 -0
  153. package/src/sidecar/reference-config.js +118 -0
  154. package/src/sidecar/reference-config.js.map +1 -0
  155. package/src/sidecar/reference-resolver.d.ts +115 -0
  156. package/src/sidecar/reference-resolver.js +262 -0
  157. package/src/sidecar/reference-resolver.js.map +1 -0
  158. package/src/sidecar/reference-sidecar.d.ts +161 -0
  159. package/src/sidecar/reference-sidecar.js +226 -0
  160. package/src/sidecar/reference-sidecar.js.map +1 -0
  161. package/src/tool-bridge.d.ts +4 -0
  162. package/src/tool-bridge.js +306 -0
  163. package/src/tool-bridge.js.map +1 -0
  164. package/src/types.d.ts +775 -0
  165. package/src/types.js +187 -0
  166. package/src/types.js.map +1 -0
  167. package/src/value-sanitizer.d.ts +133 -0
  168. package/src/value-sanitizer.js +421 -0
  169. package/src/value-sanitizer.js.map +1 -0
@@ -0,0 +1,421 @@
1
+ "use strict";
2
+ /**
3
+ * Value Sanitizer - Tool Handler Return Value Security
4
+ *
5
+ * Sanitizes values returned from tool handlers to prevent:
6
+ * - Function injection (return values containing executable functions)
7
+ * - Symbol injection (symbols can be used for prototype manipulation)
8
+ * - Prototype pollution (__proto__, constructor keys)
9
+ * - Deeply nested objects (DoS via recursion)
10
+ * - Large object graphs (DoS via memory exhaustion)
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.sanitizeValue = sanitizeValue;
16
+ exports.canSanitize = canSanitize;
17
+ exports.sanitizeValueOrFallback = sanitizeValueOrFallback;
18
+ exports.estimateSerializedSize = estimateSerializedSize;
19
+ exports.checkSerializedSize = checkSerializedSize;
20
+ /**
21
+ * Keys that are stripped from sanitized objects for security
22
+ * - __proto__: Prototype pollution vector
23
+ * - constructor: Constructor chain escape vector
24
+ */
25
+ const DANGEROUS_KEYS = new Set(['__proto__', 'constructor']);
26
+ /**
27
+ * Sanitize a value returned from a tool handler
28
+ *
29
+ * Security features:
30
+ * - Strips functions (prevent code injection)
31
+ * - Strips symbols (prevent prototype manipulation)
32
+ * - Removes __proto__ and constructor keys (prevent prototype pollution)
33
+ * - Creates null-prototype objects (prevent prototype chain attacks)
34
+ * - Enforces max depth (prevent DoS via deep recursion)
35
+ * - Enforces max properties (prevent DoS via memory exhaustion)
36
+ *
37
+ * @param value The value to sanitize
38
+ * @param options Sanitization options
39
+ * @param depth Current recursion depth (internal)
40
+ * @param propCount Property counter (internal)
41
+ * @returns Sanitized value safe for sandbox use
42
+ * @throws Error if value contains functions, symbols, or exceeds limits
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const toolResult = await toolHandler('getData', {});
47
+ * const safeResult = sanitizeValue(toolResult);
48
+ * ```
49
+ */
50
+ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: new WeakSet() }) {
51
+ const maxDepth = options.maxDepth ?? 20;
52
+ const maxProperties = options.maxProperties ?? 10000;
53
+ const allowDates = options.allowDates ?? true;
54
+ const allowErrors = options.allowErrors ?? true;
55
+ // Check depth limit
56
+ if (depth > maxDepth) {
57
+ throw new Error(`Tool handler return value exceeds maximum depth (${maxDepth}). ` +
58
+ `This limit prevents deeply nested objects that could cause stack overflow.`);
59
+ }
60
+ // Check property count limit
61
+ if (context.propCount.count > maxProperties) {
62
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}). ` +
63
+ `This limit prevents memory exhaustion from large object graphs.`);
64
+ }
65
+ // Handle null/undefined
66
+ if (value === null || value === undefined) {
67
+ return value;
68
+ }
69
+ const type = typeof value;
70
+ // Primitives are safe
71
+ if (type === 'string' || type === 'number' || type === 'boolean') {
72
+ return value;
73
+ }
74
+ // BigInt: Convert to string for JSON-safety (JSON.stringify throws on raw BigInt)
75
+ if (type === 'bigint') {
76
+ return String(value);
77
+ }
78
+ // Functions are NOT safe - prevent code injection
79
+ if (type === 'function') {
80
+ throw new Error('Tool handler returned a function. Functions cannot be returned to sandbox code ' +
81
+ 'as they could be used for code injection or host scope access.');
82
+ }
83
+ // Symbols are NOT safe - prevent prototype manipulation
84
+ if (type === 'symbol') {
85
+ throw new Error('Tool handler returned a symbol. Symbols cannot be returned to sandbox code ' +
86
+ 'as they could be used for prototype manipulation.');
87
+ }
88
+ // Check for circular references (only for objects)
89
+ if (type === 'object' && value !== null) {
90
+ if (context.visited.has(value)) {
91
+ // Return a marker for circular references instead of infinite recursion
92
+ return '[Circular]';
93
+ }
94
+ context.visited.add(value);
95
+ }
96
+ // Handle arrays
97
+ if (Array.isArray(value)) {
98
+ context.propCount.count += value.length;
99
+ if (context.propCount.count > maxProperties) {
100
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
101
+ }
102
+ return value.map((item) => sanitizeValue(item, options, depth + 1, context));
103
+ }
104
+ // Handle Date objects
105
+ if (value instanceof Date) {
106
+ if (allowDates) {
107
+ // Return a new Date to prevent reference sharing
108
+ return new Date(value.getTime());
109
+ }
110
+ // Convert to ISO string if dates not allowed
111
+ return value.toISOString();
112
+ }
113
+ // Handle Error objects
114
+ if (value instanceof Error) {
115
+ if (allowErrors) {
116
+ // Convert to plain object with safe properties only
117
+ return {
118
+ name: value.name,
119
+ message: value.message,
120
+ // Do NOT include stack trace - could leak host information
121
+ };
122
+ }
123
+ return { error: value.message };
124
+ }
125
+ // Handle RegExp objects (convert to string)
126
+ if (value instanceof RegExp) {
127
+ return value.toString();
128
+ }
129
+ // Handle Map objects
130
+ if (value instanceof Map) {
131
+ const sanitizedMap = Object.create(null);
132
+ for (const [key, val] of value.entries()) {
133
+ if (typeof key !== 'string')
134
+ continue; // Only string keys
135
+ if (DANGEROUS_KEYS.has(key))
136
+ continue; // Skip dangerous keys
137
+ context.propCount.count++;
138
+ sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
139
+ }
140
+ return sanitizedMap;
141
+ }
142
+ // Handle Set objects (convert to array)
143
+ if (value instanceof Set) {
144
+ const arr = Array.from(value);
145
+ context.propCount.count += arr.length;
146
+ return arr.map((item) => sanitizeValue(item, options, depth + 1, context));
147
+ }
148
+ // Handle plain objects
149
+ if (type === 'object') {
150
+ // Create null-prototype object to prevent prototype chain attacks
151
+ const sanitized = Object.create(null);
152
+ // Get own enumerable string keys only
153
+ const keys = Object.keys(value);
154
+ context.propCount.count += keys.length;
155
+ if (context.propCount.count > maxProperties) {
156
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
157
+ }
158
+ for (const key of keys) {
159
+ // Skip dangerous keys
160
+ if (DANGEROUS_KEYS.has(key)) {
161
+ continue;
162
+ }
163
+ // Try to access the property (may throw if getter trap)
164
+ let propValue;
165
+ try {
166
+ propValue = value[key];
167
+ }
168
+ catch {
169
+ // Skip properties that throw on access (likely getter traps)
170
+ continue;
171
+ }
172
+ // Recursively sanitize - DO NOT catch these errors, let them propagate
173
+ sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
174
+ }
175
+ return sanitized;
176
+ }
177
+ // Unknown type - convert to string
178
+ return String(value);
179
+ }
180
+ /**
181
+ * Check if a value can be safely sanitized without throwing
182
+ *
183
+ * @param value Value to check
184
+ * @param options Sanitization options
185
+ * @returns true if sanitization will succeed, false otherwise
186
+ */
187
+ function canSanitize(value, options = {}) {
188
+ try {
189
+ sanitizeValue(value, options);
190
+ return true;
191
+ }
192
+ catch {
193
+ return false;
194
+ }
195
+ }
196
+ /**
197
+ * Sanitize value with fallback on error
198
+ *
199
+ * @param value Value to sanitize
200
+ * @param fallback Fallback value if sanitization fails
201
+ * @param options Sanitization options
202
+ * @returns Sanitized value or fallback
203
+ */
204
+ function sanitizeValueOrFallback(value, fallback, options = {}) {
205
+ try {
206
+ return sanitizeValue(value, options);
207
+ }
208
+ catch {
209
+ return fallback;
210
+ }
211
+ }
212
+ /**
213
+ * Estimate the serialized (JSON) size of a string in bytes.
214
+ * Accounts for quotes and proper JSON escaping.
215
+ *
216
+ * @param str The string to estimate
217
+ * @returns Size in bytes when serialized as JSON string
218
+ */
219
+ function estimateStringSize(str) {
220
+ let bytes = 2; // quotes
221
+ for (let i = 0; i < str.length; i++) {
222
+ const code = str.charCodeAt(i);
223
+ if (code < 128) {
224
+ // ASCII: check if needs escaping
225
+ if (code === 34 || code === 92) {
226
+ // Quote and backslash: 2-byte escape (\" or \\)
227
+ bytes += 2;
228
+ }
229
+ else if (code < 32) {
230
+ // Control characters: 6-byte \uXXXX escape
231
+ bytes += 6;
232
+ }
233
+ else {
234
+ bytes += 1;
235
+ }
236
+ }
237
+ else if (code < 2048) {
238
+ bytes += 2; // 2-byte UTF-8
239
+ }
240
+ else if (code >= 0xd800 && code <= 0xdbff && i + 1 < str.length) {
241
+ // High surrogate - check for low surrogate pair (emoji, supplementary chars)
242
+ const nextCode = str.charCodeAt(i + 1);
243
+ if (nextCode >= 0xdc00 && nextCode <= 0xdfff) {
244
+ bytes += 4; // 4-byte UTF-8 for surrogate pair
245
+ i++; // Skip the low surrogate
246
+ }
247
+ else {
248
+ bytes += 3; // Unpaired high surrogate (3-byte UTF-8)
249
+ }
250
+ }
251
+ else {
252
+ bytes += 3; // 3-byte UTF-8 (BMP characters U+0800 to U+FFFF)
253
+ }
254
+ }
255
+ return bytes;
256
+ }
257
+ /**
258
+ * Estimates the serialized (JSON) size of a value in bytes.
259
+ *
260
+ * Security feature: Prevents memory exhaustion attacks (Vector 340) where:
261
+ * - Attacker creates a structure with many references to the same large string
262
+ * - In-VM memory is small (strings are shared by reference)
263
+ * - But JSON serialization expands each reference to full string copy
264
+ * - Example: 500 refs × 5 copies × 10KB string = 25MB serialized from ~20KB in-memory
265
+ *
266
+ * This function counts EVERY string occurrence, not unique strings,
267
+ * to accurately estimate the serialized output size.
268
+ *
269
+ * IMPORTANT: Circular reference handling:
270
+ * - Uses a "current path" Set to detect circular references (ancestor chain)
271
+ * - Repeated (non-circular) references to the same object are counted fully each time
272
+ * - This matches JSON.stringify behavior where repeated refs are serialized multiple times
273
+ *
274
+ * @param value The value to estimate
275
+ * @param maxBytes Maximum allowed serialized bytes (0 = no limit)
276
+ * @param depth Current recursion depth (internal)
277
+ * @param maxDepth Maximum recursion depth (default 2000 to handle deep structures)
278
+ * @param currentPath Set tracking the current ancestor path (for circular detection only)
279
+ * @returns Estimated serialized size in bytes
280
+ * @throws Error if estimated size exceeds maxBytes or depth limit
281
+ */
282
+ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2000, currentPath = new Set()) {
283
+ // Depth limit to prevent stack overflow - reject deeply nested structures
284
+ if (depth > maxDepth) {
285
+ throw new Error(`Structure exceeds maximum nesting depth (${maxDepth}). ` +
286
+ `Deeply nested structures are rejected to prevent stack overflow attacks.`);
287
+ }
288
+ // Handle null/undefined
289
+ if (value === null)
290
+ return 4; // "null"
291
+ if (value === undefined)
292
+ return 0; // undefined is omitted in JSON
293
+ const type = typeof value;
294
+ // String: count actual bytes (each occurrence, not unique!)
295
+ if (type === 'string') {
296
+ const bytes = estimateStringSize(value);
297
+ if (maxBytes > 0 && bytes > maxBytes) {
298
+ throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
299
+ }
300
+ return bytes;
301
+ }
302
+ // Number: estimate digit count
303
+ if (type === 'number') {
304
+ const num = value;
305
+ if (!Number.isFinite(num))
306
+ return 4; // "null" for Infinity/NaN
307
+ return String(num).length;
308
+ }
309
+ // Boolean
310
+ if (type === 'boolean') {
311
+ return value ? 4 : 5; // "true" or "false"
312
+ }
313
+ // BigInt: Cannot be JSON.stringify'd directly, but estimate as string for size purposes
314
+ // (caller is responsible for actual serialization, e.g., converting to string first)
315
+ if (type === 'bigint') {
316
+ return String(value).length + 2; // Estimate as quoted string
317
+ }
318
+ // Function/Symbol: shouldn't be serialized
319
+ if (type === 'function' || type === 'symbol') {
320
+ return 0; // omitted in JSON
321
+ }
322
+ // Arrays
323
+ if (Array.isArray(value)) {
324
+ // Check for circular reference (is this object an ancestor of itself?)
325
+ if (currentPath.has(value)) {
326
+ // Circular reference detected - JSON.stringify would throw, but we estimate small
327
+ return 4;
328
+ }
329
+ // Add to current path for descendant checks
330
+ currentPath.add(value);
331
+ let size = 2; // brackets []
332
+ for (let i = 0; i < value.length; i++) {
333
+ if (i > 0)
334
+ size += 1; // comma
335
+ let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);
336
+ // JSON.stringify turns undefined/function/symbol array elements into null (4 bytes)
337
+ if (elementSize === 0)
338
+ elementSize = 4;
339
+ size += elementSize;
340
+ // Check limit incrementally to fail fast
341
+ if (maxBytes > 0 && size > maxBytes) {
342
+ currentPath.delete(value); // Clean up before throwing
343
+ throw new Error(`Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. ` +
344
+ `This often indicates repeated references to large strings that expand during JSON serialization.`);
345
+ }
346
+ }
347
+ // Remove from current path (we're done with this branch)
348
+ currentPath.delete(value);
349
+ return size;
350
+ }
351
+ // Objects
352
+ if (type === 'object' && value !== null) {
353
+ // Check for circular reference (is this object an ancestor of itself?)
354
+ if (currentPath.has(value)) {
355
+ // Circular reference detected
356
+ return 4;
357
+ }
358
+ // Add to current path for descendant checks
359
+ currentPath.add(value);
360
+ // Handle special objects
361
+ if (value instanceof Date) {
362
+ currentPath.delete(value);
363
+ return 26; // ISO date string with quotes: "2024-01-01T00:00:00.000Z"
364
+ }
365
+ if (value instanceof RegExp) {
366
+ // RegExp serializes to "{}" in JSON.stringify
367
+ currentPath.delete(value);
368
+ return 2; // "{}"
369
+ }
370
+ let size = 2; // braces {}
371
+ const keys = Object.keys(value);
372
+ let first = true;
373
+ for (const key of keys) {
374
+ // Skip dangerous keys (they're stripped)
375
+ if (key === '__proto__' || key === 'constructor')
376
+ continue;
377
+ if (!first)
378
+ size += 1; // comma
379
+ first = false;
380
+ // Key: quoted string + colon (accounting for JSON escaping)
381
+ size += estimateStringSize(key) + 1; // "key":
382
+ // Value
383
+ let propValue;
384
+ try {
385
+ propValue = value[key];
386
+ }
387
+ catch {
388
+ continue; // Skip throwing properties
389
+ }
390
+ const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
391
+ size += valueSize;
392
+ // Check limit incrementally to fail fast
393
+ if (maxBytes > 0 && size > maxBytes) {
394
+ currentPath.delete(value); // Clean up before throwing
395
+ throw new Error(`Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. ` +
396
+ `This often indicates repeated references to large strings that expand during JSON serialization.`);
397
+ }
398
+ }
399
+ // Remove from current path (we're done with this branch)
400
+ currentPath.delete(value);
401
+ return size;
402
+ }
403
+ return 0;
404
+ }
405
+ /**
406
+ * Check if a value's serialized size is within limits
407
+ *
408
+ * @param value Value to check
409
+ * @param maxBytes Maximum allowed serialized bytes
410
+ * @returns Object with ok status and estimated size or error message
411
+ */
412
+ function checkSerializedSize(value, maxBytes) {
413
+ try {
414
+ const estimatedBytes = estimateSerializedSize(value, maxBytes);
415
+ return { ok: true, estimatedBytes };
416
+ }
417
+ catch (err) {
418
+ return { ok: false, error: err instanceof Error ? err.message : 'Unknown error' };
419
+ }
420
+ }
421
+ //# sourceMappingURL=value-sanitizer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"value-sanitizer.js","sourceRoot":"","sources":["../../src/value-sanitizer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;AA6EH,sCAkKC;AASD,kCAOC;AAUD,0DAMC;AAmED,wDAsJC;AASD,kDAUC;AA5dD;;;;GAIG;AACH,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC;AAiB7D;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,SAAgB,aAAa,CAC3B,KAAc,EACd,UAA2B,EAAE,EAC7B,KAAK,GAAG,CAAC,EACT,UAA2B,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,OAAO,EAAE,EAAE;IAE9E,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAC;IACxC,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,IAAI,KAAK,CAAC;IACrD,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IA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AAI,KAAiC,CAAC,GAAG,CAAC,CAAC;YACtD,CAAC;YAAC,MAAM,CAAC;gBACP,SAAS,CAAC,2BAA2B;YACvC,CAAC;YAED,MAAM,SAAS,GAAG,sBAAsB,CAAC,SAAS,EAAE,QAAQ,EAAE,KAAK,GAAG,CAAC,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;YAChG,IAAI,IAAI,SAAS,CAAC;YAElB,yCAAyC;YACzC,IAAI,QAAQ,GAAG,CAAC,IAAI,IAAI,GAAG,QAAQ,EAAE,CAAC;gBACpC,WAAW,CAAC,MAAM,CAAC,KAAe,CAAC,CAAC,CAAC,2BAA2B;gBAChE,MAAM,IAAI,KAAK,CACb,sDAAsD,IAAI,OAAO,QAAQ,UAAU;oBACjF,kGAAkG,CACrG,CAAC;YACJ,CAAC;QACH,CAAC;QAED,yDAAyD;QACzD,WAAW,CAAC,MAAM,CAAC,KAAe,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,mBAAmB,CACjC,KAAc,EACd,QAAgB;IAEhB,IAAI,CAAC;QACH,MAAM,cAAc,GAAG,sBAAsB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;QAC/D,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;IACtC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EAAE,CAAC;IACpF,CAAC;AACH,CAAC","sourcesContent":["/**\n * Value Sanitizer - Tool Handler Return Value Security\n *\n * Sanitizes values returned from tool handlers to prevent:\n * - Function injection (return values containing executable functions)\n * - Symbol injection (symbols can be used for prototype manipulation)\n * - Prototype pollution (__proto__, constructor keys)\n * - Deeply nested objects (DoS via recursion)\n * - Large object graphs (DoS via memory exhaustion)\n *\n * @packageDocumentation\n */\n\n/**\n * Options for value sanitization\n */\nexport interface SanitizeOptions {\n /**\n * Maximum depth of nested objects/arrays\n * @default 20\n */\n maxDepth?: number;\n\n /**\n * Maximum total number of properties across all nested objects\n * @default 10000\n */\n maxProperties?: number;\n\n /**\n * Whether to allow Date objects (converted to ISO strings if false)\n * @default true\n */\n allowDates?: boolean;\n\n /**\n * Whether to allow Error objects (converted to plain objects)\n * @default true\n */\n allowErrors?: boolean;\n}\n\n/**\n * Keys that are stripped from sanitized objects for security\n * - __proto__: Prototype pollution vector\n * - constructor: Constructor chain escape vector\n */\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor']);\n\n/**\n * Property counter for tracking total properties across recursive calls\n */\ninterface PropertyCounter {\n count: number;\n}\n\n/**\n * Internal context for tracking visited objects (circular reference detection)\n */\ninterface SanitizeContext {\n propCount: PropertyCounter;\n visited: WeakSet<object>;\n}\n\n/**\n * Sanitize a value returned from a tool handler\n *\n * Security features:\n * - Strips functions (prevent code injection)\n * - Strips symbols (prevent prototype manipulation)\n * - Removes __proto__ and constructor keys (prevent prototype pollution)\n * - Creates null-prototype objects (prevent prototype chain attacks)\n * - Enforces max depth (prevent DoS via deep recursion)\n * - Enforces max properties (prevent DoS via memory exhaustion)\n *\n * @param value The value to sanitize\n * @param options Sanitization options\n * @param depth Current recursion depth (internal)\n * @param propCount Property counter (internal)\n * @returns Sanitized value safe for sandbox use\n * @throws Error if value contains functions, symbols, or exceeds limits\n *\n * @example\n * ```typescript\n * const toolResult = await toolHandler('getData', {});\n * const safeResult = sanitizeValue(toolResult);\n * ```\n */\nexport function sanitizeValue(\n value: unknown,\n options: SanitizeOptions = {},\n depth = 0,\n context: SanitizeContext = { propCount: { count: 0 }, visited: new WeakSet() },\n): unknown {\n const maxDepth = options.maxDepth ?? 20;\n const maxProperties = options.maxProperties ?? 10000;\n const allowDates = options.allowDates ?? true;\n const allowErrors = options.allowErrors ?? true;\n\n // Check depth limit\n if (depth > maxDepth) {\n throw new Error(\n `Tool handler return value exceeds maximum depth (${maxDepth}). ` +\n `This limit prevents deeply nested objects that could cause stack overflow.`,\n );\n }\n\n // Check property count limit\n if (context.propCount.count > maxProperties) {\n throw new Error(\n `Tool handler return value exceeds maximum properties (${maxProperties}). ` +\n `This limit prevents memory exhaustion from large object graphs.`,\n );\n }\n\n // Handle null/undefined\n if (value === null || value === undefined) {\n return value;\n }\n\n const type = typeof value;\n\n // Primitives are safe\n if (type === 'string' || type === 'number' || type === 'boolean') {\n return value;\n }\n\n // BigInt: Convert to string for JSON-safety (JSON.stringify throws on raw BigInt)\n if (type === 'bigint') {\n return String(value);\n }\n\n // Functions are NOT safe - prevent code injection\n if (type === 'function') {\n throw new Error(\n 'Tool handler returned a function. Functions cannot be returned to sandbox code ' +\n 'as they could be used for code injection or host scope access.',\n );\n }\n\n // Symbols are NOT safe - prevent prototype manipulation\n if (type === 'symbol') {\n throw new Error(\n 'Tool handler returned a symbol. Symbols cannot be returned to sandbox code ' +\n 'as they could be used for prototype manipulation.',\n );\n }\n\n // Check for circular references (only for objects)\n if (type === 'object' && value !== null) {\n if (context.visited.has(value as object)) {\n // Return a marker for circular references instead of infinite recursion\n return '[Circular]';\n }\n context.visited.add(value as object);\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n context.propCount.count += value.length;\n if (context.propCount.count > maxProperties) {\n throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);\n }\n return value.map((item) => sanitizeValue(item, options, depth + 1, context));\n }\n\n // Handle Date objects\n if (value instanceof Date) {\n if (allowDates) {\n // Return a new Date to prevent reference sharing\n return new Date(value.getTime());\n }\n // Convert to ISO string if dates not allowed\n return value.toISOString();\n }\n\n // Handle Error objects\n if (value instanceof Error) {\n if (allowErrors) {\n // Convert to plain object with safe properties only\n return {\n name: value.name,\n message: value.message,\n // Do NOT include stack trace - could leak host information\n };\n }\n return { error: value.message };\n }\n\n // Handle RegExp objects (convert to string)\n if (value instanceof RegExp) {\n return value.toString();\n }\n\n // Handle Map objects\n if (value instanceof Map) {\n const sanitizedMap: Record<string, unknown> = Object.create(null);\n for (const [key, val] of value.entries()) {\n if (typeof key !== 'string') continue; // Only string keys\n if (DANGEROUS_KEYS.has(key)) continue; // Skip dangerous keys\n context.propCount.count++;\n sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);\n }\n return sanitizedMap;\n }\n\n // Handle Set objects (convert to array)\n if (value instanceof Set) {\n const arr = Array.from(value);\n context.propCount.count += arr.length;\n return arr.map((item) => sanitizeValue(item, options, depth + 1, context));\n }\n\n // Handle plain objects\n if (type === 'object') {\n // Create null-prototype object to prevent prototype chain attacks\n const sanitized: Record<string, unknown> = Object.create(null);\n\n // Get own enumerable string keys only\n const keys = Object.keys(value as Record<string, unknown>);\n context.propCount.count += keys.length;\n\n if (context.propCount.count > maxProperties) {\n throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);\n }\n\n for (const key of keys) {\n // Skip dangerous keys\n if (DANGEROUS_KEYS.has(key)) {\n continue;\n }\n\n // Try to access the property (may throw if getter trap)\n let propValue: unknown;\n try {\n propValue = (value as Record<string, unknown>)[key];\n } catch {\n // Skip properties that throw on access (likely getter traps)\n continue;\n }\n\n // Recursively sanitize - DO NOT catch these errors, let them propagate\n sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);\n }\n\n return sanitized;\n }\n\n // Unknown type - convert to string\n return String(value);\n}\n\n/**\n * Check if a value can be safely sanitized without throwing\n *\n * @param value Value to check\n * @param options Sanitization options\n * @returns true if sanitization will succeed, false otherwise\n */\nexport function canSanitize(value: unknown, options: SanitizeOptions = {}): boolean {\n try {\n sanitizeValue(value, options);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Sanitize value with fallback on error\n *\n * @param value Value to sanitize\n * @param fallback Fallback value if sanitization fails\n * @param options Sanitization options\n * @returns Sanitized value or fallback\n */\nexport function sanitizeValueOrFallback<T>(value: unknown, fallback: T, options: SanitizeOptions = {}): unknown | T {\n try {\n return sanitizeValue(value, options);\n } catch {\n return fallback;\n }\n}\n\n/**\n * Estimate the serialized (JSON) size of a string in bytes.\n * Accounts for quotes and proper JSON escaping.\n *\n * @param str The string to estimate\n * @returns Size in bytes when serialized as JSON string\n */\nfunction estimateStringSize(str: string): number {\n let bytes = 2; // quotes\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n if (code < 128) {\n // ASCII: check if needs escaping\n if (code === 34 || code === 92) {\n // Quote and backslash: 2-byte escape (\\\" or \\\\)\n bytes += 2;\n } else if (code < 32) {\n // Control characters: 6-byte \\uXXXX escape\n bytes += 6;\n } else {\n bytes += 1;\n }\n } else if (code < 2048) {\n bytes += 2; // 2-byte UTF-8\n } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < str.length) {\n // High surrogate - check for low surrogate pair (emoji, supplementary chars)\n const nextCode = str.charCodeAt(i + 1);\n if (nextCode >= 0xdc00 && nextCode <= 0xdfff) {\n bytes += 4; // 4-byte UTF-8 for surrogate pair\n i++; // Skip the low surrogate\n } else {\n bytes += 3; // Unpaired high surrogate (3-byte UTF-8)\n }\n } else {\n bytes += 3; // 3-byte UTF-8 (BMP characters U+0800 to U+FFFF)\n }\n }\n return bytes;\n}\n\n/**\n * Estimates the serialized (JSON) size of a value in bytes.\n *\n * Security feature: Prevents memory exhaustion attacks (Vector 340) where:\n * - Attacker creates a structure with many references to the same large string\n * - In-VM memory is small (strings are shared by reference)\n * - But JSON serialization expands each reference to full string copy\n * - Example: 500 refs × 5 copies × 10KB string = 25MB serialized from ~20KB in-memory\n *\n * This function counts EVERY string occurrence, not unique strings,\n * to accurately estimate the serialized output size.\n *\n * IMPORTANT: Circular reference handling:\n * - Uses a \"current path\" Set to detect circular references (ancestor chain)\n * - Repeated (non-circular) references to the same object are counted fully each time\n * - This matches JSON.stringify behavior where repeated refs are serialized multiple times\n *\n * @param value The value to estimate\n * @param maxBytes Maximum allowed serialized bytes (0 = no limit)\n * @param depth Current recursion depth (internal)\n * @param maxDepth Maximum recursion depth (default 2000 to handle deep structures)\n * @param currentPath Set tracking the current ancestor path (for circular detection only)\n * @returns Estimated serialized size in bytes\n * @throws Error if estimated size exceeds maxBytes or depth limit\n */\nexport function estimateSerializedSize(\n value: unknown,\n maxBytes = 0,\n depth = 0,\n maxDepth = 2000,\n currentPath: Set<object> = new Set(),\n): number {\n // Depth limit to prevent stack overflow - reject deeply nested structures\n if (depth > maxDepth) {\n throw new Error(\n `Structure exceeds maximum nesting depth (${maxDepth}). ` +\n `Deeply nested structures are rejected to prevent stack overflow attacks.`,\n );\n }\n\n // Handle null/undefined\n if (value === null) return 4; // \"null\"\n if (value === undefined) return 0; // undefined is omitted in JSON\n\n const type = typeof value;\n\n // String: count actual bytes (each occurrence, not unique!)\n if (type === 'string') {\n const bytes = estimateStringSize(value as string);\n if (maxBytes > 0 && bytes > maxBytes) {\n throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);\n }\n return bytes;\n }\n\n // Number: estimate digit count\n if (type === 'number') {\n const num = value as number;\n if (!Number.isFinite(num)) return 4; // \"null\" for Infinity/NaN\n return String(num).length;\n }\n\n // Boolean\n if (type === 'boolean') {\n return value ? 4 : 5; // \"true\" or \"false\"\n }\n\n // BigInt: Cannot be JSON.stringify'd directly, but estimate as string for size purposes\n // (caller is responsible for actual serialization, e.g., converting to string first)\n if (type === 'bigint') {\n return String(value).length + 2; // Estimate as quoted string\n }\n\n // Function/Symbol: shouldn't be serialized\n if (type === 'function' || type === 'symbol') {\n return 0; // omitted in JSON\n }\n\n // Arrays\n if (Array.isArray(value)) {\n // Check for circular reference (is this object an ancestor of itself?)\n if (currentPath.has(value)) {\n // Circular reference detected - JSON.stringify would throw, but we estimate small\n return 4;\n }\n\n // Add to current path for descendant checks\n currentPath.add(value);\n\n let size = 2; // brackets []\n for (let i = 0; i < value.length; i++) {\n if (i > 0) size += 1; // comma\n let elementSize = estimateSerializedSize(value[i], maxBytes, depth + 1, maxDepth, currentPath);\n // JSON.stringify turns undefined/function/symbol array elements into null (4 bytes)\n if (elementSize === 0) elementSize = 4;\n size += elementSize;\n\n // Check limit incrementally to fail fast\n if (maxBytes > 0 && size > maxBytes) {\n currentPath.delete(value); // Clean up before throwing\n throw new Error(\n `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. ` +\n `This often indicates repeated references to large strings that expand during JSON serialization.`,\n );\n }\n }\n\n // Remove from current path (we're done with this branch)\n currentPath.delete(value);\n return size;\n }\n\n // Objects\n if (type === 'object' && value !== null) {\n // Check for circular reference (is this object an ancestor of itself?)\n if (currentPath.has(value as object)) {\n // Circular reference detected\n return 4;\n }\n\n // Add to current path for descendant checks\n currentPath.add(value as object);\n\n // Handle special objects\n if (value instanceof Date) {\n currentPath.delete(value as object);\n return 26; // ISO date string with quotes: \"2024-01-01T00:00:00.000Z\"\n }\n if (value instanceof RegExp) {\n // RegExp serializes to \"{}\" in JSON.stringify\n currentPath.delete(value as object);\n return 2; // \"{}\"\n }\n\n let size = 2; // braces {}\n const keys = Object.keys(value as Record<string, unknown>);\n let first = true;\n\n for (const key of keys) {\n // Skip dangerous keys (they're stripped)\n if (key === '__proto__' || key === 'constructor') continue;\n\n if (!first) size += 1; // comma\n first = false;\n\n // Key: quoted string + colon (accounting for JSON escaping)\n size += estimateStringSize(key) + 1; // \"key\":\n\n // Value\n let propValue: unknown;\n try {\n propValue = (value as Record<string, unknown>)[key];\n } catch {\n continue; // Skip throwing properties\n }\n\n const valueSize = estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);\n size += valueSize;\n\n // Check limit incrementally to fail fast\n if (maxBytes > 0 && size > maxBytes) {\n currentPath.delete(value as object); // Clean up before throwing\n throw new Error(\n `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. ` +\n `This often indicates repeated references to large strings that expand during JSON serialization.`,\n );\n }\n }\n\n // Remove from current path (we're done with this branch)\n currentPath.delete(value as object);\n return size;\n }\n\n return 0;\n}\n\n/**\n * Check if a value's serialized size is within limits\n *\n * @param value Value to check\n * @param maxBytes Maximum allowed serialized bytes\n * @returns Object with ok status and estimated size or error message\n */\nexport function checkSerializedSize(\n value: unknown,\n maxBytes: number,\n): { ok: true; estimatedBytes: number } | { ok: false; error: string } {\n try {\n const estimatedBytes = estimateSerializedSize(value, maxBytes);\n return { ok: true, estimatedBytes };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : 'Unknown error' };\n }\n}\n"]}