@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,609 +0,0 @@
1
- "use strict";
2
- /**
3
- * Secure Proxy - Runtime Property Access Protection
4
- *
5
- * Wraps objects with Proxies that block access to dangerous properties like:
6
- * - constructor: Gives access to Function constructor for code execution
7
- * - __proto__: Prototype chain manipulation
8
- * - prototype: Prototype access
9
- *
10
- * This provides defense-in-depth against attacks like:
11
- * ```javascript
12
- * const m = 'const';
13
- * const Func = callTool[m + 'ructor']; // Blocked!
14
- * ```
15
- *
16
- * @packageDocumentation
17
- */
18
- Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.DEFAULT_SECURE_PROXY_CONFIG = exports.BLOCKED_PROPERTY_CATEGORIES = void 0;
20
- exports.getBlockedPropertiesForLevel = getBlockedPropertiesForLevel;
21
- exports.buildBlockedPropertiesFromConfig = buildBlockedPropertiesFromConfig;
22
- exports.createSafeReflect = createSafeReflect;
23
- exports.createSecureProxy = createSecureProxy;
24
- exports.wrapGlobalsWithSecureProxy = wrapGlobalsWithSecureProxy;
25
- exports.createSecureStandardLibrary = createSecureStandardLibrary;
26
- exports.isSecureProxy = isSecureProxy;
27
- exports.clearProxyCache = clearProxyCache;
28
- const safe_error_1 = require("./safe-error");
29
- /**
30
- * Categorized blocked properties for defense-in-depth
31
- *
32
- * Organized by attack category to support per-security-level configuration
33
- */
34
- exports.BLOCKED_PROPERTY_CATEGORIES = {
35
- /**
36
- * Core prototype manipulation properties (always blocked except PERMISSIVE)
37
- */
38
- PROTOTYPE: new Set([
39
- 'constructor',
40
- '__proto__',
41
- 'prototype',
42
- '__defineGetter__',
43
- '__defineSetter__',
44
- '__lookupGetter__',
45
- '__lookupSetter__',
46
- ]),
47
- /**
48
- * Node.js 24 Iterator helper method names
49
- * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
50
- */
51
- ITERATOR_HELPERS: new Set(['toArray', 'forEach', 'some', 'every', 'find', 'reduce', 'flatMap', 'drop', 'take']),
52
- /**
53
- * Reflection properties on Object
54
- * Blocked at STRICT to prevent introspection attacks
55
- */
56
- REFLECTION: new Set([
57
- 'getOwnPropertyDescriptor',
58
- 'getOwnPropertyDescriptors',
59
- 'getOwnPropertyNames',
60
- 'getOwnPropertySymbols',
61
- 'getPrototypeOf',
62
- 'setPrototypeOf',
63
- 'defineProperty',
64
- 'defineProperties',
65
- 'preventExtensions',
66
- 'isExtensible',
67
- 'seal',
68
- 'isSealed',
69
- 'freeze',
70
- 'isFrozen',
71
- ]),
72
- /**
73
- * Timing API properties
74
- * Blocked at STRICT to prevent timing attacks
75
- */
76
- TIMING: new Set(['hrtime', 'timeOrigin']),
77
- };
78
- /**
79
- * Get blocked properties for a security level
80
- *
81
- * @param level Security level
82
- * @returns Set of property names to block
83
- */
84
- function getBlockedPropertiesForLevel(level) {
85
- const blocked = new Set();
86
- // PERMISSIVE: No prototype blocking (handled by explicit config)
87
- // All other levels: Block core prototype manipulation
88
- if (level !== 'PERMISSIVE') {
89
- exports.BLOCKED_PROPERTY_CATEGORIES.PROTOTYPE.forEach((p) => blocked.add(p));
90
- }
91
- switch (level) {
92
- case 'STRICT':
93
- // Block everything
94
- exports.BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
95
- exports.BLOCKED_PROPERTY_CATEGORIES.REFLECTION.forEach((p) => blocked.add(p));
96
- exports.BLOCKED_PROPERTY_CATEGORIES.TIMING.forEach((p) => blocked.add(p));
97
- break;
98
- case 'SECURE':
99
- // Block iterator helpers (potential sandbox escape vectors)
100
- exports.BLOCKED_PROPERTY_CATEGORIES.ITERATOR_HELPERS.forEach((p) => blocked.add(p));
101
- break;
102
- case 'STANDARD':
103
- case 'PERMISSIVE':
104
- // Handled above
105
- break;
106
- }
107
- return blocked;
108
- }
109
- /**
110
- * Default blocked properties (for backward compatibility)
111
- */
112
- const BLOCKED_PROPERTIES = new Set([
113
- // Code execution
114
- 'constructor',
115
- // Prototype manipulation
116
- '__proto__',
117
- 'prototype',
118
- // Legacy getter/setter definition
119
- '__defineGetter__',
120
- '__defineSetter__',
121
- '__lookupGetter__',
122
- '__lookupSetter__',
123
- ]);
124
- /**
125
- * Build blocked properties set from SecureProxyLevelConfig
126
- *
127
- * @param config The security level proxy configuration
128
- * @returns Set of property names to block
129
- */
130
- function buildBlockedPropertiesFromConfig(config) {
131
- const blocked = new Set();
132
- if (config.blockConstructor) {
133
- blocked.add('constructor');
134
- }
135
- if (config.blockPrototype) {
136
- blocked.add('__proto__');
137
- blocked.add('prototype');
138
- }
139
- if (config.blockLegacyAccessors) {
140
- blocked.add('__defineGetter__');
141
- blocked.add('__defineSetter__');
142
- blocked.add('__lookupGetter__');
143
- blocked.add('__lookupSetter__');
144
- }
145
- return blocked;
146
- }
147
- /**
148
- * Default SecureProxyLevelConfig (matches current behavior - blocks everything)
149
- */
150
- exports.DEFAULT_SECURE_PROXY_CONFIG = {
151
- blockConstructor: true,
152
- blockPrototype: true,
153
- blockLegacyAccessors: true,
154
- proxyMaxDepth: 10,
155
- throwOnBlocked: true,
156
- };
157
- /**
158
- * Create a safe Reflect wrapper that blocks dangerous operations
159
- *
160
- * @param securityLevel The security level to apply
161
- * @returns A safe Reflect object or undefined (STRICT blocks Reflect entirely)
162
- */
163
- function createSafeReflect(securityLevel) {
164
- // STRICT: Block Reflect entirely
165
- if (securityLevel === 'STRICT') {
166
- return undefined;
167
- }
168
- const dangerousMethods = new Set(['setPrototypeOf']);
169
- // SECURE: Block additional methods
170
- if (securityLevel === 'SECURE') {
171
- dangerousMethods.add('apply');
172
- dangerousMethods.add('defineProperty');
173
- }
174
- return new Proxy(Reflect, {
175
- get(target, prop) {
176
- if (typeof prop === 'string' && dangerousMethods.has(prop)) {
177
- return undefined;
178
- }
179
- const value = Reflect.get(target, prop);
180
- // Wrap Reflect.construct to block Function constructors
181
- if (typeof value === 'function' && prop === 'construct') {
182
- return function (ctorTarget, args, newTarget) {
183
- // Block Function, AsyncFunction, GeneratorFunction, AsyncGeneratorFunction constructors
184
- // Intentional empty functions to obtain constructor references
185
- // eslint-disable-next-line @typescript-eslint/no-empty-function
186
- const AsyncFunction = async function () { }.constructor;
187
- // eslint-disable-next-line @typescript-eslint/no-empty-function
188
- const GeneratorFunction = function* () { }.constructor;
189
- // eslint-disable-next-line @typescript-eslint/no-empty-function
190
- const AsyncGeneratorFunction = async function* () { }.constructor;
191
- if (ctorTarget === Function ||
192
- ctorTarget === AsyncFunction ||
193
- ctorTarget === GeneratorFunction ||
194
- ctorTarget === AsyncGeneratorFunction) {
195
- throw (0, safe_error_1.createSafeError)('Reflect.construct with function constructors is blocked', 'SecurityError');
196
- }
197
- return Reflect.construct(ctorTarget, args, newTarget);
198
- };
199
- }
200
- return value;
201
- },
202
- });
203
- }
204
- /**
205
- * Properties that are specifically dangerous on Function objects
206
- */
207
- const FUNCTION_BLOCKED_PROPERTIES = new Set([
208
- // Function object properties that could leak information
209
- 'caller', // Deprecated but still exists
210
- 'arguments', // Deprecated but still exists
211
- // Binding/applying could be used for exploitation
212
- // Note: We may want to allow these in some cases
213
- // 'bind',
214
- // 'call',
215
- // 'apply',
216
- ]);
217
- /**
218
- * WeakMap to track already-proxied objects to prevent infinite recursion
219
- * and ensure we return the same proxy for the same object with the same config.
220
- *
221
- * The outer WeakMap is keyed by target object.
222
- * The inner Map is keyed by a config signature string.
223
- * This allows the same object to be proxied with different blocking configs.
224
- */
225
- const proxyCache = new WeakMap();
226
- /**
227
- * WeakSet to track proxy objects (for isSecureProxy checks)
228
- * This is separate from proxyCache because proxyCache keys are targets, not proxies.
229
- */
230
- const proxySet = new WeakSet();
231
- /**
232
- * Generate a cache key from all SecureProxyOptions that affect proxy behavior
233
- * This ensures different options create different proxies for the same target
234
- *
235
- * NOTE: onBlocked callback is intentionally excluded from cache key.
236
- * Having different callbacks for the same blocking configuration is unusual,
237
- * and including function identity would effectively disable caching.
238
- * If you need different callbacks, use different additionalBlocked values.
239
- */
240
- function getFullCacheKey(options) {
241
- const parts = [];
242
- // Level config signature
243
- if (options.levelConfig) {
244
- const cfg = options.levelConfig;
245
- parts.push(`L:${cfg.blockConstructor ? 'C' : 'c'}${cfg.blockPrototype ? 'P' : 'p'}${cfg.blockLegacyAccessors ? 'L' : 'l'}`);
246
- }
247
- else {
248
- parts.push('L:default');
249
- }
250
- // Additional blocked properties (sorted for consistent keys)
251
- if (options.additionalBlocked && options.additionalBlocked.length > 0) {
252
- parts.push(`B:${[...options.additionalBlocked].sort().join(',')}`);
253
- }
254
- // Max depth (only include if non-default)
255
- const effectiveMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
256
- if (effectiveMaxDepth !== 10) {
257
- parts.push(`D:${effectiveMaxDepth}`);
258
- }
259
- // Throw on blocked (only include if true)
260
- if (options.throwOnBlocked) {
261
- parts.push('T:1');
262
- }
263
- return parts.join('|') || 'default';
264
- }
265
- /**
266
- * Built-in objects that have internal slots and should NOT be proxied
267
- * These objects use internal mechanisms that don't work through proxies
268
- *
269
- * NOTE: Promise is intentionally NOT in this list - we proxy Promises to block
270
- * constructor access attacks. Method binding is handled specially in the get handler.
271
- */
272
- const NON_PROXYABLE_TYPES = new Set([
273
- // Map/Set have internal slots but we may need to proxy them in the future
274
- '[object Map]',
275
- '[object Set]',
276
- '[object WeakMap]',
277
- '[object WeakSet]',
278
- '[object ArrayBuffer]',
279
- '[object SharedArrayBuffer]',
280
- '[object DataView]',
281
- '[object Int8Array]',
282
- '[object Uint8Array]',
283
- '[object Uint8ClampedArray]',
284
- '[object Int16Array]',
285
- '[object Uint16Array]',
286
- '[object Int32Array]',
287
- '[object Uint32Array]',
288
- '[object Float32Array]',
289
- '[object Float64Array]',
290
- '[object BigInt64Array]',
291
- '[object BigUint64Array]',
292
- // Generators and iterators use internal slots
293
- '[object Generator]',
294
- '[object AsyncGenerator]',
295
- '[object GeneratorFunction]',
296
- '[object AsyncGeneratorFunction]',
297
- // Built-in iterators
298
- '[object Array Iterator]',
299
- '[object String Iterator]',
300
- '[object Map Iterator]',
301
- '[object Set Iterator]',
302
- '[object RegExp String Iterator]',
303
- ]);
304
- /**
305
- * Types that need method binding when proxied
306
- * These types have internal slots that require `this` to be the original object
307
- * when calling their methods (e.g., Promise.prototype.then checks [[PromiseState]])
308
- */
309
- const INTERNAL_SLOT_TYPES = new Set(['[object Promise]']);
310
- /**
311
- * Check if a value is a proxyable target (object or function)
312
- * Excludes built-in objects with internal slots that don't work through proxies
313
- */
314
- function isProxyable(value) {
315
- if (value === null)
316
- return false;
317
- if (typeof value !== 'object' && typeof value !== 'function')
318
- return false;
319
- // Check for built-in types that have internal slots
320
- const tag = Object.prototype.toString.call(value);
321
- if (NON_PROXYABLE_TYPES.has(tag)) {
322
- return false;
323
- }
324
- return true;
325
- }
326
- /**
327
- * Create a secure proxy that blocks dangerous property access
328
- *
329
- * @param target The object to wrap
330
- * @param options Configuration options
331
- * @returns A proxy that blocks dangerous property access
332
- */
333
- function createSecureProxy(target, options = {}) {
334
- // Return primitives as-is
335
- if (!isProxyable(target)) {
336
- return target;
337
- }
338
- // Generate cache key based on all options that affect proxy behavior
339
- const cacheKey = getFullCacheKey(options);
340
- // Check if already proxied with this config
341
- const targetCache = proxyCache.get(target);
342
- if (targetCache) {
343
- const cached = targetCache.get(cacheKey);
344
- if (cached) {
345
- return cached;
346
- }
347
- }
348
- // Build blocked set from levelConfig if provided, otherwise use defaults
349
- const baseBlocked = options.levelConfig
350
- ? buildBlockedPropertiesFromConfig(options.levelConfig)
351
- : new Set(BLOCKED_PROPERTIES);
352
- // Add any additional blocked properties
353
- const blockedSet = new Set([...baseBlocked, ...(options.additionalBlocked || [])]);
354
- // Use maxDepth from levelConfig if provided, otherwise from options or default
355
- const maxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
356
- // Use throwOnBlocked from options or levelConfig (options takes precedence)
357
- const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
358
- // Create inner function for recursive proxying with depth tracking
359
- function proxyWithDepth(obj, depth) {
360
- // Return primitives as-is
361
- if (!isProxyable(obj)) {
362
- return obj;
363
- }
364
- // Check cache first with config key
365
- const objCache = proxyCache.get(obj);
366
- if (objCache) {
367
- const cachedProxy = objCache.get(cacheKey);
368
- if (cachedProxy) {
369
- return cachedProxy;
370
- }
371
- }
372
- // Depth limit to prevent stack overflow
373
- if (depth > maxDepth) {
374
- return obj;
375
- }
376
- const proxy = new Proxy(obj, {
377
- get(target, property, receiver) {
378
- // Convert symbol to string for checking
379
- const propName = typeof property === 'symbol' ? property.toString() : property;
380
- // Check if property is non-configurable (proxy invariant requires returning actual value)
381
- const descriptor = Object.getOwnPropertyDescriptor(target, property);
382
- const isNonConfigurable = descriptor && !descriptor.configurable;
383
- // Block dangerous properties (but respect proxy invariants)
384
- if (typeof propName === 'string' && blockedSet.has(propName)) {
385
- if (options.onBlocked) {
386
- options.onBlocked(target, propName);
387
- }
388
- // For non-configurable, non-writable properties, JavaScript proxy invariants require
389
- // returning the EXACT same object reference. We cannot proxy the return value.
390
- // This is a fundamental JS limitation for built-in properties like Array.prototype.
391
- if (isNonConfigurable && descriptor && !descriptor.writable) {
392
- // Must return exact value to satisfy invariant
393
- return Reflect.get(target, property, receiver);
394
- }
395
- // For configurable properties, throw or return undefined
396
- if (throwOnBlocked) {
397
- throw (0, safe_error_1.createSafeError)(`Security violation: Access to '${propName}' is blocked. ` +
398
- `This property can be used for sandbox escape attacks.`, 'SecurityError');
399
- }
400
- return undefined;
401
- }
402
- // Block function-specific properties if target is a function
403
- if (typeof target === 'function' && typeof propName === 'string' && FUNCTION_BLOCKED_PROPERTIES.has(propName)) {
404
- if (options.onBlocked) {
405
- options.onBlocked(target, propName);
406
- }
407
- // Same invariant handling for non-configurable, non-writable properties
408
- if (isNonConfigurable && descriptor && !descriptor.writable) {
409
- return Reflect.get(target, property, receiver);
410
- }
411
- if (throwOnBlocked) {
412
- throw (0, safe_error_1.createSafeError)(`Security violation: Access to '${propName}' is blocked. ` +
413
- `This property can be used for sandbox escape attacks.`, 'SecurityError');
414
- }
415
- return undefined;
416
- }
417
- // Get the actual value
418
- const value = Reflect.get(target, property, receiver);
419
- // For methods on objects with internal slots (like Promise), we need to:
420
- // 1. Bind the method to the original object so internal slot checks pass
421
- // 2. Proxy the bound method to block constructor access
422
- // This prevents attacks like: callTool(...).then.constructor
423
- if (typeof value === 'function') {
424
- const tag = Object.prototype.toString.call(target);
425
- if (INTERNAL_SLOT_TYPES.has(tag)) {
426
- // Bind to original object so methods like .then() work correctly
427
- // Then proxy the bound function to block .constructor access
428
- const boundMethod = value.bind(target);
429
- return proxyWithDepth(boundMethod, depth + 1);
430
- }
431
- }
432
- // Recursively proxy objects and functions
433
- if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
434
- return proxyWithDepth(value, depth + 1);
435
- }
436
- return value;
437
- },
438
- // Block setting dangerous properties
439
- set(target, property, value, receiver) {
440
- const propName = typeof property === 'symbol' ? property.toString() : property;
441
- // Block setting dangerous properties
442
- if (typeof propName === 'string' && blockedSet.has(propName)) {
443
- if (options.onBlocked) {
444
- options.onBlocked(target, propName);
445
- }
446
- if (throwOnBlocked) {
447
- throw (0, safe_error_1.createSafeError)(`Security violation: Setting '${propName}' is blocked. ` +
448
- `This property can be used for sandbox escape attacks.`, 'SecurityError');
449
- }
450
- return false; // Silently fail
451
- }
452
- return Reflect.set(target, property, value, receiver);
453
- },
454
- // Block defining dangerous properties
455
- defineProperty(target, property, descriptor) {
456
- const propName = typeof property === 'symbol' ? property.toString() : property;
457
- if (typeof propName === 'string' && blockedSet.has(propName)) {
458
- if (options.onBlocked) {
459
- options.onBlocked(target, propName);
460
- }
461
- if (throwOnBlocked) {
462
- throw (0, safe_error_1.createSafeError)(`Security violation: Defining '${propName}' is blocked. ` +
463
- `This property can be used for sandbox escape attacks.`, 'SecurityError');
464
- }
465
- return false;
466
- }
467
- return Reflect.defineProperty(target, property, descriptor);
468
- },
469
- // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
470
- // Must respect proxy invariants: non-configurable own properties cannot be hidden
471
- ownKeys(target) {
472
- const keys = Reflect.ownKeys(target);
473
- return keys.filter((key) => {
474
- const keyStr = typeof key === 'symbol' ? key.toString() : key;
475
- // Keep non-blocked properties
476
- if (typeof keyStr !== 'string' || !blockedSet.has(keyStr)) {
477
- return true;
478
- }
479
- // Must keep non-configurable properties (proxy invariant)
480
- const descriptor = Object.getOwnPropertyDescriptor(target, key);
481
- if (descriptor && !descriptor.configurable) {
482
- return true;
483
- }
484
- // Filter out blocked configurable properties
485
- return false;
486
- });
487
- },
488
- // Hide blocked properties from property descriptor queries (defense-in-depth)
489
- // Must respect proxy invariants: non-configurable properties must return actual descriptor
490
- getOwnPropertyDescriptor(target, property) {
491
- const propName = typeof property === 'symbol' ? property.toString() : property;
492
- const descriptor = Reflect.getOwnPropertyDescriptor(target, property);
493
- // Must return actual descriptor for non-configurable properties (proxy invariant)
494
- if (descriptor && !descriptor.configurable) {
495
- return descriptor;
496
- }
497
- // Return undefined (or throw) for blocked configurable properties
498
- if (typeof propName === 'string' && blockedSet.has(propName)) {
499
- if (options.onBlocked) {
500
- options.onBlocked(target, propName);
501
- }
502
- if (throwOnBlocked) {
503
- throw (0, safe_error_1.createSafeError)(`Security violation: Access to property descriptor for '${propName}' is blocked. ` +
504
- `This property can be used for sandbox escape attacks.`, 'SecurityError');
505
- }
506
- return undefined;
507
- }
508
- return descriptor;
509
- },
510
- // Block getPrototypeOf to prevent prototype chain walking
511
- getPrototypeOf() {
512
- // Return null to hide the prototype chain
513
- return null;
514
- },
515
- // Block setPrototypeOf
516
- setPrototypeOf() {
517
- return false;
518
- },
519
- // Intercept function calls to proxy return values
520
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
521
- apply(target, thisArg, argArray) {
522
- // Call the original function
523
- const result = Reflect.apply(target, thisArg, argArray);
524
- // Proxy the return value if it's an object or function
525
- if (isProxyable(result)) {
526
- return proxyWithDepth(result, depth + 1);
527
- }
528
- return result;
529
- },
530
- });
531
- // Cache the proxy with config key
532
- let objCacheMap = proxyCache.get(obj);
533
- if (!objCacheMap) {
534
- objCacheMap = new Map();
535
- proxyCache.set(obj, objCacheMap);
536
- }
537
- objCacheMap.set(cacheKey, proxy);
538
- // Track the proxy in the WeakSet for isSecureProxy checks
539
- proxySet.add(proxy);
540
- return proxy;
541
- }
542
- return proxyWithDepth(target, 0);
543
- }
544
- /**
545
- * Wrap multiple globals with secure proxies
546
- *
547
- * @param globals Object containing global values to wrap
548
- * @param options Proxy options
549
- * @returns New object with all values wrapped in secure proxies
550
- */
551
- function wrapGlobalsWithSecureProxy(globals, options = {}) {
552
- const wrapped = {};
553
- for (const [key, value] of Object.entries(globals)) {
554
- if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
555
- wrapped[key] = createSecureProxy(value, options);
556
- }
557
- else {
558
- // Primitives don't need proxying
559
- wrapped[key] = value;
560
- }
561
- }
562
- return wrapped;
563
- }
564
- /**
565
- * Create a secure version of standard library objects
566
- *
567
- * This creates proxied versions of Math, JSON, Array, Object, etc.
568
- * that block access to dangerous properties.
569
- */
570
- function createSecureStandardLibrary(options = {}) {
571
- return wrapGlobalsWithSecureProxy({
572
- Math,
573
- JSON,
574
- Array,
575
- Object,
576
- String,
577
- Number,
578
- Date,
579
- // Note: We intentionally don't include:
580
- // - Function (dangerous)
581
- // - eval (dangerous)
582
- // - Proxy, Reflect (meta-programming)
583
- }, options);
584
- }
585
- /**
586
- * Check if an object is a secure proxy
587
- *
588
- * @param obj Object to check
589
- * @returns true if the object is wrapped in a secure proxy
590
- */
591
- function isSecureProxy(obj) {
592
- if (obj === null || typeof obj !== 'object') {
593
- return false;
594
- }
595
- return proxySet.has(obj);
596
- }
597
- /**
598
- * Clear the proxy cache
599
- *
600
- * @deprecated This function always throws an error. WeakMap and WeakSet entries are
601
- * automatically garbage collected when their target objects become unreachable.
602
- * Manual cache clearing is not supported or necessary.
603
- *
604
- * @throws {Error} Always throws to inform callers that this operation is not supported
605
- */
606
- function clearProxyCache() {
607
- throw new Error('clearProxyCache is not supported. WeakMap/WeakSet entries are automatically garbage collected when target objects become unreachable.');
608
- }
609
- //# sourceMappingURL=secure-proxy.js.map