@memberjunction/code-execution 5.28.0 → 5.30.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/src/worker.ts CHANGED
@@ -17,6 +17,28 @@
17
17
  * 2. V8 isolate (isolated-vm) - protects against sandbox escapes
18
18
  * 3. Module blocking - prevents dangerous Node.js API access
19
19
  * 4. Resource limits - prevents DoS via timeout/memory exhaustion
20
+ *
21
+ * ==============================================================================
22
+ * Bidirectional Bridge (Phase 1d)
23
+ * ==============================================================================
24
+ * Sandbox code can call `__bridgeCall(name, args)` to invoke a host-registered
25
+ * handler and await its result. The flow:
26
+ *
27
+ * 1. Sandbox calls `__bridgeCall('rv.RunView', { EntityName: '...' })`
28
+ * 2. That dispatches to the host-side `_bridgeCall` ivm.Reference via
29
+ * `applyAsync`. The reference's JS body sends a `bridge-call` IPC
30
+ * message to the parent process and waits for the matching
31
+ * `bridge-response`.
32
+ * 3. Parent process routes the request to the registered handler,
33
+ * executes it, and sends `bridge-response` back.
34
+ * 4. The worker's `process.on('message')` handler resolves the pending
35
+ * promise for that callId.
36
+ * 5. `applyAsync` resolves inside the isolate with the JSON-stringified
37
+ * result. Sandbox code parses it and sees a plain object.
38
+ *
39
+ * The bridge is scoped per-requestId: each `execute` message opens a new
40
+ * pending-calls map that is either drained on completion or rejected en
41
+ * masse on `abort`. Nothing persists between executions.
20
42
  */
21
43
 
22
44
  import ivm from 'isolated-vm';
@@ -29,7 +51,7 @@ import { getLibrarySource, isModuleAllowed, getAllowedModuleNames } from './libr
29
51
  */
30
52
  interface ExecuteMessage {
31
53
  type: 'execute';
32
- params: CodeExecutionParams;
54
+ params: Omit<CodeExecutionParams, 'bridgeHandlers' | 'abortSignal'>;
33
55
  requestId: string;
34
56
  }
35
57
 
@@ -49,8 +71,53 @@ interface ReadyMessage {
49
71
  type: 'ready';
50
72
  }
51
73
 
52
- type WorkerMessage = ExecuteMessage;
53
- type ParentMessage = ResultMessage | ErrorMessage | ReadyMessage;
74
+ interface BridgeCallMessage {
75
+ type: 'bridge-call';
76
+ requestId: string;
77
+ callId: string;
78
+ functionName: string;
79
+ args: unknown;
80
+ }
81
+
82
+ interface BridgeResponseMessage {
83
+ type: 'bridge-response';
84
+ requestId: string;
85
+ callId: string;
86
+ result?: unknown;
87
+ error?: string;
88
+ }
89
+
90
+ interface AbortMessage {
91
+ type: 'abort';
92
+ requestId: string;
93
+ reason: string;
94
+ }
95
+
96
+ type ParentInboundMessage = ExecuteMessage | BridgeResponseMessage | AbortMessage;
97
+ type ParentOutboundMessage = ResultMessage | ErrorMessage | ReadyMessage | BridgeCallMessage;
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Bridge state — one entry per in-flight execution.
101
+ //
102
+ // The key is the host-assigned `requestId` for the execute() call. Each entry
103
+ // owns a Map of in-flight bridge calls (callId → { resolve, reject }) so
104
+ // multiple concurrent `await __bridgeCall(...)` invocations from inside one
105
+ // execution (e.g. Promise.all) are correlated by callId. The `callCount` +
106
+ // `maxCalls` fields enforce the per-execution bridge-call cap.
107
+ // ---------------------------------------------------------------------------
108
+ interface BridgeExecutionState {
109
+ pending: Map<string, { resolve: (value: unknown) => void; reject: (err: Error) => void }>;
110
+ callCount: number;
111
+ maxCalls: number;
112
+ aborted: boolean;
113
+ abortReason?: string;
114
+ }
115
+
116
+ const bridgeStates = new Map<string, BridgeExecutionState>();
117
+
118
+ function getBridgeState(requestId: string): BridgeExecutionState | undefined {
119
+ return bridgeStates.get(requestId);
120
+ }
54
121
 
55
122
  /**
56
123
  * Execute JavaScript code in an isolated-vm isolate
@@ -60,10 +127,24 @@ type ParentMessage = ResultMessage | ErrorMessage | ReadyMessage;
60
127
  * - Module loading is strictly controlled via allowlist
61
128
  * - Input/output data is properly serialized (no object references leak)
62
129
  */
63
- async function executeInIsolate(params: CodeExecutionParams): Promise<CodeExecutionResult> {
130
+ async function executeInIsolate(
131
+ params: ExecuteMessage['params'],
132
+ requestId: string
133
+ ): Promise<CodeExecutionResult> {
64
134
  const startTime = Date.now();
65
135
  const timeoutMs = (params.timeoutSeconds || 30) * 1000;
66
136
  const memoryLimitMB = params.memoryLimitMB || 128;
137
+ const maxBridgeCalls = params.maxBridgeCalls ?? 100;
138
+
139
+ // Open the bridge state for this execution before the isolate starts so
140
+ // any bridge-response / abort messages that race in are delivered to a
141
+ // real slot rather than dropped.
142
+ bridgeStates.set(requestId, {
143
+ pending: new Map(),
144
+ callCount: 0,
145
+ maxCalls: maxBridgeCalls,
146
+ aborted: false
147
+ });
67
148
 
68
149
  let isolate: ivm.Isolate | null = null;
69
150
  let context: ivm.Context | null = null;
@@ -131,6 +212,108 @@ async function executeInIsolate(params: CodeExecutionParams): Promise<CodeExecut
131
212
  };
132
213
  `);
133
214
 
215
+ // ===================================================================
216
+ // BRIDGE SETUP
217
+ //
218
+ // Inject a single host-backed async function as `_bridgeCall`. The
219
+ // reference's body sends an IPC message to the parent and awaits the
220
+ // matching `bridge-response` via the `bridgeStates` map above. The
221
+ // isolate wraps it as `globalThis.__bridgeCall(name, args)` which
222
+ // returns a Promise resolving to the parsed JSON result (or rejects
223
+ // with the host error message).
224
+ //
225
+ // Args + result cross the boundary as JSON strings so complex object
226
+ // shapes, Dates, etc. behave consistently and no ivm.Reference ever
227
+ // leaks back into user code.
228
+ // ===================================================================
229
+ // The bridge callback NEVER throws — errors are encoded as a JSON
230
+ // envelope `{ __bridgeError: '...' }` and re-thrown inside the
231
+ // isolate. This avoids firing unhandled-rejection in the worker
232
+ // process when the caller exceeds maxBridgeCalls or the host handler
233
+ // throws; isolated-vm would propagate the rejection across the
234
+ // boundary, but Node 24+'s strict unhandled-rejection semantics can
235
+ // fire a process.unhandledRejection handler before isolated-vm's
236
+ // delivery settles, killing the worker.
237
+ const bridgeCall = new ivm.Reference(
238
+ async (callId: string, functionName: string, argsJson: string): Promise<string> => {
239
+ try {
240
+ const state = getBridgeState(requestId);
241
+ if (!state) {
242
+ throw new Error('Bridge state missing for this execution');
243
+ }
244
+ if (state.aborted) {
245
+ throw new Error(state.abortReason ?? 'Execution aborted');
246
+ }
247
+ if (state.callCount >= state.maxCalls) {
248
+ throw new Error(
249
+ `Bridge call limit exceeded (maxBridgeCalls=${state.maxCalls}). ` +
250
+ 'Runtime action tried to make too many host round-trips.'
251
+ );
252
+ }
253
+ state.callCount++;
254
+
255
+ let args: unknown;
256
+ try {
257
+ args = JSON.parse(argsJson);
258
+ } catch {
259
+ throw new Error('Bridge call args must be JSON-serializable');
260
+ }
261
+
262
+ const resultPromise = new Promise<unknown>((resolve, reject) => {
263
+ state.pending.set(callId, { resolve, reject });
264
+ });
265
+
266
+ const callMessage: BridgeCallMessage = {
267
+ type: 'bridge-call',
268
+ requestId,
269
+ callId,
270
+ functionName,
271
+ args
272
+ };
273
+ // SECURITY: IPC is JSON-serialized by Node's child-process
274
+ // plumbing; no references leak.
275
+ process.send!(callMessage);
276
+
277
+ const hostResult = await resultPromise;
278
+ // Return as a JSON string so the isolate receives a primitive
279
+ // it can safely JSON.parse — no copyInto / ExternalCopy needed.
280
+ return JSON.stringify({ ok: hostResult === undefined ? null : hostResult });
281
+ } catch (err) {
282
+ const message = err instanceof Error ? err.message : String(err);
283
+ return JSON.stringify({ __bridgeError: message });
284
+ }
285
+ }
286
+ );
287
+
288
+ await jail.set('_bridgeCall', bridgeCall);
289
+
290
+ // Counter inside the isolate for unique callIds — we use a monotonic
291
+ // counter instead of Math.random() so the sequence is deterministic
292
+ // for debugging and tests.
293
+ await context.eval(`
294
+ globalThis.__bridgeCallSeq = 0;
295
+ globalThis.__bridgeCall = async function(functionName, args) {
296
+ const callId = 'bc-' + (++globalThis.__bridgeCallSeq);
297
+ const argsJson = JSON.stringify(args ?? null);
298
+ // Reference.apply returns a Promise when called from inside
299
+ // an isolate. { result: { promise: true } } tells isolated-vm
300
+ // that the host callback returns a Promise it should await
301
+ // before resolving. The result is a primitive string, which
302
+ // transfers cleanly without needing ExternalCopy.
303
+ const envelope = await _bridgeCall.apply(
304
+ undefined,
305
+ [callId, functionName, argsJson],
306
+ { result: { promise: true } }
307
+ );
308
+ const parsed = envelope ? JSON.parse(envelope) : null;
309
+ if (parsed && parsed.__bridgeError) {
310
+ throw new Error(parsed.__bridgeError);
311
+ }
312
+ // Envelope is always { ok: value } on success.
313
+ return parsed ? parsed.ok : null;
314
+ };
315
+ `);
316
+
134
317
  // Set up module cache for require()
135
318
  await jail.set('_moduleCache', new ivm.Reference({}));
136
319
 
@@ -193,8 +376,14 @@ async function executeInIsolate(params: CodeExecutionParams): Promise<CodeExecut
193
376
  // return the IIFE's return value - we need to extract it from the context
194
377
  await jail.set('_output', undefined);
195
378
 
379
+ // Now that the bridge can be awaited, user code may be async. Wrap in
380
+ // an async IIFE that exposes its return value via globalThis._output.
381
+ // The script.run() call below awaits the script completion (the IIFE
382
+ // itself returns a Promise, and with `promise: true` script.run
383
+ // awaits it). Back-compat: code that does NOT use await still works
384
+ // because the wrapper is an async function.
196
385
  const wrappedCode = `
197
- (function() {
386
+ (async function() {
198
387
  let output;
199
388
  ${params.code}
200
389
  globalThis._output = output;
@@ -205,7 +394,9 @@ async function executeInIsolate(params: CodeExecutionParams): Promise<CodeExecut
205
394
  // CVE-2022-39266: Never use cachedData from untrusted sources
206
395
  // We do NOT pass any cachedData parameter here - only compile from source
207
396
  const script = await isolate.compileScript(wrappedCode);
208
- await script.run(context, { timeout: timeoutMs });
397
+ // `promise: true` ensures script.run awaits the IIFE's returned Promise
398
+ // so await __bridgeCall(...) inside user code works end-to-end.
399
+ await script.run(context, { timeout: timeoutMs, promise: true });
209
400
 
210
401
  // SECURITY: Extract output value - use .copySync() to get plain data, not References
211
402
  // This ensures no ivm objects leak back to caller
@@ -248,6 +439,16 @@ async function executeInIsolate(params: CodeExecutionParams): Promise<CodeExecut
248
439
  };
249
440
 
250
441
  } finally {
442
+ // Clean up bridge state — reject any promises that didn't resolve
443
+ // naturally (e.g. execution threw before a bridge call returned).
444
+ const state = bridgeStates.get(requestId);
445
+ if (state) {
446
+ for (const [, entry] of state.pending) {
447
+ entry.reject(new Error('Execution ended with pending bridge call'));
448
+ }
449
+ bridgeStates.delete(requestId);
450
+ }
451
+
251
452
  // Clean up resources
252
453
  if (context) {
253
454
  context.release();
@@ -278,10 +479,10 @@ function formatConsoleArg(arg: any): string {
278
479
  * Handle messages from parent process via IPC
279
480
  * Messages are automatically JSON serialized/deserialized by Node.js
280
481
  */
281
- process.on('message', async (message: WorkerMessage) => {
482
+ process.on('message', async (message: ParentInboundMessage) => {
282
483
  if (message.type === 'execute') {
283
484
  try {
284
- const result = await executeInIsolate(message.params);
485
+ const result = await executeInIsolate(message.params, message.requestId);
285
486
  const response: ResultMessage = {
286
487
  type: 'result',
287
488
  requestId: message.requestId,
@@ -297,8 +498,54 @@ process.on('message', async (message: WorkerMessage) => {
297
498
  };
298
499
  process.send!(response);
299
500
  }
501
+ return;
502
+ }
503
+
504
+ if (message.type === 'bridge-response') {
505
+ const state = bridgeStates.get(message.requestId);
506
+ if (!state) {
507
+ // Stale response — execution already ended. Drop silently.
508
+ return;
509
+ }
510
+ const entry = state.pending.get(message.callId);
511
+ if (!entry) {
512
+ // Unknown callId — either it was already aborted or we've got a
513
+ // bug. Drop silently; the server-side WorkerPool would re-issue
514
+ // if it still cared.
515
+ return;
516
+ }
517
+ state.pending.delete(message.callId);
518
+ if (message.error) {
519
+ entry.reject(new Error(message.error));
520
+ } else {
521
+ entry.resolve(message.result);
522
+ }
523
+ return;
524
+ }
525
+
526
+ if (message.type === 'abort') {
527
+ const state = bridgeStates.get(message.requestId);
528
+ if (!state) {
529
+ return;
530
+ }
531
+ state.aborted = true;
532
+ state.abortReason = message.reason;
533
+ const pending = Array.from(state.pending.entries());
534
+ state.pending.clear();
535
+ for (const [, entry] of pending) {
536
+ entry.reject(new Error(message.reason || 'Execution aborted'));
537
+ }
538
+ // Note: we do NOT dispose the isolate from here. isolated-vm's
539
+ // `script.run(..., { timeout })` will still terminate the script
540
+ // when its own deadline fires, and rejecting the pending bridge
541
+ // calls is enough for cooperative user code to unwind.
542
+ return;
300
543
  }
301
544
  });
302
545
 
546
+ // Export nothing — this file is only executed as a child process entrypoint.
547
+ // The ParentOutboundMessage type is exported via the types module instead.
548
+ void ({} as ParentOutboundMessage);
549
+
303
550
  // Signal that worker is ready to accept work
304
551
  process.send!({ type: 'ready' });