@memberjunction/code-execution 2.108.0 → 2.109.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.
@@ -1,6 +1,77 @@
1
- # Analysis of our approach from Claude Code (Sonnet 4.5) on 19 Oct 2025
2
1
  # Code Execution Security Model
3
2
 
3
+ ## Executive Summary
4
+
5
+ **Status**: Production-ready, multi-layered defense architecture
6
+ **Last Updated**: 2025-10-20
7
+ **Security Confidence**: High for multi-tenant production environments
8
+
9
+ ### Implementation Overview
10
+
11
+ MemberJunction's code execution system uses a **defense-in-depth** approach with five independent security layers:
12
+
13
+ 1. **Process Isolation** - Workers run in separate OS processes, protecting against V8 catastrophic failures
14
+ 2. **V8 Isolates** - Each execution runs in completely isolated V8 context (via `isolated-vm`)
15
+ 3. **Module Blocking** - Dangerous Node.js modules (fs, http, child_process) are blocked
16
+ 4. **Resource Limits** - Enforced timeout (30s) and memory limits (128MB) prevent DoS
17
+ 5. **Library Allowlist** - Only 4 pre-vetted libraries with inline implementations
18
+
19
+ ### Key Security Features
20
+
21
+ - ✅ **True fault isolation** - Worker process crashes don't affect main application
22
+ - ✅ **Automatic recovery** - Crashed workers restart automatically with circuit breaker
23
+ - ✅ **No known sandbox escapes** - Uses `isolated-vm` (no CVEs when used correctly)
24
+ - ✅ **Supply chain protection** - Libraries provided as inline source code
25
+ - ✅ **Complete audit trail** - Integrated with MemberJunction action logging
26
+
27
+ ### Hardening Measures Implemented
28
+
29
+ Based on external security review by Gemini 2.5 Pro (see below), we implemented:
30
+
31
+ 1. **Worker Process Pool** - Separate processes with health monitoring and auto-restart
32
+ 2. **Code Review Policy** - Mandatory review for isolate boundary changes (documented in code)
33
+ 3. **CVE Documentation** - Explicit protection against CVE-2022-39266 (documented in code)
34
+ 4. **Maintenance Plan** - Annual review of alternatives and contingency documentation
35
+
36
+ ### Appropriate Use Cases
37
+
38
+ **Recommended For**:
39
+ - AI-generated code execution
40
+ - User-supplied data transformation scripts
41
+ - Multi-tenant analytics platforms
42
+ - Workflow automation systems
43
+
44
+ **Not Recommended For**:
45
+ - Executing code from completely untrusted/malicious sources without review
46
+ - High-volume (>1000 req/sec) without horizontal scaling
47
+ - Long-running computations (>30 seconds)
48
+
49
+ ### Performance Characteristics
50
+
51
+ - **Cold start**: ~50ms (worker process spawn + isolate creation)
52
+ - **Warm execution**: ~5-10ms (isolate creation only)
53
+ - **Memory per worker**: ~50-100MB baseline + 128MB per isolate
54
+ - **Throughput**: ~100-200 executions/sec per worker (depends on code complexity)
55
+
56
+ ### Comparison to Alternatives
57
+
58
+ | Solution | Security | Complexity | Performance | Verdict |
59
+ |----------|----------|------------|-------------|---------|
60
+ | **isolated-vm (our choice)** | High | Medium | High | ✅ Best balance |
61
+ | Node.js `vm` module | None | Low | High | ❌ Not secure |
62
+ | vm2 (deprecated) | Low | Low | Medium | ❌ Multiple CVEs |
63
+ | Deno | High | High | Medium | ✅ Good alternative |
64
+ | Docker/containers | Highest | Very High | Low | ⚠️ Overkill for most cases |
65
+
66
+ ---
67
+
68
+ ## Original Security Research
69
+
70
+ The sections below contain our original security analysis and external review findings.
71
+
72
+ # Analysis from Claude Code (Sonnet 4.5) on 19 Oct 2025
73
+ # Initial Security Model Overview
74
+
4
75
  ## Overview
5
76
  Production-grade sandboxed JavaScript execution using **isolated-vm** for AI agents to safely generate and run code for data analysis and transformations.
6
77
 
@@ -22,7 +93,7 @@ Production-grade sandboxed JavaScript execution using **isolated-vm** for AI age
22
93
  #### 2. Module Blocking
23
94
  Dangerous modules throw security errors:
24
95
  - **Filesystem**: `fs`, `path` (blocked)
25
- - **Network**: `http`, `https`, `net`, `axios` (blocked)
96
+ - **Network**: `http`, `https`, `net`, `axios` (modules blocked), `fetch()` (API disabled)
26
97
  - **Process**: `child_process`, `cluster`, `os`, `process` (blocked)
27
98
 
28
99
  #### 3. Library Allowlist
@@ -70,7 +141,7 @@ Libraries are provided as inline JavaScript implementations:
70
141
 
71
142
  ## What Code CANNOT Do
72
143
  - Access filesystem (fs blocked)
73
- - Make network requests (http/https/net blocked)
144
+ - Make network requests (http/https/net modules blocked, fetch() API disabled)
74
145
  - Spawn processes (child_process blocked)
75
146
  - Use eval() or Function constructor
76
147
  - Run beyond timeout limit
@@ -223,4 +294,63 @@ https://backstage.io/blog/2023/06/21/switching-out-sandbox/
223
294
  https://github.com/patriksimek/vm2/issues/533
224
295
  https://docs.deno.com/runtime/fundamentals/security/
225
296
  https://healeycodes.com/sandboxing-javascript-code
226
- https://nvd.nist.gov/vuln/detail/CVE-2022-39266
297
+ https://nvd.nist.gov/vuln/detail/CVE-2022-39266
298
+
299
+
300
+
301
+ # Gemini Feedback with ideas for improvement
302
+ Based on the provided security research document, here is a detailed evaluation of the MemberJunction code execution approach.
303
+
304
+ ### **Overall Verdict: Largely Valid and Safe, with Areas for Hardening**
305
+
306
+ The described approach is **strong, well-researched, and fundamentally sound**. It demonstrates a mature understanding of the challenges associated with running untrusted code in a Node.js environment. The decision to use `isolated-vm` and the implementation of a multi-layered defense strategy align with current industry best practices for JavaScript sandboxing.
307
+
308
+ However, while the architecture is robust, there are potential holes and implicit risks that depend on meticulous implementation and could be further hardened.
309
+
310
+ ---
311
+
312
+ ### Strengths of the Approach
313
+
314
+ The security model outlined has several significant strengths:
315
+
316
+ 1. **Excellent Choice of Core Technology:** The migration from the deprecated and vulnerable `vm2` to `isolated-vm` is the single most important and correct decision. The document correctly identifies that `isolated-vm`'s use of true V8 Isolates provides engine-level separation, which is inherently far more secure than the context-based proxy approach of `vm2`.
317
+
318
+ 2. **Defense-in-Depth Strategy:** The model doesn't rely solely on `isolated-vm`. The multi-layer defense is comprehensive and addresses a wide range of attack vectors:
319
+ * **Module Blocking:** Proactively blocking access to `fs`, `http`, `child_process`, and other dangerous Node.js modules is critical and correctly implemented.
320
+ * **Library Allowlisting:** Limiting the available libraries to a small, pre-vetted set (`lodash`, `date-fns`, etc.) minimizes the potential attack surface that could be introduced by third-party code.
321
+ * **Resource Limiting:** Enforcing strict timeout and memory limits is an essential defense against Denial of Service (DoS) attacks from infinite loops or memory exhaustion.
322
+ * **Execution Control:** Explicitly blocking `eval()` and the `Function()` constructor within the sandboxed code prevents common code injection and obfuscation techniques.
323
+
324
+ 3. **Secure Library Loading Mechanism:** The method of providing libraries as inline source code strings is a clever and secure pattern. It ensures that the library code itself is executed within the sandbox and is subject to the exact same restrictions (memory, timeout, module access) as the user's code. This prevents any possibility of the library code acting as a privileged bridge to the host environment.
325
+
326
+ 4. **Clear Threat Modeling and Auditing:** The document shows a clear understanding of potential threats (Sandbox Escape, Resource Exhaustion, etc.) and maps them directly to specific mitigations. Furthermore, the integration with MemberJunction's existing action logging provides a crucial audit trail for forensics and performance monitoring.
327
+
328
+ ### Potential Holes and Areas for Improvement
329
+
330
+ Despite the strong foundation, the provided research itself highlights several risks that are not explicitly addressed in the final security architecture summary. These represent potential holes or areas that require further hardening.
331
+
332
+ 1. **Lack of Process-Level Isolation (Single Point of Failure):**
333
+ * **The Hole:** The research correctly states that `isolated-vm` operates **in-process**. A catastrophic failure within a V8 isolate, particularly a severe out-of-memory (OOM) error, can crash the *entire* parent Node.js process. The document mentions V8 is "not resilient to out-of-memory conditions" and the `onCatastrophicError` hook is a "band-aid."
334
+ * **The Risk:** A single piece of malicious or simply poorly written code from one user could trigger this condition, causing a Denial of Service that affects all users by crashing the main application.
335
+ * **Recommendation:** For a truly production-ready, multi-tenant system, the isolates themselves should be run in a separate worker process or a pool of worker processes. This contains any catastrophic failure to the worker, which can be restarted without affecting the main application server.
336
+
337
+ 2. **Risk of Misconfiguration and Leaked Host Objects:**
338
+ * **The Hole:** The research warns that `isolated-vm` is only as safe as its implementation. A developer accidentally exposing an `ivm.Reference` or `ivm.ExternalCopy` object to the untrusted script could create a bridge back to the host, leading to a full sandbox escape.
339
+ * **The Risk:** While the current architecture seems to avoid this by only passing in string-based code and input data, any future feature development that requires more complex data or function bridging could introduce this vulnerability if not handled with extreme care. The summary does not mention what safeguards or code review processes are in place to prevent such a leak.
340
+ * **Recommendation:** The security policy should include strict guidelines and a mandatory code review process for any code that handles the boundary between the host and the `isolated-vm` context.
341
+
342
+ 3. **Handling of V8 `cachedData` Vulnerability (CVE-2022-39266):**
343
+ * **The Hole:** The research document explicitly calls out CVE-2022-39266, where feeding untrusted V8 cached bytecode into `isolated-vm` could lead to a sandbox escape. The summary of the security architecture does not mention this specific vector or its mitigation.
344
+ * **The Risk:** If any part of the system accepts or uses V8 `cachedData` from an untrusted source, it could be vulnerable to this known critical issue.
345
+ * **Recommendation:** The security model should explicitly state that accepting or using `cachedData` from any user-provided or AI-generated source is forbidden.
346
+
347
+ 4. **Reliance on a Library in "Maintenance Mode":**
348
+ * **The Hole:** The research notes that `isolated-vm` is in maintenance mode, with the author having identified potential architectural improvements that are not yet implemented.
349
+ * **The Risk:** While the library is currently stable and secure, its maintenance status poses a long-term strategic risk. If a new, complex vulnerability is discovered in V8 that requires significant changes to `isolated-vm`, the response time for a patch might be slow.
350
+ * **Recommendation:** The team should have a contingency plan. This could involve actively monitoring the `isolated-vm` project, being prepared to fork and patch it themselves, or periodically re-evaluating newer sandboxing alternatives (like Deno or WASM-based runtimes) as they mature.
351
+
352
+ ### Conclusion
353
+
354
+ The MemberJunction team has conducted thorough research and designed a security architecture for code execution that is **valid and safe for its intended purpose**. The choice of `isolated-vm` combined with a multi-layered defense strategy effectively mitigates the most common and severe risks associated with running untrusted JavaScript.
355
+
356
+ To elevate the model from "strong" to "fully hardened," the team should focus on implementing **process-level isolation** using a worker pool to eliminate the risk of a single point of failure. Additionally, formalizing policies around bridge code review, the handling of `cachedData`, and long-term library maintenance will close the remaining potential gaps and ensure the platform's security and stability over time.
@@ -1,40 +1,72 @@
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
- * - Uses isolated-vm for true V8 isolate separation
10
- * - No filesystem access (fs module blocked)
11
- * - No network access (http/https/net modules blocked)
12
- * - Configurable timeout and memory limits
13
- * - Curated allowlist of safe npm packages
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
 
18
- import ivm from 'isolated-vm';
19
20
  import { CodeExecutionParams, CodeExecutionResult } from './types';
20
- import { getLibrarySource, isModuleAllowed, getAllowedModuleNames } from './libraries';
21
+ import { WorkerPool, WorkerPoolOptions } from './WorkerPool';
21
22
 
22
23
  /**
23
24
  * Service for executing JavaScript code in a secure sandbox
25
+ *
26
+ * This service manages a pool of worker processes that execute code with full isolation.
27
+ * If a worker crashes due to catastrophic errors, it's automatically restarted without
28
+ * affecting the main application or other workers.
24
29
  */
25
30
  export class CodeExecutionService {
31
+ private workerPool: WorkerPool;
32
+ private initialized: boolean = false;
26
33
  /**
27
- * Cache of loaded modules per isolate
34
+ * Create a new CodeExecutionService
35
+ *
36
+ * @param options - Worker pool configuration options
28
37
  */
29
- private moduleCache: Map<string, any> = new Map();
38
+ constructor(options: WorkerPoolOptions = {}) {
39
+ this.workerPool = new WorkerPool(options);
40
+ }
41
+
42
+ /**
43
+ * Initialize the service and worker pool
44
+ *
45
+ * This must be called before executing any code. It starts the worker processes
46
+ * and waits for them to be ready.
47
+ */
48
+ async initialize(): Promise<void> {
49
+ if (!this.initialized) {
50
+ await this.workerPool.initialize();
51
+ this.initialized = true;
52
+ }
53
+ }
54
+
30
55
  /**
31
56
  * Execute JavaScript code in a sandboxed environment
32
57
  *
58
+ * The code runs in a worker process with full isolation. If the worker crashes
59
+ * due to catastrophic errors, it will be automatically restarted without affecting
60
+ * this call or the main application.
61
+ *
33
62
  * @param params - Execution parameters (code, language, input data, limits)
34
63
  * @returns Execution result with output, logs, or error
35
64
  */
36
65
  async execute(params: CodeExecutionParams): Promise<CodeExecutionResult> {
37
- const startTime = Date.now();
66
+ // Auto-initialize if not already done
67
+ if (!this.initialized) {
68
+ await this.initialize();
69
+ }
38
70
 
39
71
  // Validate parameters
40
72
  if (!params.code || typeof params.code !== 'string') {
@@ -53,215 +85,29 @@ export class CodeExecutionService {
53
85
  };
54
86
  }
55
87
 
56
- try {
57
- return await this.executeJavaScript(params, startTime);
58
- } catch (error) {
59
- return {
60
- success: false,
61
- error: error instanceof Error ? error.message : String(error),
62
- errorType: 'RUNTIME_ERROR',
63
- executionTimeMs: Date.now() - startTime
64
- };
65
- }
88
+ // Execute in worker pool
89
+ return this.workerPool.execute(params);
66
90
  }
67
91
 
68
92
  /**
69
- * Execute JavaScript code using isolated-vm
70
- * @private
93
+ * Get worker pool statistics
94
+ *
95
+ * @returns Pool statistics including worker count and queue length
71
96
  */
72
- private async executeJavaScript(params: CodeExecutionParams, startTime: number): Promise<CodeExecutionResult> {
73
- const timeoutMs = (params.timeoutSeconds || 30) * 1000;
74
- const memoryLimitMB = params.memoryLimitMB || 128;
75
-
76
- let isolate: ivm.Isolate | null = null;
77
- let context: ivm.Context | null = null;
78
-
79
- try {
80
- // Create isolated VM with memory limit
81
- isolate = new ivm.Isolate({ memoryLimit: memoryLimitMB });
82
- context = await isolate.createContext();
83
-
84
- // Capture console logs
85
- const logs: string[] = [];
86
-
87
- // Set up console object
88
- const jail = context.global;
89
- await jail.set('global', jail.derefInto());
90
-
91
- // Create console methods that capture output
92
- const consoleLog = new ivm.Reference((level: string, ...args: any[]) => {
93
- const formattedArgs = args.map(arg => this.formatConsoleArg(arg)).join(' ');
94
- logs.push(`[${level}] ${formattedArgs}`);
95
- });
96
-
97
- await jail.set('_consoleLog', consoleLog);
98
-
99
- // Set up console in the isolate
100
- await context.eval(`
101
- globalThis.console = {
102
- log: (...args) => _consoleLog.applySync(undefined, ['LOG', ...args]),
103
- error: (...args) => _consoleLog.applySync(undefined, ['ERROR', ...args]),
104
- warn: (...args) => _consoleLog.applySync(undefined, ['WARN', ...args]),
105
- info: (...args) => _consoleLog.applySync(undefined, ['INFO', ...args])
106
- };
107
- `);
108
-
109
- // Set up input data if provided
110
- if (params.inputData !== undefined) {
111
- const inputDataStr = JSON.stringify(params.inputData);
112
- await jail.set('_inputData', inputDataStr);
113
- await context.eval('globalThis.input = JSON.parse(_inputData);');
114
- }
115
-
116
- // Set up safe built-in objects
117
- await context.eval(`
118
- globalThis.JSON = JSON;
119
- globalThis.Math = Math;
120
- globalThis.Date = Date;
121
- globalThis.Array = Array;
122
- globalThis.Object = Object;
123
- globalThis.String = String;
124
- globalThis.Number = Number;
125
- globalThis.Boolean = Boolean;
126
- globalThis.RegExp = RegExp;
127
- globalThis.Error = Error;
128
- globalThis.TypeError = TypeError;
129
- globalThis.RangeError = RangeError;
130
- globalThis.SyntaxError = SyntaxError;
131
- `);
132
-
133
- // Set up module cache for require()
134
- await jail.set('_moduleCache', new ivm.Reference({}));
135
-
136
- // Create require() function that loads allowed libraries
137
- const requireFunc = new ivm.Reference(async (moduleName: string) => {
138
- const blockedModules = ['fs', 'path', 'http', 'https', 'net', 'child_process', 'cluster', 'os', 'process'];
139
-
140
- // Check if module is blocked
141
- if (blockedModules.includes(moduleName)) {
142
- throw new Error(`Security Error: Module '${moduleName}' is not allowed in sandboxed code`);
143
- }
144
-
145
- // Check if module is allowed
146
- if (!isModuleAllowed(moduleName)) {
147
- const allowedList = getAllowedModuleNames().join(', ');
148
- throw new Error(`Module '${moduleName}' is not available. Allowed modules: ${allowedList}`);
149
- }
150
-
151
- // Load the library source
152
- const libSource = getLibrarySource(moduleName);
153
- if (!libSource) {
154
- throw new Error(`Failed to load library '${moduleName}'`);
155
- }
156
-
157
- return libSource;
158
- });
159
-
160
- await jail.set('_requireLoader', requireFunc);
161
-
162
- // Set up require() and module loading in the isolate
163
- // We keep eval temporarily for module loading, then delete it after user code runs
164
- await context.eval(`
165
- globalThis._loadedModules = {};
166
-
167
- // Save a reference to eval for controlled module loading
168
- const _controlledEval = eval;
169
-
170
- globalThis.require = function(moduleName) {
171
- // Check cache first
172
- if (globalThis._loadedModules[moduleName]) {
173
- return globalThis._loadedModules[moduleName];
174
- }
175
-
176
- // Load the module source from host
177
- const moduleSource = _requireLoader.applySync(undefined, [moduleName]);
178
-
179
- // Evaluate the module source to get the exports (controlled eval for library loading only)
180
- const moduleExports = _controlledEval('(' + moduleSource + ')');
181
-
182
- // Cache it
183
- globalThis._loadedModules[moduleName] = moduleExports;
184
-
185
- return moduleExports;
186
- };
187
- `);
188
-
189
- // Wrap user code to capture output
190
- const wrappedCode = `
191
- (function() {
192
- let output;
193
- ${params.code}
194
- return output;
195
- })();
196
- `;
197
-
198
- // Execute the code with timeout
199
- const script = await isolate.compileScript(wrappedCode);
200
- const result = await script.run(context, { timeout: timeoutMs });
201
-
202
- // Extract output value
203
- let output: any;
204
- if (result && typeof result === 'object' && 'copy' in result) {
205
- output = await result.copy();
206
- } else {
207
- output = result;
208
- }
209
-
210
- return {
211
- success: true,
212
- output,
213
- logs: logs.length > 0 ? logs : undefined,
214
- executionTimeMs: Date.now() - startTime
215
- };
216
-
217
- } catch (error) {
218
- let errorType: CodeExecutionResult['errorType'] = 'RUNTIME_ERROR';
219
- let errorMessage = error instanceof Error ? error.message : String(error);
220
-
221
- // Classify error types
222
- if (errorMessage.includes('Script execution timed out')) {
223
- errorType = 'TIMEOUT';
224
- errorMessage = `Code execution exceeded timeout of ${params.timeoutSeconds || 30} seconds`;
225
- } else if (errorMessage.includes('SyntaxError') || errorMessage.includes('Unexpected')) {
226
- errorType = 'SYNTAX_ERROR';
227
- } else if (errorMessage.includes('Security Error')) {
228
- errorType = 'SECURITY_ERROR';
229
- } else if (errorMessage.includes('memory limit')) {
230
- errorType = 'MEMORY_LIMIT';
231
- }
232
-
233
- return {
234
- success: false,
235
- error: errorMessage,
236
- errorType,
237
- executionTimeMs: Date.now() - startTime
238
- };
239
-
240
- } finally {
241
- // Clean up resources
242
- if (context) {
243
- context.release();
244
- }
245
- if (isolate) {
246
- isolate.dispose();
247
- }
248
- }
97
+ getStats() {
98
+ return this.workerPool.getStats();
249
99
  }
250
100
 
251
101
  /**
252
- * Format console arguments for logging
253
- * @private
102
+ * Shutdown the service and all worker processes
103
+ *
104
+ * This should be called during application shutdown to gracefully terminate
105
+ * all workers and reject any pending requests.
254
106
  */
255
- private formatConsoleArg(arg: any): string {
256
- if (arg === null) return 'null';
257
- if (arg === undefined) return 'undefined';
258
- if (typeof arg === 'string') return arg;
259
- if (typeof arg === 'number' || typeof arg === 'boolean') return String(arg);
260
-
261
- try {
262
- return JSON.stringify(arg, null, 2);
263
- } catch {
264
- return String(arg);
107
+ async shutdown(): Promise<void> {
108
+ if (this.initialized) {
109
+ await this.workerPool.shutdown();
110
+ this.initialized = false;
265
111
  }
266
112
  }
267
113
  }