@memberjunction/code-execution 2.108.0 → 2.110.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.
- package/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +14 -0
- package/README.md +100 -17
- package/SECURITY-MAINTENANCE.md +228 -0
- package/dist/CodeExecutionService.d.ts +46 -16
- package/dist/CodeExecutionService.d.ts.map +1 -1
- package/dist/CodeExecutionService.js +58 -203
- package/dist/CodeExecutionService.js.map +1 -1
- package/dist/WorkerPool.d.ts +79 -0
- package/dist/WorkerPool.d.ts.map +1 -0
- package/dist/WorkerPool.js +309 -0
- package/dist/WorkerPool.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/worker.d.ts +22 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +254 -0
- package/dist/worker.js.map +1 -0
- package/package.json +1 -1
- package/security-research.md +134 -4
- package/src/CodeExecutionService.ts +60 -214
- package/src/WorkerPool.ts +368 -0
- package/src/index.ts +1 -0
- package/src/worker.ts +298 -0
package/.turbo/turbo-build.log
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @memberjunction/code-execution
|
|
2
2
|
|
|
3
|
+
## 2.110.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- @memberjunction/core@2.110.0
|
|
8
|
+
- @memberjunction/global@2.110.0
|
|
9
|
+
|
|
10
|
+
## 2.109.0
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- @memberjunction/core@2.109.0
|
|
15
|
+
- @memberjunction/global@2.109.0
|
|
16
|
+
|
|
3
17
|
## 2.108.0
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -4,15 +4,21 @@ Sandboxed JavaScript code execution service for MemberJunction AI agents and wor
|
|
|
4
4
|
|
|
5
5
|
## Overview
|
|
6
6
|
|
|
7
|
-
This package provides secure, isolated execution of JavaScript code in a sandboxed environment using
|
|
7
|
+
This package provides secure, isolated execution of JavaScript code in a sandboxed environment using `isolated-vm` with worker process isolation. It's designed to enable AI agents to generate and run code for data analysis, transformations, and calculations without compromising system security or stability.
|
|
8
|
+
|
|
9
|
+
**⚠️ Security**: This package handles untrusted code execution. Please review [security-research.md](./security-research.md) for comprehensive security analysis, threat model, and implementation details.
|
|
8
10
|
|
|
9
11
|
## Features
|
|
10
12
|
|
|
11
|
-
- **
|
|
13
|
+
- **Multi-Layer Security**: 5 independent defense layers (process isolation, V8 isolates, module blocking, resource limits, library allowlist)
|
|
14
|
+
- **Fault Isolation**: Workers run in separate processes - crashes don't affect main application
|
|
15
|
+
- **Automatic Recovery**: Crashed workers automatically restart with circuit breaker protection
|
|
12
16
|
- **Timeout Protection**: Configurable execution timeouts (default: 30 seconds)
|
|
13
|
-
- **
|
|
17
|
+
- **Memory Limits**: Configurable per-execution memory limits (default: 128MB)
|
|
18
|
+
- **Safe Library Access**: Curated allowlist of npm packages with inline implementations
|
|
14
19
|
- **Console Logging**: Captures console output for debugging
|
|
15
20
|
- **Type Safety**: Full TypeScript support with comprehensive interfaces
|
|
21
|
+
- **Audit Trail**: Integrated with MemberJunction action logging
|
|
16
22
|
|
|
17
23
|
## Installation
|
|
18
24
|
|
|
@@ -27,8 +33,18 @@ npm install @memberjunction/code-execution
|
|
|
27
33
|
```typescript
|
|
28
34
|
import { CodeExecutionService } from '@memberjunction/code-execution';
|
|
29
35
|
|
|
30
|
-
|
|
36
|
+
// Create service with optional worker pool configuration
|
|
37
|
+
const service = new CodeExecutionService({
|
|
38
|
+
poolSize: 2, // Number of worker processes (default: 2)
|
|
39
|
+
maxQueueSize: 100, // Max queued requests (default: 100)
|
|
40
|
+
maxCrashesPerWorker: 3, // Crashes before marking unhealthy (default: 3)
|
|
41
|
+
crashTimeWindow: 60000 // Time window for crash counting (default: 60s)
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// Initialize the worker pool (can also be done automatically on first execute)
|
|
45
|
+
await service.initialize();
|
|
31
46
|
|
|
47
|
+
// Execute code
|
|
32
48
|
const result = await service.execute({
|
|
33
49
|
code: `
|
|
34
50
|
const sum = input.values.reduce((a, b) => a + b, 0);
|
|
@@ -36,7 +52,9 @@ const result = await service.execute({
|
|
|
36
52
|
output = { sum, average };
|
|
37
53
|
`,
|
|
38
54
|
language: 'javascript',
|
|
39
|
-
inputData: { values: [10, 20, 30, 40, 50] }
|
|
55
|
+
inputData: { values: [10, 20, 30, 40, 50] },
|
|
56
|
+
timeoutSeconds: 30, // Optional: execution timeout (default: 30)
|
|
57
|
+
memoryLimitMB: 128 // Optional: memory limit (default: 128)
|
|
40
58
|
});
|
|
41
59
|
|
|
42
60
|
if (result.success) {
|
|
@@ -44,7 +62,17 @@ if (result.success) {
|
|
|
44
62
|
console.log(result.logs); // Any console.log output from the code
|
|
45
63
|
} else {
|
|
46
64
|
console.error(result.error);
|
|
65
|
+
console.error(result.errorType); // 'TIMEOUT' | 'MEMORY_LIMIT' | 'SYNTAX_ERROR' | etc.
|
|
47
66
|
}
|
|
67
|
+
|
|
68
|
+
// Check worker pool health
|
|
69
|
+
const stats = service.getStats();
|
|
70
|
+
console.log('Active workers:', stats.activeWorkers);
|
|
71
|
+
console.log('Busy workers:', stats.busyWorkers);
|
|
72
|
+
console.log('Queue length:', stats.queueLength);
|
|
73
|
+
|
|
74
|
+
// Graceful shutdown (important for clean application exit)
|
|
75
|
+
await service.shutdown();
|
|
48
76
|
```
|
|
49
77
|
|
|
50
78
|
### With Actions (for AI Agents)
|
|
@@ -114,23 +142,35 @@ const result = await service.execute({
|
|
|
114
142
|
|
|
115
143
|
## Security Model
|
|
116
144
|
|
|
145
|
+
**For detailed security analysis, see [security-research.md](./security-research.md)**
|
|
146
|
+
|
|
147
|
+
This package uses a **defense-in-depth** approach with five independent security layers:
|
|
148
|
+
|
|
149
|
+
1. **Process Isolation** - Workers run in separate OS processes
|
|
150
|
+
2. **V8 Isolates** - Each execution runs in isolated V8 context (via `isolated-vm`)
|
|
151
|
+
3. **Module Blocking** - Dangerous Node.js modules are blocked
|
|
152
|
+
4. **Resource Limits** - Enforced timeout and memory limits
|
|
153
|
+
5. **Library Allowlist** - Only pre-vetted libraries available
|
|
154
|
+
|
|
117
155
|
### What Code CAN Do
|
|
118
156
|
|
|
119
157
|
- Access input data via `input` variable
|
|
120
158
|
- Set output data via `output` variable
|
|
121
159
|
- Use console methods (log, error, warn, info)
|
|
122
|
-
- Require allowed npm packages
|
|
160
|
+
- Require allowed npm packages (lodash, date-fns, uuid, validator)
|
|
123
161
|
- Perform calculations and data transformations
|
|
124
162
|
- Use safe built-in objects (JSON, Math, Date, Array, Object, String, Number, Boolean)
|
|
125
163
|
|
|
126
164
|
### What Code CANNOT Do
|
|
127
165
|
|
|
128
|
-
- Access filesystem (`fs`
|
|
129
|
-
- Make network requests (`http`, `https`, `net`, `axios`
|
|
130
|
-
- Spawn processes (`child_process`
|
|
166
|
+
- Access filesystem (`fs`, `path` modules blocked)
|
|
167
|
+
- Make network requests (`http`, `https`, `net`, `axios` modules blocked, `fetch()` API disabled)
|
|
168
|
+
- Spawn processes (`child_process`, `cluster` blocked)
|
|
169
|
+
- Access system information (`os`, `process` blocked)
|
|
131
170
|
- Access environment variables
|
|
132
|
-
- Use `eval()` or `Function` constructor
|
|
171
|
+
- Use `eval()` or `Function` constructor (for user code)
|
|
133
172
|
- Run indefinitely (timeout enforced)
|
|
173
|
+
- Exceed memory limits (128MB default)
|
|
134
174
|
|
|
135
175
|
## API Reference
|
|
136
176
|
|
|
@@ -289,19 +329,62 @@ const result = await service.execute({
|
|
|
289
329
|
|
|
290
330
|
## Best Practices
|
|
291
331
|
|
|
292
|
-
1. **
|
|
293
|
-
2. **
|
|
294
|
-
3. **
|
|
295
|
-
4. **
|
|
296
|
-
5. **
|
|
297
|
-
6. **
|
|
332
|
+
1. **Initialize Once**: Create one `CodeExecutionService` instance and reuse it (worker pool is shared)
|
|
333
|
+
2. **Shutdown Gracefully**: Call `service.shutdown()` during application shutdown to clean up workers
|
|
334
|
+
3. **Set Appropriate Timeouts**: Adjust `timeoutSeconds` based on expected workload
|
|
335
|
+
4. **Validate Input Data**: Ensure input data is in expected format before execution
|
|
336
|
+
5. **Handle Errors Gracefully**: Always check `result.success` before using `result.output`
|
|
337
|
+
6. **Monitor Pool Health**: Use `service.getStats()` to monitor worker health and queue depth
|
|
338
|
+
7. **Use Console Logging**: Add `console.log()` statements for debugging
|
|
339
|
+
8. **Leverage Libraries**: Use lodash, date-fns, etc. instead of reinventing the wheel
|
|
340
|
+
9. **Keep Code Focused**: Break complex logic into smaller execution chunks
|
|
341
|
+
10. **Review Security Docs**: Read [security-research.md](./security-research.md) for threat model and security considerations
|
|
342
|
+
|
|
343
|
+
## Architecture
|
|
344
|
+
|
|
345
|
+
### Worker Process Pool
|
|
346
|
+
|
|
347
|
+
The service maintains a pool of worker processes for fault isolation:
|
|
348
|
+
|
|
349
|
+
```
|
|
350
|
+
┌─────────────────────────────────────┐
|
|
351
|
+
│ Main Application Process │
|
|
352
|
+
│ │
|
|
353
|
+
│ ┌────────────────────────────┐ │
|
|
354
|
+
│ │ CodeExecutionService │ │
|
|
355
|
+
│ │ │ │
|
|
356
|
+
│ │ ┌──────────────────────┐ │ │
|
|
357
|
+
│ │ │ WorkerPool │ │ │
|
|
358
|
+
│ │ │ - Queue Requests │ │ │
|
|
359
|
+
│ │ │ - Monitor Health │ │ │
|
|
360
|
+
│ │ │ - Auto Restart │ │ │
|
|
361
|
+
│ │ └──────────────────────┘ │ │
|
|
362
|
+
│ └────────────────────────────┘ │
|
|
363
|
+
│ │ │ │
|
|
364
|
+
└──────────┼──────────┼───────────────┘
|
|
365
|
+
│ │ IPC (JSON)
|
|
366
|
+
┌──────▼───┐ ┌───▼──────┐
|
|
367
|
+
│ Worker 1 │ │ Worker 2 │ (Separate OS Processes)
|
|
368
|
+
│ │ │ │
|
|
369
|
+
│ isolated │ │ isolated │
|
|
370
|
+
│ -vm │ │ -vm │
|
|
371
|
+
│ │ │ │
|
|
372
|
+
└──────────┘ └──────────┘
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
### Benefits of Process Isolation
|
|
376
|
+
|
|
377
|
+
- **Fault Tolerance**: Worker crashes don't affect main app or other workers
|
|
378
|
+
- **Resource Isolation**: Per-process memory limits and cleanup
|
|
379
|
+
- **Automatic Recovery**: Crashed workers restart automatically
|
|
380
|
+
- **Circuit Breaker**: Too many crashes → worker disabled to prevent crash loops
|
|
298
381
|
|
|
299
382
|
## Limitations
|
|
300
383
|
|
|
301
384
|
- **Language Support**: Currently only JavaScript (Python may be added in future)
|
|
302
385
|
- **Async Code**: No support for `async/await` or Promises (synchronous code only)
|
|
303
|
-
- **Memory**: No hard memory limits enforced (relies on Node.js process limits)
|
|
304
386
|
- **Library Expansion**: New libraries require code changes (not configurable at runtime)
|
|
387
|
+
- **Throughput**: ~100-200 executions/sec per worker (horizontal scaling recommended for higher loads)
|
|
305
388
|
|
|
306
389
|
## Contributing
|
|
307
390
|
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# Security Maintenance Plan
|
|
2
|
+
|
|
3
|
+
This document outlines the security maintenance policies and procedures for the code execution package.
|
|
4
|
+
|
|
5
|
+
## Code Review Policy for Isolate Boundary
|
|
6
|
+
|
|
7
|
+
### What Requires Mandatory Review
|
|
8
|
+
|
|
9
|
+
Any changes to the following files **MUST** undergo security-focused code review:
|
|
10
|
+
|
|
11
|
+
1. **[worker.ts](./src/worker.ts)** - Handles the isolate boundary between host and sandbox
|
|
12
|
+
2. **[WorkerPool.ts](./src/WorkerPool.ts)** - Manages worker processes and IPC communication
|
|
13
|
+
3. **[libraries/index.ts](./src/libraries/index.ts)** - Defines allowed libraries and their implementations
|
|
14
|
+
|
|
15
|
+
### Review Checklist
|
|
16
|
+
|
|
17
|
+
When reviewing changes to isolate boundary code, verify:
|
|
18
|
+
|
|
19
|
+
- [ ] **No ivm.Reference leakage**: Ensure no `ivm.Reference` or `ivm.ExternalCopy` objects are exposed to untrusted code
|
|
20
|
+
- [ ] **Only primitives via IPC**: Verify only JSON-serializable data crosses process boundaries
|
|
21
|
+
- [ ] **No cachedData from untrusted sources**: Confirm no V8 `cachedData` from user input (CVE-2022-39266)
|
|
22
|
+
- [ ] **Module blocking intact**: Verify dangerous modules remain in blocked list
|
|
23
|
+
- [ ] **Library allowlist enforced**: Confirm only approved libraries can be loaded
|
|
24
|
+
- [ ] **Resource limits enforced**: Check timeout and memory limits are properly set
|
|
25
|
+
- [ ] **Error handling**: Ensure errors don't leak sensitive information
|
|
26
|
+
|
|
27
|
+
### Security Review Process
|
|
28
|
+
|
|
29
|
+
1. **Self-Review**: Developer completes checklist above
|
|
30
|
+
2. **Peer Review**: Another developer reviews with security focus
|
|
31
|
+
3. **Testing**: Add test cases for new security-sensitive paths
|
|
32
|
+
4. **Documentation**: Update security docs if threat model changes
|
|
33
|
+
|
|
34
|
+
## Known Vulnerabilities and Mitigations
|
|
35
|
+
|
|
36
|
+
### CVE-2022-39266 (isolated-vm cachedData)
|
|
37
|
+
|
|
38
|
+
**Vulnerability**: Accepting untrusted V8 `cachedData` can lead to sandbox escape
|
|
39
|
+
|
|
40
|
+
**Mitigation**:
|
|
41
|
+
- Never pass `cachedData` parameter to `isolate.compileScript()`
|
|
42
|
+
- Only compile from source code strings
|
|
43
|
+
- Documented in [worker.ts:190](./src/worker.ts#L190)
|
|
44
|
+
|
|
45
|
+
**Status**: ✅ Protected (no cachedData usage in codebase)
|
|
46
|
+
|
|
47
|
+
### Future CVE Monitoring
|
|
48
|
+
|
|
49
|
+
Monitor these resources for new vulnerabilities:
|
|
50
|
+
|
|
51
|
+
- `isolated-vm` GitHub issues: https://github.com/laverdet/isolated-vm/issues
|
|
52
|
+
- `isolated-vm` security advisories: https://github.com/laverdet/isolated-vm/security/advisories
|
|
53
|
+
- Node.js security releases: https://nodejs.org/en/security/
|
|
54
|
+
- V8 security updates: https://chromium.googlesource.com/v8/v8/+/refs/heads/main/docs/security.md
|
|
55
|
+
|
|
56
|
+
## Dependency Maintenance Plan
|
|
57
|
+
|
|
58
|
+
### Current Status (as of 2025-10-20)
|
|
59
|
+
|
|
60
|
+
**Primary Dependency**: `isolated-vm@5.0.1`
|
|
61
|
+
- **Status**: Maintenance mode (mature, stable)
|
|
62
|
+
- **Security**: No known CVEs when used correctly
|
|
63
|
+
- **Support**: Active community, responsive maintainer
|
|
64
|
+
- **Recommendation**: Safe for production use
|
|
65
|
+
|
|
66
|
+
### Annual Review Schedule
|
|
67
|
+
|
|
68
|
+
**When**: Every January (or immediately upon security advisory)
|
|
69
|
+
|
|
70
|
+
**Review Tasks**:
|
|
71
|
+
|
|
72
|
+
1. **Check isolated-vm status**
|
|
73
|
+
- Review GitHub activity and issue tracker
|
|
74
|
+
- Check for security advisories
|
|
75
|
+
- Verify Node.js/V8 compatibility with latest versions
|
|
76
|
+
- Assess community health and maintainer responsiveness
|
|
77
|
+
|
|
78
|
+
2. **Evaluate alternatives**
|
|
79
|
+
- **Deno**: Check maturity of Deno as Node.js module
|
|
80
|
+
- **WASM-based solutions**: Evaluate QuickJS-wasm or similar
|
|
81
|
+
- **Container solutions**: Review lightweight container options
|
|
82
|
+
- **New sandboxes**: Survey any new sandboxing technologies
|
|
83
|
+
|
|
84
|
+
3. **Decision tree**:
|
|
85
|
+
```
|
|
86
|
+
Is isolated-vm maintained? ──Yes→ Continue using
|
|
87
|
+
│
|
|
88
|
+
No
|
|
89
|
+
│
|
|
90
|
+
Is Deno mature enough? ──Yes→ Plan migration to Deno
|
|
91
|
+
│
|
|
92
|
+
No
|
|
93
|
+
│
|
|
94
|
+
Fork isolated-vm? ──Yes→ Fork and maintain internally
|
|
95
|
+
│
|
|
96
|
+
No
|
|
97
|
+
│
|
|
98
|
+
Migrate to containers → Plan containerized solution
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
4. **Document findings**
|
|
102
|
+
- Update this file with review date and findings
|
|
103
|
+
- Update security-research.md if threat model changes
|
|
104
|
+
- Create migration plan if needed
|
|
105
|
+
|
|
106
|
+
### Emergency Response Plan
|
|
107
|
+
|
|
108
|
+
If a critical vulnerability is discovered in `isolated-vm`:
|
|
109
|
+
|
|
110
|
+
1. **Immediate Actions** (Day 1)
|
|
111
|
+
- Assess severity and exploitability
|
|
112
|
+
- Check if MJ's usage is affected
|
|
113
|
+
- Deploy temporary workaround if possible (e.g., disable code execution feature)
|
|
114
|
+
|
|
115
|
+
2. **Short-term Response** (Week 1)
|
|
116
|
+
- Apply patches if available
|
|
117
|
+
- If no patch: evaluate fork vs. alternative solutions
|
|
118
|
+
- Communicate with users about status
|
|
119
|
+
|
|
120
|
+
3. **Long-term Solution** (Month 1)
|
|
121
|
+
- Implement permanent fix (patch, fork, or migration)
|
|
122
|
+
- Add regression tests for the vulnerability
|
|
123
|
+
- Update security documentation
|
|
124
|
+
|
|
125
|
+
### Contingency Options
|
|
126
|
+
|
|
127
|
+
If `isolated-vm` becomes unmaintained or insecure:
|
|
128
|
+
|
|
129
|
+
1. **Option A: Fork and Maintain**
|
|
130
|
+
- **Pros**: Full control, minimal code changes
|
|
131
|
+
- **Cons**: Requires C++ expertise for V8 integration
|
|
132
|
+
- **Timeline**: 2-4 weeks for initial fork setup
|
|
133
|
+
|
|
134
|
+
2. **Option B: Migrate to Deno**
|
|
135
|
+
- **Pros**: Active development, secure by default
|
|
136
|
+
- **Cons**: Separate process overhead, different API
|
|
137
|
+
- **Timeline**: 4-6 weeks for migration
|
|
138
|
+
|
|
139
|
+
3. **Option C: Container-based Isolation**
|
|
140
|
+
- **Pros**: Maximum isolation, mature tooling
|
|
141
|
+
- **Cons**: High overhead, complex deployment
|
|
142
|
+
- **Timeline**: 6-8 weeks for implementation
|
|
143
|
+
|
|
144
|
+
## Security Testing
|
|
145
|
+
|
|
146
|
+
### Recommended Test Cases
|
|
147
|
+
|
|
148
|
+
Add tests for these scenarios:
|
|
149
|
+
|
|
150
|
+
1. **Sandbox Escape Attempts**
|
|
151
|
+
- Try to access `ivm` objects via prototype pollution
|
|
152
|
+
- Attempt to use `Function` constructor
|
|
153
|
+
- Try to access Node.js globals
|
|
154
|
+
|
|
155
|
+
2. **Resource Exhaustion**
|
|
156
|
+
- Infinite loops (should timeout)
|
|
157
|
+
- Memory exhaustion (should hit limit)
|
|
158
|
+
- Recursive explosions (stack overflow)
|
|
159
|
+
|
|
160
|
+
3. **Module Access**
|
|
161
|
+
- Try to require blocked modules
|
|
162
|
+
- Try to require non-existent modules
|
|
163
|
+
- Verify allowed modules work correctly
|
|
164
|
+
|
|
165
|
+
4. **Process Isolation**
|
|
166
|
+
- Simulate worker crashes
|
|
167
|
+
- Verify main process continues
|
|
168
|
+
- Verify other workers continue
|
|
169
|
+
- Confirm automatic restart
|
|
170
|
+
|
|
171
|
+
5. **Error Handling**
|
|
172
|
+
- Verify error messages don't leak internals
|
|
173
|
+
- Confirm proper error classification
|
|
174
|
+
- Test all error types
|
|
175
|
+
|
|
176
|
+
### Penetration Testing
|
|
177
|
+
|
|
178
|
+
Consider annual penetration testing focused on:
|
|
179
|
+
- Sandbox escape attempts
|
|
180
|
+
- Resource exhaustion attacks
|
|
181
|
+
- Process isolation bypass
|
|
182
|
+
- Supply chain attacks (library tampering)
|
|
183
|
+
|
|
184
|
+
## Incident Response
|
|
185
|
+
|
|
186
|
+
If a security issue is discovered:
|
|
187
|
+
|
|
188
|
+
1. **Contain**: Disable affected functionality if severity is high
|
|
189
|
+
2. **Assess**: Determine scope and impact
|
|
190
|
+
3. **Fix**: Develop and test patch
|
|
191
|
+
4. **Deploy**: Roll out fix with priority
|
|
192
|
+
5. **Disclose**: Notify users of issue and resolution
|
|
193
|
+
6. **Learn**: Update policies and tests based on learnings
|
|
194
|
+
|
|
195
|
+
## Contact
|
|
196
|
+
|
|
197
|
+
For security concerns, contact:
|
|
198
|
+
- MemberJunction security team: [security contact info]
|
|
199
|
+
- `isolated-vm` maintainer: https://github.com/laverdet/isolated-vm/security
|
|
200
|
+
|
|
201
|
+
## Review History
|
|
202
|
+
|
|
203
|
+
| Date | Reviewer | Findings | Actions Taken |
|
|
204
|
+
|------|----------|----------|---------------|
|
|
205
|
+
| 2025-10-20 | Initial | Initial security hardening | Implemented process isolation, code review policy, CVE documentation |
|
|
206
|
+
| 2025-10-20 | Colleague | Missing fetch() API blocking | Added explicit fetch() disabling in worker.ts - blocks Node.js 18+ global fetch() |
|
|
207
|
+
|
|
208
|
+
## Lessons Learned
|
|
209
|
+
|
|
210
|
+
### fetch() API Security Hole (2025-10-20)
|
|
211
|
+
|
|
212
|
+
**Issue**: Node.js 18+ includes a global `fetch()` API that was not blocked in initial implementation. This would allow network access despite module blocking.
|
|
213
|
+
|
|
214
|
+
**Root Cause**: Focus on `require()` module blocking missed newer global APIs added to Node.js runtime.
|
|
215
|
+
|
|
216
|
+
**Fix**: Explicitly override `globalThis.fetch` with error-throwing function in worker.ts
|
|
217
|
+
|
|
218
|
+
**Prevention**:
|
|
219
|
+
- Document all Node.js global APIs that need blocking (fetch, WebSocket, etc.)
|
|
220
|
+
- Review Node.js release notes for new globals during version upgrades
|
|
221
|
+
- Add test case for attempting network access via fetch()
|
|
222
|
+
|
|
223
|
+
**Action Items**:
|
|
224
|
+
- [ ] Add test case: `fetch('https://example.com')` should throw security error
|
|
225
|
+
- [ ] Review Node.js 18+ globals: WebSocket, structuredClone, BroadcastChannel, etc.
|
|
226
|
+
- [ ] Document "Blocked Globals" section in security-research.md
|
|
227
|
+
|
|
228
|
+
## Next Review Due: January 2026
|
|
@@ -1,44 +1,74 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Code Execution Service
|
|
3
3
|
*
|
|
4
|
-
* Provides secure, sandboxed execution of JavaScript code using isolated-vm
|
|
4
|
+
* Provides secure, sandboxed execution of JavaScript code using isolated-vm
|
|
5
|
+
* running in separate worker processes for fault isolation.
|
|
6
|
+
*
|
|
5
7
|
* This service enables AI agents and workflows to generate and run code safely
|
|
6
|
-
* without compromising system security.
|
|
8
|
+
* without compromising system security or stability.
|
|
7
9
|
*
|
|
8
|
-
* Security Model:
|
|
9
|
-
*
|
|
10
|
-
* -
|
|
11
|
-
* -
|
|
12
|
-
* -
|
|
13
|
-
* -
|
|
10
|
+
* Security Model (Multi-Layer Defense):
|
|
11
|
+
* 1. Process Isolation - Workers run in separate processes (protects against V8 crashes)
|
|
12
|
+
* 2. V8 Isolates - Code runs in isolated V8 contexts (protects against sandbox escapes)
|
|
13
|
+
* 3. Module Blocking - Dangerous Node.js modules are blocked (fs, http, child_process, etc.)
|
|
14
|
+
* 4. Resource Limits - Enforced timeout and memory limits (prevents DoS)
|
|
15
|
+
* 5. Library Allowlist - Only pre-vetted libraries available (prevents supply chain attacks)
|
|
14
16
|
*
|
|
15
17
|
* @module @memberjunction/code-execution
|
|
16
18
|
*/
|
|
17
19
|
import { CodeExecutionParams, CodeExecutionResult } from './types';
|
|
20
|
+
import { WorkerPoolOptions } from './WorkerPool';
|
|
18
21
|
/**
|
|
19
22
|
* Service for executing JavaScript code in a secure sandbox
|
|
23
|
+
*
|
|
24
|
+
* This service manages a pool of worker processes that execute code with full isolation.
|
|
25
|
+
* If a worker crashes due to catastrophic errors, it's automatically restarted without
|
|
26
|
+
* affecting the main application or other workers.
|
|
20
27
|
*/
|
|
21
28
|
export declare class CodeExecutionService {
|
|
29
|
+
private workerPool;
|
|
30
|
+
private initialized;
|
|
22
31
|
/**
|
|
23
|
-
*
|
|
32
|
+
* Create a new CodeExecutionService
|
|
33
|
+
*
|
|
34
|
+
* @param options - Worker pool configuration options
|
|
24
35
|
*/
|
|
25
|
-
|
|
36
|
+
constructor(options?: WorkerPoolOptions);
|
|
37
|
+
/**
|
|
38
|
+
* Initialize the service and worker pool
|
|
39
|
+
*
|
|
40
|
+
* This must be called before executing any code. It starts the worker processes
|
|
41
|
+
* and waits for them to be ready.
|
|
42
|
+
*/
|
|
43
|
+
initialize(): Promise<void>;
|
|
26
44
|
/**
|
|
27
45
|
* Execute JavaScript code in a sandboxed environment
|
|
28
46
|
*
|
|
47
|
+
* The code runs in a worker process with full isolation. If the worker crashes
|
|
48
|
+
* due to catastrophic errors, it will be automatically restarted without affecting
|
|
49
|
+
* this call or the main application.
|
|
50
|
+
*
|
|
29
51
|
* @param params - Execution parameters (code, language, input data, limits)
|
|
30
52
|
* @returns Execution result with output, logs, or error
|
|
31
53
|
*/
|
|
32
54
|
execute(params: CodeExecutionParams): Promise<CodeExecutionResult>;
|
|
33
55
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
56
|
+
* Get worker pool statistics
|
|
57
|
+
*
|
|
58
|
+
* @returns Pool statistics including worker count and queue length
|
|
36
59
|
*/
|
|
37
|
-
|
|
60
|
+
getStats(): {
|
|
61
|
+
totalWorkers: number;
|
|
62
|
+
activeWorkers: number;
|
|
63
|
+
busyWorkers: number;
|
|
64
|
+
queueLength: number;
|
|
65
|
+
};
|
|
38
66
|
/**
|
|
39
|
-
*
|
|
40
|
-
*
|
|
67
|
+
* Shutdown the service and all worker processes
|
|
68
|
+
*
|
|
69
|
+
* This should be called during application shutdown to gracefully terminate
|
|
70
|
+
* all workers and reject any pending requests.
|
|
41
71
|
*/
|
|
42
|
-
|
|
72
|
+
shutdown(): Promise<void>;
|
|
43
73
|
}
|
|
44
74
|
//# sourceMappingURL=CodeExecutionService.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeExecutionService.d.ts","sourceRoot":"","sources":["../src/CodeExecutionService.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"CodeExecutionService.d.ts","sourceRoot":"","sources":["../src/CodeExecutionService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AACnE,OAAO,EAAc,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAE7D;;;;;;GAMG;AACH,qBAAa,oBAAoB;IAC7B,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,WAAW,CAAkB;IACrC;;;;OAIG;gBACS,OAAO,GAAE,iBAAsB;IAI3C;;;;;OAKG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAOjC;;;;;;;;;OASG;IACG,OAAO,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IA2BxE;;;;OAIG;IACH,QAAQ;;;;;;IAIR;;;;;OAKG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAMlC"}
|