@memberjunction/code-execution 2.115.0 → 2.117.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,359 @@
1
+ /**
2
+ * Library Provider for isolated-vm
3
+ *
4
+ * This module provides allowlisted utility libraries to sandboxed code.
5
+ * Libraries are provided as inline implementations or bundled source code.
6
+ *
7
+ * SECURITY NOTE: Only add libraries here that are safe for untrusted code execution.
8
+ */
9
+
10
+ /**
11
+ * Allowed module names
12
+ */
13
+ export const ALLOWED_MODULES = [
14
+ 'lodash',
15
+ 'date-fns',
16
+ 'uuid',
17
+ 'validator'
18
+ ] as const;
19
+
20
+ export type AllowedModule = typeof ALLOWED_MODULES[number];
21
+
22
+ /**
23
+ * Check if a module is allowed
24
+ */
25
+ export function isModuleAllowed(moduleName: string): moduleName is AllowedModule {
26
+ return ALLOWED_MODULES.includes(moduleName as AllowedModule);
27
+ }
28
+
29
+ /**
30
+ * Get list of all allowed module names
31
+ */
32
+ export function getAllowedModuleNames(): string[] {
33
+ return [...ALLOWED_MODULES];
34
+ }
35
+
36
+ /**
37
+ * Get the source code for a library module
38
+ * Returns JavaScript code that evaluates to the module exports
39
+ */
40
+ export function getLibrarySource(moduleName: string): string | null {
41
+ if (!isModuleAllowed(moduleName)) {
42
+ return null;
43
+ }
44
+
45
+ switch (moduleName) {
46
+ case 'lodash':
47
+ return getLodashSource();
48
+ case 'date-fns':
49
+ return getDateFnsSource();
50
+ case 'uuid':
51
+ return getUuidSource();
52
+ case 'validator':
53
+ return getValidatorSource();
54
+ default:
55
+ return null;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Lodash subset implementation
61
+ * Provides most commonly used lodash functions inline
62
+ */
63
+ function getLodashSource(): string {
64
+ return `
65
+ (function() {
66
+ const _ = {
67
+ // Array functions
68
+ chunk: function(array, size = 1) {
69
+ const result = [];
70
+ for (let i = 0; i < array.length; i += size) {
71
+ result.push(array.slice(i, i + size));
72
+ }
73
+ return result;
74
+ },
75
+
76
+ compact: function(array) {
77
+ return array.filter(Boolean);
78
+ },
79
+
80
+ flatten: function(array) {
81
+ return array.flat();
82
+ },
83
+
84
+ uniq: function(array) {
85
+ return [...new Set(array)];
86
+ },
87
+
88
+ difference: function(array, ...values) {
89
+ const others = new Set(values.flat());
90
+ return array.filter(x => !others.has(x));
91
+ },
92
+
93
+ intersection: function(...arrays) {
94
+ if (arrays.length === 0) return [];
95
+ const first = new Set(arrays[0]);
96
+ return arrays[0].filter(x => arrays.every(arr => arr.includes(x)));
97
+ },
98
+
99
+ union: function(...arrays) {
100
+ return [...new Set(arrays.flat())];
101
+ },
102
+
103
+ zip: function(...arrays) {
104
+ const maxLength = Math.max(...arrays.map(a => a.length));
105
+ return Array.from({ length: maxLength }, (_, i) => arrays.map(arr => arr[i]));
106
+ },
107
+
108
+ // Collection functions
109
+ groupBy: function(collection, iteratee) {
110
+ const fn = typeof iteratee === 'function' ? iteratee : x => x[iteratee];
111
+ return collection.reduce((result, item) => {
112
+ const key = fn(item);
113
+ (result[key] = result[key] || []).push(item);
114
+ return result;
115
+ }, {});
116
+ },
117
+
118
+ keyBy: function(collection, iteratee) {
119
+ const fn = typeof iteratee === 'function' ? iteratee : x => x[iteratee];
120
+ return collection.reduce((result, item) => {
121
+ result[fn(item)] = item;
122
+ return result;
123
+ }, {});
124
+ },
125
+
126
+ sortBy: function(collection, iteratees) {
127
+ const fns = Array.isArray(iteratees) ? iteratees : [iteratees];
128
+ return [...collection].sort((a, b) => {
129
+ for (const fn of fns) {
130
+ const iteratee = typeof fn === 'function' ? fn : x => x[fn];
131
+ const aVal = iteratee(a);
132
+ const bVal = iteratee(b);
133
+ if (aVal !== bVal) return aVal < bVal ? -1 : 1;
134
+ }
135
+ return 0;
136
+ });
137
+ },
138
+
139
+ // Object functions
140
+ pick: function(object, ...paths) {
141
+ const keys = paths.flat();
142
+ return keys.reduce((result, key) => {
143
+ if (key in object) result[key] = object[key];
144
+ return result;
145
+ }, {});
146
+ },
147
+
148
+ omit: function(object, ...paths) {
149
+ const keys = new Set(paths.flat());
150
+ return Object.keys(object).reduce((result, key) => {
151
+ if (!keys.has(key)) result[key] = object[key];
152
+ return result;
153
+ }, {});
154
+ },
155
+
156
+ mapValues: function(object, iteratee) {
157
+ const fn = typeof iteratee === 'function' ? iteratee : () => iteratee;
158
+ return Object.keys(object).reduce((result, key) => {
159
+ result[key] = fn(object[key], key, object);
160
+ return result;
161
+ }, {});
162
+ },
163
+
164
+ // Utility functions
165
+ get: function(object, path, defaultValue) {
166
+ const paths = Array.isArray(path) ? path : path.split('.');
167
+ let result = object;
168
+ for (const p of paths) {
169
+ result = result?.[p];
170
+ if (result === undefined) return defaultValue;
171
+ }
172
+ return result;
173
+ },
174
+
175
+ set: function(object, path, value) {
176
+ const paths = Array.isArray(path) ? path : path.split('.');
177
+ let current = object;
178
+ for (let i = 0; i < paths.length - 1; i++) {
179
+ const p = paths[i];
180
+ current[p] = current[p] || {};
181
+ current = current[p];
182
+ }
183
+ current[paths[paths.length - 1]] = value;
184
+ return object;
185
+ },
186
+
187
+ sum: function(array) {
188
+ return array.reduce((sum, n) => sum + n, 0);
189
+ },
190
+
191
+ sumBy: function(array, iteratee) {
192
+ const fn = typeof iteratee === 'function' ? iteratee : x => x[iteratee];
193
+ return array.reduce((sum, item) => sum + fn(item), 0);
194
+ },
195
+
196
+ mean: function(array) {
197
+ return array.length ? _.sum(array) / array.length : 0;
198
+ },
199
+
200
+ cloneDeep: function(value) {
201
+ return JSON.parse(JSON.stringify(value));
202
+ }
203
+ };
204
+
205
+ return _;
206
+ })()
207
+ `.trim();
208
+ }
209
+
210
+ /**
211
+ * date-fns subset implementation
212
+ * Provides essential date manipulation functions
213
+ */
214
+ function getDateFnsSource(): string {
215
+ return `
216
+ (function() {
217
+ const dateFns = {
218
+ format: function(date, formatStr) {
219
+ const d = new Date(date);
220
+ const tokens = {
221
+ 'yyyy': d.getFullYear(),
222
+ 'MM': String(d.getMonth() + 1).padStart(2, '0'),
223
+ 'dd': String(d.getDate()).padStart(2, '0'),
224
+ 'HH': String(d.getHours()).padStart(2, '0'),
225
+ 'mm': String(d.getMinutes()).padStart(2, '0'),
226
+ 'ss': String(d.getSeconds()).padStart(2, '0')
227
+ };
228
+ return formatStr.replace(/yyyy|MM|dd|HH|mm|ss/g, match => tokens[match]);
229
+ },
230
+
231
+ addDays: function(date, days) {
232
+ const d = new Date(date);
233
+ d.setDate(d.getDate() + days);
234
+ return d;
235
+ },
236
+
237
+ subDays: function(date, days) {
238
+ return dateFns.addDays(date, -days);
239
+ },
240
+
241
+ addMonths: function(date, months) {
242
+ const d = new Date(date);
243
+ d.setMonth(d.getMonth() + months);
244
+ return d;
245
+ },
246
+
247
+ differenceInDays: function(dateLeft, dateRight) {
248
+ const msPerDay = 1000 * 60 * 60 * 24;
249
+ return Math.floor((new Date(dateLeft) - new Date(dateRight)) / msPerDay);
250
+ },
251
+
252
+ isAfter: function(date, dateToCompare) {
253
+ return new Date(date) > new Date(dateToCompare);
254
+ },
255
+
256
+ isBefore: function(date, dateToCompare) {
257
+ return new Date(date) < new Date(dateToCompare);
258
+ },
259
+
260
+ startOfDay: function(date) {
261
+ const d = new Date(date);
262
+ d.setHours(0, 0, 0, 0);
263
+ return d;
264
+ },
265
+
266
+ endOfDay: function(date) {
267
+ const d = new Date(date);
268
+ d.setHours(23, 59, 59, 999);
269
+ return d;
270
+ },
271
+
272
+ parseISO: function(dateString) {
273
+ return new Date(dateString);
274
+ }
275
+ };
276
+
277
+ return dateFns;
278
+ })()
279
+ `.trim();
280
+ }
281
+
282
+ /**
283
+ * uuid implementation
284
+ * Provides UUID v4 generation
285
+ */
286
+ function getUuidSource(): string {
287
+ return `
288
+ (function() {
289
+ const uuid = {
290
+ v4: function() {
291
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
292
+ const r = Math.random() * 16 | 0;
293
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
294
+ return v.toString(16);
295
+ });
296
+ }
297
+ };
298
+
299
+ return uuid;
300
+ })()
301
+ `.trim();
302
+ }
303
+
304
+ /**
305
+ * validator subset implementation
306
+ * Provides common validation functions
307
+ */
308
+ function getValidatorSource(): string {
309
+ return `
310
+ (function() {
311
+ const validator = {
312
+ isEmail: function(str) {
313
+ const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
314
+ return emailRegex.test(str);
315
+ },
316
+
317
+ isURL: function(str) {
318
+ try {
319
+ new URL(str);
320
+ return true;
321
+ } catch {
322
+ return false;
323
+ }
324
+ },
325
+
326
+ isNumeric: function(str) {
327
+ return /^-?\\d+(\\.\\d+)?$/.test(str);
328
+ },
329
+
330
+ isAlpha: function(str) {
331
+ return /^[A-Za-z]+$/.test(str);
332
+ },
333
+
334
+ isAlphanumeric: function(str) {
335
+ return /^[A-Za-z0-9]+$/.test(str);
336
+ },
337
+
338
+ isEmpty: function(str) {
339
+ return str.length === 0;
340
+ },
341
+
342
+ isLength: function(str, options) {
343
+ const len = str.length;
344
+ return (!options.min || len >= options.min) && (!options.max || len <= options.max);
345
+ },
346
+
347
+ isIn: function(str, values) {
348
+ return values.includes(str);
349
+ },
350
+
351
+ matches: function(str, pattern) {
352
+ return new RegExp(pattern).test(str);
353
+ }
354
+ };
355
+
356
+ return validator;
357
+ })()
358
+ `.trim();
359
+ }
@@ -2,7 +2,9 @@
2
2
  * Library Provider for isolated-vm
3
3
  *
4
4
  * This module provides allowlisted utility libraries to sandboxed code.
5
- * Libraries are provided as inline implementations or bundled source code.
5
+ * Libraries are provided as either:
6
+ * - Inline implementations (lodash, date-fns, uuid, validator) - simpler, hand-coded subsets
7
+ * - Bundled source code (mathjs, papaparse, jstat) - full libraries with complex functionality
6
8
  *
7
9
  * SECURITY NOTE: Only add libraries here that are safe for untrusted code execution.
8
10
  */
@@ -13,6 +15,9 @@
13
15
  export const ALLOWED_MODULES = [
14
16
  'lodash',
15
17
  'date-fns',
18
+ 'mathjs',
19
+ 'papaparse',
20
+ 'jstat',
16
21
  'uuid',
17
22
  'validator'
18
23
  ] as const;
@@ -47,6 +52,12 @@ export function getLibrarySource(moduleName: string): string | null {
47
52
  return getLodashSource();
48
53
  case 'date-fns':
49
54
  return getDateFnsSource();
55
+ case 'mathjs':
56
+ return getMathjsSource();
57
+ case 'papaparse':
58
+ return getPapaparseSource();
59
+ case 'jstat':
60
+ return getJstatSource();
50
61
  case 'uuid':
51
62
  return getUuidSource();
52
63
  case 'validator':
@@ -197,6 +208,12 @@ function getLodashSource(): string {
197
208
  return array.length ? _.sum(array) / array.length : 0;
198
209
  },
199
210
 
211
+ meanBy: function(array, iteratee) {
212
+ const fn = typeof iteratee === 'function' ? iteratee : x => x[iteratee];
213
+ const values = array.map(fn);
214
+ return values.length ? _.sum(values) / values.length : 0;
215
+ },
216
+
200
217
  cloneDeep: function(value) {
201
218
  return JSON.parse(JSON.stringify(value));
202
219
  }
@@ -357,3 +374,69 @@ function getValidatorSource(): string {
357
374
  })()
358
375
  `.trim();
359
376
  }
377
+
378
+ /**
379
+ * mathjs implementation
380
+ * Provides comprehensive mathematics and statistics functions
381
+ * We bundle the actual mathjs library for full functionality
382
+ */
383
+ function getMathjsSource(): string {
384
+ // Load bundled library source at compile time
385
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
386
+ const fs = require('fs');
387
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
388
+ const path = require('path');
389
+
390
+ const libPath = path.join(__dirname, 'bundled-libs', 'mathjs.js');
391
+ const source = fs.readFileSync(libPath, 'utf8');
392
+
393
+ // Wrap in IIFE that returns the math object
394
+ return `(function() {
395
+ ${source}
396
+ return math;
397
+ })()`;
398
+ }
399
+
400
+ /**
401
+ * papaparse implementation
402
+ * Provides CSV parsing and generation
403
+ * We bundle the actual papaparse library
404
+ */
405
+ function getPapaparseSource(): string {
406
+ // Load bundled library source at compile time
407
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
408
+ const fs = require('fs');
409
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
410
+ const path = require('path');
411
+
412
+ const libPath = path.join(__dirname, 'bundled-libs', 'papaparse.js');
413
+ const source = fs.readFileSync(libPath, 'utf8');
414
+
415
+ // Wrap in IIFE that returns the Papa object
416
+ return `(function() {
417
+ ${source}
418
+ return Papa;
419
+ })()`;
420
+ }
421
+
422
+ /**
423
+ * jstat implementation
424
+ * Provides statistical distributions, hypothesis testing, and regression
425
+ * We bundle the actual jstat library
426
+ */
427
+ function getJstatSource(): string {
428
+ // Load bundled library source at compile time
429
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
430
+ const fs = require('fs');
431
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
432
+ const path = require('path');
433
+
434
+ const libPath = path.join(__dirname, 'bundled-libs', 'jstat.js');
435
+ const source = fs.readFileSync(libPath, 'utf8');
436
+
437
+ // Wrap in IIFE that returns the jStat object
438
+ return `(function() {
439
+ ${source}
440
+ return jStat;
441
+ })()`;
442
+ }
package/src/worker.ts CHANGED
@@ -136,7 +136,8 @@ async function executeInIsolate(params: CodeExecutionParams): Promise<CodeExecut
136
136
 
137
137
  // SECURITY: Create require() function with strict module allowlisting
138
138
  // This ivm.Reference is safe - it's a loader function we control
139
- const requireFunc = new ivm.Reference(async (moduleName: string) => {
139
+ // CRITICAL: Must be synchronous (not async) - see file header comments for why
140
+ const requireFunc = new ivm.Reference((moduleName: string) => {
140
141
  const blockedModules = ['fs', 'path', 'http', 'https', 'net', 'child_process', 'cluster', 'os', 'process', 'axios'];
141
142
 
142
143
  // Check if module is blocked
@@ -188,11 +189,15 @@ async function executeInIsolate(params: CodeExecutionParams): Promise<CodeExecut
188
189
  `);
189
190
 
190
191
  // Wrap user code to capture output
192
+ // We store output in globalThis._output because script.run() doesn't reliably
193
+ // return the IIFE's return value - we need to extract it from the context
194
+ await jail.set('_output', undefined);
195
+
191
196
  const wrappedCode = `
192
197
  (function() {
193
198
  let output;
194
199
  ${params.code}
195
- return output;
200
+ globalThis._output = output;
196
201
  })();
197
202
  `;
198
203
 
@@ -200,15 +205,16 @@ async function executeInIsolate(params: CodeExecutionParams): Promise<CodeExecut
200
205
  // CVE-2022-39266: Never use cachedData from untrusted sources
201
206
  // We do NOT pass any cachedData parameter here - only compile from source
202
207
  const script = await isolate.compileScript(wrappedCode);
203
- const result = await script.run(context, { timeout: timeoutMs });
208
+ await script.run(context, { timeout: timeoutMs });
204
209
 
205
- // SECURITY: Extract output value - use .copy() to get plain data, not References
210
+ // SECURITY: Extract output value - use .copySync() to get plain data, not References
206
211
  // This ensures no ivm objects leak back to caller
212
+ const outputRef = await jail.get('_output');
207
213
  let output: any;
208
- if (result && typeof result === 'object' && 'copy' in result) {
209
- output = await result.copy();
214
+ if (outputRef && typeof outputRef === 'object' && 'copySync' in outputRef) {
215
+ output = outputRef.copySync();
210
216
  } else {
211
- output = result;
217
+ output = outputRef;
212
218
  }
213
219
 
214
220
  return {
@@ -0,0 +1,114 @@
1
+ const { CodeExecutionService } = require('./dist/index.js');
2
+
3
+ async function testAllLibraries() {
4
+ const service = new CodeExecutionService();
5
+ await service.initialize();
6
+
7
+ const tests = [
8
+ {
9
+ name: 'lodash',
10
+ code: `
11
+ const _ = require('lodash');
12
+ const numbers = [1, 2, 3, 4, 5];
13
+ output = { sum: _.sum(numbers), mean: _.mean(numbers) };
14
+ `
15
+ },
16
+ {
17
+ name: 'date-fns',
18
+ code: `
19
+ const { format, addDays } = require('date-fns');
20
+ const today = new Date('2025-01-01');
21
+ const future = addDays(today, 7);
22
+ output = { formatted: format(future, 'yyyy-MM-dd') };
23
+ `
24
+ },
25
+ {
26
+ name: 'uuid',
27
+ code: `
28
+ const { v4 } = require('uuid');
29
+ const id = v4();
30
+ output = { hasUUID: id.length === 36 && id.includes('-') };
31
+ `
32
+ },
33
+ {
34
+ name: 'validator',
35
+ code: `
36
+ const validator = require('validator');
37
+ output = {
38
+ email: validator.isEmail('test@example.com'),
39
+ notEmail: validator.isEmail('notanemail')
40
+ };
41
+ `
42
+ },
43
+ {
44
+ name: 'mathjs',
45
+ code: `
46
+ const math = require('mathjs');
47
+ const values = [1, 2, 3, 4, 5];
48
+ output = {
49
+ mean: math.mean(values),
50
+ median: math.median(values),
51
+ std: math.std(values)
52
+ };
53
+ `
54
+ },
55
+ {
56
+ name: 'papaparse',
57
+ code: `
58
+ const Papa = require('papaparse');
59
+ const csv = 'name,age\\nAlice,30\\nBob,25';
60
+ const parsed = Papa.parse(csv, { header: true });
61
+ output = { rowCount: parsed.data.length };
62
+ `
63
+ },
64
+ {
65
+ name: 'jstat',
66
+ code: `
67
+ const jStat = require('jstat');
68
+ const values = [1, 2, 3, 4, 5];
69
+ output = {
70
+ mean: jStat.mean(values),
71
+ stdev: jStat.stdev(values)
72
+ };
73
+ `
74
+ }
75
+ ];
76
+
77
+ console.log('\n========================================');
78
+ console.log('Testing All 7 Libraries');
79
+ console.log('========================================\n');
80
+
81
+ let passed = 0;
82
+ let failed = 0;
83
+
84
+ for (const test of tests) {
85
+ console.log(`\nTesting ${test.name}...`);
86
+ const result = await service.execute({
87
+ code: test.code,
88
+ language: 'javascript'
89
+ });
90
+
91
+ if (result.success && result.output) {
92
+ console.log(`✅ ${test.name}: PASS`);
93
+ console.log(` Output:`, JSON.stringify(result.output, null, 2));
94
+ passed++;
95
+ } else {
96
+ console.log(`❌ ${test.name}: FAIL`);
97
+ console.log(` Error: ${result.error}`);
98
+ console.log(` Output:`, result.output);
99
+ failed++;
100
+ }
101
+ }
102
+
103
+ console.log('\n========================================');
104
+ console.log(`Results: ${passed} passed, ${failed} failed`);
105
+ console.log('========================================\n');
106
+
107
+ await service.shutdown();
108
+ process.exit(failed > 0 ? 1 : 0);
109
+ }
110
+
111
+ testAllLibraries().catch(err => {
112
+ console.error('Test suite error:', err);
113
+ process.exit(1);
114
+ });