@enclave-vm/core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +732 -0
  3. package/SECURITY-AUDIT.md +916 -0
  4. package/package.json +59 -0
  5. package/src/adapters/vm-adapter.d.ts +32 -0
  6. package/src/adapters/vm-adapter.js +1140 -0
  7. package/src/adapters/vm-adapter.js.map +1 -0
  8. package/src/adapters/worker-pool/config.d.ts +149 -0
  9. package/src/adapters/worker-pool/config.js +129 -0
  10. package/src/adapters/worker-pool/config.js.map +1 -0
  11. package/src/adapters/worker-pool/errors.d.ts +109 -0
  12. package/src/adapters/worker-pool/errors.js +181 -0
  13. package/src/adapters/worker-pool/errors.js.map +1 -0
  14. package/src/adapters/worker-pool/execution-queue.d.ts +85 -0
  15. package/src/adapters/worker-pool/execution-queue.js +179 -0
  16. package/src/adapters/worker-pool/execution-queue.js.map +1 -0
  17. package/src/adapters/worker-pool/index.d.ts +48 -0
  18. package/src/adapters/worker-pool/index.js +73 -0
  19. package/src/adapters/worker-pool/index.js.map +1 -0
  20. package/src/adapters/worker-pool/memory-monitor.d.ts +106 -0
  21. package/src/adapters/worker-pool/memory-monitor.js +184 -0
  22. package/src/adapters/worker-pool/memory-monitor.js.map +1 -0
  23. package/src/adapters/worker-pool/protocol.d.ts +314 -0
  24. package/src/adapters/worker-pool/protocol.js +143 -0
  25. package/src/adapters/worker-pool/protocol.js.map +1 -0
  26. package/src/adapters/worker-pool/rate-limiter.d.ts +60 -0
  27. package/src/adapters/worker-pool/rate-limiter.js +101 -0
  28. package/src/adapters/worker-pool/rate-limiter.js.map +1 -0
  29. package/src/adapters/worker-pool/safe-deserialize.d.ts +50 -0
  30. package/src/adapters/worker-pool/safe-deserialize.js +141 -0
  31. package/src/adapters/worker-pool/safe-deserialize.js.map +1 -0
  32. package/src/adapters/worker-pool/worker-pool-adapter.d.ts +84 -0
  33. package/src/adapters/worker-pool/worker-pool-adapter.js +506 -0
  34. package/src/adapters/worker-pool/worker-pool-adapter.js.map +1 -0
  35. package/src/adapters/worker-pool/worker-script.d.ts +12 -0
  36. package/src/adapters/worker-pool/worker-script.js +770 -0
  37. package/src/adapters/worker-pool/worker-script.js.map +1 -0
  38. package/src/adapters/worker-pool/worker-slot.d.ts +116 -0
  39. package/src/adapters/worker-pool/worker-slot.js +301 -0
  40. package/src/adapters/worker-pool/worker-slot.js.map +1 -0
  41. package/src/babel/babel-wrapper.d.ts +118 -0
  42. package/src/babel/babel-wrapper.js +395 -0
  43. package/src/babel/babel-wrapper.js.map +1 -0
  44. package/src/babel/index.d.ts +9 -0
  45. package/src/babel/index.js +17 -0
  46. package/src/babel/index.js.map +1 -0
  47. package/src/babel/multi-file-transform.d.ts +122 -0
  48. package/src/babel/multi-file-transform.js +344 -0
  49. package/src/babel/multi-file-transform.js.map +1 -0
  50. package/src/double-vm/double-vm-wrapper.d.ts +65 -0
  51. package/src/double-vm/double-vm-wrapper.js +523 -0
  52. package/src/double-vm/double-vm-wrapper.js.map +1 -0
  53. package/src/double-vm/index.d.ts +31 -0
  54. package/src/double-vm/index.js +34 -0
  55. package/src/double-vm/index.js.map +1 -0
  56. package/src/double-vm/parent-vm-bootstrap.d.ts +63 -0
  57. package/src/double-vm/parent-vm-bootstrap.js +1695 -0
  58. package/src/double-vm/parent-vm-bootstrap.js.map +1 -0
  59. package/src/double-vm/suspicious-patterns.d.ts +57 -0
  60. package/src/double-vm/suspicious-patterns.js +304 -0
  61. package/src/double-vm/suspicious-patterns.js.map +1 -0
  62. package/src/double-vm/types.d.ts +178 -0
  63. package/src/double-vm/types.js +11 -0
  64. package/src/double-vm/types.js.map +1 -0
  65. package/src/double-vm/wrap-adapter.d.ts +36 -0
  66. package/src/double-vm/wrap-adapter.js +59 -0
  67. package/src/double-vm/wrap-adapter.js.map +1 -0
  68. package/src/enclave.d.ts +159 -0
  69. package/src/enclave.js +671 -0
  70. package/src/enclave.js.map +1 -0
  71. package/src/globals-validator.d.ts +80 -0
  72. package/src/globals-validator.js +206 -0
  73. package/src/globals-validator.js.map +1 -0
  74. package/src/index.d.ts +29 -0
  75. package/src/index.js +130 -0
  76. package/src/index.js.map +1 -0
  77. package/src/memory-proxy.d.ts +69 -0
  78. package/src/memory-proxy.js +310 -0
  79. package/src/memory-proxy.js.map +1 -0
  80. package/src/memory-tracker.d.ts +170 -0
  81. package/src/memory-tracker.js +230 -0
  82. package/src/memory-tracker.js.map +1 -0
  83. package/src/safe-error.d.ts +18 -0
  84. package/src/safe-error.js +76 -0
  85. package/src/safe-error.js.map +1 -0
  86. package/src/safe-runtime.d.ts +72 -0
  87. package/src/safe-runtime.js +656 -0
  88. package/src/safe-runtime.js.map +1 -0
  89. package/src/scoring/cache.d.ts +68 -0
  90. package/src/scoring/cache.js +158 -0
  91. package/src/scoring/cache.js.map +1 -0
  92. package/src/scoring/feature-extractor.d.ts +61 -0
  93. package/src/scoring/feature-extractor.js +366 -0
  94. package/src/scoring/feature-extractor.js.map +1 -0
  95. package/src/scoring/index.d.ts +33 -0
  96. package/src/scoring/index.js +53 -0
  97. package/src/scoring/index.js.map +1 -0
  98. package/src/scoring/scorer.interface.d.ts +65 -0
  99. package/src/scoring/scorer.interface.js +49 -0
  100. package/src/scoring/scorer.interface.js.map +1 -0
  101. package/src/scoring/scorers/disabled.scorer.d.ts +19 -0
  102. package/src/scoring/scorers/disabled.scorer.js +34 -0
  103. package/src/scoring/scorers/disabled.scorer.js.map +1 -0
  104. package/src/scoring/scorers/external-api.scorer.d.ts +29 -0
  105. package/src/scoring/scorers/external-api.scorer.js +141 -0
  106. package/src/scoring/scorers/external-api.scorer.js.map +1 -0
  107. package/src/scoring/scorers/index.d.ts +10 -0
  108. package/src/scoring/scorers/index.js +22 -0
  109. package/src/scoring/scorers/index.js.map +1 -0
  110. package/src/scoring/scorers/local-llm.scorer.d.ts +116 -0
  111. package/src/scoring/scorers/local-llm.scorer.js +474 -0
  112. package/src/scoring/scorers/local-llm.scorer.js.map +1 -0
  113. package/src/scoring/scorers/progressive.scorer.d.ts +77 -0
  114. package/src/scoring/scorers/progressive.scorer.js +199 -0
  115. package/src/scoring/scorers/progressive.scorer.js.map +1 -0
  116. package/src/scoring/scorers/rule-based.scorer.d.ts +66 -0
  117. package/src/scoring/scorers/rule-based.scorer.js +316 -0
  118. package/src/scoring/scorers/rule-based.scorer.js.map +1 -0
  119. package/src/scoring/scoring-gate.d.ts +76 -0
  120. package/src/scoring/scoring-gate.js +246 -0
  121. package/src/scoring/scoring-gate.js.map +1 -0
  122. package/src/scoring/types.d.ts +690 -0
  123. package/src/scoring/types.js +107 -0
  124. package/src/scoring/types.js.map +1 -0
  125. package/src/secure-proxy.d.ts +157 -0
  126. package/src/secure-proxy.js +609 -0
  127. package/src/secure-proxy.js.map +1 -0
  128. package/src/session/channels/embedded-channel.d.ts +76 -0
  129. package/src/session/channels/embedded-channel.js +130 -0
  130. package/src/session/channels/embedded-channel.js.map +1 -0
  131. package/src/session/channels/index.d.ts +9 -0
  132. package/src/session/channels/index.js +14 -0
  133. package/src/session/channels/index.js.map +1 -0
  134. package/src/session/index.d.ts +15 -0
  135. package/src/session/index.js +27 -0
  136. package/src/session/index.js.map +1 -0
  137. package/src/session/session-emitter.d.ts +119 -0
  138. package/src/session/session-emitter.js +253 -0
  139. package/src/session/session-emitter.js.map +1 -0
  140. package/src/session/session-state-machine.d.ts +108 -0
  141. package/src/session/session-state-machine.js +182 -0
  142. package/src/session/session-state-machine.js.map +1 -0
  143. package/src/session/session.d.ts +135 -0
  144. package/src/session/session.js +398 -0
  145. package/src/session/session.js.map +1 -0
  146. package/src/session-types.d.ts +313 -0
  147. package/src/session-types.js +39 -0
  148. package/src/session-types.js.map +1 -0
  149. package/src/sidecar/index.d.ts +12 -0
  150. package/src/sidecar/index.js +31 -0
  151. package/src/sidecar/index.js.map +1 -0
  152. package/src/sidecar/reference-config.d.ts +81 -0
  153. package/src/sidecar/reference-config.js +118 -0
  154. package/src/sidecar/reference-config.js.map +1 -0
  155. package/src/sidecar/reference-resolver.d.ts +115 -0
  156. package/src/sidecar/reference-resolver.js +262 -0
  157. package/src/sidecar/reference-resolver.js.map +1 -0
  158. package/src/sidecar/reference-sidecar.d.ts +161 -0
  159. package/src/sidecar/reference-sidecar.js +226 -0
  160. package/src/sidecar/reference-sidecar.js.map +1 -0
  161. package/src/tool-bridge.d.ts +4 -0
  162. package/src/tool-bridge.js +306 -0
  163. package/src/tool-bridge.js.map +1 -0
  164. package/src/types.d.ts +775 -0
  165. package/src/types.js +187 -0
  166. package/src/types.js.map +1 -0
  167. package/src/value-sanitizer.d.ts +133 -0
  168. package/src/value-sanitizer.js +421 -0
  169. package/src/value-sanitizer.js.map +1 -0
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Double VM Types and Interfaces
3
+ *
4
+ * Types for the double VM security layer that provides
5
+ * enhanced isolation by running user code inside a nested VM.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ /**
10
+ * Operation history entry for pattern detection
11
+ *
12
+ * Tracks operations (e.g., tool calls) for suspicious pattern analysis.
13
+ */
14
+ export interface OperationHistory {
15
+ /** Name of the operation that was executed */
16
+ operationName: string;
17
+ /** Timestamp when the operation was executed */
18
+ timestamp: number;
19
+ /** Keys of the arguments object (for pattern analysis) */
20
+ argKeys: string[];
21
+ }
22
+ /**
23
+ * Suspicious pattern detector
24
+ *
25
+ * Used to detect potentially malicious operation sequences
26
+ * like data exfiltration (list -> send) or rapid enumeration.
27
+ */
28
+ export interface SuspiciousPattern {
29
+ /** Unique identifier for the pattern */
30
+ id: string;
31
+ /** Human-readable description of what this pattern detects */
32
+ description: string;
33
+ /**
34
+ * Detection function
35
+ *
36
+ * @param operationName - The operation being executed
37
+ * @param args - The arguments being passed
38
+ * @param history - Previous operations in this execution
39
+ * @returns true if the pattern is detected (suspicious)
40
+ */
41
+ detect: (operationName: string, args: unknown, history: OperationHistory[]) => boolean;
42
+ }
43
+ /**
44
+ * Serializable version of SuspiciousPattern for passing to parent VM
45
+ *
46
+ * Since functions cannot be passed across VM boundaries, we serialize
47
+ * the detection logic as a string that gets evaluated in the parent VM.
48
+ */
49
+ export interface SerializableSuspiciousPattern {
50
+ /** Unique identifier for the pattern */
51
+ id: string;
52
+ /** Human-readable description */
53
+ description: string;
54
+ /**
55
+ * Detection function body as a string
56
+ * Will be wrapped in: `function(operationName, args, history) { ... }`
57
+ */
58
+ detectBody: string;
59
+ }
60
+ /**
61
+ * Parent VM validation configuration
62
+ *
63
+ * Controls enhanced validation performed by the parent VM
64
+ * before forwarding operations to the host.
65
+ */
66
+ export interface ParentValidationConfig {
67
+ /**
68
+ * Whether to validate operation names against patterns
69
+ * @default true
70
+ */
71
+ validateOperationNames: boolean;
72
+ /**
73
+ * Optional whitelist regex pattern for operation names
74
+ * If set, only operations matching this pattern are allowed
75
+ */
76
+ allowedOperationPattern?: RegExp;
77
+ /**
78
+ * Blacklist regex patterns for operation names
79
+ * Operations matching any of these patterns are blocked
80
+ */
81
+ blockedOperationPatterns?: RegExp[];
82
+ /**
83
+ * Maximum operations per second (rate limiting)
84
+ * Prevents rapid enumeration attacks
85
+ * @default 100
86
+ */
87
+ maxOperationsPerSecond: number;
88
+ /**
89
+ * Whether to detect and block suspicious operation sequences
90
+ * @default true
91
+ */
92
+ blockSuspiciousSequences: boolean;
93
+ /**
94
+ * Threshold for RAPID_ENUMERATION detection.
95
+ * Same operation called more than this many times in 5 seconds is suspicious.
96
+ * @default 30
97
+ */
98
+ rapidEnumerationThreshold: number;
99
+ /**
100
+ * Per-operation overrides for rapid enumeration threshold.
101
+ * Keys are operation names, values are the threshold for that operation.
102
+ * Example: { 'users.list': 50, 'search': 100 }
103
+ */
104
+ rapidEnumerationOverrides: Record<string, number>;
105
+ /**
106
+ * Custom suspicious pattern detectors
107
+ *
108
+ * These are combined with DEFAULT_SUSPICIOUS_PATTERNS at runtime
109
+ * by DoubleVmWrapper when building the parent VM bootstrap.
110
+ */
111
+ suspiciousPatterns: SuspiciousPattern[];
112
+ }
113
+ /**
114
+ * Serializable version of ParentValidationConfig for passing to parent VM
115
+ */
116
+ export interface SerializableParentValidationConfig {
117
+ validateOperationNames: boolean;
118
+ allowedOperationPatternSource?: string;
119
+ allowedOperationPatternFlags?: string;
120
+ blockedOperationPatternSources?: string[];
121
+ blockedOperationPatternFlags?: string[];
122
+ maxOperationsPerSecond: number;
123
+ blockSuspiciousSequences: boolean;
124
+ rapidEnumerationThreshold: number;
125
+ rapidEnumerationOverrides: Record<string, number>;
126
+ suspiciousPatterns: SerializableSuspiciousPattern[];
127
+ }
128
+ /**
129
+ * Double VM configuration
130
+ *
131
+ * Controls the double VM security layer behavior.
132
+ */
133
+ export interface DoubleVmConfig {
134
+ /**
135
+ * Whether double VM is enabled
136
+ *
137
+ * When disabled, a security warning is logged and user code
138
+ * runs in a single VM with direct tool handler access.
139
+ *
140
+ * @default true
141
+ */
142
+ enabled: boolean;
143
+ /**
144
+ * Extra timeout buffer for parent VM (ms)
145
+ *
146
+ * The parent VM timeout = inner VM timeout + this buffer.
147
+ * This allows the parent VM to properly handle inner VM timeouts.
148
+ *
149
+ * @default 1000
150
+ */
151
+ parentTimeoutBuffer: number;
152
+ /**
153
+ * Parent VM validation configuration
154
+ */
155
+ parentValidation: ParentValidationConfig;
156
+ }
157
+ /**
158
+ * Partial configuration for user input
159
+ * (all fields optional, merged with defaults)
160
+ */
161
+ export interface PartialDoubleVmConfig {
162
+ enabled?: boolean;
163
+ parentTimeoutBuffer?: number;
164
+ parentValidation?: Partial<Omit<ParentValidationConfig, 'suspiciousPatterns'>> & {
165
+ suspiciousPatterns?: SuspiciousPattern[];
166
+ };
167
+ }
168
+ /**
169
+ * Execution statistics from double VM
170
+ */
171
+ export interface DoubleVmStats {
172
+ /** Number of operations that passed validation */
173
+ validatedOperations: number;
174
+ /** Number of operations blocked by validation */
175
+ blockedOperations: number;
176
+ /** Patterns that were triggered (for logging/debugging) */
177
+ triggeredPatterns: string[];
178
+ }
@@ -0,0 +1,11 @@
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
@@ -0,0 +1 @@
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"]}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Adapter Wrapper Factory
3
+ *
4
+ * Provides a function to wrap any SandboxAdapter with the double VM layer.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import type { SandboxAdapter, SecurityLevel } from '../types';
9
+ import type { DoubleVmConfig } from './types';
10
+ /**
11
+ * Wrap a sandbox adapter with the double VM layer
12
+ *
13
+ * When enabled, this creates a nested VM structure where:
14
+ * - The Parent VM acts as a security barrier with enhanced validation
15
+ * - The Inner VM is where user code actually executes
16
+ * - Tool calls flow: Inner VM -> Parent VM validation -> Host handler
17
+ *
18
+ * When disabled, a security warning is logged and the original adapter
19
+ * is returned unchanged. This is NOT recommended for production use.
20
+ *
21
+ * @param baseAdapter - The original adapter. When double VM is enabled, this parameter
22
+ * is not used (a new DoubleVmWrapper is created). When disabled, this must be provided
23
+ * and will be returned directly. Pass undefined when double VM is enabled.
24
+ * @param config - Double VM configuration
25
+ * @param securityLevel - The security level for dangerous global removal
26
+ * @returns The wrapped adapter (or original if disabled)
27
+ * @throws Error if double VM is disabled and baseAdapter is not provided
28
+ */
29
+ export declare function wrapWithDoubleVm(baseAdapter: SandboxAdapter | undefined, config: DoubleVmConfig, securityLevel: SecurityLevel): SandboxAdapter;
30
+ /**
31
+ * Check if double VM is enabled in the config
32
+ *
33
+ * @param config - Partial double VM config
34
+ * @returns Whether double VM is enabled (defaults to true)
35
+ */
36
+ export declare function isDoubleVmEnabled(config?: Partial<DoubleVmConfig>): boolean;
@@ -0,0 +1,59 @@
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
@@ -0,0 +1 @@
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"]}
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Enclave - Safe AgentScript Execution Environment
3
+ *
4
+ * Provides a sandboxed environment for executing AgentScript code with:
5
+ * - AST validation
6
+ * - Code transformation
7
+ * - Runtime safety wrappers
8
+ * - Resource limits (timeout, memory, iterations)
9
+ * - Pass-by-reference support for large data
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ import type { CreateEnclaveOptions, ExecutionResult, ToolHandler, SecurityLevel } from './types';
14
+ import { ScoringGate } from './scoring';
15
+ /**
16
+ * Enclave - Safe AgentScript Execution Environment
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * import { Enclave } from '@enclave-vm/core';
21
+ *
22
+ * // Create enclave with tool handler
23
+ * const enclave = new Enclave({
24
+ * timeout: 5000,
25
+ * maxToolCalls: 50,
26
+ * toolHandler: async (toolName, args) => {
27
+ * // Handle tool calls
28
+ * return { result: 'data' };
29
+ * },
30
+ * });
31
+ *
32
+ * // Execute AgentScript code
33
+ * const code = `
34
+ * const users = await callTool('users:list', {});
35
+ * return users.items.length;
36
+ * `;
37
+ *
38
+ * const result = await enclave.run(code);
39
+ * console.log(result.value); // Number of users
40
+ * ```
41
+ */
42
+ export declare class Enclave {
43
+ private readonly config;
44
+ private readonly securityLevel;
45
+ private readonly validator;
46
+ private readonly validateCode;
47
+ private readonly transformCode;
48
+ private readonly referenceConfig?;
49
+ private readonly scoringGate?;
50
+ private readonly doubleVmConfig;
51
+ private adapter?;
52
+ constructor(options?: CreateEnclaveOptions);
53
+ /**
54
+ * Build double VM configuration from user options
55
+ *
56
+ * Merges user options with defaults, handling nested validation config.
57
+ */
58
+ private buildDoubleVmConfig;
59
+ /**
60
+ * Initialize async components (scoring gate, etc.)
61
+ *
62
+ * Call this before run() if using scorers that require initialization
63
+ * (e.g., local-llm needs to download the model)
64
+ */
65
+ initialize(): Promise<void>;
66
+ /**
67
+ * Execute AgentScript code
68
+ *
69
+ * @param code AgentScript code to execute
70
+ * @param toolHandler Optional tool handler (overrides constructor config)
71
+ * @returns Execution result
72
+ */
73
+ run<T = unknown>(code: string, toolHandler?: ToolHandler): Promise<ExecutionResult<T>>;
74
+ /**
75
+ * Apply memory tracking transforms to code
76
+ *
77
+ * Transforms concatenation operations to use __safe_concat for memory tracking.
78
+ * This is used when memoryLimit is set but no sidecar is configured.
79
+ *
80
+ * @param code The code to transform
81
+ * @returns The transformed code
82
+ */
83
+ private applyMemoryTrackingTransforms;
84
+ /**
85
+ * Apply sidecar transforms to code
86
+ *
87
+ * Extracts large strings and transforms concatenation to use safe functions.
88
+ *
89
+ * @param code The code to transform
90
+ * @param sidecar The sidecar to store extracted strings
91
+ * @returns The transformed code
92
+ */
93
+ private applySidecarTransforms;
94
+ /**
95
+ * Get or create the sandbox adapter
96
+ *
97
+ * When double VM is enabled (default), the base adapter is wrapped
98
+ * with a double VM layer that provides:
99
+ * - Nested VM isolation (Parent VM + Inner VM)
100
+ * - Enhanced tool call validation
101
+ * - Suspicious pattern detection
102
+ * - Defense-in-depth against VM escape attacks
103
+ */
104
+ private getAdapter;
105
+ /**
106
+ * Get the current security level
107
+ *
108
+ * @returns The security level this enclave was configured with
109
+ */
110
+ getSecurityLevel(): SecurityLevel;
111
+ /**
112
+ * Get the effective configuration
113
+ *
114
+ * Useful for debugging and understanding what settings are active
115
+ *
116
+ * @returns A copy of the current configuration
117
+ */
118
+ getEffectiveConfig(): {
119
+ securityLevel: SecurityLevel;
120
+ timeout: number;
121
+ maxIterations: number;
122
+ maxToolCalls: number;
123
+ sanitizeStackTraces: boolean;
124
+ maxSanitizeDepth: number;
125
+ maxSanitizeProperties: number;
126
+ memoryLimit: number;
127
+ };
128
+ /**
129
+ * Create a validator based on the selected preset
130
+ *
131
+ * @param presetName The preset to use
132
+ * @param customAllowedGlobals Custom globals to whitelist
133
+ * @returns A configured JSAstValidator
134
+ */
135
+ private createValidator;
136
+ /**
137
+ * Dispose the enclave and cleanup resources
138
+ */
139
+ dispose(): void;
140
+ /**
141
+ * Get scoring gate statistics (if configured)
142
+ */
143
+ getScoringStats(): ReturnType<ScoringGate['getCacheStats']> | null;
144
+ /**
145
+ * Format validation errors with line numbers and deduplication
146
+ *
147
+ * @param issues Array of validation issues
148
+ * @returns Formatted error message string
149
+ */
150
+ private formatValidationErrors;
151
+ }
152
+ /**
153
+ * Convenience function to create an enclave and run code in one step
154
+ *
155
+ * @param code AgentScript code to execute
156
+ * @param options Enclave configuration options
157
+ * @returns Execution result
158
+ */
159
+ export declare function runAgentScript<T = unknown>(code: string, options?: CreateEnclaveOptions): Promise<ExecutionResult<T>>;