@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.
- package/LICENSE +201 -0
- package/README.md +732 -0
- package/SECURITY-AUDIT.md +916 -0
- package/package.json +59 -0
- package/src/adapters/vm-adapter.d.ts +32 -0
- package/src/adapters/vm-adapter.js +1140 -0
- package/src/adapters/vm-adapter.js.map +1 -0
- package/src/adapters/worker-pool/config.d.ts +149 -0
- package/src/adapters/worker-pool/config.js +129 -0
- package/src/adapters/worker-pool/config.js.map +1 -0
- package/src/adapters/worker-pool/errors.d.ts +109 -0
- package/src/adapters/worker-pool/errors.js +181 -0
- package/src/adapters/worker-pool/errors.js.map +1 -0
- package/src/adapters/worker-pool/execution-queue.d.ts +85 -0
- package/src/adapters/worker-pool/execution-queue.js +179 -0
- package/src/adapters/worker-pool/execution-queue.js.map +1 -0
- package/src/adapters/worker-pool/index.d.ts +48 -0
- package/src/adapters/worker-pool/index.js +73 -0
- package/src/adapters/worker-pool/index.js.map +1 -0
- package/src/adapters/worker-pool/memory-monitor.d.ts +106 -0
- package/src/adapters/worker-pool/memory-monitor.js +184 -0
- package/src/adapters/worker-pool/memory-monitor.js.map +1 -0
- package/src/adapters/worker-pool/protocol.d.ts +314 -0
- package/src/adapters/worker-pool/protocol.js +143 -0
- package/src/adapters/worker-pool/protocol.js.map +1 -0
- package/src/adapters/worker-pool/rate-limiter.d.ts +60 -0
- package/src/adapters/worker-pool/rate-limiter.js +101 -0
- package/src/adapters/worker-pool/rate-limiter.js.map +1 -0
- package/src/adapters/worker-pool/safe-deserialize.d.ts +50 -0
- package/src/adapters/worker-pool/safe-deserialize.js +141 -0
- package/src/adapters/worker-pool/safe-deserialize.js.map +1 -0
- package/src/adapters/worker-pool/worker-pool-adapter.d.ts +84 -0
- package/src/adapters/worker-pool/worker-pool-adapter.js +506 -0
- package/src/adapters/worker-pool/worker-pool-adapter.js.map +1 -0
- package/src/adapters/worker-pool/worker-script.d.ts +12 -0
- package/src/adapters/worker-pool/worker-script.js +770 -0
- package/src/adapters/worker-pool/worker-script.js.map +1 -0
- package/src/adapters/worker-pool/worker-slot.d.ts +116 -0
- package/src/adapters/worker-pool/worker-slot.js +301 -0
- package/src/adapters/worker-pool/worker-slot.js.map +1 -0
- package/src/babel/babel-wrapper.d.ts +118 -0
- package/src/babel/babel-wrapper.js +395 -0
- package/src/babel/babel-wrapper.js.map +1 -0
- package/src/babel/index.d.ts +9 -0
- package/src/babel/index.js +17 -0
- package/src/babel/index.js.map +1 -0
- package/src/babel/multi-file-transform.d.ts +122 -0
- package/src/babel/multi-file-transform.js +344 -0
- package/src/babel/multi-file-transform.js.map +1 -0
- package/src/double-vm/double-vm-wrapper.d.ts +65 -0
- package/src/double-vm/double-vm-wrapper.js +523 -0
- package/src/double-vm/double-vm-wrapper.js.map +1 -0
- package/src/double-vm/index.d.ts +31 -0
- package/src/double-vm/index.js +34 -0
- package/src/double-vm/index.js.map +1 -0
- package/src/double-vm/parent-vm-bootstrap.d.ts +63 -0
- package/src/double-vm/parent-vm-bootstrap.js +1695 -0
- package/src/double-vm/parent-vm-bootstrap.js.map +1 -0
- package/src/double-vm/suspicious-patterns.d.ts +57 -0
- package/src/double-vm/suspicious-patterns.js +304 -0
- package/src/double-vm/suspicious-patterns.js.map +1 -0
- package/src/double-vm/types.d.ts +178 -0
- package/src/double-vm/types.js +11 -0
- package/src/double-vm/types.js.map +1 -0
- package/src/double-vm/wrap-adapter.d.ts +36 -0
- package/src/double-vm/wrap-adapter.js +59 -0
- package/src/double-vm/wrap-adapter.js.map +1 -0
- package/src/enclave.d.ts +159 -0
- package/src/enclave.js +671 -0
- package/src/enclave.js.map +1 -0
- package/src/globals-validator.d.ts +80 -0
- package/src/globals-validator.js +206 -0
- package/src/globals-validator.js.map +1 -0
- package/src/index.d.ts +29 -0
- package/src/index.js +130 -0
- package/src/index.js.map +1 -0
- package/src/memory-proxy.d.ts +69 -0
- package/src/memory-proxy.js +310 -0
- package/src/memory-proxy.js.map +1 -0
- package/src/memory-tracker.d.ts +170 -0
- package/src/memory-tracker.js +230 -0
- package/src/memory-tracker.js.map +1 -0
- package/src/safe-error.d.ts +18 -0
- package/src/safe-error.js +76 -0
- package/src/safe-error.js.map +1 -0
- package/src/safe-runtime.d.ts +72 -0
- package/src/safe-runtime.js +656 -0
- package/src/safe-runtime.js.map +1 -0
- package/src/scoring/cache.d.ts +68 -0
- package/src/scoring/cache.js +158 -0
- package/src/scoring/cache.js.map +1 -0
- package/src/scoring/feature-extractor.d.ts +61 -0
- package/src/scoring/feature-extractor.js +366 -0
- package/src/scoring/feature-extractor.js.map +1 -0
- package/src/scoring/index.d.ts +33 -0
- package/src/scoring/index.js +53 -0
- package/src/scoring/index.js.map +1 -0
- package/src/scoring/scorer.interface.d.ts +65 -0
- package/src/scoring/scorer.interface.js +49 -0
- package/src/scoring/scorer.interface.js.map +1 -0
- package/src/scoring/scorers/disabled.scorer.d.ts +19 -0
- package/src/scoring/scorers/disabled.scorer.js +34 -0
- package/src/scoring/scorers/disabled.scorer.js.map +1 -0
- package/src/scoring/scorers/external-api.scorer.d.ts +29 -0
- package/src/scoring/scorers/external-api.scorer.js +141 -0
- package/src/scoring/scorers/external-api.scorer.js.map +1 -0
- package/src/scoring/scorers/index.d.ts +10 -0
- package/src/scoring/scorers/index.js +22 -0
- package/src/scoring/scorers/index.js.map +1 -0
- package/src/scoring/scorers/local-llm.scorer.d.ts +116 -0
- package/src/scoring/scorers/local-llm.scorer.js +474 -0
- package/src/scoring/scorers/local-llm.scorer.js.map +1 -0
- package/src/scoring/scorers/progressive.scorer.d.ts +77 -0
- package/src/scoring/scorers/progressive.scorer.js +199 -0
- package/src/scoring/scorers/progressive.scorer.js.map +1 -0
- package/src/scoring/scorers/rule-based.scorer.d.ts +66 -0
- package/src/scoring/scorers/rule-based.scorer.js +316 -0
- package/src/scoring/scorers/rule-based.scorer.js.map +1 -0
- package/src/scoring/scoring-gate.d.ts +76 -0
- package/src/scoring/scoring-gate.js +246 -0
- package/src/scoring/scoring-gate.js.map +1 -0
- package/src/scoring/types.d.ts +690 -0
- package/src/scoring/types.js +107 -0
- package/src/scoring/types.js.map +1 -0
- package/src/secure-proxy.d.ts +157 -0
- package/src/secure-proxy.js +609 -0
- package/src/secure-proxy.js.map +1 -0
- package/src/session/channels/embedded-channel.d.ts +76 -0
- package/src/session/channels/embedded-channel.js +130 -0
- package/src/session/channels/embedded-channel.js.map +1 -0
- package/src/session/channels/index.d.ts +9 -0
- package/src/session/channels/index.js +14 -0
- package/src/session/channels/index.js.map +1 -0
- package/src/session/index.d.ts +15 -0
- package/src/session/index.js +27 -0
- package/src/session/index.js.map +1 -0
- package/src/session/session-emitter.d.ts +119 -0
- package/src/session/session-emitter.js +253 -0
- package/src/session/session-emitter.js.map +1 -0
- package/src/session/session-state-machine.d.ts +108 -0
- package/src/session/session-state-machine.js +182 -0
- package/src/session/session-state-machine.js.map +1 -0
- package/src/session/session.d.ts +135 -0
- package/src/session/session.js +398 -0
- package/src/session/session.js.map +1 -0
- package/src/session-types.d.ts +313 -0
- package/src/session-types.js +39 -0
- package/src/session-types.js.map +1 -0
- package/src/sidecar/index.d.ts +12 -0
- package/src/sidecar/index.js +31 -0
- package/src/sidecar/index.js.map +1 -0
- package/src/sidecar/reference-config.d.ts +81 -0
- package/src/sidecar/reference-config.js +118 -0
- package/src/sidecar/reference-config.js.map +1 -0
- package/src/sidecar/reference-resolver.d.ts +115 -0
- package/src/sidecar/reference-resolver.js +262 -0
- package/src/sidecar/reference-resolver.js.map +1 -0
- package/src/sidecar/reference-sidecar.d.ts +161 -0
- package/src/sidecar/reference-sidecar.js +226 -0
- package/src/sidecar/reference-sidecar.js.map +1 -0
- package/src/tool-bridge.d.ts +4 -0
- package/src/tool-bridge.js +306 -0
- package/src/tool-bridge.js.map +1 -0
- package/src/types.d.ts +775 -0
- package/src/types.js +187 -0
- package/src/types.js.map +1 -0
- package/src/value-sanitizer.d.ts +133 -0
- package/src/value-sanitizer.js +421 -0
- package/src/value-sanitizer.js.map +1 -0
package/README.md
ADDED
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
# @enclave-vm/core
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@enclave-vm/core)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
[](https://www.typescriptlang.org/)
|
|
6
|
+
|
|
7
|
+
> Secure AgentScript execution environment with defense-in-depth architecture
|
|
8
|
+
|
|
9
|
+
The @enclave-vm/core package provides a hardened execution environment for running LLM-generated JavaScript code (AgentScript) safely. It combines AST validation, code transformation, runtime guards, and VM sandboxing to prevent sandbox escapes and resource exhaustion.
|
|
10
|
+
|
|
11
|
+
## Security
|
|
12
|
+
|
|
13
|
+
| Metric | Value |
|
|
14
|
+
| -------------- | ---------------------------------------------------------------------- |
|
|
15
|
+
| Security Tests | 1900+ tests, 100% pass rate |
|
|
16
|
+
| Attack Vectors | 150+ blocked (including function gadget attacks) |
|
|
17
|
+
| CVE Protection | Covers known vm2, isolated-vm, node-vm exploits |
|
|
18
|
+
| Defense Layers | 6 (Pre-Scanner, AST, Transform, Scoring, VM/Worker Pool, Sanitization) |
|
|
19
|
+
|
|
20
|
+
For the full security audit report, see [SECURITY-AUDIT.md](./SECURITY-AUDIT.md).
|
|
21
|
+
|
|
22
|
+
## Features
|
|
23
|
+
|
|
24
|
+
- **Defense-in-Depth**: 6 layers of security (Pre-Scanner → AST → transformation → AI Scoring → VM/Worker Pool → output sanitization)
|
|
25
|
+
- **Worker Pool Adapter** (NEW): Optional OS-level memory isolation via worker threads with hard halt capability
|
|
26
|
+
- **Safe Tool Calls**: Secure `callTool()` execution with iteration and call limits
|
|
27
|
+
- **Reference Sidecar**: Handle large data without embedding it in the script
|
|
28
|
+
- **Configurable Security Levels**: From STRICT to PERMISSIVE based on trust level
|
|
29
|
+
- **Resource Limits**: Timeout, iteration limits, and tool call limits
|
|
30
|
+
- **AI Scoring Gate**: Semantic analysis detects exfiltration patterns and sensitive data access
|
|
31
|
+
- **Zero Dependencies on Vulnerable Packages**: Uses Node.js native `vm` module
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npm install @enclave-vm/core
|
|
37
|
+
# or
|
|
38
|
+
yarn add @enclave-vm/core
|
|
39
|
+
# or
|
|
40
|
+
pnpm add @enclave-vm/core
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Quick Start
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
import { Enclave } from '@enclave-vm/core';
|
|
47
|
+
|
|
48
|
+
// Create enclave with a tool handler
|
|
49
|
+
const enclave = new Enclave({
|
|
50
|
+
timeout: 5000,
|
|
51
|
+
maxToolCalls: 10,
|
|
52
|
+
maxIterations: 1000,
|
|
53
|
+
toolHandler: async (toolName, args) => {
|
|
54
|
+
// Your tool execution logic
|
|
55
|
+
return { success: true, data: `Called ${toolName}` };
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// Execute AgentScript code
|
|
60
|
+
const result = await enclave.run(`
|
|
61
|
+
const user = await callTool('getUser', { id: 123 });
|
|
62
|
+
const orders = await callTool('getOrders', { userId: user.id });
|
|
63
|
+
return { user, orderCount: orders.length };
|
|
64
|
+
`);
|
|
65
|
+
|
|
66
|
+
if (result.success) {
|
|
67
|
+
console.log('Result:', result.value);
|
|
68
|
+
} else {
|
|
69
|
+
console.error('Error:', result.error);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Always dispose when done
|
|
73
|
+
enclave.dispose();
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Configuration
|
|
77
|
+
|
|
78
|
+
### CreateEnclaveOptions
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
interface CreateEnclaveOptions {
|
|
82
|
+
// Execution limits
|
|
83
|
+
timeout?: number; // Execution timeout in ms (default: 5000)
|
|
84
|
+
maxToolCalls?: number; // Maximum tool calls allowed (default: 100)
|
|
85
|
+
maxIterations?: number; // Maximum loop iterations (default: 10000)
|
|
86
|
+
|
|
87
|
+
// Security
|
|
88
|
+
securityLevel?: SecurityLevel; // STRICT | SECURE | STANDARD | PERMISSIVE
|
|
89
|
+
validate?: boolean; // Enable AST validation (default: true)
|
|
90
|
+
transform?: boolean; // Enable code transformation (default: true)
|
|
91
|
+
|
|
92
|
+
// Tool execution
|
|
93
|
+
toolHandler?: ToolHandler; // Function to execute tool calls
|
|
94
|
+
|
|
95
|
+
// Custom globals
|
|
96
|
+
globals?: Record<string, unknown>; // Additional globals for the VM
|
|
97
|
+
allowFunctionsInGlobals?: boolean; // Allow functions in globals (default: false)
|
|
98
|
+
|
|
99
|
+
// Sidecar (large data handling)
|
|
100
|
+
sidecar?: ReferenceSidecarOptions;
|
|
101
|
+
|
|
102
|
+
// Double VM security layer
|
|
103
|
+
doubleVm?: PartialDoubleVmConfig; // See "Double VM Security Layer" section
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Security Levels
|
|
108
|
+
|
|
109
|
+
| Level | Description | Use Case |
|
|
110
|
+
| ------------ | ------------------------------------------ | -------------------- |
|
|
111
|
+
| `STRICT` | Maximum security, absolute minimum globals | Untrusted code |
|
|
112
|
+
| `SECURE` | High security with safe utility functions | Semi-trusted code |
|
|
113
|
+
| `STANDARD` | Balanced security for most use cases | Trusted code |
|
|
114
|
+
| `PERMISSIVE` | Adds console for debugging | Internal/development |
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
import { Enclave, SecurityLevel } from '@enclave-vm/core';
|
|
118
|
+
|
|
119
|
+
const enclave = new Enclave({
|
|
120
|
+
securityLevel: SecurityLevel.STRICT,
|
|
121
|
+
toolHandler: async (name, args) => {
|
|
122
|
+
/* ... */
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### Allowed Globals by Security Level
|
|
128
|
+
|
|
129
|
+
Both AST validation and runtime sandbox enforce the same allowed globals for defense-in-depth:
|
|
130
|
+
|
|
131
|
+
| Global | STRICT | SECURE | STANDARD | PERMISSIVE |
|
|
132
|
+
| --------------------- | ------ | ------ | -------- | ---------- |
|
|
133
|
+
| **Core API** | | | | |
|
|
134
|
+
| `callTool` | ✅ | ✅ | ✅ | ✅ |
|
|
135
|
+
| **Data Types** | | | | |
|
|
136
|
+
| `Math` | ✅ | ✅ | ✅ | ✅ |
|
|
137
|
+
| `JSON` | ✅ | ✅ | ✅ | ✅ |
|
|
138
|
+
| `Array` | ✅ | ✅ | ✅ | ✅ |
|
|
139
|
+
| `Object` | ✅ | ✅ | ✅ | ✅ |
|
|
140
|
+
| `String` | ✅ | ✅ | ✅ | ✅ |
|
|
141
|
+
| `Number` | ✅ | ✅ | ✅ | ✅ |
|
|
142
|
+
| `Date` | ✅ | ✅ | ✅ | ✅ |
|
|
143
|
+
| **Constants** | | | | |
|
|
144
|
+
| `undefined` | ✅ | ✅ | ✅ | ✅ |
|
|
145
|
+
| `NaN` | ✅ | ✅ | ✅ | ✅ |
|
|
146
|
+
| `Infinity` | ✅ | ✅ | ✅ | ✅ |
|
|
147
|
+
| **Utility Functions** | | | | |
|
|
148
|
+
| `parseInt` | ❌ | ✅ | ✅ | ✅ |
|
|
149
|
+
| `parseFloat` | ❌ | ✅ | ✅ | ✅ |
|
|
150
|
+
| `isNaN` | ❌ | ✅ | ✅ | ✅ |
|
|
151
|
+
| `isFinite` | ❌ | ✅ | ✅ | ✅ |
|
|
152
|
+
| `encodeURI` | ❌ | ✅ | ✅ | ✅ |
|
|
153
|
+
| `decodeURI` | ❌ | ✅ | ✅ | ✅ |
|
|
154
|
+
| `encodeURIComponent` | ❌ | ✅ | ✅ | ✅ |
|
|
155
|
+
| `decodeURIComponent` | ❌ | ✅ | ✅ | ✅ |
|
|
156
|
+
| **Debugging** | | | | |
|
|
157
|
+
| `console` | ❌ | ❌ | ❌ | ✅ |
|
|
158
|
+
|
|
159
|
+
### Blocked Globals (All Security Levels)
|
|
160
|
+
|
|
161
|
+
These dangerous globals are **always blocked** regardless of security level:
|
|
162
|
+
|
|
163
|
+
| Category | Blocked Globals |
|
|
164
|
+
| ------------------ | ------------------------------------------------------------------------------ |
|
|
165
|
+
| **Code Execution** | `eval`, `Function`, `AsyncFunction`, `GeneratorFunction` |
|
|
166
|
+
| **System Access** | `process`, `require`, `module`, `exports`, `__dirname`, `__filename`, `Buffer` |
|
|
167
|
+
| **Global Objects** | `window`, `globalThis`, `self`, `global`, `this` |
|
|
168
|
+
| **Prototype** | `constructor`, `__proto__`, `prototype` |
|
|
169
|
+
| **Reflection** | `Proxy`, `Reflect` |
|
|
170
|
+
| **Async Flooding** | `Promise`, `setTimeout`, `setInterval`, `setImmediate`, `queueMicrotask` |
|
|
171
|
+
| **Network** | `fetch`, `XMLHttpRequest`, `WebSocket` |
|
|
172
|
+
| **Workers** | `Worker`, `SharedWorker`, `ServiceWorker` |
|
|
173
|
+
| **Memory Hazards** | `Map`, `Set`, `WeakMap`, `WeakSet`, `WeakRef`, `FinalizationRegistry` |
|
|
174
|
+
| **Binary/Wasm** | `WebAssembly`, `ArrayBuffer`, `SharedArrayBuffer`, `Atomics` |
|
|
175
|
+
| **Error Types** | `Error`, `TypeError`, `ReferenceError`, `SyntaxError`, `RangeError` |
|
|
176
|
+
| **Symbols/Regex** | `Symbol`, `RegExp` |
|
|
177
|
+
|
|
178
|
+
### AST Presets
|
|
179
|
+
|
|
180
|
+
The `preset` option controls **AST-level validation** - what JavaScript constructs are allowed before code transformation. This is separate from `securityLevel` which controls runtime security.
|
|
181
|
+
|
|
182
|
+
| Preset | Description | Custom Globals |
|
|
183
|
+
| ------------- | --------------------------------------------- | ---------------- |
|
|
184
|
+
| `agentscript` | Default. Safe subset for LLM-generated code | ✅ Supported |
|
|
185
|
+
| `strict` | Maximum restrictions, blocks most JS features | ❌ Not supported |
|
|
186
|
+
| `secure` | High security with essential features | ❌ Not supported |
|
|
187
|
+
| `standard` | Balanced security for general use | ❌ Not supported |
|
|
188
|
+
| `permissive` | Minimal AST restrictions | ❌ Not supported |
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
import { Enclave } from '@enclave-vm/core';
|
|
192
|
+
|
|
193
|
+
const enclave = new Enclave({
|
|
194
|
+
preset: 'agentscript', // AST validation preset (default)
|
|
195
|
+
securityLevel: SecurityLevel.STRICT, // Runtime security level
|
|
196
|
+
toolHandler: async (name, args) => {
|
|
197
|
+
/* ... */
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
**Key Differences:**
|
|
203
|
+
|
|
204
|
+
| Aspect | `preset` (AST) | `securityLevel` (Runtime) |
|
|
205
|
+
| ------------------------ | ---------------------------- | --------------------------- |
|
|
206
|
+
| When applied | Before execution | During execution |
|
|
207
|
+
| What it controls | JavaScript syntax/constructs | Resource limits, timeouts |
|
|
208
|
+
| Function expressions | Blocked in `agentscript` | N/A |
|
|
209
|
+
| Getter/setter syntax | Blocked in `agentscript` | N/A |
|
|
210
|
+
| Custom globals whitelist | Only `agentscript` preset | Always available at runtime |
|
|
211
|
+
|
|
212
|
+
**Note:** Only the `agentscript` preset supports the `allowedGlobals` option for whitelisting custom global identifiers in AST validation. Other presets use their own fixed rule sets.
|
|
213
|
+
|
|
214
|
+
## Worker Pool Adapter (Optional)
|
|
215
|
+
|
|
216
|
+
For environments requiring **OS-level memory isolation**, enable the Worker Pool Adapter. This provides a dual-layer sandbox with hard halt capability:
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
import { Enclave } from '@enclave-vm/core';
|
|
220
|
+
|
|
221
|
+
const enclave = new Enclave({
|
|
222
|
+
adapter: 'worker_threads', // Enable Worker Pool
|
|
223
|
+
workerPoolConfig: {
|
|
224
|
+
minWorkers: 2,
|
|
225
|
+
maxWorkers: 8,
|
|
226
|
+
memoryLimitPerWorker: 256 * 1024 * 1024, // 256MB
|
|
227
|
+
},
|
|
228
|
+
toolHandler: async (name, args) => {
|
|
229
|
+
/* ... */
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### When to Use Worker Pool
|
|
235
|
+
|
|
236
|
+
| Scenario | Recommendation |
|
|
237
|
+
| --------------------------- | ------------------------------- |
|
|
238
|
+
| Trusted internal scripts | Standard VM (lower overhead) |
|
|
239
|
+
| Multi-tenant execution | Worker Pool (OS isolation) |
|
|
240
|
+
| Untrusted AI-generated code | Worker Pool (hard halt) |
|
|
241
|
+
| Memory-sensitive workloads | Worker Pool (per-worker limits) |
|
|
242
|
+
|
|
243
|
+
### Worker Pool Presets
|
|
244
|
+
|
|
245
|
+
| Level | minWorkers | maxWorkers | memoryLimit | messagesPerSec |
|
|
246
|
+
| ---------- | ---------- | ---------- | ----------- | -------------- |
|
|
247
|
+
| STRICT | 2 | 4 | 64MB | 100 |
|
|
248
|
+
| SECURE | 2 | 8 | 128MB | 500 |
|
|
249
|
+
| STANDARD | 2 | 16 | 256MB | 1000 |
|
|
250
|
+
| PERMISSIVE | 4 | 32 | 512MB | 5000 |
|
|
251
|
+
|
|
252
|
+
### Worker Pool Configuration Options
|
|
253
|
+
|
|
254
|
+
| Option | Default | Description |
|
|
255
|
+
| ------------------------ | --------- | ------------------------------- |
|
|
256
|
+
| `minWorkers` | 2 | Minimum warm workers |
|
|
257
|
+
| `maxWorkers` | CPU count | Maximum concurrent workers |
|
|
258
|
+
| `memoryLimitPerWorker` | 128MB | Per-worker memory limit |
|
|
259
|
+
| `maxMessagesPerSecond` | 1000 | Rate limit per worker |
|
|
260
|
+
| `maxExecutionsPerWorker` | 1000 | Recycle after N executions |
|
|
261
|
+
| `maxQueueSize` | 100 | Maximum pending executions |
|
|
262
|
+
| `idleTimeoutMs` | 30000 | Time before idle worker release |
|
|
263
|
+
|
|
264
|
+
### Dual-Layer Sandbox
|
|
265
|
+
|
|
266
|
+
When using Worker Pool, code runs in a **dual-layer sandbox**:
|
|
267
|
+
|
|
268
|
+
```
|
|
269
|
+
┌─────────────────────────────────────────────────┐
|
|
270
|
+
│ Worker Thread (OS-level isolation) │
|
|
271
|
+
│ ┌─────────────────────────────────────────────┐│
|
|
272
|
+
│ │ VM Context (prototype isolation) ││
|
|
273
|
+
│ │ - Whitelist-only globals ││
|
|
274
|
+
│ │ - __safe_* runtime functions ││
|
|
275
|
+
│ └─────────────────────────────────────────────┘│
|
|
276
|
+
│ - parentPort removed from globals │
|
|
277
|
+
│ - JSON-only message serialization │
|
|
278
|
+
│ - Hard halt via worker.terminate() │
|
|
279
|
+
└─────────────────────────────────────────────────┘
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### Security Features
|
|
283
|
+
|
|
284
|
+
- **`worker.terminate()`**: Hard halt runaway scripts when VM timeout fails
|
|
285
|
+
- **`--max-old-space-size`**: Per-worker memory limits enforced by V8
|
|
286
|
+
- **JSON-only serialization**: Prevents structured clone gadget attacks
|
|
287
|
+
- **Dangerous global removal**: parentPort, workerData inaccessible in worker
|
|
288
|
+
- **Rate limiting**: Message flood protection per worker
|
|
289
|
+
- **Safe deserialize**: Prototype pollution prevention via JSON-only parsing
|
|
290
|
+
|
|
291
|
+
## Double VM Security Layer
|
|
292
|
+
|
|
293
|
+
The Double VM provides defense-in-depth by running user code in a nested VM structure. User code runs in an **Inner VM** which is isolated inside a **Parent VM**, providing enhanced protection against VM escape attacks.
|
|
294
|
+
|
|
295
|
+
### Configuration
|
|
296
|
+
|
|
297
|
+
```typescript
|
|
298
|
+
const enclave = new Enclave({
|
|
299
|
+
toolHandler: async (name, args) => {
|
|
300
|
+
/* ... */
|
|
301
|
+
},
|
|
302
|
+
doubleVm: {
|
|
303
|
+
enabled: true, // Default: true
|
|
304
|
+
parentTimeoutBuffer: 1000, // Extra timeout buffer for parent VM (ms)
|
|
305
|
+
parentValidation: {
|
|
306
|
+
validateOperationNames: true, // Validate tool names against patterns
|
|
307
|
+
allowedOperationPattern: /^(db|api):[a-z]+$/i, // Whitelist pattern
|
|
308
|
+
blockedOperationPatterns: [/^shell:/i, /^system:/i], // Blacklist patterns
|
|
309
|
+
maxOperationsPerSecond: 100, // Rate limiting
|
|
310
|
+
blockSuspiciousSequences: true, // Enable suspicious pattern detection
|
|
311
|
+
rapidEnumerationThreshold: 30, // Max same-operation calls in 5s
|
|
312
|
+
rapidEnumerationOverrides: {
|
|
313
|
+
// Per-operation overrides for rapidEnumerationThreshold
|
|
314
|
+
search: 100, // Allow 100 search calls
|
|
315
|
+
'users.list': 50, // Allow 50 user list calls
|
|
316
|
+
},
|
|
317
|
+
},
|
|
318
|
+
},
|
|
319
|
+
});
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
### Parent Validation Options
|
|
323
|
+
|
|
324
|
+
| Option | Type | Default | Description |
|
|
325
|
+
| --------------------------- | ----------------------- | ------- | -------------------------------------------- |
|
|
326
|
+
| `validateOperationNames` | `boolean` | `true` | Enable operation name validation |
|
|
327
|
+
| `allowedOperationPattern` | `RegExp` | - | Whitelist pattern for operation names |
|
|
328
|
+
| `blockedOperationPatterns` | `RegExp[]` | - | Blacklist patterns for operation names |
|
|
329
|
+
| `maxOperationsPerSecond` | `number` | `100` | Rate limit for operations per second |
|
|
330
|
+
| `blockSuspiciousSequences` | `boolean` | `true` | Enable suspicious pattern detection |
|
|
331
|
+
| `rapidEnumerationThreshold` | `number` | `30` | Max same-operation calls in 5 seconds |
|
|
332
|
+
| `rapidEnumerationOverrides` | `Record<string,number>` | `{}` | Per-operation thresholds (overrides default) |
|
|
333
|
+
| `suspiciousPatterns` | `SuspiciousPattern[]` | `[]` | Custom suspicious pattern detectors |
|
|
334
|
+
|
|
335
|
+
### Built-in Suspicious Pattern Detection
|
|
336
|
+
|
|
337
|
+
When `blockSuspiciousSequences: true`, the following patterns are detected:
|
|
338
|
+
|
|
339
|
+
| Pattern ID | Description |
|
|
340
|
+
| --------------------- | --------------------------------------------------- |
|
|
341
|
+
| `EXFIL_LIST_SEND` | List/query followed by send/export (data exfil) |
|
|
342
|
+
| `RAPID_ENUMERATION` | Same operation called too many times (configurable) |
|
|
343
|
+
| `CREDENTIAL_EXFIL` | Credential access followed by external operation |
|
|
344
|
+
| `BULK_OPERATION` | Bulk/batch operations (mass data extraction) |
|
|
345
|
+
| `DELETE_AFTER_ACCESS` | Delete operation after data access (cover-up) |
|
|
346
|
+
|
|
347
|
+
### Configuring Rapid Enumeration Detection
|
|
348
|
+
|
|
349
|
+
The `RAPID_ENUMERATION` pattern blocks excessive repeated calls to the same operation. Use `rapidEnumerationThreshold` and `rapidEnumerationOverrides` to tune this:
|
|
350
|
+
|
|
351
|
+
```typescript
|
|
352
|
+
const enclave = new Enclave({
|
|
353
|
+
toolHandler: async (name, args) => {
|
|
354
|
+
/* ... */
|
|
355
|
+
},
|
|
356
|
+
doubleVm: {
|
|
357
|
+
parentValidation: {
|
|
358
|
+
// Default: Block if same operation called >30 times in 5 seconds
|
|
359
|
+
rapidEnumerationThreshold: 30,
|
|
360
|
+
|
|
361
|
+
// Per-operation overrides
|
|
362
|
+
rapidEnumerationOverrides: {
|
|
363
|
+
search: 100, // Search can be called 100 times (pagination)
|
|
364
|
+
'db.query': 50, // Database queries up to 50 times
|
|
365
|
+
'users.filter': 200, // High-volume filtering allowed
|
|
366
|
+
},
|
|
367
|
+
},
|
|
368
|
+
},
|
|
369
|
+
});
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
### Custom Suspicious Patterns
|
|
373
|
+
|
|
374
|
+
You can add custom pattern detectors:
|
|
375
|
+
|
|
376
|
+
```typescript
|
|
377
|
+
const enclave = new Enclave({
|
|
378
|
+
toolHandler: async (name, args) => {
|
|
379
|
+
/* ... */
|
|
380
|
+
},
|
|
381
|
+
doubleVm: {
|
|
382
|
+
parentValidation: {
|
|
383
|
+
suspiciousPatterns: [
|
|
384
|
+
{
|
|
385
|
+
id: 'CUSTOM_PATTERN',
|
|
386
|
+
description: 'Detect sensitive + external call',
|
|
387
|
+
detect: (operationName, args, history) => {
|
|
388
|
+
const hasSensitiveAccess = history.some((h) => h.operationName.includes('sensitive'));
|
|
389
|
+
const isExternalCall = operationName.includes('external');
|
|
390
|
+
return hasSensitiveAccess && isExternalCall;
|
|
391
|
+
},
|
|
392
|
+
},
|
|
393
|
+
],
|
|
394
|
+
},
|
|
395
|
+
},
|
|
396
|
+
});
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
## AI Scoring Gate
|
|
400
|
+
|
|
401
|
+
The AI Scoring Gate provides semantic security analysis to detect attack patterns beyond what static AST validation can catch. It analyzes tool call patterns, sensitive data access, and exfiltration attempts.
|
|
402
|
+
|
|
403
|
+
### Configuration
|
|
404
|
+
|
|
405
|
+
```typescript
|
|
406
|
+
const enclave = new Enclave({
|
|
407
|
+
toolHandler: async (name, args) => {
|
|
408
|
+
/* ... */
|
|
409
|
+
},
|
|
410
|
+
scoring: {
|
|
411
|
+
scorer: 'rule-based', // 'disabled' | 'rule-based' | 'local-llm' | 'external-api'
|
|
412
|
+
blockThreshold: 70, // Block if score >= 70
|
|
413
|
+
warnThreshold: 40, // Warn if score >= 40
|
|
414
|
+
},
|
|
415
|
+
});
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
### Scorer Types
|
|
419
|
+
|
|
420
|
+
| Type | Description | Latency |
|
|
421
|
+
| -------------- | ------------------------------------------ | ------- |
|
|
422
|
+
| `disabled` | No scoring (pass-through) | 0ms |
|
|
423
|
+
| `rule-based` | Pure TypeScript rules, zero dependencies | ~1ms |
|
|
424
|
+
| `local-llm` | On-device ML with HuggingFace transformers | ~5-10ms |
|
|
425
|
+
| `external-api` | External API-based scoring | ~100ms |
|
|
426
|
+
|
|
427
|
+
### Custom Analyzer (Extensibility)
|
|
428
|
+
|
|
429
|
+
For advanced use cases, you can provide a custom analyzer to integrate external LLMs or static code analyzers:
|
|
430
|
+
|
|
431
|
+
```typescript
|
|
432
|
+
import { Enclave, CustomAnalyzer } from '@enclave-vm/core';
|
|
433
|
+
|
|
434
|
+
const myAnalyzer: CustomAnalyzer = {
|
|
435
|
+
async analyze(prompt, features) {
|
|
436
|
+
// Call your external LLM or static analyzer
|
|
437
|
+
const response = await fetch('https://my-analyzer-api.com/score', {
|
|
438
|
+
method: 'POST',
|
|
439
|
+
body: JSON.stringify({ prompt, features }),
|
|
440
|
+
});
|
|
441
|
+
const result = await response.json();
|
|
442
|
+
return {
|
|
443
|
+
score: result.riskScore,
|
|
444
|
+
signals: result.signals,
|
|
445
|
+
};
|
|
446
|
+
},
|
|
447
|
+
// Optional lifecycle methods
|
|
448
|
+
async initialize() {
|
|
449
|
+
/* connect to service */
|
|
450
|
+
},
|
|
451
|
+
dispose() {
|
|
452
|
+
/* cleanup */
|
|
453
|
+
},
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
const enclave = new Enclave({
|
|
457
|
+
toolHandler: async (name, args) => {
|
|
458
|
+
/* ... */
|
|
459
|
+
},
|
|
460
|
+
scoringGate: {
|
|
461
|
+
scorer: 'local-llm',
|
|
462
|
+
localLlm: {
|
|
463
|
+
modelId: 'Xenova/all-MiniLM-L6-v2',
|
|
464
|
+
customAnalyzer: myAnalyzer,
|
|
465
|
+
},
|
|
466
|
+
},
|
|
467
|
+
});
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
### CustomAnalyzer Interface
|
|
471
|
+
|
|
472
|
+
```typescript
|
|
473
|
+
interface CustomAnalyzer {
|
|
474
|
+
// Analyze prompt and features, return risk score and signals
|
|
475
|
+
analyze(prompt: string, features: ExtractedFeatures): Promise<{ score: number; signals: RiskSignal[] }>;
|
|
476
|
+
|
|
477
|
+
// Optional: Initialize resources (e.g., connect to external service)
|
|
478
|
+
initialize?(): Promise<void>;
|
|
479
|
+
|
|
480
|
+
// Optional: Cleanup resources
|
|
481
|
+
dispose?(): void;
|
|
482
|
+
}
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
## Reference Sidecar
|
|
486
|
+
|
|
487
|
+
The Reference Sidecar is a powerful feature for handling large data in AgentScript without embedding it directly in the script. This is essential when:
|
|
488
|
+
|
|
489
|
+
- Tool responses contain large datasets
|
|
490
|
+
- You need to pass large data between tool calls
|
|
491
|
+
- Script size must be kept small for security validation
|
|
492
|
+
|
|
493
|
+
### How It Works
|
|
494
|
+
|
|
495
|
+
1. **Large Data Extraction**: When a tool returns large data, it's stored in a sidecar storage and replaced with a reference token (`__ref_abc123`)
|
|
496
|
+
2. **Lazy Resolution**: When the script accesses the reference, it's resolved just-in-time
|
|
497
|
+
3. **Safe Property Access**: Only specific properties can be accessed, preventing data exfiltration
|
|
498
|
+
|
|
499
|
+
### Enabling Sidecar
|
|
500
|
+
|
|
501
|
+
```typescript
|
|
502
|
+
const enclave = new Enclave({
|
|
503
|
+
toolHandler: async (name, args) => {
|
|
504
|
+
/* ... */
|
|
505
|
+
},
|
|
506
|
+
sidecar: {
|
|
507
|
+
enabled: true,
|
|
508
|
+
maxTotalSize: 10 * 1024 * 1024, // 10MB total storage
|
|
509
|
+
maxReferenceSize: 1 * 1024 * 1024, // 1MB per reference
|
|
510
|
+
extractionThreshold: 1024, // Extract strings > 1KB
|
|
511
|
+
maxResolvedSize: 5 * 1024 * 1024, // 5MB max resolved size
|
|
512
|
+
allowComposites: false, // Block string concatenation with refs
|
|
513
|
+
},
|
|
514
|
+
});
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
### Sidecar Options
|
|
518
|
+
|
|
519
|
+
| Option | Type | Default | Description |
|
|
520
|
+
| --------------------- | --------- | ------- | ------------------------------------------------ |
|
|
521
|
+
| `enabled` | `boolean` | `false` | Enable the sidecar feature |
|
|
522
|
+
| `maxTotalSize` | `number` | 10MB | Maximum total size of all stored references |
|
|
523
|
+
| `maxReferenceSize` | `number` | 1MB | Maximum size of a single reference |
|
|
524
|
+
| `extractionThreshold` | `number` | 1024 | Minimum string size to extract to sidecar |
|
|
525
|
+
| `maxResolvedSize` | `number` | 5MB | Maximum size when resolving references |
|
|
526
|
+
| `allowComposites` | `boolean` | `false` | Allow string concatenation with reference tokens |
|
|
527
|
+
|
|
528
|
+
### Example with Sidecar
|
|
529
|
+
|
|
530
|
+
```typescript
|
|
531
|
+
const enclave = new Enclave({
|
|
532
|
+
sidecar: {
|
|
533
|
+
enabled: true,
|
|
534
|
+
extractionThreshold: 100, // Extract strings > 100 bytes
|
|
535
|
+
allowComposites: false, // Block: ref + "suffix" (security measure)
|
|
536
|
+
},
|
|
537
|
+
toolHandler: async (name, args) => {
|
|
538
|
+
if (name === 'getLargeData') {
|
|
539
|
+
// Returns 1MB of data - automatically stored in sidecar
|
|
540
|
+
return { data: 'x'.repeat(1024 * 1024) };
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
const result = await enclave.run(`
|
|
546
|
+
// Large data is transparently handled via sidecar
|
|
547
|
+
const response = await callTool('getLargeData', {});
|
|
548
|
+
|
|
549
|
+
// Access properties - resolved on demand
|
|
550
|
+
return { hasData: response.data.length > 0 };
|
|
551
|
+
`);
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
### Security Considerations
|
|
555
|
+
|
|
556
|
+
The `allowComposites: false` setting (default) blocks string concatenation with reference tokens. This prevents attacks like:
|
|
557
|
+
|
|
558
|
+
```javascript
|
|
559
|
+
// BLOCKED when allowComposites: false
|
|
560
|
+
const malicious = ref + '__proto__'; // Attempting prototype pollution
|
|
561
|
+
```
|
|
562
|
+
|
|
563
|
+
Set `allowComposites: true` only if you need to concatenate strings and understand the security implications.
|
|
564
|
+
|
|
565
|
+
## Custom Globals
|
|
566
|
+
|
|
567
|
+
You can provide custom globals to the VM:
|
|
568
|
+
|
|
569
|
+
```typescript
|
|
570
|
+
const enclave = new Enclave({
|
|
571
|
+
globals: {
|
|
572
|
+
config: { apiUrl: 'https://api.example.com' },
|
|
573
|
+
helpers: {
|
|
574
|
+
formatDate: (date: Date) => date.toISOString(),
|
|
575
|
+
},
|
|
576
|
+
},
|
|
577
|
+
allowFunctionsInGlobals: true, // Required when globals contain functions
|
|
578
|
+
toolHandler: async (name, args) => {
|
|
579
|
+
/* ... */
|
|
580
|
+
},
|
|
581
|
+
});
|
|
582
|
+
|
|
583
|
+
const result = await enclave.run(`
|
|
584
|
+
const url = config.apiUrl;
|
|
585
|
+
const formatted = helpers.formatDate(new Date());
|
|
586
|
+
return { url, formatted };
|
|
587
|
+
`);
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
**Security Note**: Set `allowFunctionsInGlobals: true` only when you intentionally provide functions. Functions in globals can potentially leak host scope via closures.
|
|
591
|
+
|
|
592
|
+
## Execution Result
|
|
593
|
+
|
|
594
|
+
```typescript
|
|
595
|
+
interface ExecutionResult<T> {
|
|
596
|
+
success: boolean;
|
|
597
|
+
value?: T; // Result when success is true
|
|
598
|
+
error?: {
|
|
599
|
+
message: string;
|
|
600
|
+
name: string;
|
|
601
|
+
code?: string; // Error code (e.g., 'VALIDATION_ERROR', 'TIMEOUT')
|
|
602
|
+
stack?: string;
|
|
603
|
+
data?: Record<string, unknown>;
|
|
604
|
+
};
|
|
605
|
+
stats: {
|
|
606
|
+
duration: number; // Execution time in ms
|
|
607
|
+
toolCallCount: number; // Number of tool calls made
|
|
608
|
+
iterationCount: number; // Number of loop iterations
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
### Error Codes
|
|
614
|
+
|
|
615
|
+
| Code | Description |
|
|
616
|
+
| ------------------ | -------------------------------------- |
|
|
617
|
+
| `VALIDATION_ERROR` | AST validation failed (dangerous code) |
|
|
618
|
+
| `TIMEOUT` | Execution exceeded timeout |
|
|
619
|
+
| `MAX_TOOL_CALLS` | Exceeded maximum tool calls |
|
|
620
|
+
| `MAX_ITERATIONS` | Exceeded maximum loop iterations |
|
|
621
|
+
| `TOOL_ERROR` | Tool handler threw an error |
|
|
622
|
+
| `RUNTIME_ERROR` | General runtime error in script |
|
|
623
|
+
|
|
624
|
+
## Defense-in-Depth Architecture
|
|
625
|
+
|
|
626
|
+
```
|
|
627
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
628
|
+
│ User Code Input │
|
|
629
|
+
└─────────────────────────────────────────────────────────────┘
|
|
630
|
+
│
|
|
631
|
+
▼
|
|
632
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
633
|
+
│ Layer 0: Pre-Scanner (ast-guard) │
|
|
634
|
+
│ ├── Blocks ReDoS patterns │
|
|
635
|
+
│ ├── Blocks BiDi/Trojan source attacks │
|
|
636
|
+
│ ├── Input size limits │
|
|
637
|
+
│ └── Nesting depth limits │
|
|
638
|
+
└─────────────────────────────────────────────────────────────┘
|
|
639
|
+
│
|
|
640
|
+
▼
|
|
641
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
642
|
+
│ Layer 1: AST Validation (ast-guard) │
|
|
643
|
+
│ ├── NoEvalRule - Blocks eval(), Function() │
|
|
644
|
+
│ ├── NoGlobalAccessRule - Blocks dangerous globals │
|
|
645
|
+
│ ├── DisallowedIdentifierRule - Blocks reserved prefixes │
|
|
646
|
+
│ └── RequiredFunctionCallRule - Enforces callTool usage │
|
|
647
|
+
└─────────────────────────────────────────────────────────────┘
|
|
648
|
+
│
|
|
649
|
+
▼
|
|
650
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
651
|
+
│ Layer 2: Code Transformation │
|
|
652
|
+
│ ├── Wraps in async function __ag_main() │
|
|
653
|
+
│ ├── callTool → __safe_callTool (tracked) │
|
|
654
|
+
│ ├── Loops → __safe_for, __safe_forOf (guarded) │
|
|
655
|
+
│ └── String literals → extracted to sidecar (if enabled) │
|
|
656
|
+
└─────────────────────────────────────────────────────────────┘
|
|
657
|
+
│
|
|
658
|
+
▼
|
|
659
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
660
|
+
│ Layer 3: AI Scoring Gate │
|
|
661
|
+
│ ├── Semantic security analysis via AST features │
|
|
662
|
+
│ ├── Exfiltration pattern detection │
|
|
663
|
+
│ ├── Sensitive field access tracking │
|
|
664
|
+
│ └── Risk scoring (0-100) with thresholds │
|
|
665
|
+
└─────────────────────────────────────────────────────────────┘
|
|
666
|
+
│
|
|
667
|
+
▼
|
|
668
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
669
|
+
│ Layer 4: Runtime Sandbox │
|
|
670
|
+
│ ├── Standard: Node.js vm (prototype isolation) │
|
|
671
|
+
│ ├── Optional: Worker Pool (OS-level isolation) │
|
|
672
|
+
│ │ ├── Dual-layer: worker thread + VM context │
|
|
673
|
+
│ │ ├── Hard halt via worker.terminate() │
|
|
674
|
+
│ │ └── Per-worker memory limits │
|
|
675
|
+
│ ├── __safe_callTool - Enforces maxToolCalls │
|
|
676
|
+
│ ├── __safe_forOf - Enforces maxIterations │
|
|
677
|
+
│ └── Timeout enforcement │
|
|
678
|
+
└─────────────────────────────────────────────────────────────┘
|
|
679
|
+
│
|
|
680
|
+
▼
|
|
681
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
682
|
+
│ Layer 5: Output Sanitization │
|
|
683
|
+
│ ├── Removes stack traces │
|
|
684
|
+
│ ├── Sanitizes file paths │
|
|
685
|
+
│ └── Truncates oversized outputs │
|
|
686
|
+
└─────────────────────────────────────────────────────────────┘
|
|
687
|
+
│
|
|
688
|
+
▼
|
|
689
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
690
|
+
│ Safe Execution Result │
|
|
691
|
+
└─────────────────────────────────────────────────────────────┘
|
|
692
|
+
```
|
|
693
|
+
|
|
694
|
+
## API Reference
|
|
695
|
+
|
|
696
|
+
### Enclave Class
|
|
697
|
+
|
|
698
|
+
```typescript
|
|
699
|
+
class Enclave {
|
|
700
|
+
constructor(options?: CreateEnclaveOptions);
|
|
701
|
+
|
|
702
|
+
// Execute AgentScript code
|
|
703
|
+
run<T = unknown>(code: string): Promise<ExecutionResult<T>>;
|
|
704
|
+
|
|
705
|
+
// Clean up resources
|
|
706
|
+
dispose(): void;
|
|
707
|
+
}
|
|
708
|
+
```
|
|
709
|
+
|
|
710
|
+
### ToolHandler Type
|
|
711
|
+
|
|
712
|
+
```typescript
|
|
713
|
+
type ToolHandler = (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
|
|
714
|
+
```
|
|
715
|
+
|
|
716
|
+
## Testing
|
|
717
|
+
|
|
718
|
+
```bash
|
|
719
|
+
# Run tests
|
|
720
|
+
nx test enclave-vm
|
|
721
|
+
|
|
722
|
+
# Run tests with coverage
|
|
723
|
+
nx test enclave --coverage
|
|
724
|
+
```
|
|
725
|
+
|
|
726
|
+
## Related Packages
|
|
727
|
+
|
|
728
|
+
- [`ast-guard`](../ast-guard) - AST validation rules used by enclave
|
|
729
|
+
|
|
730
|
+
## License
|
|
731
|
+
|
|
732
|
+
Apache-2.0
|