@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.
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Worker Pool Manager
3
+ *
4
+ * Manages a pool of worker processes for executing code with fault isolation.
5
+ * Each worker runs in a separate OS process, so a catastrophic failure in one
6
+ * worker (e.g., V8 OOM crash) doesn't affect the main application or other workers.
7
+ *
8
+ * Features:
9
+ * - Process-level isolation for fault tolerance
10
+ * - Automatic worker restart on crashes
11
+ * - Request queuing when all workers are busy
12
+ * - Health monitoring and circuit breaker pattern
13
+ */
14
+
15
+ import { fork, ChildProcess } from 'child_process';
16
+ import * as path from 'path';
17
+ import { CodeExecutionParams, CodeExecutionResult } from './types';
18
+ import { LogError, LogStatus } from '@memberjunction/core';
19
+
20
+ interface PendingRequest {
21
+ requestId: string;
22
+ params: CodeExecutionParams;
23
+ resolve: (result: CodeExecutionResult) => void;
24
+ reject: (error: Error) => void;
25
+ timeout: NodeJS.Timeout;
26
+ }
27
+
28
+ interface Worker {
29
+ process: ChildProcess;
30
+ id: number;
31
+ busy: boolean;
32
+ currentRequest: PendingRequest | null;
33
+ crashCount: number;
34
+ lastCrashTime: number;
35
+ }
36
+
37
+ /**
38
+ * Configuration options for worker pool
39
+ */
40
+ export interface WorkerPoolOptions {
41
+ /** Number of worker processes to maintain (default: 2) */
42
+ poolSize?: number;
43
+ /** Maximum crashes per worker before marking unhealthy (default: 3) */
44
+ maxCrashesPerWorker?: number;
45
+ /** Time window in ms for crash counting (default: 60000 = 1 minute) */
46
+ crashTimeWindow?: number;
47
+ /** Maximum queue size before rejecting requests (default: 100) */
48
+ maxQueueSize?: number;
49
+ }
50
+
51
+ /**
52
+ * Manages a pool of worker processes for code execution
53
+ */
54
+ export class WorkerPool {
55
+ private workers: Worker[] = [];
56
+ private requestQueue: PendingRequest[] = [];
57
+ private nextRequestId = 0;
58
+ private poolSize: number;
59
+ private maxCrashesPerWorker: number;
60
+ private crashTimeWindow: number;
61
+ private maxQueueSize: number;
62
+ private isShuttingDown = false;
63
+
64
+ constructor(options: WorkerPoolOptions = {}) {
65
+ this.poolSize = options.poolSize || 2;
66
+ this.maxCrashesPerWorker = options.maxCrashesPerWorker || 3;
67
+ this.crashTimeWindow = options.crashTimeWindow || 60000; // 1 minute
68
+ this.maxQueueSize = options.maxQueueSize || 100;
69
+ }
70
+
71
+ /**
72
+ * Initialize the worker pool
73
+ */
74
+ async initialize(): Promise<void> {
75
+ LogStatus('Initializing code execution worker pool with ' + this.poolSize + ' workers');
76
+
77
+ for (let i = 0; i < this.poolSize; i++) {
78
+ await this.createWorker(i);
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Create a new worker process
84
+ */
85
+ private async createWorker(id: number): Promise<void> {
86
+ const workerPath = path.join(__dirname, 'worker.js'); // Use .js because worker.ts is compiled
87
+ const childProcess = fork(workerPath, [], {
88
+ stdio: ['ignore', 'inherit', 'inherit', 'ipc'] // Inherit stdout/stderr for debugging
89
+ });
90
+
91
+ const worker: Worker = {
92
+ process: childProcess,
93
+ id,
94
+ busy: false,
95
+ currentRequest: null,
96
+ crashCount: 0,
97
+ lastCrashTime: 0
98
+ };
99
+
100
+ this.workers[id] = worker;
101
+
102
+ // Wait for ready message
103
+ await new Promise<void>((resolve, reject) => {
104
+ const timeout = setTimeout(() => {
105
+ reject(new Error(`Worker ${id} failed to start within 5 seconds`));
106
+ }, 5000);
107
+
108
+ childProcess.once('message', (msg: any) => {
109
+ if (msg.type === 'ready') {
110
+ clearTimeout(timeout);
111
+ resolve();
112
+ }
113
+ });
114
+
115
+ childProcess.once('error', (error) => {
116
+ clearTimeout(timeout);
117
+ reject(error);
118
+ });
119
+ });
120
+
121
+ // Set up message handler for responses
122
+ childProcess.on('message', (message: any) => {
123
+ this.handleWorkerMessage(worker, message);
124
+ });
125
+
126
+ // Set up crash handler
127
+ childProcess.on('exit', (code, signal) => {
128
+ this.handleWorkerCrash(worker, code, signal);
129
+ });
130
+
131
+ LogStatus(`Worker ${id} initialized and ready`);
132
+ }
133
+
134
+ /**
135
+ * Handle messages from worker process
136
+ */
137
+ private handleWorkerMessage(worker: Worker, message: any): void {
138
+ if (message.type === 'ready') {
139
+ // Worker is ready (initial startup or after restart)
140
+ return;
141
+ }
142
+
143
+ if (!worker.currentRequest) {
144
+ LogError(new Error(`Worker ${worker.id} sent message but has no current request`));
145
+ return;
146
+ }
147
+
148
+ const request = worker.currentRequest;
149
+ clearTimeout(request.timeout);
150
+
151
+ if (message.type === 'result') {
152
+ request.resolve(message.result);
153
+ } else if (message.type === 'error') {
154
+ request.reject(new Error(message.error));
155
+ }
156
+
157
+ // Mark worker as available and process queue
158
+ worker.busy = false;
159
+ worker.currentRequest = null;
160
+ this.processQueue();
161
+ }
162
+
163
+ /**
164
+ * Handle worker process crash
165
+ */
166
+ private handleWorkerCrash(worker: Worker, code: number | null, signal: string | null): void {
167
+ const now = Date.now();
168
+
169
+ // Update crash tracking
170
+ if (now - worker.lastCrashTime > this.crashTimeWindow) {
171
+ // Outside time window, reset count
172
+ worker.crashCount = 1;
173
+ } else {
174
+ worker.crashCount++;
175
+ }
176
+ worker.lastCrashTime = now;
177
+
178
+ LogError(new Error(
179
+ `Worker ${worker.id} crashed (code: ${code}, signal: ${signal}). ` +
180
+ `Crash count: ${worker.crashCount}/${this.maxCrashesPerWorker}`
181
+ ));
182
+
183
+ // Reject current request if any
184
+ if (worker.currentRequest) {
185
+ clearTimeout(worker.currentRequest.timeout);
186
+ worker.currentRequest.reject(new Error(
187
+ 'Worker process crashed during code execution. This may indicate a severe error in the code.'
188
+ ));
189
+ worker.currentRequest = null;
190
+ }
191
+
192
+ // Check if worker should be restarted
193
+ if (worker.crashCount >= this.maxCrashesPerWorker) {
194
+ LogError(new Error(
195
+ `Worker ${worker.id} has crashed ${worker.crashCount} times within ${this.crashTimeWindow}ms. ` +
196
+ 'Not restarting to prevent crash loop. Code execution capacity reduced.'
197
+ ));
198
+ // Remove from pool
199
+ this.workers[worker.id] = null as any;
200
+ return;
201
+ }
202
+
203
+ // Restart worker if not shutting down
204
+ if (!this.isShuttingDown) {
205
+ LogStatus(`Restarting worker ${worker.id}...`);
206
+ this.createWorker(worker.id).catch(error => {
207
+ LogError(new Error(`Failed to restart worker ${worker.id}: ${error.message}`));
208
+ });
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Execute code in an available worker
214
+ */
215
+ async execute(params: CodeExecutionParams): Promise<CodeExecutionResult> {
216
+ if (this.isShuttingDown) {
217
+ return {
218
+ success: false,
219
+ error: 'Worker pool is shutting down',
220
+ errorType: 'RUNTIME_ERROR'
221
+ };
222
+ }
223
+
224
+ // Check if queue is full
225
+ if (this.requestQueue.length >= this.maxQueueSize) {
226
+ return {
227
+ success: false,
228
+ error: `Request queue is full (${this.maxQueueSize} pending requests). Please try again later.`,
229
+ errorType: 'RUNTIME_ERROR'
230
+ };
231
+ }
232
+
233
+ const requestId = `req-${this.nextRequestId++}`;
234
+
235
+ return new Promise<CodeExecutionResult>((resolve, reject) => {
236
+ // Create timeout for entire request (includes queue time + execution)
237
+ const totalTimeout = ((params.timeoutSeconds || 30) + 5) * 1000; // Add 5s buffer for overhead
238
+ const timeout = setTimeout(() => {
239
+ // Remove from queue if still there
240
+ const queueIndex = this.requestQueue.findIndex(r => r.requestId === requestId);
241
+ if (queueIndex >= 0) {
242
+ this.requestQueue.splice(queueIndex, 1);
243
+ }
244
+ resolve({
245
+ success: false,
246
+ error: 'Request timed out waiting for worker availability',
247
+ errorType: 'TIMEOUT'
248
+ });
249
+ }, totalTimeout);
250
+
251
+ const request: PendingRequest = {
252
+ requestId,
253
+ params,
254
+ resolve,
255
+ reject,
256
+ timeout
257
+ };
258
+
259
+ // Add to queue
260
+ this.requestQueue.push(request);
261
+
262
+ // Try to process immediately
263
+ this.processQueue();
264
+ });
265
+ }
266
+
267
+ /**
268
+ * Process queued requests by assigning them to available workers
269
+ */
270
+ private processQueue(): void {
271
+ if (this.requestQueue.length === 0) {
272
+ return;
273
+ }
274
+
275
+ // Find an available worker
276
+ const worker = this.workers.find(w => w && !w.busy);
277
+ if (!worker) {
278
+ return; // All workers busy, wait for one to finish
279
+ }
280
+
281
+ // Get next request from queue
282
+ const request = this.requestQueue.shift();
283
+ if (!request) {
284
+ return;
285
+ }
286
+
287
+ // Assign request to worker
288
+ worker.busy = true;
289
+ worker.currentRequest = request;
290
+
291
+ // Send execution request to worker
292
+ worker.process.send({
293
+ type: 'execute',
294
+ requestId: request.requestId,
295
+ params: request.params
296
+ });
297
+
298
+ // Try to process more if queue has items
299
+ if (this.requestQueue.length > 0) {
300
+ setImmediate(() => this.processQueue());
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Get pool statistics
306
+ */
307
+ getStats(): {
308
+ totalWorkers: number;
309
+ activeWorkers: number;
310
+ busyWorkers: number;
311
+ queueLength: number;
312
+ } {
313
+ const activeWorkers = this.workers.filter(w => w !== null).length;
314
+ const busyWorkers = this.workers.filter(w => w && w.busy).length;
315
+
316
+ return {
317
+ totalWorkers: this.poolSize,
318
+ activeWorkers,
319
+ busyWorkers,
320
+ queueLength: this.requestQueue.length
321
+ };
322
+ }
323
+
324
+ /**
325
+ * Shutdown the worker pool gracefully
326
+ */
327
+ async shutdown(): Promise<void> {
328
+ this.isShuttingDown = true;
329
+ LogStatus('Shutting down code execution worker pool...');
330
+
331
+ // Reject all queued requests
332
+ for (const request of this.requestQueue) {
333
+ clearTimeout(request.timeout);
334
+ request.resolve({
335
+ success: false,
336
+ error: 'Worker pool is shutting down',
337
+ errorType: 'RUNTIME_ERROR'
338
+ });
339
+ }
340
+ this.requestQueue = [];
341
+
342
+ // Kill all workers
343
+ const killPromises = this.workers
344
+ .filter(w => w !== null)
345
+ .map(worker => {
346
+ return new Promise<void>((resolve) => {
347
+ if (worker.process.killed) {
348
+ resolve();
349
+ return;
350
+ }
351
+
352
+ worker.process.once('exit', () => resolve());
353
+ worker.process.kill('SIGTERM');
354
+
355
+ // Force kill after 5 seconds
356
+ setTimeout(() => {
357
+ if (!worker.process.killed) {
358
+ worker.process.kill('SIGKILL');
359
+ }
360
+ resolve();
361
+ }, 5000);
362
+ });
363
+ });
364
+
365
+ await Promise.all(killPromises);
366
+ LogStatus('Worker pool shutdown complete');
367
+ }
368
+ }
package/src/index.ts CHANGED
@@ -4,5 +4,6 @@
4
4
  */
5
5
 
6
6
  export * from './CodeExecutionService';
7
+ export * from './WorkerPool';
7
8
  export * from './types';
8
9
  export * from './libraries';
package/src/worker.ts ADDED
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Worker Process for Code Execution
3
+ *
4
+ * This worker runs in a SEPARATE PROCESS to provide true process-level isolation
5
+ * for code execution. If a catastrophic V8 error occurs (e.g., severe OOM that crashes V8),
6
+ * only this worker process terminates, not the main application.
7
+ *
8
+ * SECURITY CRITICAL: This file handles the isolate boundary between host and sandbox.
9
+ * Any changes to this file MUST be reviewed for security implications:
10
+ * - NEVER expose ivm.Reference or ivm.ExternalCopy objects to untrusted code
11
+ * - NEVER accept untrusted V8 cachedData (CVE-2022-39266)
12
+ * - ALWAYS validate and sanitize data crossing the isolate boundary
13
+ * - ONLY pass primitives and plain objects via IPC (JSON-serializable data)
14
+ *
15
+ * Defense-in-depth layers:
16
+ * 1. Process isolation (this file) - protects against V8 catastrophic failures
17
+ * 2. V8 isolate (isolated-vm) - protects against sandbox escapes
18
+ * 3. Module blocking - prevents dangerous Node.js API access
19
+ * 4. Resource limits - prevents DoS via timeout/memory exhaustion
20
+ */
21
+
22
+ import ivm from 'isolated-vm';
23
+ import { CodeExecutionParams, CodeExecutionResult } from './types';
24
+ import { getLibrarySource, isModuleAllowed, getAllowedModuleNames } from './libraries';
25
+
26
+ /**
27
+ * Message types for IPC communication with parent process
28
+ * All messages use JSON serialization (primitives and plain objects only)
29
+ */
30
+ interface ExecuteMessage {
31
+ type: 'execute';
32
+ params: CodeExecutionParams;
33
+ requestId: string;
34
+ }
35
+
36
+ interface ResultMessage {
37
+ type: 'result';
38
+ requestId: string;
39
+ result: CodeExecutionResult;
40
+ }
41
+
42
+ interface ErrorMessage {
43
+ type: 'error';
44
+ requestId: string;
45
+ error: string;
46
+ }
47
+
48
+ interface ReadyMessage {
49
+ type: 'ready';
50
+ }
51
+
52
+ type WorkerMessage = ExecuteMessage;
53
+ type ParentMessage = ResultMessage | ErrorMessage | ReadyMessage;
54
+
55
+ /**
56
+ * Execute JavaScript code in an isolated-vm isolate
57
+ *
58
+ * SECURITY: This function creates and manages the V8 isolate. It must ensure:
59
+ * - Only safe built-ins are exposed to untrusted code
60
+ * - Module loading is strictly controlled via allowlist
61
+ * - Input/output data is properly serialized (no object references leak)
62
+ */
63
+ async function executeInIsolate(params: CodeExecutionParams): Promise<CodeExecutionResult> {
64
+ const startTime = Date.now();
65
+ const timeoutMs = (params.timeoutSeconds || 30) * 1000;
66
+ const memoryLimitMB = params.memoryLimitMB || 128;
67
+
68
+ let isolate: ivm.Isolate | null = null;
69
+ let context: ivm.Context | null = null;
70
+
71
+ try {
72
+ // Create isolated VM with memory limit
73
+ isolate = new ivm.Isolate({ memoryLimit: memoryLimitMB });
74
+ context = await isolate.createContext();
75
+
76
+ // Capture console logs
77
+ const logs: string[] = [];
78
+
79
+ // Set up console object
80
+ const jail = context.global;
81
+ await jail.set('global', jail.derefInto());
82
+
83
+ // SECURITY: Create console methods that capture output
84
+ // This ivm.Reference is safe - it's a callback we control, not exposed to user code
85
+ const consoleLog = new ivm.Reference((level: string, ...args: any[]) => {
86
+ const formattedArgs = args.map(arg => formatConsoleArg(arg)).join(' ');
87
+ logs.push(`[${level}] ${formattedArgs}`);
88
+ });
89
+
90
+ await jail.set('_consoleLog', consoleLog);
91
+
92
+ // Set up console in the isolate
93
+ await context.eval(`
94
+ globalThis.console = {
95
+ log: (...args) => _consoleLog.applySync(undefined, ['LOG', ...args]),
96
+ error: (...args) => _consoleLog.applySync(undefined, ['ERROR', ...args]),
97
+ warn: (...args) => _consoleLog.applySync(undefined, ['WARN', ...args]),
98
+ info: (...args) => _consoleLog.applySync(undefined, ['INFO', ...args])
99
+ };
100
+ `);
101
+
102
+ // SECURITY: Set up input data - only primitives and plain objects, no References
103
+ if (params.inputData !== undefined) {
104
+ const inputDataStr = JSON.stringify(params.inputData);
105
+ await jail.set('_inputData', inputDataStr);
106
+ await context.eval('globalThis.input = JSON.parse(_inputData);');
107
+ }
108
+
109
+ // Set up safe built-in objects
110
+ await context.eval(`
111
+ globalThis.JSON = JSON;
112
+ globalThis.Math = Math;
113
+ globalThis.Date = Date;
114
+ globalThis.Array = Array;
115
+ globalThis.Object = Object;
116
+ globalThis.String = String;
117
+ globalThis.Number = Number;
118
+ globalThis.Boolean = Boolean;
119
+ globalThis.RegExp = RegExp;
120
+ globalThis.Error = Error;
121
+ globalThis.TypeError = TypeError;
122
+ globalThis.RangeError = RangeError;
123
+ globalThis.SyntaxError = SyntaxError;
124
+ `);
125
+
126
+ // SECURITY: Block network access via fetch() API (available in Node.js 18+)
127
+ // This is a global in modern Node.js and must be explicitly disabled
128
+ await context.eval(`
129
+ globalThis.fetch = () => {
130
+ throw new Error('Security Error: Network access via fetch() is not allowed in sandboxed code');
131
+ };
132
+ `);
133
+
134
+ // Set up module cache for require()
135
+ await jail.set('_moduleCache', new ivm.Reference({}));
136
+
137
+ // SECURITY: Create require() function with strict module allowlisting
138
+ // This ivm.Reference is safe - it's a loader function we control
139
+ const requireFunc = new ivm.Reference(async (moduleName: string) => {
140
+ const blockedModules = ['fs', 'path', 'http', 'https', 'net', 'child_process', 'cluster', 'os', 'process', 'axios'];
141
+
142
+ // Check if module is blocked
143
+ if (blockedModules.includes(moduleName)) {
144
+ throw new Error(`Security Error: Module '${moduleName}' is not allowed in sandboxed code`);
145
+ }
146
+
147
+ // Check if module is allowed
148
+ if (!isModuleAllowed(moduleName)) {
149
+ const allowedList = getAllowedModuleNames().join(', ');
150
+ throw new Error(`Module '${moduleName}' is not available. Allowed modules: ${allowedList}`);
151
+ }
152
+
153
+ // Load the library source
154
+ const libSource = getLibrarySource(moduleName);
155
+ if (!libSource) {
156
+ throw new Error(`Failed to load library '${moduleName}'`);
157
+ }
158
+
159
+ return libSource;
160
+ });
161
+
162
+ await jail.set('_requireLoader', requireFunc);
163
+
164
+ // Set up require() and module loading in the isolate
165
+ await context.eval(`
166
+ globalThis._loadedModules = {};
167
+
168
+ // Save a reference to eval for controlled module loading
169
+ const _controlledEval = eval;
170
+
171
+ globalThis.require = function(moduleName) {
172
+ // Check cache first
173
+ if (globalThis._loadedModules[moduleName]) {
174
+ return globalThis._loadedModules[moduleName];
175
+ }
176
+
177
+ // Load the module source from host
178
+ const moduleSource = _requireLoader.applySync(undefined, [moduleName]);
179
+
180
+ // Evaluate the module source to get the exports (controlled eval for library loading only)
181
+ const moduleExports = _controlledEval('(' + moduleSource + ')');
182
+
183
+ // Cache it
184
+ globalThis._loadedModules[moduleName] = moduleExports;
185
+
186
+ return moduleExports;
187
+ };
188
+ `);
189
+
190
+ // Wrap user code to capture output
191
+ const wrappedCode = `
192
+ (function() {
193
+ let output;
194
+ ${params.code}
195
+ return output;
196
+ })();
197
+ `;
198
+
199
+ // SECURITY: Compile and execute code with timeout
200
+ // CVE-2022-39266: Never use cachedData from untrusted sources
201
+ // We do NOT pass any cachedData parameter here - only compile from source
202
+ const script = await isolate.compileScript(wrappedCode);
203
+ const result = await script.run(context, { timeout: timeoutMs });
204
+
205
+ // SECURITY: Extract output value - use .copy() to get plain data, not References
206
+ // This ensures no ivm objects leak back to caller
207
+ let output: any;
208
+ if (result && typeof result === 'object' && 'copy' in result) {
209
+ output = await result.copy();
210
+ } else {
211
+ output = result;
212
+ }
213
+
214
+ return {
215
+ success: true,
216
+ output,
217
+ logs: logs.length > 0 ? logs : undefined,
218
+ executionTimeMs: Date.now() - startTime
219
+ };
220
+
221
+ } catch (error) {
222
+ let errorType: CodeExecutionResult['errorType'] = 'RUNTIME_ERROR';
223
+ let errorMessage = error instanceof Error ? error.message : String(error);
224
+
225
+ // Classify error types
226
+ if (errorMessage.includes('Script execution timed out')) {
227
+ errorType = 'TIMEOUT';
228
+ errorMessage = `Code execution exceeded timeout of ${params.timeoutSeconds || 30} seconds`;
229
+ } else if (errorMessage.includes('SyntaxError') || errorMessage.includes('Unexpected')) {
230
+ errorType = 'SYNTAX_ERROR';
231
+ } else if (errorMessage.includes('Security Error')) {
232
+ errorType = 'SECURITY_ERROR';
233
+ } else if (errorMessage.includes('memory limit')) {
234
+ errorType = 'MEMORY_LIMIT';
235
+ }
236
+
237
+ return {
238
+ success: false,
239
+ error: errorMessage,
240
+ errorType,
241
+ executionTimeMs: Date.now() - startTime
242
+ };
243
+
244
+ } finally {
245
+ // Clean up resources
246
+ if (context) {
247
+ context.release();
248
+ }
249
+ if (isolate) {
250
+ isolate.dispose();
251
+ }
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Format console arguments for logging
257
+ */
258
+ function formatConsoleArg(arg: any): string {
259
+ if (arg === null) return 'null';
260
+ if (arg === undefined) return 'undefined';
261
+ if (typeof arg === 'string') return arg;
262
+ if (typeof arg === 'number' || typeof arg === 'boolean') return String(arg);
263
+
264
+ try {
265
+ return JSON.stringify(arg, null, 2);
266
+ } catch {
267
+ return String(arg);
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Handle messages from parent process via IPC
273
+ * Messages are automatically JSON serialized/deserialized by Node.js
274
+ */
275
+ process.on('message', async (message: WorkerMessage) => {
276
+ if (message.type === 'execute') {
277
+ try {
278
+ const result = await executeInIsolate(message.params);
279
+ const response: ResultMessage = {
280
+ type: 'result',
281
+ requestId: message.requestId,
282
+ result
283
+ };
284
+ // SECURITY: Only plain objects are sent via IPC - no References or functions
285
+ process.send!(response);
286
+ } catch (error) {
287
+ const response: ErrorMessage = {
288
+ type: 'error',
289
+ requestId: message.requestId,
290
+ error: error instanceof Error ? error.message : String(error)
291
+ };
292
+ process.send!(response);
293
+ }
294
+ }
295
+ });
296
+
297
+ // Signal that worker is ready to accept work
298
+ process.send!({ type: 'ready' });