@enclave-vm/core 0.0.1 → 2.9.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 +0,0 @@
1
- {"version":3,"file":"parent-vm-bootstrap.js","sourceRoot":"","sources":["../../../src/double-vm/parent-vm-bootstrap.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;AA4LH,8DA6jDC;AA5rDD;;;;;;;;;;;GAWG;AACH,MAAM,2BAA2B,GAAoC;IACnE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esContent":["/**\n * Parent VM Bootstrap Script Generator\n *\n * Generates the JavaScript code that runs inside the Parent VM.\n * The Parent VM is responsible for:\n * - Creating and managing the Inner VM where user code runs\n * - Intercepting and validating all tool calls from the Inner VM\n * - Applying enhanced security validation (rate limiting, pattern detection)\n * - Proxying validated tool calls to the host\n *\n * @packageDocumentation\n */\n\nimport type { SerializableParentValidationConfig, SerializableSuspiciousPattern } from './types';\nimport type { SecurityLevel } from '../types';\n\n/**\n * Options for generating the parent VM bootstrap script\n */\nexport interface ParentVmBootstrapOptions {\n /** User code to execute (already transformed by ast-guard) */\n userCode: string;\n\n /** Timeout for the inner VM in milliseconds */\n innerTimeout: number;\n\n /** Maximum iterations allowed in loops */\n maxIterations: number;\n\n /** Maximum tool calls allowed */\n maxToolCalls: number;\n\n /**\n * Tool bridge mode used for host tool calls.\n * @default 'string'\n */\n toolBridgeMode: 'string' | 'direct';\n\n /**\n * Maximum size (in bytes) of a tool request/response payload.\n * @default 5 * 1024 * 1024 (5MB)\n */\n toolBridgeMaxPayloadBytes: number;\n\n /**\n * Whether to sanitize stack traces in the sandbox.\n * Prevents host stack frame/path leakage via `error.stack` when user code catches errors.\n */\n sanitizeStackTraces: boolean;\n\n /** Security level for dangerous global removal */\n securityLevel: SecurityLevel;\n\n /** Serialized validation config */\n validationConfig: SerializableParentValidationConfig;\n\n /** Serialized suspicious patterns */\n suspiciousPatterns: SerializableSuspiciousPattern[];\n\n /** List of property names to block via secure proxy */\n blockedProperties: string[];\n\n /** Whether composite reference handles are allowed (for string concatenation) */\n allowComposites?: boolean;\n\n /** Memory limit in bytes (0 = unlimited) */\n memoryLimit?: number;\n\n /** Whether to throw errors instead of returning undefined for blocked properties */\n throwOnBlocked?: boolean;\n}\n\n/**\n * Node.js 24 dangerous globals that should be removed per security level\n * (Same as in vm-adapter.ts)\n *\n * Defense-in-depth: Even though codeGeneration.strings=false blocks\n * new Function() from strings, removing Function entirely eliminates\n * any potential bypass vectors discovered in the future.\n *\n * ATK-RECON-01 identified these accessible globals as attack surface:\n * Function, eval, Proxy, Reflect, WeakRef, FinalizationRegistry,\n * SharedArrayBuffer, Atomics, gc, WebAssembly, globalThis\n */\nconst NODEJS_24_DANGEROUS_GLOBALS: Record<SecurityLevel, string[]> = {\n STRICT: [\n // Code execution - CRITICAL\n 'Function', // Constructor for functions - primary escape vector\n 'eval', // Direct code execution\n 'globalThis', // Indirect access to all globals\n\n // Metaprogramming - sandbox escape vectors\n 'Proxy', // Can intercept all operations\n 'Reflect', // Metaprogramming primitive\n\n // Memory/timing attacks\n 'SharedArrayBuffer', // Spectre/timing attacks\n 'Atomics', // Shared memory operations\n 'gc', // Force garbage collection (shouldn't be exposed)\n\n // Future/experimental APIs\n 'Iterator', // Iterator helpers\n 'AsyncIterator', // Async iterator helpers\n 'ShadowRealm', // New realm creation (major escape risk)\n 'WeakRef', // Can observe GC behavior\n 'FinalizationRegistry', // Can observe GC behavior\n 'performance', // Timing information\n 'Temporal', // New date/time API\n ],\n SECURE: [\n // Code execution - CRITICAL\n 'Function',\n 'eval',\n 'globalThis',\n\n // Most dangerous metaprogramming\n 'Proxy',\n\n // Memory/timing attacks\n 'SharedArrayBuffer',\n 'Atomics',\n 'gc',\n\n // Future APIs\n 'Iterator',\n 'AsyncIterator',\n 'ShadowRealm',\n 'WeakRef',\n 'FinalizationRegistry',\n ],\n STANDARD: [\n // Code execution - always block these\n 'Function',\n 'eval',\n\n // Memory/timing attacks\n 'SharedArrayBuffer',\n 'Atomics',\n 'gc',\n\n // Definitely dangerous\n 'ShadowRealm',\n 'WeakRef',\n 'FinalizationRegistry',\n ],\n PERMISSIVE: [\n // Even PERMISSIVE should block the most dangerous\n 'ShadowRealm', // Too dangerous to allow\n 'gc', // Shouldn't be exposed at all\n 'SharedArrayBuffer', // Spectre risk\n 'Atomics', // Goes with SharedArrayBuffer\n ],\n};\n\n/**\n * Generate code to sanitize the inner VM context\n */\nfunction generateSanitizeContextCode(securityLevel: SecurityLevel): string {\n const globalsToRemove = NODEJS_24_DANGEROUS_GLOBALS[securityLevel];\n\n return globalsToRemove\n .map(\n (g) => `\n if ('${g}' in innerContext) {\n try { delete innerContext['${g}']; } catch (e) {\n try { innerContext['${g}'] = undefined; } catch (e2) {}\n }\n }`,\n )\n .join('\\n');\n}\n\n/**\n * Generate code for pattern detectors\n */\nfunction generatePatternDetectorsCode(patterns: SerializableSuspiciousPattern[]): string {\n const patternDefs = patterns\n .map(\n (p) => `{\n id: ${JSON.stringify(p.id)},\n description: ${JSON.stringify(p.description)},\n detect: function(operationName, args, history) {\n ${p.detectBody}\n }\n }`,\n )\n .join(',\\n ');\n\n return `[\n ${patternDefs}\n ]`;\n}\n\n/**\n * Generate the parent VM bootstrap script\n *\n * This returns JavaScript code as a string that will be executed\n * inside the parent VM context.\n */\nexport function generateParentVmBootstrap(options: ParentVmBootstrapOptions): string {\n const {\n userCode,\n innerTimeout,\n maxIterations,\n maxToolCalls,\n toolBridgeMode = 'string',\n toolBridgeMaxPayloadBytes = 5 * 1024 * 1024,\n sanitizeStackTraces,\n securityLevel,\n validationConfig,\n suspiciousPatterns,\n blockedProperties,\n allowComposites = false,\n memoryLimit = 0,\n throwOnBlocked = true,\n } = options;\n\n const sanitizeContextCode = generateSanitizeContextCode(securityLevel);\n const patternDetectorsCode = generatePatternDetectorsCode(suspiciousPatterns);\n\n // Patch code executed inside VM realms to prevent leaking host stack traces via error.stack.\n // We avoid including any file names/paths/line numbers in the formatted stack.\n const stackTraceHardeningCode = `\n(function() {\n function __ag_redactStackString(stackStr) {\n try {\n if (typeof stackStr !== 'string' || !stackStr) return 'Error';\n var lines = String(stackStr).split('\\\\n');\n var header = lines[0] ? String(lines[0]) : 'Error';\n var frameCount = (lines.length > 1) ? (lines.length - 1) : 0;\n var max = frameCount;\n if (max > 25) max = 25;\n var out = [header];\n for (var i = 0; i < max; i++) out.push(' at [REDACTED]');\n if (frameCount > max) out.push(' at [REDACTED]');\n return out.join('\\\\n');\n } catch (e) {\n return 'Error';\n }\n }\n\n function __ag_prepareStackTrace(err, stack) {\n try {\n var name = (err && err.name) ? String(err.name) : 'Error';\n var message = (err && err.message) ? String(err.message) : '';\n var header = message ? (name + ': ' + message) : name;\n if (!stack || !stack.length) return header;\n var lines = [header];\n var max = stack.length;\n if (max > 25) max = 25;\n for (var i = 0; i < max; i++) {\n lines.push(' at [REDACTED]');\n }\n if (stack.length > max) {\n lines.push(' at [REDACTED]');\n }\n return lines.join('\\\\n');\n } catch (e) {\n return 'Error';\n }\n }\n\n function __ag_lockStackGetter(proto) {\n if (!proto) return;\n try {\n var desc = Object.getOwnPropertyDescriptor(proto, 'stack');\n if (!desc || typeof desc.get !== 'function') return;\n var origGet = desc.get;\n var origSet = desc.set;\n Object.defineProperty(proto, 'stack', {\n get: function() {\n try {\n return __ag_redactStackString(origGet.call(this));\n } catch (e) {\n return 'Error';\n }\n },\n set: function(v) {\n try {\n if (typeof origSet === 'function') return origSet.call(this, v);\n } catch (e) {}\n },\n configurable: false,\n enumerable: false\n });\n } catch (e) {}\n }\n\n function __ag_lockPrepareStackTrace(ErrCtor) {\n if (!ErrCtor) return;\n try {\n Object.defineProperty(ErrCtor, 'prepareStackTrace', {\n value: __ag_prepareStackTrace,\n writable: false,\n configurable: false,\n enumerable: false\n });\n } catch (e) {}\n try {\n Object.defineProperty(ErrCtor, 'stackTraceLimit', {\n value: 25,\n writable: false,\n configurable: false,\n enumerable: false\n });\n } catch (e) {}\n }\n\n __ag_lockStackGetter(Error && Error.prototype);\n __ag_lockPrepareStackTrace(Error);\n __ag_lockPrepareStackTrace(EvalError);\n __ag_lockPrepareStackTrace(RangeError);\n __ag_lockPrepareStackTrace(ReferenceError);\n __ag_lockPrepareStackTrace(SyntaxError);\n __ag_lockPrepareStackTrace(TypeError);\n __ag_lockPrepareStackTrace(URIError);\n try {\n if (typeof AggregateError !== 'undefined') __ag_lockPrepareStackTrace(AggregateError);\n } catch (e) {}\n})();\n`.trim();\n const stackTraceHardeningCodeJson = JSON.stringify(stackTraceHardeningCode);\n\n // Detect and report code-generation attempts (Function/eval) even if user code catches the thrown error.\n // Used to fail closed in STRICT/SECURE modes.\n const codeGenViolationDetectorCode = `\n(function() {\n var __ag_report = (typeof __ag_reportViolation__ === 'function') ? __ag_reportViolation__ : null;\n function __ag_reportOnce(kind) {\n try {\n if (__ag_report) __ag_report(kind);\n } catch (e) {}\n }\n\n var __ag_Reflect = (typeof Reflect !== 'undefined') ? Reflect : null;\n var __ag_Proxy = (typeof Proxy !== 'undefined') ? Proxy : null;\n var __ag_Object = (typeof Object !== 'undefined') ? Object : null;\n\n function __ag_wrapCtor(Ctor, kind) {\n if (!Ctor || !__ag_Proxy || !__ag_Reflect || !__ag_Object) return;\n try {\n var proxy = new __ag_Proxy(Ctor, {\n apply: function(target, thisArg, args) {\n __ag_reportOnce(kind);\n return __ag_Reflect.apply(target, thisArg, args);\n },\n construct: function(target, args, newTarget) {\n __ag_reportOnce(kind);\n return __ag_Reflect.construct(target, args, newTarget);\n }\n });\n\n try {\n if (Ctor.prototype) {\n __ag_Object.defineProperty(Ctor.prototype, 'constructor', {\n value: proxy,\n writable: false,\n configurable: false,\n enumerable: false\n });\n }\n } catch (e) {}\n } catch (e) {}\n }\n\n try { __ag_wrapCtor(Function, 'CODE_GENERATION'); } catch (e) {}\n try { __ag_wrapCtor((async function(){}).constructor, 'CODE_GENERATION'); } catch (e) {}\n try { __ag_wrapCtor((function*(){}).constructor, 'CODE_GENERATION'); } catch (e) {}\n try { __ag_wrapCtor((async function*(){}).constructor, 'CODE_GENERATION'); } catch (e) {}\n})();\n`.trim();\n const codeGenViolationDetectorCodeJson = JSON.stringify(codeGenViolationDetectorCode);\n\n // Define __safe_concat/__safe_template inside the INNER VM realm.\n //\n // Why: when `__safe_concat` is a host/parent-realm function (injected into the inner context),\n // stack-overflow errors can span multiple realms and Node/V8 may bypass Error.prepareStackTrace\n // formatting entirely, leaking internal filenames like \"parent-vm.js\" into user-accessible stacks.\n //\n // By defining these helpers inside the inner realm, stack overflows stay within the inner realm\n // and our stack-trace hardening can reliably redact frames.\n const innerRealmSafeConcatAndTemplateCode = `\n(function() {\n${stackTraceHardeningCode}\n})();\n\n\t(function() {\n\t var __ag_Object = Object;\n\t var __ag_Reflect = (typeof Reflect !== 'undefined') ? Reflect : null;\n\t var __ag_Proxy = (typeof Proxy !== 'undefined') ? Proxy : null;\n\t var __ag_WeakMap = (typeof WeakMap !== 'undefined') ? WeakMap : null;\n\t var __ag_proxyCache = __ag_WeakMap ? new __ag_WeakMap() : null;\n\n\t // Capture intrinsics before any later global sanitization/proxying.\n\t var __ag_String = String;\n\t var __ag_ArrayProto = __ag_Object.getPrototypeOf([]);\n\t var __ag_refIdPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;\n var __ag_allowComposites = ${allowComposites};\n var __ag_memoryLimit = ${memoryLimit};\n var __ag_track = (typeof __host_memory_track__ === 'function') ? __host_memory_track__ : null;\n\n\t // Best-effort secure proxy to block dangerous property access on these runtime helpers.\n\t // This mirrors the \"constructor/__proto__/prototype\" defense-in-depth used elsewhere.\n\t var __ag_blocked = new Set(${JSON.stringify(blockedProperties)});\n\t function __ag_createSecureProxy(obj, depth) {\n\t if (depth === undefined) depth = 0;\n\t if (!__ag_Proxy || !__ag_Reflect) return obj;\n\t if (depth > 10) return obj;\n\t if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) return obj;\n\n\t if (__ag_proxyCache) {\n\t try {\n\t var cached = __ag_proxyCache.get(obj);\n\t if (cached) return cached;\n\t } catch (e) {}\n\t }\n\n\t var proxy = new __ag_Proxy(obj, {\n\t get: function(target, property, receiver) {\n\t var propName = __ag_String(property);\n\t if (__ag_blocked.has(propName)) {\n\t throw new Error(\n\t \"Security violation: Access to '\" + propName + \"' is blocked. \" +\n \"This property can be used for sandbox escape attacks.\"\n );\n }\n var value = __ag_Reflect.get(target, property, receiver);\n if (typeof value === 'function') {\n // Bind methods to preserve internal slots when relevant.\n try { value = value.bind(target); } catch (e) {}\n }\n return __ag_createSecureProxy(value, depth + 1);\n\t },\n\t apply: function(target, thisArg, args) {\n\t return __ag_Reflect.apply(target, thisArg, args);\n\t },\n\t construct: function(target, args, newTarget) {\n\t return __ag_Reflect.construct(target, args, newTarget);\n\t }\n\t });\n\n\t if (__ag_proxyCache) {\n\t try {\n\t __ag_proxyCache.set(obj, proxy);\n\t } catch (e) {}\n\t }\n\n\t return proxy;\n\t }\n\n function __ag_createSafeError(message, name) {\n if (name === undefined) name = 'Error';\n var error = new Error(message);\n // NOTE: Use __ag_Object.defineProperty instead of direct assignment because\n // Error.prototype.name is frozen, and in strict mode direct assignment fails.\n try {\n __ag_Object.defineProperty(error, 'name', {\n value: name,\n writable: true,\n enumerable: false,\n configurable: true\n });\n } catch (e) {}\n try {\n var SafeConstructor = __ag_Object.create(null);\n __ag_Object.defineProperties(SafeConstructor, {\n constructor: { value: SafeConstructor, writable: false, enumerable: false, configurable: false },\n prototype: { value: null, writable: false, enumerable: false, configurable: false },\n name: { value: 'SafeError', writable: false, enumerable: false, configurable: false }\n });\n __ag_Object.freeze(SafeConstructor);\n __ag_Object.defineProperty(error, 'constructor', {\n value: SafeConstructor,\n writable: false,\n enumerable: false,\n configurable: false\n });\n } catch (e) {}\n try {\n __ag_Object.defineProperty(error, '__proto__', {\n value: null,\n writable: false,\n enumerable: false,\n configurable: false\n });\n } catch (e) {}\n try {\n __ag_Object.defineProperty(error, 'stack', {\n value: undefined,\n writable: false,\n enumerable: false,\n configurable: false\n });\n } catch (e) {}\n try { __ag_Object.freeze(error); } catch (e) {}\n return error;\n }\n\n function __ag_innerConcat(left, right) {\n if (typeof left === 'number' && typeof right === 'number') {\n return left + right;\n }\n\n if (typeof left === 'string' && typeof right === 'string') {\n var leftLen = left.length;\n var rightLen = right.length;\n\n var leftIsRef = __ag_refIdPattern.test(left);\n var rightIsRef = __ag_refIdPattern.test(right);\n\n if (!leftIsRef && !rightIsRef) {\n if (__ag_track && __ag_memoryLimit > 0) {\n __ag_track(rightLen * 2);\n }\n return left + right;\n }\n\n if (!__ag_allowComposites) {\n throw __ag_createSafeError(\n 'Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +\n 'Composite handles are disabled in the current security configuration.'\n );\n }\n\n return {\n __type: 'composite',\n __operation: 'concat',\n __parts: [left, right],\n __estimatedSize: 0\n };\n }\n\n if (typeof left === 'string' || typeof right === 'string') {\n var leftIsRef2 = typeof left === 'string' && __ag_refIdPattern.test(left);\n var rightIsRef2 = typeof right === 'string' && __ag_refIdPattern.test(right);\n\n if (leftIsRef2 || rightIsRef2) {\n if (!__ag_allowComposites) {\n throw __ag_createSafeError(\n 'Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +\n 'Composite handles are disabled in the current security configuration.'\n );\n }\n\n var leftStr = __ag_String(left);\n var rightStr = __ag_String(right);\n return {\n __type: 'composite',\n __operation: 'concat',\n __parts: [leftStr, rightStr],\n __estimatedSize: 0\n };\n }\n }\n\n var result = left + right;\n if (typeof result === 'string' && __ag_track && __ag_memoryLimit > 0) {\n __ag_track(result.length * 2);\n }\n return result;\n }\n\n function __ag_innerTemplate(quasis) {\n var values = __ag_ArrayProto.slice.call(arguments, 1);\n var parts = [];\n var hasReferences = false;\n\n for (var i = 0; i < quasis.length; i++) {\n parts.push(quasis[i]);\n if (i < values.length) {\n var valueStr = __ag_String(values[i]);\n parts.push(valueStr);\n if (__ag_refIdPattern.test(valueStr)) {\n hasReferences = true;\n }\n }\n }\n\n if (!hasReferences) {\n var joined = parts.join('');\n if (typeof joined === 'string' && __ag_track && __ag_memoryLimit > 0) {\n __ag_track(joined.length * 2);\n }\n return joined;\n }\n\n if (!__ag_allowComposites) {\n throw __ag_createSafeError(\n 'Cannot concatenate reference IDs in template literals. Pass references directly to callTool arguments. ' +\n 'Composite handles are disabled in the current security configuration.'\n );\n }\n\n return {\n __type: 'composite',\n __operation: 'concat',\n __parts: parts,\n __estimatedSize: 0\n };\n }\n\n try {\n __ag_Object.defineProperty(globalThis, '__safe_concat', {\n value: __ag_createSecureProxy(__ag_innerConcat, 0),\n writable: false,\n configurable: false,\n enumerable: false\n });\n } catch (e) {}\n\n try {\n __ag_Object.defineProperty(globalThis, '__safe_template', {\n value: __ag_createSecureProxy(__ag_innerTemplate, 0),\n writable: false,\n configurable: false,\n enumerable: false\n });\n } catch (e) {}\n})();\n`.trim();\n const innerRealmSafeConcatAndTemplateCodeJson = JSON.stringify(innerRealmSafeConcatAndTemplateCode);\n\n // Generate allowed/blocked pattern reconstruction code\n let patternReconstructCode = '';\n if (validationConfig.allowedOperationPatternSource) {\n patternReconstructCode += `\n const allowedOperationPattern = new RegExp(${JSON.stringify(\n validationConfig.allowedOperationPatternSource,\n )}, ${JSON.stringify(validationConfig.allowedOperationPatternFlags || '')});\n`;\n }\n\n if (validationConfig.blockedOperationPatternSources && validationConfig.blockedOperationPatternSources.length > 0) {\n const blockedPatterns = validationConfig.blockedOperationPatternSources\n .map(\n (src, i) =>\n `new RegExp(${JSON.stringify(src)}, ${JSON.stringify(\n validationConfig.blockedOperationPatternFlags?.[i] || '',\n )})`,\n )\n .join(', ');\n patternReconstructCode += `\n const blockedOperationPatterns = [${blockedPatterns}];\n`;\n }\n\n return `\n'use strict';\n\n// Parent VM Bootstrap Script\n// This code runs inside the Parent VM and creates/manages the Inner VM\n\n (async function parentVmMain() {\n // Get injected references from host\n const vm = __host_vm_module__;\n const hostCallTool = __host_callTool__;\n const hostStats = __host_stats__;\n const hostAbortCheck = __host_abort_check__;\n const hostReportViolation = __host_reportViolation__;\n const hostConfig = __host_config__;\n const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};\n const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};\n\n // Defense-in-depth: remove direct access to host bridge references after capture.\n // If the inner VM escapes to the parent global, these names should not be discoverable.\n try { delete globalThis.__host_callTool__; } catch (e) { /* ignore */ }\n try { delete globalThis.__host_vm_module__; } catch (e) { /* ignore */ }\n try { delete globalThis.__host_stats__; } catch (e) { /* ignore */ }\n try { delete globalThis.__host_abort_check__; } catch (e) { /* ignore */ }\n try { delete globalThis.__host_reportViolation__; } catch (e) { /* ignore */ }\n try { delete globalThis.__host_config__; } catch (e) { /* ignore */ }\n\n // Policy violation reporter (best-effort; host decides how to handle based on security level)\n function __ag_reportViolation(kind) {\n try {\n if (typeof hostReportViolation === 'function') hostReportViolation(kind);\n } catch (e) { /* ignore */ }\n }\n\n // SECURITY HARDENING: prevent leaking host stack traces via error.stack inside the sandbox.\n const sanitizeStackTraces = ${sanitizeStackTraces};\n if (sanitizeStackTraces) {\n try {\n // Patch the PARENT VM realm (errors thrown from safe runtime functions).\n // Note: we execute code directly here, and separately apply the same patch to the INNER VM.\n ${stackTraceHardeningCode}\n } catch (e) { /* ignore */ }\n }\n\n /**\n * Creates a \"safe\" error object that cannot be used to escape the sandbox.\n *\n * SECURITY: This function creates error objects with a severed prototype chain\n * to prevent attacks that climb the prototype chain to reach the host Function constructor.\n * It also removes the stack trace to prevent information leakage (Vector 1230).\n *\n * Attack vectors blocked:\n * - err.constructor.constructor('return process.env.SECRET')()\n * - err.__proto__.constructor.constructor('malicious code')()\n * - err.stack leaking internal function frames and file paths (Vector 1230)\n */\n // Unique symbol-like marker for identifying safe errors (not a real Symbol to avoid sandbox escape)\n var SAFE_ERROR_MARKER = '__enclave_safe_error_' + Math.random().toString(36).slice(2);\n\n function createSafeError(message, name) {\n if (name === undefined) name = 'Error';\n\n // Create the real error\n var error = new Error(message);\n // NOTE: Use Object.defineProperty instead of direct assignment because\n // Error.prototype.name is frozen, and in strict mode direct assignment fails.\n Object.defineProperty(error, 'name', {\n value: name,\n writable: true,\n enumerable: false,\n configurable: true\n });\n\n // CRITICAL: sever the *actual* prototype chain (native getters / Object.getPrototypeOf).\n // A shadowing __proto__ data property is not sufficient.\n Object.setPrototypeOf(error, null);\n\n // Create a null-prototype object to use as a safe \"constructor\"\n // This object has no prototype chain to climb\n var SafeConstructor = Object.create(null);\n Object.defineProperties(SafeConstructor, {\n // Make constructor point to itself to break the chain\n constructor: {\n value: SafeConstructor,\n writable: false,\n enumerable: false,\n configurable: false\n },\n // Block prototype access\n prototype: {\n value: null,\n writable: false,\n enumerable: false,\n configurable: false\n },\n // Add name for debugging\n name: {\n value: 'SafeError',\n writable: false,\n enumerable: false,\n configurable: false\n }\n });\n Object.freeze(SafeConstructor);\n\n // Override the constructor property on the error instance\n // This breaks the prototype chain: err.constructor.constructor no longer reaches Function\n Object.defineProperty(error, 'constructor', {\n value: SafeConstructor,\n writable: false,\n enumerable: false,\n configurable: false\n });\n\n // SECURITY: Override __proto__ on the error instance to prevent prototype chain escape\n // Attack vector blocked: err.__proto__.constructor.constructor('malicious code')()\n Object.defineProperty(error, '__proto__', {\n value: null,\n writable: false,\n enumerable: false,\n configurable: false\n });\n\n // SECURITY: Remove the stack property to prevent information leakage (Vector 1230)\n // The stack trace can reveal internal implementation details like function names,\n // file paths, and line numbers which can be used for reconnaissance attacks.\n Object.defineProperty(error, 'stack', {\n value: undefined,\n writable: false,\n enumerable: false,\n configurable: false\n });\n\n // Add a unique marker to identify this as a safe error from our runtime\n // This is used by suspicious pattern detection to distinguish our errors from user errors\n Object.defineProperty(error, SAFE_ERROR_MARKER, {\n value: true,\n writable: false,\n enumerable: false,\n configurable: false\n });\n\n // Freeze the error to prevent modifications\n Object.freeze(error);\n\n return error;\n }\n\n // Helper to check if an error is a safe error from our runtime\n function isSafeError(e) {\n return e && e[SAFE_ERROR_MARKER] === true;\n }\n\n // Validation configuration\n const validationConfig = ${JSON.stringify({\n validateOperationNames: validationConfig.validateOperationNames,\n maxOperationsPerSecond: validationConfig.maxOperationsPerSecond,\n blockSuspiciousSequences: validationConfig.blockSuspiciousSequences,\n rapidEnumerationThreshold: validationConfig.rapidEnumerationThreshold,\n rapidEnumerationOverrides: validationConfig.rapidEnumerationOverrides,\n })};\n ${patternReconstructCode}\n\n // Suspicious pattern detectors\n const suspiciousPatterns = ${patternDetectorsCode};\n\n // Operation history for pattern detection\n const operationHistory = [];\n\n // Tool call stats for rate limiting\n let toolCallCount = 0;\n\n // Blocked properties for secure proxy (from security level)\n const blockedPropertiesSet = new Set(${JSON.stringify(blockedProperties)});\n\n // Whether to throw errors instead of returning undefined for blocked properties\n const throwOnBlocked = ${throwOnBlocked};\n\n // Whether composite reference handles are allowed (for string concatenation)\n const allowComposites = ${allowComposites};\n\n // Memory limit in bytes (0 = unlimited)\n const memoryLimit = ${memoryLimit};\n\n // Reference ID pattern for detecting sidecar references\n const refIdPattern = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;\n\n // Proxy cache to avoid infinite recursion and duplicate wrapping\n const proxyCache = new WeakMap();\n\n /**\n * Create a secure proxy that blocks access to dangerous properties\n * Defense-in-depth against attacks like: callTool['const' + 'ructor']\n *\n * IMPORTANT: Must respect JavaScript proxy invariants:\n * - Non-configurable properties must return their actual value\n * - Non-configurable non-writable properties cannot be hidden\n */\n function createSecureProxy(obj, depth) {\n if (depth === undefined) depth = 0;\n if (depth > 10) return obj; // Max depth to prevent infinite recursion\n\n // Skip primitives and null\n if (obj === null || typeof obj !== 'object' && typeof obj !== 'function') {\n return obj;\n }\n\n // Check cache\n if (proxyCache.has(obj)) {\n return proxyCache.get(obj);\n }\n\n var proxy = new Proxy(obj, {\n get: function(target, property, receiver) {\n var propName = String(property);\n\n // Check if property is non-configurable (proxy invariant requires returning actual value)\n var descriptor = Object.getOwnPropertyDescriptor(target, property);\n var isNonConfigurable = descriptor && !descriptor.configurable;\n\n // Proxy invariant: if the target has a non-configurable, non-writable data property,\n // the proxy must return the exact same value (cannot wrap/bind/proxy it).\n // This matters for hardened properties like Error.prepareStackTrace.\n if (descriptor && isNonConfigurable && 'value' in descriptor && descriptor.writable === false) {\n return descriptor.value;\n }\n\n // Block dangerous properties - but respect proxy invariants\n if (blockedPropertiesSet.has(propName)) {\n // For non-configurable properties, we MUST return the actual value\n // (JavaScript proxy invariant - can't hide non-configurable properties)\n if (isNonConfigurable) {\n return Reflect.get(target, property, receiver);\n }\n if (throwOnBlocked) {\n throw createSafeError(\n \"Security violation: Access to '\" + propName + \"' is blocked. \" +\n \"This property can be used for sandbox escape attacks.\"\n );\n }\n return undefined;\n }\n\n var value = Reflect.get(target, property, receiver);\n\n // For function values, bind to target first (preserves internal slot access for Promises, etc.)\n // Then recursively proxy the bound function to block constructor access\n if (typeof value === 'function') {\n var boundMethod = value.bind(target);\n return createSecureProxy(boundMethod, depth + 1);\n }\n\n // Recursively proxy nested objects to maintain security barrier\n // This prevents attacks like: process.env.__proto__.constructor\n if (value !== null && typeof value === 'object') {\n return createSecureProxy(value, depth + 1);\n }\n\n return value;\n },\n set: function(target, property, value, receiver) {\n var propName = String(property);\n if (blockedPropertiesSet.has(propName)) {\n if (throwOnBlocked) {\n throw createSafeError(\n \"Security violation: Setting '\" + propName + \"' is blocked. \" +\n \"This property can be used for sandbox escape attacks.\"\n );\n }\n return false;\n }\n return Reflect.set(target, property, value, receiver);\n },\n defineProperty: function(target, property, descriptor) {\n var propName = String(property);\n if (blockedPropertiesSet.has(propName)) {\n if (throwOnBlocked) {\n throw createSafeError(\n \"Security violation: Defining '\" + propName + \"' is blocked. \" +\n \"This property can be used for sandbox escape attacks.\"\n );\n }\n return false;\n }\n return Reflect.defineProperty(target, property, descriptor);\n },\n getOwnPropertyDescriptor: function(target, property) {\n var propName = String(property);\n var descriptor = Reflect.getOwnPropertyDescriptor(target, property);\n\n // Must return actual descriptor for non-configurable properties (proxy invariant)\n if (descriptor && !descriptor.configurable) {\n return descriptor;\n }\n\n // Block configurable dangerous properties\n if (blockedPropertiesSet.has(propName)) {\n if (throwOnBlocked) {\n throw createSafeError(\n \"Security violation: Access to property descriptor for '\" + propName + \"' is blocked. \" +\n \"This property can be used for sandbox escape attacks.\"\n );\n }\n return undefined;\n }\n return descriptor;\n },\n ownKeys: function(target) {\n var keys = Reflect.ownKeys(target);\n return keys.filter(function(key) {\n var keyStr = String(key);\n // Keep non-blocked properties\n if (!blockedPropertiesSet.has(keyStr)) {\n return true;\n }\n // Must keep non-configurable properties (proxy invariant)\n var descriptor = Object.getOwnPropertyDescriptor(target, key);\n if (descriptor && !descriptor.configurable) {\n return true;\n }\n // Filter out blocked configurable properties\n return false;\n });\n },\n getPrototypeOf: function(target) {\n // Return null to hide prototype chain\n return null;\n }\n });\n\n proxyCache.set(obj, proxy);\n return proxy;\n }\n\n /**\n * Validate an operation before forwarding to host\n */\n function validateOperation(operationName, args) {\n // Rate limiting check with sliding window cleanup\n const now = Date.now();\n // Clean up old entries to prevent unbounded growth (keep only last 2 seconds)\n while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {\n operationHistory.shift();\n }\n const recentOperations = operationHistory.filter(function(h) { return now - h.timestamp < 1000; });\n if (recentOperations.length >= validationConfig.maxOperationsPerSecond) {\n throw createSafeError('Operation rate limit exceeded (' + validationConfig.maxOperationsPerSecond + ' operations/second)');\n }\n\n // Operation name format validation\n if (typeof operationName !== 'string' || !operationName) {\n throw createSafeError('Operation name must be a non-empty string', 'TypeError');\n }\n\n // Operation name pattern validation (whitelist)\n if (validationConfig.validateOperationNames && typeof allowedOperationPattern !== 'undefined') {\n if (!allowedOperationPattern.test(operationName)) {\n throw createSafeError('Operation \"' + operationName + '\" does not match allowed pattern');\n }\n }\n\n // Operation name pattern validation (blacklist)\n if (typeof blockedOperationPatterns !== 'undefined') {\n for (var i = 0; i < blockedOperationPatterns.length; i++) {\n if (blockedOperationPatterns[i].test(operationName)) {\n throw createSafeError('Operation \"' + operationName + '\" matches blocked pattern');\n }\n }\n }\n\n // Suspicious sequence detection\n // NOTE: User-provided pattern functions can throw; those errors are intentionally ignored to avoid\n // breaking the sandbox due to a buggy detector. If a detector returns true, we always fail closed.\n if (validationConfig.blockSuspiciousSequences) {\n for (var j = 0; j < suspiciousPatterns.length; j++) {\n var pattern = suspiciousPatterns[j];\n var detected = false;\n try {\n detected = !!pattern.detect(operationName, args, operationHistory);\n } catch (e) {\n detected = false;\n }\n if (detected) {\n throw createSafeError('Suspicious pattern detected: ' + pattern.description + ' [' + pattern.id + ']');\n }\n }\n }\n }\n\n /**\n * Inner VM's callTool function\n * Proxies through parent VM with validation\n */\n function innerCallTool(toolName, args) {\n // Check if aborted\n if (hostAbortCheck()) {\n throw createSafeError('Execution aborted');\n }\n\n // Increment count and check limit\n toolCallCount++;\n if (toolCallCount > ${maxToolCalls}) {\n throw createSafeError('Maximum tool call limit exceeded (${maxToolCalls}). This limit prevents runaway script execution.');\n }\n\n // Validate args\n if (typeof args !== 'object' || args === null || Array.isArray(args)) {\n throw createSafeError('Tool arguments must be an object', 'TypeError');\n }\n\n // Double sanitization (defense in depth)\n var sanitizedArgs;\n try {\n sanitizedArgs = JSON.parse(JSON.stringify(args));\n } catch (e) {\n throw createSafeError('Tool arguments must be JSON-serializable');\n }\n\n // Enhanced validation\n validateOperation(toolName, sanitizedArgs);\n\n // Record in history\n operationHistory.push({\n operationName: toolName,\n timestamp: Date.now(),\n argKeys: Object.keys(sanitizedArgs)\n });\n\n // Update host stats\n hostStats.toolCallCount = toolCallCount;\n\n // Forward to host and wrap the Promise + result in secure proxies\n // This prevents access to Promise.constructor and result object constructors\n var promise;\n if (toolBridgeMode === 'string') {\n var requestJson;\n try {\n requestJson = JSON.stringify({ v: 1, tool: toolName, args: sanitizedArgs });\n } catch (e) {\n throw createSafeError('Tool request must be JSON-serializable');\n }\n\n // Conservative byte estimate: UTF-8 is at most 4 bytes per code unit.\n if (requestJson && (requestJson.length * 4) > toolBridgeMaxPayloadBytes) {\n throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');\n }\n\n promise = hostCallTool(requestJson).then(function(responseJson) {\n if (typeof responseJson !== 'string') {\n throw createSafeError('Tool bridge returned non-string response');\n }\n\n if ((responseJson.length * 4) > toolBridgeMaxPayloadBytes) {\n throw createSafeError('Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');\n }\n\n var response;\n try {\n response = JSON.parse(responseJson);\n } catch (e) {\n throw createSafeError('Tool bridge returned invalid JSON');\n }\n\n if (!response || typeof response !== 'object' || Array.isArray(response)) {\n throw createSafeError('Tool bridge returned invalid response');\n }\n\n if (response.v !== 1) {\n throw createSafeError('Tool bridge protocol version mismatch');\n }\n\n if (response.ok === true) {\n if (Object.prototype.hasOwnProperty.call(response, 'value')) {\n return response.value;\n }\n return undefined;\n }\n\n if (response.ok === false) {\n var err = response.error;\n var msg = (err && typeof err.message === 'string') ? err.message : 'Tool call failed';\n var name = (err && typeof err.name === 'string') ? err.name : 'Error';\n throw createSafeError(msg, name);\n }\n\n throw createSafeError('Tool bridge returned invalid response');\n });\n } else {\n promise = hostCallTool(toolName, sanitizedArgs);\n }\n\n // Create a secure promise that wraps both the promise object and its result\n // Note: We can't just wrap the promise because Promise.then/catch/finally must work\n // Instead, we chain the promise to wrap the result\n return createSecureProxy(promise.then(function(result) {\n return createSecureProxy(result);\n }));\n }\n\n /**\n * Safe for-of iterator for inner VM\n */\n function* innerForOf(iterable) {\n var iterations = 0;\n for (var item of iterable) {\n if (hostAbortCheck()) {\n throw createSafeError('Execution aborted');\n }\n iterations++;\n hostStats.iterationCount++;\n if (iterations > ${maxIterations}) {\n throw createSafeError('Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.');\n }\n yield item;\n }\n }\n\n /**\n * Safe for loop wrapper for inner VM\n */\n function innerFor(init, test, update, body) {\n var iterations = 0;\n init();\n while (test()) {\n if (hostAbortCheck()) {\n throw createSafeError('Execution aborted');\n }\n iterations++;\n hostStats.iterationCount++;\n if (iterations > ${maxIterations}) {\n throw createSafeError('Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.');\n }\n body();\n update();\n }\n }\n\n /**\n * Safe while loop wrapper for inner VM\n */\n function innerWhile(test, body) {\n var iterations = 0;\n while (test()) {\n if (hostAbortCheck()) {\n throw createSafeError('Execution aborted');\n }\n iterations++;\n hostStats.iterationCount++;\n if (iterations > ${maxIterations}) {\n throw createSafeError('Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.');\n }\n body();\n }\n }\n\n /**\n * Safe do-while loop wrapper for inner VM\n */\n function innerDoWhile(test, body) {\n var iterations = 0;\n do {\n if (hostAbortCheck()) {\n throw createSafeError('Execution aborted');\n }\n iterations++;\n hostStats.iterationCount++;\n if (iterations > ${maxIterations}) {\n throw createSafeError('Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.');\n }\n body();\n } while (test());\n }\n\n /**\n * Safe addition/concatenation for inner VM\n * Supports numeric addition, string concatenation, and reference ID handling.\n * Also tracks memory allocation when memoryLimit is set.\n */\n function innerConcat(left, right) {\n // Fast path: both are numbers - do numeric addition (JavaScript + semantics)\n if (typeof left === 'number' && typeof right === 'number') {\n return left + right;\n }\n\n // Fast path: both are strings\n if (typeof left === 'string' && typeof right === 'string') {\n var leftLen = left.length;\n var rightLen = right.length;\n\n var leftIsRef = refIdPattern.test(left);\n var rightIsRef = refIdPattern.test(right);\n\n if (!leftIsRef && !rightIsRef) {\n // Track memory if enabled\n if (memoryLimit > 0) {\n __host_memory_track__(rightLen * 2); // UTF-16 encoding\n }\n return left + right;\n }\n\n // References detected - check if composites are allowed\n if (!allowComposites) {\n throw createSafeError(\n 'Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +\n 'Composite handles are disabled in the current security configuration.'\n );\n }\n\n return {\n __type: 'composite',\n __operation: 'concat',\n __parts: [left, right],\n __estimatedSize: 0\n };\n }\n\n // For mixed types (one string, one non-string), check for references first\n // then use native + for proper ToPrimitive handling\n if (typeof left === 'string' || typeof right === 'string') {\n // Check if the string operand(s) are references BEFORE coercion\n var leftIsRef = typeof left === 'string' && refIdPattern.test(left);\n var rightIsRef = typeof right === 'string' && refIdPattern.test(right);\n\n if (leftIsRef || rightIsRef) {\n // Reference detected - check if composites are allowed\n if (!allowComposites) {\n throw createSafeError(\n 'Cannot concatenate reference IDs. Pass references directly to callTool arguments. ' +\n 'Composite handles are disabled in the current security configuration.'\n );\n }\n\n // Convert both to strings for composite\n var leftStr = String(left);\n var rightStr = String(right);\n return {\n __type: 'composite',\n __operation: 'concat',\n __parts: [leftStr, rightStr],\n __estimatedSize: 0\n };\n }\n }\n\n // For all other cases (objects, booleans, null, undefined, or strings without refs),\n // use JavaScript's default + behavior which correctly handles ToPrimitive\n var result = left + right;\n\n // Track if result is a string\n if (typeof result === 'string' && memoryLimit > 0) {\n __host_memory_track__(result.length * 2);\n }\n\n return result;\n }\n\n /**\n * Safe template literal for inner VM\n * Detects reference IDs and handles them according to allowComposites config\n */\n function innerTemplate(quasis) {\n var values = Array.prototype.slice.call(arguments, 1);\n var parts = [];\n var hasReferences = false;\n\n for (var i = 0; i < quasis.length; i++) {\n parts.push(quasis[i]);\n if (i < values.length) {\n var valueStr = String(values[i]);\n parts.push(valueStr);\n if (refIdPattern.test(valueStr)) {\n hasReferences = true;\n }\n }\n }\n\n // If no references, just concatenate normally\n if (!hasReferences) {\n return parts.join('');\n }\n\n // References detected - check if composites are allowed\n if (!allowComposites) {\n throw createSafeError(\n 'Cannot concatenate reference IDs in template literals. Pass references directly to callTool arguments. ' +\n 'Composite handles are disabled in the current security configuration.'\n );\n }\n\n // Create a composite handle for lazy resolution at callTool boundary\n return {\n __type: 'composite',\n __operation: 'concat',\n __parts: parts,\n __estimatedSize: 0\n };\n }\n\n /**\n * Safe parallel execution for inner VM\n */\n async function innerParallel(items, fn) {\n if (!Array.isArray(items)) {\n throw createSafeError('parallel() requires an array', 'TypeError');\n }\n if (typeof fn !== 'function') {\n throw createSafeError('parallel() requires a callback function as second argument', 'TypeError');\n }\n if (items.length > 100) {\n throw createSafeError('parallel() is limited to 100 items');\n }\n return await Promise.all(items.map(fn));\n }\n\n /**\n * Rate-limited console for inner VM\n */\n var consoleStats = { totalBytes: 0, callCount: 0 };\n var maxConsoleBytes = hostConfig.maxConsoleOutputBytes || 65536;\n var maxConsoleCalls = hostConfig.maxConsoleCalls || 100;\n\n function createSafeConsoleMethod(method) {\n return function() {\n consoleStats.callCount++;\n if (consoleStats.callCount > maxConsoleCalls) {\n throw createSafeError('Console call limit exceeded (max: ' + maxConsoleCalls + '). This limit prevents I/O flood attacks.');\n }\n var output = Array.prototype.map.call(arguments, function(a) {\n if (a === undefined) return 'undefined';\n if (a === null) return 'null';\n if (typeof a === 'object') {\n try { return JSON.stringify(a); } catch (e) { return String(a); }\n }\n return String(a);\n }).join(' ');\n consoleStats.totalBytes += output.length;\n if (consoleStats.totalBytes > maxConsoleBytes) {\n throw createSafeError('Console output size limit exceeded (max: ' + maxConsoleBytes + ' bytes). This limit prevents I/O flood attacks.');\n }\n method.apply(console, arguments);\n };\n }\n\n var innerConsole = {\n log: createSafeConsoleMethod(console.log.bind(console)),\n error: createSafeConsoleMethod(console.error.bind(console)),\n warn: createSafeConsoleMethod(console.warn.bind(console)),\n info: createSafeConsoleMethod(console.info.bind(console))\n };\n\n // ============================================================\n // Create Inner VM\n // ============================================================\n\n // Create completely isolated context\n // codeGeneration.strings=false disables new Function() and eval() from strings\n // This prevents sandbox escape via constructor chain: [][c][c]('malicious code')\n var innerContext = vm.createContext({}, {\n codeGeneration: { strings: false, wasm: false }\n });\n\n // STRICT/SECURE: record code-generation attempts (Function/eval) even if user code catches them.\n if (${securityLevel === 'STRICT' || securityLevel === 'SECURE'}) {\n try {\n Object.defineProperty(innerContext, '__ag_reportViolation__', {\n value: __ag_reportViolation,\n writable: false,\n configurable: false,\n enumerable: false\n });\n var codeGenPatchScript = new vm.Script(${codeGenViolationDetectorCodeJson});\n codeGenPatchScript.runInContext(innerContext);\n } catch (e) { /* ignore */ }\n }\n\n // Apply stack trace hardening to INNER VM realm (prevents error.stack leakage to user code).\n if (sanitizeStackTraces) {\n try {\n var stackPatchScript = new vm.Script(${stackTraceHardeningCodeJson});\n stackPatchScript.runInContext(innerContext);\n } catch (e) { /* ignore */ }\n }\n\n // CRITICAL: Inject memory-safe prototype methods BEFORE sanitization\n // This must happen FIRST because sanitization may remove globals needed for patching.\n // The patch needs the intrinsic Object.getPrototypeOf to access the VM's actual\n // String.prototype and Array.prototype (not the global realm's).\n // Security: Prevents ATK-JSON-03 (Parser Bomb) and similar attacks\n // These checks happen BEFORE allocation, not after\n //\n // SECURITY FIX (Vector 320): Track CUMULATIVE memory usage across all allocations\n // Previously only checked if single allocation exceeded limit, allowing attackers\n // to create many smaller allocations that together exceed the limit.\n // We use __host_memory_track__ to track cumulative memory in the host's MemoryTracker.\n (function() {\n var memoryLimit = hostConfig.memoryLimit || 0;\n if (memoryLimit > 0) {\n // First, inject the host memory tracking callback into innerContext\n // This allows the patched methods to track cumulative memory\n Object.defineProperty(innerContext, '__host_memory_track__', {\n value: __host_memory_track__,\n writable: false,\n configurable: false,\n enumerable: false\n });\n\n // Run the patching code in innerContext\n var patchCode = '(function() {' +\n 'var memoryLimit = ' + memoryLimit + ';' +\n 'var trackMemory = __host_memory_track__;' +\n // Get the ACTUAL prototype used by literals in this realm\n 'var stringProto = Object.getPrototypeOf(\"\");' +\n 'var arrayProto = Object.getPrototypeOf([]);' +\n // Patch string repeat\n 'var originalRepeat = stringProto.repeat;' +\n 'stringProto.repeat = function(count) {' +\n ' var estimatedSize = this.length * count * 2;' +\n ' if (estimatedSize > memoryLimit) {' +\n ' throw new RangeError(\"String.repeat would exceed memory limit: \" +' +\n ' Math.round(estimatedSize / 1024 / 1024) + \"MB > \" +' +\n ' Math.round(memoryLimit / 1024 / 1024) + \"MB\");' +\n ' }' +\n ' trackMemory(estimatedSize);' +\n ' return originalRepeat.call(this, count);' +\n '};' +\n // Patch array join\n 'var originalJoin = arrayProto.join;' +\n 'arrayProto.join = function(separator) {' +\n ' var sep = separator === undefined ? \",\" : String(separator);' +\n ' var estimatedSize = 0;' +\n ' for (var i = 0; i < this.length; i++) {' +\n ' var item = this[i];' +\n ' estimatedSize += (item === null || item === undefined) ? 0 : String(item).length;' +\n ' if (i > 0) estimatedSize += sep.length;' +\n ' }' +\n ' estimatedSize *= 2;' +\n ' if (estimatedSize > memoryLimit) {' +\n ' throw new RangeError(\"Array.join would exceed memory limit: \" +' +\n ' Math.round(estimatedSize / 1024 / 1024) + \"MB > \" +' +\n ' Math.round(memoryLimit / 1024 / 1024) + \"MB\");' +\n ' }' +\n ' trackMemory(estimatedSize);' +\n ' return originalJoin.call(this, separator);' +\n '};' +\n // Patch string padStart/padEnd\n 'var originalPadStart = stringProto.padStart;' +\n 'var originalPadEnd = stringProto.padEnd;' +\n 'stringProto.padStart = function(targetLength, padString) {' +\n ' var estimatedSize = Math.max(this.length, targetLength) * 2;' +\n ' if (estimatedSize > memoryLimit) {' +\n ' throw new RangeError(\"String.padStart would exceed memory limit\");' +\n ' }' +\n ' trackMemory(estimatedSize);' +\n ' return originalPadStart.call(this, targetLength, padString);' +\n '};' +\n 'stringProto.padEnd = function(targetLength, padString) {' +\n ' var estimatedSize = Math.max(this.length, targetLength) * 2;' +\n ' if (estimatedSize > memoryLimit) {' +\n ' throw new RangeError(\"String.padEnd would exceed memory limit\");' +\n ' }' +\n ' trackMemory(estimatedSize);' +\n ' return originalPadEnd.call(this, targetLength, padString);' +\n '};' +\n // Patch array fill - converts sparse arrays to dense (allocates memory)\n // Vector 1110/1170: Array(dynamicSize).fill() can exhaust memory\n 'var originalFill = arrayProto.fill;' +\n 'arrayProto.fill = function(value, start, end) {' +\n ' var len = this.length >>> 0;' +\n ' var relativeStart = start === undefined ? 0 : (start >> 0);' +\n ' var relativeEnd = end === undefined ? len : (end >> 0);' +\n ' var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len);' +\n ' var finalEnd = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len);' +\n ' var fillCount = Math.max(0, finalEnd - k);' +\n ' var estimatedSize = fillCount * 8;' +\n ' if (estimatedSize > memoryLimit) {' +\n ' throw new RangeError(\"Array.fill would exceed memory limit: \" +' +\n ' Math.round(estimatedSize / 1024 / 1024) + \"MB > \" +' +\n ' Math.round(memoryLimit / 1024 / 1024) + \"MB\");' +\n ' }' +\n ' trackMemory(estimatedSize);' +\n ' return originalFill.call(this, value, start, end);' +\n '};' +\n '})();';\n var patchScript = new vm.Script(patchCode);\n patchScript.runInContext(innerContext);\n }\n })();\n\n // Remove dangerous globals from inner VM (AFTER memory patching)\n ${sanitizeContextCode}\n\n // Freeze built-in prototypes to prevent prototype pollution\n // and cut off constructor chain access for sandbox escape prevention\n //\n // We freeze prototypes in TWO places:\n // 1. PARENT VM prototypes - because SafeObject.prototype = Object.prototype uses parent's prototype\n // and user code accessing Object.prototype gets SafeObject.prototype\n // 2. INNER VM prototypes - for string/array literals which use intrinsic prototypes\n //\n // This provides defense-in-depth against prototype pollution attacks.\n\n // Freeze PARENT VM prototypes (used by SafeObject and other safe globals)\n Object.freeze(Object.prototype);\n Object.freeze(Array.prototype);\n Object.freeze(Function.prototype);\n Object.freeze(String.prototype);\n Object.freeze(Number.prototype);\n Object.freeze(Boolean.prototype);\n Object.freeze(Date.prototype);\n Object.freeze(Error.prototype);\n Object.freeze(TypeError.prototype);\n Object.freeze(RangeError.prototype);\n Object.freeze(SyntaxError.prototype);\n Object.freeze(ReferenceError.prototype);\n Object.freeze(Promise.prototype);\n\n // Freeze INNER VM prototypes (used by literals like '', [], etc.)\n (function() {\n var freezeCode =\n 'Object.freeze(Object.prototype);' +\n 'Object.freeze(Array.prototype);' +\n 'Object.freeze(Function.prototype);' +\n 'Object.freeze(String.prototype);' +\n 'Object.freeze(Number.prototype);' +\n 'Object.freeze(Boolean.prototype);' +\n 'Object.freeze(Date.prototype);' +\n 'Object.freeze(Error.prototype);' +\n 'Object.freeze(TypeError.prototype);' +\n 'Object.freeze(RangeError.prototype);' +\n 'Object.freeze(SyntaxError.prototype);' +\n 'Object.freeze(ReferenceError.prototype);' +\n 'Object.freeze(Promise.prototype);';\n var freezeScript = new vm.Script(freezeCode);\n freezeScript.runInContext(innerContext);\n })();\n\n // Inject safe runtime functions (non-writable, non-configurable)\n // Wrap with secure proxy to block dangerous property access\n var safeRuntime = {\n __safe_callTool: createSecureProxy(innerCallTool),\n __safe_forOf: createSecureProxy(innerForOf),\n __safe_for: createSecureProxy(innerFor),\n __safe_while: createSecureProxy(innerWhile),\n __safe_doWhile: createSecureProxy(innerDoWhile),\n __safe_parallel: createSecureProxy(innerParallel),\n __safe_console: createSecureProxy(innerConsole),\n callTool: createSecureProxy(innerCallTool),\n parallel: createSecureProxy(innerParallel),\n // Loop transformation runtime support\n __maxIterations: ${maxIterations}\n };\n\n // SECURITY FIX (Vector 640): Use enumerable: false to prevent valueOf context-hijack\n // Attack uses arrow functions in valueOf hooks where \"this\" refers to global scope.\n // Object.values(this) would enumerate all enumerable properties including internal\n // functions, leaking their source code. Non-enumerable prevents this information leak.\n for (var key in safeRuntime) {\n if (safeRuntime.hasOwnProperty(key)) {\n Object.defineProperty(innerContext, key, {\n value: safeRuntime[key],\n writable: false,\n configurable: false,\n enumerable: false\n });\n }\n }\n\n // Define __safe_concat and __safe_template in the INNER realm to avoid cross-realm stacks.\n // (See innerRealmSafeConcatAndTemplateCode for rationale.)\n try {\n var innerRuntimeScript = new vm.Script(${innerRealmSafeConcatAndTemplateCodeJson}, { filename: 'inner-runtime.js' });\n innerRuntimeScript.runInContext(innerContext);\n } catch (e) { /* ignore */ }\n\n // Create a safe Object that blocks dangerous STATIC methods\n // Prevents ATK-DATA-02 (Serialization Hijack via defineProperty)\n // Note: __defineGetter__ etc. are on Object.prototype (instance methods), not static\n var DANGEROUS_OBJECT_STATIC_METHODS = [\n 'defineProperty',\n 'defineProperties',\n 'setPrototypeOf',\n 'getOwnPropertyDescriptor',\n 'getOwnPropertyDescriptors'\n ];\n\n var SafeObject = function(value) {\n if (value === null || value === undefined) return {};\n return Object(value);\n };\n\n // Copy safe static methods\n var safeObjectMethods = [\n 'keys', 'values', 'entries', 'fromEntries', 'assign', 'is', 'hasOwn',\n 'freeze', 'isFrozen', 'seal', 'isSealed', 'preventExtensions', 'isExtensible',\n 'getOwnPropertyNames', 'getOwnPropertySymbols', 'getPrototypeOf'\n ];\n for (var i = 0; i < safeObjectMethods.length; i++) {\n var m = safeObjectMethods[i];\n if (m in Object) SafeObject[m] = Object[m];\n }\n\n // Safe Object.create without property descriptors\n SafeObject.create = function(proto, props) {\n if (props !== undefined) {\n throw createSafeError('Object.create with property descriptors is not allowed (security restriction)');\n }\n return Object.create(proto);\n };\n\n SafeObject.prototype = Object.prototype;\n\n // Block dangerous methods with helpful errors\n for (var i = 0; i < DANGEROUS_OBJECT_STATIC_METHODS.length; i++) {\n (function(method) {\n SafeObject[method] = function() {\n throw createSafeError('Object.' + method + ' is not allowed (security restriction: prevents property manipulation attacks)');\n };\n })(DANGEROUS_OBJECT_STATIC_METHODS[i]);\n }\n\n // Get INNER context's intrinsic constructors\n // CRITICAL: We must use the inner context's Array/String/etc constructors\n // so that objects created with new Array() use the patched prototypes.\n // Using parent VM constructors would bypass our memory-safe prototype patches.\n var innerIntrinsics = (function() {\n var getIntrinsicsCode =\n '({ ' +\n ' Array: Array, ' +\n ' String: String, ' +\n ' Number: Number, ' +\n ' Boolean: Boolean, ' +\n ' Date: Date, ' +\n ' RegExp: RegExp, ' +\n ' Error: Error, ' +\n ' TypeError: TypeError, ' +\n ' RangeError: RangeError, ' +\n ' Promise: Promise, ' +\n ' Math: Math, ' +\n ' JSON: JSON ' +\n '})';\n var script = new vm.Script(getIntrinsicsCode);\n return script.runInContext(innerContext);\n })();\n\n // Add safe standard globals wrapped with secure proxy\n // Use inner context intrinsics for constructors to ensure patched prototypes are used\n var safeGlobals = {\n Math: createSecureProxy(innerIntrinsics.Math),\n JSON: createSecureProxy(innerIntrinsics.JSON),\n Array: createSecureProxy(innerIntrinsics.Array),\n Object: createSecureProxy(SafeObject),\n String: createSecureProxy(innerIntrinsics.String),\n Number: createSecureProxy(innerIntrinsics.Number),\n Date: createSecureProxy(innerIntrinsics.Date),\n Boolean: createSecureProxy(innerIntrinsics.Boolean),\n RegExp: createSecureProxy(innerIntrinsics.RegExp),\n Error: createSecureProxy(innerIntrinsics.Error),\n TypeError: createSecureProxy(innerIntrinsics.TypeError),\n RangeError: createSecureProxy(innerIntrinsics.RangeError),\n Promise: createSecureProxy(innerIntrinsics.Promise),\n undefined: undefined,\n NaN: NaN,\n Infinity: Infinity,\n isNaN: isNaN,\n isFinite: isFinite,\n parseInt: parseInt,\n parseFloat: parseFloat,\n encodeURI: encodeURI,\n decodeURI: decodeURI,\n encodeURIComponent: encodeURIComponent,\n decodeURIComponent: decodeURIComponent\n };\n\n // SECURITY FIX (Vector 640): Use enumerable: false for defense-in-depth\n // While standard globals (Math, JSON, etc.) are less sensitive than internal functions,\n // making them non-enumerable prevents Object.values(this) from revealing sandbox structure.\n // Skip globals that the user is providing their own version of\n for (var gKey in safeGlobals) {\n if (safeGlobals.hasOwnProperty(gKey)) {\n // If user provides this global, skip so their version takes precedence\n if (hostConfig.globals && hostConfig.globals.hasOwnProperty(gKey)) {\n continue;\n }\n Object.defineProperty(innerContext, gKey, {\n value: safeGlobals[gKey],\n writable: false,\n configurable: false,\n enumerable: false\n });\n }\n }\n\n // Add user-provided globals if any (also wrapped with secure proxy and non-writable)\n // SECURITY: Use enumerable: false to prevent Object.assign({}, this) from copying globals\n // This blocks Vector 380 (Bridge-Serialized State Reflection) attack\n if (hostConfig.globals) {\n for (var uKey in hostConfig.globals) {\n if (hostConfig.globals.hasOwnProperty(uKey)) {\n var wrappedGlobal = createSecureProxy(hostConfig.globals[uKey]);\n Object.defineProperty(innerContext, uKey, {\n value: wrappedGlobal,\n writable: false,\n configurable: false,\n enumerable: false\n });\n // Also add __safe_ prefixed version\n Object.defineProperty(innerContext, '__safe_' + uKey, {\n value: wrappedGlobal,\n writable: false,\n configurable: false,\n enumerable: false\n });\n }\n }\n }\n\n // ============================================================\n // Execute User Code\n // ============================================================\n\n var userCode = ${JSON.stringify(userCode)};\n // IMPORTANT: For stack overflow errors (RangeError: Maximum call stack size exceeded),\n // Node/V8 may ignore Error.prepareStackTrace when it was installed by a different Script\n // than the one that triggered the overflow. To make stack sanitization reliable,\n // we also prepend the hardening code into the same Script that executes user code.\n var __ag_stackHardenPrefix = sanitizeStackTraces ? (${stackTraceHardeningCodeJson} + '\\\\n') : '';\n var wrappedCode =\n '(async function() { ' +\n __ag_stackHardenPrefix +\n userCode +\n ' return typeof __ag_main === \"function\" ? await __ag_main() : undefined; })()';\n\n var script = new vm.Script(wrappedCode, { filename: 'inner-agentscript.js' });\n\n // SECURITY HARDENING: Disable vm module before running user code\n // This prevents access to vm module even if user code escapes to parent context\n // We null out the vm object's methods since we can't delete globals in strict mode\n try {\n vm.createContext = null;\n vm.Script = null;\n } catch (e) { /* ignore if properties are non-writable */ }\n\n // Note: codeGeneration is set in createContext(), not runInContext()\n var result = await script.runInContext(innerContext, {\n timeout: ${innerTimeout},\n breakOnSigint: true\n });\n\n return result;\n})();\n`.trim();\n}\n"]}
@@ -1,304 +0,0 @@
1
- "use strict";
2
- /**
3
- * Default Suspicious Pattern Detectors
4
- *
5
- * These patterns detect potentially malicious operation sequences
6
- * that may indicate data exfiltration, enumeration attacks, or
7
- * other security threats.
8
- *
9
- * @packageDocumentation
10
- */
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.DEFAULT_SUSPICIOUS_PATTERNS = void 0;
13
- exports.serializePattern = serializePattern;
14
- exports.serializePatterns = serializePatterns;
15
- exports.generatePatternDetectorsCode = generatePatternDetectorsCode;
16
- /**
17
- * Detect list/query followed by send/export (potential data exfiltration)
18
- *
19
- * This pattern detects when a script queries data and then attempts
20
- * to send it somewhere, which could indicate data theft.
21
- */
22
- const EXFIL_LIST_SEND = {
23
- id: 'EXFIL_LIST_SEND',
24
- description: 'List/query followed by send/export (potential exfiltration)',
25
- detect: (operationName, _args, history) => {
26
- // Look for recent data retrieval operations
27
- const recentQueries = history.filter((h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 5000);
28
- // Check if current operation is a send/export operation
29
- const isSendOperation = /send|export|post|write|upload|publish|emit|transmit|forward/i.test(operationName);
30
- return recentQueries.length > 0 && isSendOperation;
31
- },
32
- };
33
- /**
34
- * Detect rapid enumeration of resources
35
- *
36
- * This pattern detects when the same operation is called excessively
37
- * in quick succession, which could indicate enumeration attacks or DoS.
38
- *
39
- * Legitimate use cases are allowed:
40
- * - Pagination: Up to N calls to same operation (configurable via rapidEnumerationThreshold)
41
- * - Iteration: Up to N calls with different arguments
42
- *
43
- * Suspicious patterns that trigger detection:
44
- * - Same operation called more than threshold times in 5s
45
- *
46
- * @remarks
47
- * The default threshold of 30 allows legitimate pagination and iteration scenarios
48
- * while still protecting against excessive enumeration attacks.
49
- * Configure via:
50
- * - rapidEnumerationThreshold: Default threshold for all operations
51
- * - rapidEnumerationOverrides: Per-operation thresholds (e.g., { 'search': 100 })
52
- * For stricter control, use maxToolCalls config option.
53
- */
54
- const RAPID_ENUMERATION = {
55
- id: 'RAPID_ENUMERATION',
56
- description: 'Rapid enumeration of resources (same operation called too many times in 5s)',
57
- detect: (operationName, _args, history) => {
58
- const now = Date.now();
59
- const recentSameOperation = history.filter((h) => h.operationName === operationName && now - h.timestamp < 5000);
60
- // Get the threshold - check for per-operation override first, then use default
61
- // Note: validationConfig is available in the parent VM scope where this runs
62
- // We use a try-catch to safely access it since it doesn't exist at compile time
63
- let threshold = 30; // Default fallback
64
- try {
65
- // Try direct access (works in parent VM where validationConfig is a local variable)
66
- // @ts-expect-error validationConfig exists in parent VM runtime scope
67
- const localConfig = typeof validationConfig !== 'undefined' ? validationConfig : null;
68
- if (localConfig) {
69
- const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;
70
- const overrides = localConfig.rapidEnumerationOverrides ?? {};
71
- threshold = overrides[operationName] ?? defaultThreshold;
72
- }
73
- }
74
- catch {
75
- // Fallback to default if config is not accessible
76
- threshold = 30;
77
- }
78
- return recentSameOperation.length > threshold;
79
- },
80
- };
81
- /**
82
- * Detect credential/secret access followed by external call
83
- *
84
- * This pattern detects when credentials are accessed and then
85
- * an external-looking operation is attempted.
86
- */
87
- const CREDENTIAL_EXFIL = {
88
- id: 'CREDENTIAL_EXFIL',
89
- description: 'Credential access followed by external operation',
90
- detect: (operationName, _args, history) => {
91
- // Look for recent credential access
92
- const recentCredentialAccess = history.filter((h) => /secret|credential|password|token|key|auth|api[_-]?key/i.test(h.operationName) &&
93
- Date.now() - h.timestamp < 10000);
94
- // Check if current operation looks like external communication
95
- const isExternalOperation = /http|api|external|webhook|slack|email|sms|notification/i.test(operationName);
96
- return recentCredentialAccess.length > 0 && isExternalOperation;
97
- },
98
- };
99
- /**
100
- * Detect bulk data operations
101
- *
102
- * This pattern detects when bulk/batch operations are used,
103
- * which could indicate mass data extraction.
104
- * Note: Uses word boundaries to avoid false positives like "install" matching "all"
105
- */
106
- const BULK_OPERATION = {
107
- id: 'BULK_OPERATION',
108
- description: 'Bulk/batch operation detected',
109
- detect: (operationName, args, _history) => {
110
- // Check operation name for bulk indicators (with word boundaries to avoid false positives)
111
- // Examples that should match: bulk_export, batch:process, export_all, mass-delete
112
- // Examples that should NOT match: install, deleteAll, getAllUsers
113
- const isBulkOperation = /\b(bulk|batch|mass|dump)\b|export[_-]all\b/i.test(operationName);
114
- // Check for suspicious arguments that indicate bulk access
115
- if (typeof args === 'object' && args !== null) {
116
- try {
117
- const argStr = JSON.stringify(args).toLowerCase();
118
- const hasBulkArgs = /limit.*[0-9]{4,}|"\*"|no[_-]?limit/i.test(argStr);
119
- if (hasBulkArgs)
120
- return true;
121
- }
122
- catch {
123
- // If args contains circular references or is not serializable,
124
- // we can't check for bulk patterns - return false to allow the call
125
- // (the call will fail later if args are truly malformed)
126
- }
127
- }
128
- return isBulkOperation;
129
- },
130
- };
131
- /**
132
- * Detect delete operations after data access
133
- *
134
- * This pattern detects potential cover-up attempts where
135
- * data is accessed and then deleted.
136
- */
137
- const DELETE_AFTER_ACCESS = {
138
- id: 'DELETE_AFTER_ACCESS',
139
- description: 'Delete operation after data access (potential cover-up)',
140
- detect: (operationName, _args, history) => {
141
- // Check if current operation is a delete operation
142
- const isDeleteOperation = /delete|remove|destroy|purge|clear|wipe|erase/i.test(operationName);
143
- if (!isDeleteOperation)
144
- return false;
145
- // Look for recent data access
146
- const recentDataAccess = history.filter((h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 30000);
147
- return recentDataAccess.length > 0;
148
- },
149
- };
150
- /**
151
- * Default suspicious patterns
152
- *
153
- * These are enabled by default when blockSuspiciousSequences is true.
154
- */
155
- exports.DEFAULT_SUSPICIOUS_PATTERNS = [
156
- EXFIL_LIST_SEND,
157
- RAPID_ENUMERATION,
158
- CREDENTIAL_EXFIL,
159
- BULK_OPERATION,
160
- DELETE_AFTER_ACCESS,
161
- ];
162
- /**
163
- * Convert a SuspiciousPattern to serializable form
164
- *
165
- * Since functions cannot be passed across VM boundaries,
166
- * we extract the function body as a string.
167
- *
168
- * @remarks
169
- * This function expects standard JavaScript function definitions. It may not work
170
- * correctly with:
171
- * - Minified/bundled code where functions are transformed
172
- * - Native functions (returns "[native code]")
173
- * - Functions with unusual formatting
174
- *
175
- * @throws {Error} If the function cannot be serialized or appears malformed
176
- */
177
- function serializePattern(pattern) {
178
- if (typeof pattern.detect !== 'function') {
179
- throw new Error(`Pattern "${pattern.id}": detect must be a function`);
180
- }
181
- const funcStr = pattern.detect.toString();
182
- // Validate the function string is usable
183
- if (funcStr.includes('[native code]')) {
184
- throw new Error(`Pattern "${pattern.id}": Cannot serialize native functions`);
185
- }
186
- // Extract the function body
187
- // Handles arrow functions: (a, b, c) => { body } or (a, b, c) => expr
188
- // Handles regular functions: function(a, b, c) { body }
189
- let detectBody;
190
- try {
191
- if (funcStr.includes('=>')) {
192
- // Arrow function
193
- const arrowIndex = funcStr.indexOf('=>');
194
- const bodyPart = funcStr.substring(arrowIndex + 2).trim();
195
- if (bodyPart.startsWith('{')) {
196
- // Block body - extract contents
197
- detectBody = bodyPart.slice(1, -1).trim();
198
- }
199
- else {
200
- // Expression body - wrap in return
201
- detectBody = `return ${bodyPart};`;
202
- }
203
- }
204
- else {
205
- // Regular function - extract body between first { and last }
206
- const firstBrace = funcStr.indexOf('{');
207
- const lastBrace = funcStr.lastIndexOf('}');
208
- if (firstBrace === -1 || lastBrace === -1 || firstBrace >= lastBrace) {
209
- throw new Error('Could not extract function body');
210
- }
211
- detectBody = funcStr.substring(firstBrace + 1, lastBrace).trim();
212
- }
213
- // Basic validation that extracted body is not empty
214
- if (!detectBody || detectBody.length === 0) {
215
- throw new Error('Extracted function body is empty');
216
- }
217
- }
218
- catch (error) {
219
- throw new Error(`Pattern "${pattern.id}": Failed to serialize detect function - ${error.message}`);
220
- }
221
- return {
222
- id: pattern.id,
223
- description: pattern.description,
224
- detectBody,
225
- };
226
- }
227
- /**
228
- * Serialize all patterns for passing to parent VM
229
- */
230
- function serializePatterns(patterns) {
231
- return patterns.map(serializePattern);
232
- }
233
- /**
234
- * Dangerous patterns that should not appear in detectBody
235
- *
236
- * These patterns could indicate code injection attempts:
237
- * - Function/class declarations trying to break out of the function body
238
- * - Module system access (require, import)
239
- * - Global object access
240
- */
241
- const DANGEROUS_BODY_PATTERNS = [
242
- /\bfunction\s+[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/g, // Named function declarations
243
- /\bclass\s+[a-zA-Z_$]/g, // Class declarations
244
- /\brequire\s*\(/g, // CommonJS require
245
- /\bimport\s*\(/g, // Dynamic import
246
- /\bimport\s+/g, // Static import
247
- /\bglobal\b/g, // Global object
248
- /\bglobalThis\b/g, // GlobalThis object
249
- /\bprocess\b/g, // Node.js process
250
- ];
251
- /**
252
- * Validate detectBody for potential code injection
253
- *
254
- * @param detectBody - The function body string to validate
255
- * @param patternId - Pattern ID for error messages
256
- * @throws Error if dangerous patterns are detected
257
- */
258
- function validateDetectBody(detectBody, patternId) {
259
- for (const pattern of DANGEROUS_BODY_PATTERNS) {
260
- pattern.lastIndex = 0;
261
- if (pattern.test(detectBody)) {
262
- throw new Error(`Pattern "${patternId}": detectBody contains potentially dangerous code. ` +
263
- `Custom patterns should only contain detection logic, not function declarations, ` +
264
- `imports, or global object access.`);
265
- }
266
- }
267
- }
268
- /**
269
- * Create detection function source code for parent VM
270
- *
271
- * This generates JavaScript code that recreates the detection functions
272
- * inside the parent VM context.
273
- *
274
- * @remarks
275
- * **Security Warning**: Custom patterns are provided by developers (not end users)
276
- * and execute in the parent VM context. The parent VM is trusted infrastructure
277
- * with limited capabilities (no require, no global). However, patterns should
278
- * be reviewed carefully as they become part of the security validation layer.
279
- *
280
- * Basic validation is performed to detect obvious injection attempts, but
281
- * determined attackers with code-level access could potentially bypass this.
282
- * Only use patterns from trusted sources.
283
- *
284
- * @param patterns - Serialized patterns to generate code for
285
- * @returns JavaScript code string defining the pattern array
286
- * @throws Error if any pattern contains dangerous code
287
- */
288
- function generatePatternDetectorsCode(patterns) {
289
- // Validate all pattern bodies before generating code
290
- for (const p of patterns) {
291
- validateDetectBody(p.detectBody, p.id);
292
- }
293
- const patternDefs = patterns
294
- .map((p) => `{
295
- id: ${JSON.stringify(p.id)},
296
- description: ${JSON.stringify(p.description)},
297
- detect: function(operationName, args, history) {
298
- ${p.detectBody}
299
- }
300
- }`)
301
- .join(',\n ');
302
- return `[${patternDefs}]`;
303
- }
304
- //# sourceMappingURL=suspicious-patterns.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"suspicious-patterns.js","sourceRoot":"","sources":["../../../src/double-vm/suspicious-patterns.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAyLH,4CAuDC;AAKD,8CAEC;AA6DD,oEAmBC;AAnUD;;;;;GAKG;AACH,MAAM,eAAe,GAAsB;IACzC,EAAE,EAAE,iBAAiB;IACrB,WAAW,EAAE,6DAA6D;IAC1E,MAAM,EAAE,CAAC,aAAqB,EAAE,KAAc,EAAE,OAA2B,EAAW,EAAE;QACtF,4CAA4C;QAC5C,MAAM,aAAa,GAAG,O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AqD;IACrD,KAAK,MAAM,CAAC,IAAI,QAAQ,EAAE,CAAC;QACzB,kBAAkB,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IACzC,CAAC;IAED,MAAM,WAAW,GAAG,QAAQ;SACzB,GAAG,CACF,CAAC,CAAC,EAAE,EAAE,CAAC;UACH,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;mBACX,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;;QAExC,CAAC,CAAC,UAAU;;IAEhB,CACC;SACA,IAAI,CAAC,OAAO,CAAC,CAAC;IAEjB,OAAO,IAAI,WAAW,GAAG,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * Default Suspicious Pattern Detectors\n *\n * These patterns detect potentially malicious operation sequences\n * that may indicate data exfiltration, enumeration attacks, or\n * other security threats.\n *\n * @packageDocumentation\n */\n\nimport type { SuspiciousPattern, SerializableSuspiciousPattern, OperationHistory } from './types';\n\n/**\n * Detect list/query followed by send/export (potential data exfiltration)\n *\n * This pattern detects when a script queries data and then attempts\n * to send it somewhere, which could indicate data theft.\n */\nconst EXFIL_LIST_SEND: SuspiciousPattern = {\n id: 'EXFIL_LIST_SEND',\n description: 'List/query followed by send/export (potential exfiltration)',\n detect: (operationName: string, _args: unknown, history: OperationHistory[]): boolean => {\n // Look for recent data retrieval operations\n const recentQueries = history.filter(\n (h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 5000,\n );\n\n // Check if current operation is a send/export operation\n const isSendOperation = /send|export|post|write|upload|publish|emit|transmit|forward/i.test(operationName);\n\n return recentQueries.length > 0 && isSendOperation;\n },\n};\n\n/**\n * Detect rapid enumeration of resources\n *\n * This pattern detects when the same operation is called excessively\n * in quick succession, which could indicate enumeration attacks or DoS.\n *\n * Legitimate use cases are allowed:\n * - Pagination: Up to N calls to same operation (configurable via rapidEnumerationThreshold)\n * - Iteration: Up to N calls with different arguments\n *\n * Suspicious patterns that trigger detection:\n * - Same operation called more than threshold times in 5s\n *\n * @remarks\n * The default threshold of 30 allows legitimate pagination and iteration scenarios\n * while still protecting against excessive enumeration attacks.\n * Configure via:\n * - rapidEnumerationThreshold: Default threshold for all operations\n * - rapidEnumerationOverrides: Per-operation thresholds (e.g., { 'search': 100 })\n * For stricter control, use maxToolCalls config option.\n */\nconst RAPID_ENUMERATION: SuspiciousPattern = {\n id: 'RAPID_ENUMERATION',\n description: 'Rapid enumeration of resources (same operation called too many times in 5s)',\n detect: (operationName: string, _args: unknown, history: OperationHistory[]): boolean => {\n const now = Date.now();\n const recentSameOperation = history.filter((h) => h.operationName === operationName && now - h.timestamp < 5000);\n\n // Get the threshold - check for per-operation override first, then use default\n // Note: validationConfig is available in the parent VM scope where this runs\n // We use a try-catch to safely access it since it doesn't exist at compile time\n let threshold = 30; // Default fallback\n try {\n // Try direct access (works in parent VM where validationConfig is a local variable)\n // @ts-expect-error validationConfig exists in parent VM runtime scope\n const localConfig = typeof validationConfig !== 'undefined' ? validationConfig : null;\n if (localConfig) {\n const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;\n const overrides = localConfig.rapidEnumerationOverrides ?? {};\n threshold = overrides[operationName] ?? defaultThreshold;\n }\n } catch {\n // Fallback to default if config is not accessible\n threshold = 30;\n }\n\n return recentSameOperation.length > threshold;\n },\n};\n\n/**\n * Detect credential/secret access followed by external call\n *\n * This pattern detects when credentials are accessed and then\n * an external-looking operation is attempted.\n */\nconst CREDENTIAL_EXFIL: SuspiciousPattern = {\n id: 'CREDENTIAL_EXFIL',\n description: 'Credential access followed by external operation',\n detect: (operationName: string, _args: unknown, history: OperationHistory[]): boolean => {\n // Look for recent credential access\n const recentCredentialAccess = history.filter(\n (h) =>\n /secret|credential|password|token|key|auth|api[_-]?key/i.test(h.operationName) &&\n Date.now() - h.timestamp < 10000,\n );\n\n // Check if current operation looks like external communication\n const isExternalOperation = /http|api|external|webhook|slack|email|sms|notification/i.test(operationName);\n\n return recentCredentialAccess.length > 0 && isExternalOperation;\n },\n};\n\n/**\n * Detect bulk data operations\n *\n * This pattern detects when bulk/batch operations are used,\n * which could indicate mass data extraction.\n * Note: Uses word boundaries to avoid false positives like \"install\" matching \"all\"\n */\nconst BULK_OPERATION: SuspiciousPattern = {\n id: 'BULK_OPERATION',\n description: 'Bulk/batch operation detected',\n detect: (operationName: string, args: unknown, _history: OperationHistory[]): boolean => {\n // Check operation name for bulk indicators (with word boundaries to avoid false positives)\n // Examples that should match: bulk_export, batch:process, export_all, mass-delete\n // Examples that should NOT match: install, deleteAll, getAllUsers\n const isBulkOperation = /\\b(bulk|batch|mass|dump)\\b|export[_-]all\\b/i.test(operationName);\n\n // Check for suspicious arguments that indicate bulk access\n if (typeof args === 'object' && args !== null) {\n try {\n const argStr = JSON.stringify(args).toLowerCase();\n const hasBulkArgs = /limit.*[0-9]{4,}|\"\\*\"|no[_-]?limit/i.test(argStr);\n if (hasBulkArgs) return true;\n } catch {\n // If args contains circular references or is not serializable,\n // we can't check for bulk patterns - return false to allow the call\n // (the call will fail later if args are truly malformed)\n }\n }\n\n return isBulkOperation;\n },\n};\n\n/**\n * Detect delete operations after data access\n *\n * This pattern detects potential cover-up attempts where\n * data is accessed and then deleted.\n */\nconst DELETE_AFTER_ACCESS: SuspiciousPattern = {\n id: 'DELETE_AFTER_ACCESS',\n description: 'Delete operation after data access (potential cover-up)',\n detect: (operationName: string, _args: unknown, history: OperationHistory[]): boolean => {\n // Check if current operation is a delete operation\n const isDeleteOperation = /delete|remove|destroy|purge|clear|wipe|erase/i.test(operationName);\n\n if (!isDeleteOperation) return false;\n\n // Look for recent data access\n const recentDataAccess = history.filter(\n (h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 30000,\n );\n\n return recentDataAccess.length > 0;\n },\n};\n\n/**\n * Default suspicious patterns\n *\n * These are enabled by default when blockSuspiciousSequences is true.\n */\nexport const DEFAULT_SUSPICIOUS_PATTERNS: SuspiciousPattern[] = [\n EXFIL_LIST_SEND,\n RAPID_ENUMERATION,\n CREDENTIAL_EXFIL,\n BULK_OPERATION,\n DELETE_AFTER_ACCESS,\n];\n\n/**\n * Convert a SuspiciousPattern to serializable form\n *\n * Since functions cannot be passed across VM boundaries,\n * we extract the function body as a string.\n *\n * @remarks\n * This function expects standard JavaScript function definitions. It may not work\n * correctly with:\n * - Minified/bundled code where functions are transformed\n * - Native functions (returns \"[native code]\")\n * - Functions with unusual formatting\n *\n * @throws {Error} If the function cannot be serialized or appears malformed\n */\nexport function serializePattern(pattern: SuspiciousPattern): SerializableSuspiciousPattern {\n if (typeof pattern.detect !== 'function') {\n throw new Error(`Pattern \"${pattern.id}\": detect must be a function`);\n }\n\n const funcStr = pattern.detect.toString();\n\n // Validate the function string is usable\n if (funcStr.includes('[native code]')) {\n throw new Error(`Pattern \"${pattern.id}\": Cannot serialize native functions`);\n }\n\n // Extract the function body\n // Handles arrow functions: (a, b, c) => { body } or (a, b, c) => expr\n // Handles regular functions: function(a, b, c) { body }\n let detectBody: string;\n\n try {\n if (funcStr.includes('=>')) {\n // Arrow function\n const arrowIndex = funcStr.indexOf('=>');\n const bodyPart = funcStr.substring(arrowIndex + 2).trim();\n\n if (bodyPart.startsWith('{')) {\n // Block body - extract contents\n detectBody = bodyPart.slice(1, -1).trim();\n } else {\n // Expression body - wrap in return\n detectBody = `return ${bodyPart};`;\n }\n } else {\n // Regular function - extract body between first { and last }\n const firstBrace = funcStr.indexOf('{');\n const lastBrace = funcStr.lastIndexOf('}');\n\n if (firstBrace === -1 || lastBrace === -1 || firstBrace >= lastBrace) {\n throw new Error('Could not extract function body');\n }\n\n detectBody = funcStr.substring(firstBrace + 1, lastBrace).trim();\n }\n\n // Basic validation that extracted body is not empty\n if (!detectBody || detectBody.length === 0) {\n throw new Error('Extracted function body is empty');\n }\n } catch (error) {\n throw new Error(`Pattern \"${pattern.id}\": Failed to serialize detect function - ${(error as Error).message}`);\n }\n\n return {\n id: pattern.id,\n description: pattern.description,\n detectBody,\n };\n}\n\n/**\n * Serialize all patterns for passing to parent VM\n */\nexport function serializePatterns(patterns: SuspiciousPattern[]): SerializableSuspiciousPattern[] {\n return patterns.map(serializePattern);\n}\n\n/**\n * Dangerous patterns that should not appear in detectBody\n *\n * These patterns could indicate code injection attempts:\n * - Function/class declarations trying to break out of the function body\n * - Module system access (require, import)\n * - Global object access\n */\nconst DANGEROUS_BODY_PATTERNS = [\n /\\bfunction\\s+[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/g, // Named function declarations\n /\\bclass\\s+[a-zA-Z_$]/g, // Class declarations\n /\\brequire\\s*\\(/g, // CommonJS require\n /\\bimport\\s*\\(/g, // Dynamic import\n /\\bimport\\s+/g, // Static import\n /\\bglobal\\b/g, // Global object\n /\\bglobalThis\\b/g, // GlobalThis object\n /\\bprocess\\b/g, // Node.js process\n];\n\n/**\n * Validate detectBody for potential code injection\n *\n * @param detectBody - The function body string to validate\n * @param patternId - Pattern ID for error messages\n * @throws Error if dangerous patterns are detected\n */\nfunction validateDetectBody(detectBody: string, patternId: string): void {\n for (const pattern of DANGEROUS_BODY_PATTERNS) {\n pattern.lastIndex = 0;\n if (pattern.test(detectBody)) {\n throw new Error(\n `Pattern \"${patternId}\": detectBody contains potentially dangerous code. ` +\n `Custom patterns should only contain detection logic, not function declarations, ` +\n `imports, or global object access.`,\n );\n }\n }\n}\n\n/**\n * Create detection function source code for parent VM\n *\n * This generates JavaScript code that recreates the detection functions\n * inside the parent VM context.\n *\n * @remarks\n * **Security Warning**: Custom patterns are provided by developers (not end users)\n * and execute in the parent VM context. The parent VM is trusted infrastructure\n * with limited capabilities (no require, no global). However, patterns should\n * be reviewed carefully as they become part of the security validation layer.\n *\n * Basic validation is performed to detect obvious injection attempts, but\n * determined attackers with code-level access could potentially bypass this.\n * Only use patterns from trusted sources.\n *\n * @param patterns - Serialized patterns to generate code for\n * @returns JavaScript code string defining the pattern array\n * @throws Error if any pattern contains dangerous code\n */\nexport function generatePatternDetectorsCode(patterns: SerializableSuspiciousPattern[]): string {\n // Validate all pattern bodies before generating code\n for (const p of patterns) {\n validateDetectBody(p.detectBody, p.id);\n }\n\n const patternDefs = patterns\n .map(\n (p) => `{\n id: ${JSON.stringify(p.id)},\n description: ${JSON.stringify(p.description)},\n detect: function(operationName, args, history) {\n ${p.detectBody}\n }\n }`,\n )\n .join(',\\n ');\n\n return `[${patternDefs}]`;\n}\n"]}
@@ -1,11 +0,0 @@
1
- "use strict";
2
- /**
3
- * Double VM Types and Interfaces
4
- *
5
- * Types for the double VM security layer that provides
6
- * enhanced isolation by running user code inside a nested VM.
7
- *
8
- * @packageDocumentation
9
- */
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/double-vm/types.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG","sourcesContent":["/**\n * Double VM Types and Interfaces\n *\n * Types for the double VM security layer that provides\n * enhanced isolation by running user code inside a nested VM.\n *\n * @packageDocumentation\n */\n\n/**\n * Operation history entry for pattern detection\n *\n * Tracks operations (e.g., tool calls) for suspicious pattern analysis.\n */\nexport interface OperationHistory {\n /** Name of the operation that was executed */\n operationName: string;\n /** Timestamp when the operation was executed */\n timestamp: number;\n /** Keys of the arguments object (for pattern analysis) */\n argKeys: string[];\n}\n\n/**\n * Suspicious pattern detector\n *\n * Used to detect potentially malicious operation sequences\n * like data exfiltration (list -> send) or rapid enumeration.\n */\nexport interface SuspiciousPattern {\n /** Unique identifier for the pattern */\n id: string;\n /** Human-readable description of what this pattern detects */\n description: string;\n /**\n * Detection function\n *\n * @param operationName - The operation being executed\n * @param args - The arguments being passed\n * @param history - Previous operations in this execution\n * @returns true if the pattern is detected (suspicious)\n */\n detect: (operationName: string, args: unknown, history: OperationHistory[]) => boolean;\n}\n\n/**\n * Serializable version of SuspiciousPattern for passing to parent VM\n *\n * Since functions cannot be passed across VM boundaries, we serialize\n * the detection logic as a string that gets evaluated in the parent VM.\n */\nexport interface SerializableSuspiciousPattern {\n /** Unique identifier for the pattern */\n id: string;\n /** Human-readable description */\n description: string;\n /**\n * Detection function body as a string\n * Will be wrapped in: `function(operationName, args, history) { ... }`\n */\n detectBody: string;\n}\n\n/**\n * Parent VM validation configuration\n *\n * Controls enhanced validation performed by the parent VM\n * before forwarding operations to the host.\n */\nexport interface ParentValidationConfig {\n /**\n * Whether to validate operation names against patterns\n * @default true\n */\n validateOperationNames: boolean;\n\n /**\n * Optional whitelist regex pattern for operation names\n * If set, only operations matching this pattern are allowed\n */\n allowedOperationPattern?: RegExp;\n\n /**\n * Blacklist regex patterns for operation names\n * Operations matching any of these patterns are blocked\n */\n blockedOperationPatterns?: RegExp[];\n\n /**\n * Maximum operations per second (rate limiting)\n * Prevents rapid enumeration attacks\n * @default 100\n */\n maxOperationsPerSecond: number;\n\n /**\n * Whether to detect and block suspicious operation sequences\n * @default true\n */\n blockSuspiciousSequences: boolean;\n\n /**\n * Threshold for RAPID_ENUMERATION detection.\n * Same operation called more than this many times in 5 seconds is suspicious.\n * @default 30\n */\n rapidEnumerationThreshold: number;\n\n /**\n * Per-operation overrides for rapid enumeration threshold.\n * Keys are operation names, values are the threshold for that operation.\n * Example: { 'users.list': 50, 'search': 100 }\n */\n rapidEnumerationOverrides: Record<string, number>;\n\n /**\n * Custom suspicious pattern detectors\n *\n * These are combined with DEFAULT_SUSPICIOUS_PATTERNS at runtime\n * by DoubleVmWrapper when building the parent VM bootstrap.\n */\n suspiciousPatterns: SuspiciousPattern[];\n}\n\n/**\n * Serializable version of ParentValidationConfig for passing to parent VM\n */\nexport interface SerializableParentValidationConfig {\n validateOperationNames: boolean;\n allowedOperationPatternSource?: string;\n allowedOperationPatternFlags?: string;\n blockedOperationPatternSources?: string[];\n blockedOperationPatternFlags?: string[];\n maxOperationsPerSecond: number;\n blockSuspiciousSequences: boolean;\n rapidEnumerationThreshold: number;\n rapidEnumerationOverrides: Record<string, number>;\n suspiciousPatterns: SerializableSuspiciousPattern[];\n}\n\n/**\n * Double VM configuration\n *\n * Controls the double VM security layer behavior.\n */\nexport interface DoubleVmConfig {\n /**\n * Whether double VM is enabled\n *\n * When disabled, a security warning is logged and user code\n * runs in a single VM with direct tool handler access.\n *\n * @default true\n */\n enabled: boolean;\n\n /**\n * Extra timeout buffer for parent VM (ms)\n *\n * The parent VM timeout = inner VM timeout + this buffer.\n * This allows the parent VM to properly handle inner VM timeouts.\n *\n * @default 1000\n */\n parentTimeoutBuffer: number;\n\n /**\n * Parent VM validation configuration\n */\n parentValidation: ParentValidationConfig;\n}\n\n/**\n * Partial configuration for user input\n * (all fields optional, merged with defaults)\n */\nexport interface PartialDoubleVmConfig {\n enabled?: boolean;\n parentTimeoutBuffer?: number;\n parentValidation?: Partial<Omit<ParentValidationConfig, 'suspiciousPatterns'>> & {\n suspiciousPatterns?: SuspiciousPattern[];\n };\n}\n\n/**\n * Execution statistics from double VM\n */\nexport interface DoubleVmStats {\n /** Number of operations that passed validation */\n validatedOperations: number;\n /** Number of operations blocked by validation */\n blockedOperations: number;\n /** Patterns that were triggered (for logging/debugging) */\n triggeredPatterns: string[];\n}\n"]}
@@ -1,59 +0,0 @@
1
- "use strict";
2
- /**
3
- * Adapter Wrapper Factory
4
- *
5
- * Provides a function to wrap any SandboxAdapter with the double VM layer.
6
- *
7
- * @packageDocumentation
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.wrapWithDoubleVm = wrapWithDoubleVm;
11
- exports.isDoubleVmEnabled = isDoubleVmEnabled;
12
- const double_vm_wrapper_1 = require("./double-vm-wrapper");
13
- /**
14
- * Wrap a sandbox adapter with the double VM layer
15
- *
16
- * When enabled, this creates a nested VM structure where:
17
- * - The Parent VM acts as a security barrier with enhanced validation
18
- * - The Inner VM is where user code actually executes
19
- * - Tool calls flow: Inner VM -> Parent VM validation -> Host handler
20
- *
21
- * When disabled, a security warning is logged and the original adapter
22
- * is returned unchanged. This is NOT recommended for production use.
23
- *
24
- * @param baseAdapter - The original adapter. When double VM is enabled, this parameter
25
- * is not used (a new DoubleVmWrapper is created). When disabled, this must be provided
26
- * and will be returned directly. Pass undefined when double VM is enabled.
27
- * @param config - Double VM configuration
28
- * @param securityLevel - The security level for dangerous global removal
29
- * @returns The wrapped adapter (or original if disabled)
30
- * @throws Error if double VM is disabled and baseAdapter is not provided
31
- */
32
- function wrapWithDoubleVm(baseAdapter, config, securityLevel) {
33
- // If disabled, warn and return original adapter
34
- if (!config.enabled) {
35
- if (!baseAdapter) {
36
- throw new Error('baseAdapter is required when double VM is disabled. ' +
37
- 'Either enable double VM (recommended) or provide a base adapter.');
38
- }
39
- console.warn('[SECURITY WARNING] Double VM is disabled. ' +
40
- 'This reduces security isolation and is NOT recommended for production. ' +
41
- 'User code will run in a single VM with direct tool handler access. ' +
42
- 'To enable double VM protection, set doubleVm.enabled = true.');
43
- return baseAdapter;
44
- }
45
- // Create the double VM wrapper
46
- // Note: When enabled, baseAdapter is not used - DoubleVmWrapper creates its own VMs
47
- // This is intentional: the double VM replaces the base adapter rather than wrapping it
48
- return new double_vm_wrapper_1.DoubleVmWrapper(config, securityLevel);
49
- }
50
- /**
51
- * Check if double VM is enabled in the config
52
- *
53
- * @param config - Partial double VM config
54
- * @returns Whether double VM is enabled (defaults to true)
55
- */
56
- function isDoubleVmEnabled(config) {
57
- return config?.enabled !== false;
58
- }
59
- //# sourceMappingURL=wrap-adapter.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wrap-adapter.js","sourceRoot":"","sources":["../../../src/double-vm/wrap-adapter.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAyBH,4CA0BC;AAQD,8CAEC;AAzDD,2DAAsD;AAEtD;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,gBAAgB,CAC9B,WAAuC,EACvC,MAAsB,EACtB,aAA4B;IAE5B,gDAAgD;IAChD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CACb,sDAAsD;gBACpD,kEAAkE,CACrE,CAAC;QACJ,CAAC;QACD,OAAO,CAAC,IAAI,CACV,4CAA4C;YAC1C,yEAAyE;YACzE,qEAAqE;YACrE,8DAA8D,CACjE,CAAC;QACF,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,+BAA+B;IAC/B,oFAAoF;IACpF,uFAAuF;IACvF,OAAO,IAAI,mCAAe,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;AACpD,CAAC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,MAAgC;IAChE,OAAO,MAAM,EAAE,OAAO,KAAK,KAAK,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Adapter Wrapper Factory\n *\n * Provides a function to wrap any SandboxAdapter with the double VM layer.\n *\n * @packageDocumentation\n */\n\nimport type { SandboxAdapter, SecurityLevel } from '../types';\nimport type { DoubleVmConfig } from './types';\nimport { DoubleVmWrapper } from './double-vm-wrapper';\n\n/**\n * Wrap a sandbox adapter with the double VM layer\n *\n * When enabled, this creates a nested VM structure where:\n * - The Parent VM acts as a security barrier with enhanced validation\n * - The Inner VM is where user code actually executes\n * - Tool calls flow: Inner VM -> Parent VM validation -> Host handler\n *\n * When disabled, a security warning is logged and the original adapter\n * is returned unchanged. This is NOT recommended for production use.\n *\n * @param baseAdapter - The original adapter. When double VM is enabled, this parameter\n * is not used (a new DoubleVmWrapper is created). When disabled, this must be provided\n * and will be returned directly. Pass undefined when double VM is enabled.\n * @param config - Double VM configuration\n * @param securityLevel - The security level for dangerous global removal\n * @returns The wrapped adapter (or original if disabled)\n * @throws Error if double VM is disabled and baseAdapter is not provided\n */\nexport function wrapWithDoubleVm(\n baseAdapter: SandboxAdapter | undefined,\n config: DoubleVmConfig,\n securityLevel: SecurityLevel,\n): SandboxAdapter {\n // If disabled, warn and return original adapter\n if (!config.enabled) {\n if (!baseAdapter) {\n throw new Error(\n 'baseAdapter is required when double VM is disabled. ' +\n 'Either enable double VM (recommended) or provide a base adapter.',\n );\n }\n console.warn(\n '[SECURITY WARNING] Double VM is disabled. ' +\n 'This reduces security isolation and is NOT recommended for production. ' +\n 'User code will run in a single VM with direct tool handler access. ' +\n 'To enable double VM protection, set doubleVm.enabled = true.',\n );\n return baseAdapter;\n }\n\n // Create the double VM wrapper\n // Note: When enabled, baseAdapter is not used - DoubleVmWrapper creates its own VMs\n // This is intentional: the double VM replaces the base adapter rather than wrapping it\n return new DoubleVmWrapper(config, securityLevel);\n}\n\n/**\n * Check if double VM is enabled in the config\n *\n * @param config - Partial double VM config\n * @returns Whether double VM is enabled (defaults to true)\n */\nexport function isDoubleVmEnabled(config?: Partial<DoubleVmConfig>): boolean {\n return config?.enabled !== false;\n}\n"]}