@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.
@@ -2,42 +2,69 @@
2
2
  /**
3
3
  * Code Execution Service
4
4
  *
5
- * Provides secure, sandboxed execution of JavaScript code using isolated-vm.
5
+ * Provides secure, sandboxed execution of JavaScript code using isolated-vm
6
+ * running in separate worker processes for fault isolation.
7
+ *
6
8
  * This service enables AI agents and workflows to generate and run code safely
7
- * without compromising system security.
9
+ * without compromising system security or stability.
8
10
  *
9
- * Security Model:
10
- * - Uses isolated-vm for true V8 isolate separation
11
- * - No filesystem access (fs module blocked)
12
- * - No network access (http/https/net modules blocked)
13
- * - Configurable timeout and memory limits
14
- * - Curated allowlist of safe npm packages
11
+ * Security Model (Multi-Layer Defense):
12
+ * 1. Process Isolation - Workers run in separate processes (protects against V8 crashes)
13
+ * 2. V8 Isolates - Code runs in isolated V8 contexts (protects against sandbox escapes)
14
+ * 3. Module Blocking - Dangerous Node.js modules are blocked (fs, http, child_process, etc.)
15
+ * 4. Resource Limits - Enforced timeout and memory limits (prevents DoS)
16
+ * 5. Library Allowlist - Only pre-vetted libraries available (prevents supply chain attacks)
15
17
  *
16
18
  * @module @memberjunction/code-execution
17
19
  */
18
- var __importDefault = (this && this.__importDefault) || function (mod) {
19
- return (mod && mod.__esModule) ? mod : { "default": mod };
20
- };
21
20
  Object.defineProperty(exports, "__esModule", { value: true });
22
21
  exports.CodeExecutionService = void 0;
23
- const isolated_vm_1 = __importDefault(require("isolated-vm"));
24
- const libraries_1 = require("./libraries");
22
+ const WorkerPool_1 = require("./WorkerPool");
25
23
  /**
26
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.
27
29
  */
28
30
  class CodeExecutionService {
31
+ workerPool;
32
+ initialized = false;
29
33
  /**
30
- * Cache of loaded modules per isolate
34
+ * Create a new CodeExecutionService
35
+ *
36
+ * @param options - Worker pool configuration options
37
+ */
38
+ constructor(options = {}) {
39
+ this.workerPool = new WorkerPool_1.WorkerPool(options);
40
+ }
41
+ /**
42
+ * Initialize the service and worker pool
43
+ *
44
+ * This must be called before executing any code. It starts the worker processes
45
+ * and waits for them to be ready.
31
46
  */
32
- moduleCache = new Map();
47
+ async initialize() {
48
+ if (!this.initialized) {
49
+ await this.workerPool.initialize();
50
+ this.initialized = true;
51
+ }
52
+ }
33
53
  /**
34
54
  * Execute JavaScript code in a sandboxed environment
35
55
  *
56
+ * The code runs in a worker process with full isolation. If the worker crashes
57
+ * due to catastrophic errors, it will be automatically restarted without affecting
58
+ * this call or the main application.
59
+ *
36
60
  * @param params - Execution parameters (code, language, input data, limits)
37
61
  * @returns Execution result with output, logs, or error
38
62
  */
39
63
  async execute(params) {
40
- const startTime = Date.now();
64
+ // Auto-initialize if not already done
65
+ if (!this.initialized) {
66
+ await this.initialize();
67
+ }
41
68
  // Validate parameters
42
69
  if (!params.code || typeof params.code !== 'string') {
43
70
  return {
@@ -53,199 +80,27 @@ class CodeExecutionService {
53
80
  errorType: 'RUNTIME_ERROR'
54
81
  };
55
82
  }
56
- try {
57
- return await this.executeJavaScript(params, startTime);
58
- }
59
- catch (error) {
60
- return {
61
- success: false,
62
- error: error instanceof Error ? error.message : String(error),
63
- errorType: 'RUNTIME_ERROR',
64
- executionTimeMs: Date.now() - startTime
65
- };
66
- }
83
+ // Execute in worker pool
84
+ return this.workerPool.execute(params);
67
85
  }
68
86
  /**
69
- * Execute JavaScript code using isolated-vm
70
- * @private
87
+ * Get worker pool statistics
88
+ *
89
+ * @returns Pool statistics including worker count and queue length
71
90
  */
72
- async executeJavaScript(params, startTime) {
73
- const timeoutMs = (params.timeoutSeconds || 30) * 1000;
74
- const memoryLimitMB = params.memoryLimitMB || 128;
75
- let isolate = null;
76
- let context = null;
77
- try {
78
- // Create isolated VM with memory limit
79
- isolate = new isolated_vm_1.default.Isolate({ memoryLimit: memoryLimitMB });
80
- context = await isolate.createContext();
81
- // Capture console logs
82
- const logs = [];
83
- // Set up console object
84
- const jail = context.global;
85
- await jail.set('global', jail.derefInto());
86
- // Create console methods that capture output
87
- const consoleLog = new isolated_vm_1.default.Reference((level, ...args) => {
88
- const formattedArgs = args.map(arg => this.formatConsoleArg(arg)).join(' ');
89
- logs.push(`[${level}] ${formattedArgs}`);
90
- });
91
- await jail.set('_consoleLog', consoleLog);
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
- // Set up input data if provided
102
- if (params.inputData !== undefined) {
103
- const inputDataStr = JSON.stringify(params.inputData);
104
- await jail.set('_inputData', inputDataStr);
105
- await context.eval('globalThis.input = JSON.parse(_inputData);');
106
- }
107
- // Set up safe built-in objects
108
- await context.eval(`
109
- globalThis.JSON = JSON;
110
- globalThis.Math = Math;
111
- globalThis.Date = Date;
112
- globalThis.Array = Array;
113
- globalThis.Object = Object;
114
- globalThis.String = String;
115
- globalThis.Number = Number;
116
- globalThis.Boolean = Boolean;
117
- globalThis.RegExp = RegExp;
118
- globalThis.Error = Error;
119
- globalThis.TypeError = TypeError;
120
- globalThis.RangeError = RangeError;
121
- globalThis.SyntaxError = SyntaxError;
122
- `);
123
- // Set up module cache for require()
124
- await jail.set('_moduleCache', new isolated_vm_1.default.Reference({}));
125
- // Create require() function that loads allowed libraries
126
- const requireFunc = new isolated_vm_1.default.Reference(async (moduleName) => {
127
- const blockedModules = ['fs', 'path', 'http', 'https', 'net', 'child_process', 'cluster', 'os', 'process'];
128
- // Check if module is blocked
129
- if (blockedModules.includes(moduleName)) {
130
- throw new Error(`Security Error: Module '${moduleName}' is not allowed in sandboxed code`);
131
- }
132
- // Check if module is allowed
133
- if (!(0, libraries_1.isModuleAllowed)(moduleName)) {
134
- const allowedList = (0, libraries_1.getAllowedModuleNames)().join(', ');
135
- throw new Error(`Module '${moduleName}' is not available. Allowed modules: ${allowedList}`);
136
- }
137
- // Load the library source
138
- const libSource = (0, libraries_1.getLibrarySource)(moduleName);
139
- if (!libSource) {
140
- throw new Error(`Failed to load library '${moduleName}'`);
141
- }
142
- return libSource;
143
- });
144
- await jail.set('_requireLoader', requireFunc);
145
- // Set up require() and module loading in the isolate
146
- // We keep eval temporarily for module loading, then delete it after user code runs
147
- await context.eval(`
148
- globalThis._loadedModules = {};
149
-
150
- // Save a reference to eval for controlled module loading
151
- const _controlledEval = eval;
152
-
153
- globalThis.require = function(moduleName) {
154
- // Check cache first
155
- if (globalThis._loadedModules[moduleName]) {
156
- return globalThis._loadedModules[moduleName];
157
- }
158
-
159
- // Load the module source from host
160
- const moduleSource = _requireLoader.applySync(undefined, [moduleName]);
161
-
162
- // Evaluate the module source to get the exports (controlled eval for library loading only)
163
- const moduleExports = _controlledEval('(' + moduleSource + ')');
164
-
165
- // Cache it
166
- globalThis._loadedModules[moduleName] = moduleExports;
167
-
168
- return moduleExports;
169
- };
170
- `);
171
- // Wrap user code to capture output
172
- const wrappedCode = `
173
- (function() {
174
- let output;
175
- ${params.code}
176
- return output;
177
- })();
178
- `;
179
- // Execute the code with timeout
180
- const script = await isolate.compileScript(wrappedCode);
181
- const result = await script.run(context, { timeout: timeoutMs });
182
- // Extract output value
183
- let output;
184
- if (result && typeof result === 'object' && 'copy' in result) {
185
- output = await result.copy();
186
- }
187
- else {
188
- output = result;
189
- }
190
- return {
191
- success: true,
192
- output,
193
- logs: logs.length > 0 ? logs : undefined,
194
- executionTimeMs: Date.now() - startTime
195
- };
196
- }
197
- catch (error) {
198
- let errorType = 'RUNTIME_ERROR';
199
- let errorMessage = error instanceof Error ? error.message : String(error);
200
- // Classify error types
201
- if (errorMessage.includes('Script execution timed out')) {
202
- errorType = 'TIMEOUT';
203
- errorMessage = `Code execution exceeded timeout of ${params.timeoutSeconds || 30} seconds`;
204
- }
205
- else if (errorMessage.includes('SyntaxError') || errorMessage.includes('Unexpected')) {
206
- errorType = 'SYNTAX_ERROR';
207
- }
208
- else if (errorMessage.includes('Security Error')) {
209
- errorType = 'SECURITY_ERROR';
210
- }
211
- else if (errorMessage.includes('memory limit')) {
212
- errorType = 'MEMORY_LIMIT';
213
- }
214
- return {
215
- success: false,
216
- error: errorMessage,
217
- errorType,
218
- executionTimeMs: Date.now() - startTime
219
- };
220
- }
221
- finally {
222
- // Clean up resources
223
- if (context) {
224
- context.release();
225
- }
226
- if (isolate) {
227
- isolate.dispose();
228
- }
229
- }
91
+ getStats() {
92
+ return this.workerPool.getStats();
230
93
  }
231
94
  /**
232
- * Format console arguments for logging
233
- * @private
95
+ * Shutdown the service and all worker processes
96
+ *
97
+ * This should be called during application shutdown to gracefully terminate
98
+ * all workers and reject any pending requests.
234
99
  */
235
- formatConsoleArg(arg) {
236
- if (arg === null)
237
- return 'null';
238
- if (arg === undefined)
239
- return 'undefined';
240
- if (typeof arg === 'string')
241
- return arg;
242
- if (typeof arg === 'number' || typeof arg === 'boolean')
243
- return String(arg);
244
- try {
245
- return JSON.stringify(arg, null, 2);
246
- }
247
- catch {
248
- return String(arg);
100
+ async shutdown() {
101
+ if (this.initialized) {
102
+ await this.workerPool.shutdown();
103
+ this.initialized = false;
249
104
  }
250
105
  }
251
106
  }
@@ -1 +1 @@
1
- {"version":3,"file":"CodeExecutionService.js","sourceRoot":"","sources":["../src/CodeExecutionService.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;;;AAEH,8DAA8B;AAE9B,2CAAuF;AAEvF;;GAEG;AACH,MAAa,oBAAoB;IAC7B;;OAEG;IACK,WAAW,GAAqB,IAAI,GAAG,EAAE,CAAC;IAClD;;;;;OAKG;IACH,KAAK,CAAC,OAAO,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,IAAI,CAAC,WAAW,EAAE,CAAC;YACnB,MAAM,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;YACjC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QAC7B,CAAC;IACL,CAAC;CACJ;AAnFD,oDAmFC"}
@@ -0,0 +1,79 @@
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
+ import { CodeExecutionParams, CodeExecutionResult } from './types';
15
+ /**
16
+ * Configuration options for worker pool
17
+ */
18
+ export interface WorkerPoolOptions {
19
+ /** Number of worker processes to maintain (default: 2) */
20
+ poolSize?: number;
21
+ /** Maximum crashes per worker before marking unhealthy (default: 3) */
22
+ maxCrashesPerWorker?: number;
23
+ /** Time window in ms for crash counting (default: 60000 = 1 minute) */
24
+ crashTimeWindow?: number;
25
+ /** Maximum queue size before rejecting requests (default: 100) */
26
+ maxQueueSize?: number;
27
+ }
28
+ /**
29
+ * Manages a pool of worker processes for code execution
30
+ */
31
+ export declare class WorkerPool {
32
+ private workers;
33
+ private requestQueue;
34
+ private nextRequestId;
35
+ private poolSize;
36
+ private maxCrashesPerWorker;
37
+ private crashTimeWindow;
38
+ private maxQueueSize;
39
+ private isShuttingDown;
40
+ constructor(options?: WorkerPoolOptions);
41
+ /**
42
+ * Initialize the worker pool
43
+ */
44
+ initialize(): Promise<void>;
45
+ /**
46
+ * Create a new worker process
47
+ */
48
+ private createWorker;
49
+ /**
50
+ * Handle messages from worker process
51
+ */
52
+ private handleWorkerMessage;
53
+ /**
54
+ * Handle worker process crash
55
+ */
56
+ private handleWorkerCrash;
57
+ /**
58
+ * Execute code in an available worker
59
+ */
60
+ execute(params: CodeExecutionParams): Promise<CodeExecutionResult>;
61
+ /**
62
+ * Process queued requests by assigning them to available workers
63
+ */
64
+ private processQueue;
65
+ /**
66
+ * Get pool statistics
67
+ */
68
+ getStats(): {
69
+ totalWorkers: number;
70
+ activeWorkers: number;
71
+ busyWorkers: number;
72
+ queueLength: number;
73
+ };
74
+ /**
75
+ * Shutdown the worker pool gracefully
76
+ */
77
+ shutdown(): Promise<void>;
78
+ }
79
+ //# sourceMappingURL=WorkerPool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WorkerPool.d.ts","sourceRoot":"","sources":["../src/WorkerPool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAoBnE;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAC9B,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uEAAuE;IACvE,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,uEAAuE;IACvE,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,kEAAkE;IAClE,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;GAEG;AACH,qBAAa,UAAU;IACnB,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,YAAY,CAAwB;IAC5C,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,cAAc,CAAS;gBAEnB,OAAO,GAAE,iBAAsB;IAO3C;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAQjC;;OAEG;YACW,YAAY;IAiD1B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IA0B3B;;OAEG;IACH,OAAO,CAAC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