@memberjunction/code-execution 2.108.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,298 @@
1
+ /**
2
+ * @fileoverview Sandboxed code execution service for MemberJunction
3
+ *
4
+ * Provides secure execution of JavaScript code in a controlled environment using vm2.
5
+ * Supports a curated list of safe npm packages for data manipulation and analysis.
6
+ *
7
+ * @module @memberjunction/code-execution
8
+ * @author MemberJunction.com
9
+ * @since 2.46.0
10
+ */
11
+
12
+ import { LogError, LogStatus } from '@memberjunction/core';
13
+ import {
14
+ CodeExecutionParams,
15
+ CodeExecutionResult,
16
+ JavaScriptExecutionOptions
17
+ } from './types';
18
+
19
+ /**
20
+ * Service for executing code in a sandboxed environment
21
+ *
22
+ * Security features:
23
+ * - Isolated VM using vm2's NodeVM
24
+ * - Timeout protection
25
+ * - No filesystem access (fs module mocked)
26
+ * - No network access (http, https, net modules blocked)
27
+ * - Allowlist-only npm package imports
28
+ * - Memory limits (requires Node.js process flags)
29
+ *
30
+ * Supported libraries:
31
+ * - lodash: Data manipulation
32
+ * - date-fns: Date utilities
33
+ * - mathjs: Advanced mathematics
34
+ * - papaparse: CSV parsing
35
+ * - uuid: ID generation
36
+ * - validator: Input validation
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * const service = new CodeExecutionService();
41
+ * const result = await service.execute({
42
+ * code: 'const sum = input.values.reduce((a,b) => a+b, 0); output = sum;',
43
+ * language: 'javascript',
44
+ * inputData: { values: [1, 2, 3, 4, 5] }
45
+ * });
46
+ * console.log(result.output); // 15
47
+ * ```
48
+ */
49
+ export class CodeExecutionService {
50
+ /**
51
+ * List of npm packages that are safe to import
52
+ * These packages have been vetted for security and don't provide
53
+ * filesystem, network, or process access
54
+ */
55
+ private readonly SAFE_LIBRARIES = [
56
+ 'lodash', // Data manipulation and utilities
57
+ 'date-fns', // Modern date utility library
58
+ 'mathjs', // Extended math library
59
+ 'papaparse', // CSV parsing
60
+ 'uuid', // UUID generation
61
+ 'validator' // String validators and sanitizers
62
+ ];
63
+
64
+ /**
65
+ * Execute code in a sandboxed environment
66
+ *
67
+ * @param params - Execution parameters including code and input data
68
+ * @returns Promise resolving to execution result
69
+ */
70
+ async execute(params: CodeExecutionParams): Promise<CodeExecutionResult> {
71
+ const startTime = Date.now();
72
+
73
+ // Validate language
74
+ if (params.language !== 'javascript') {
75
+ return {
76
+ success: false,
77
+ errorType: 'SECURITY_ERROR',
78
+ error: `Unsupported language: ${params.language}. Only 'javascript' is supported.`
79
+ };
80
+ }
81
+
82
+ // Validate code is provided
83
+ if (!params.code || params.code.trim().length === 0) {
84
+ return {
85
+ success: false,
86
+ errorType: 'RUNTIME_ERROR',
87
+ error: 'Code parameter is required and cannot be empty'
88
+ };
89
+ }
90
+
91
+ // Set default options
92
+ const options: JavaScriptExecutionOptions = {
93
+ timeout: params.timeoutSeconds || 30,
94
+ memoryLimit: params.memoryLimitMB || 128,
95
+ allowedLibraries: this.SAFE_LIBRARIES
96
+ };
97
+
98
+ // Execute JavaScript
99
+ const result = await this.executeJavaScript(
100
+ params.code,
101
+ params.inputData,
102
+ options
103
+ );
104
+
105
+ result.executionTimeMs = Date.now() - startTime;
106
+ return result;
107
+ }
108
+
109
+ /**
110
+ * Execute JavaScript code using vm2 NodeVM sandbox
111
+ *
112
+ * The code has access to:
113
+ * - input: The inputData parameter
114
+ * - output: Variable where code should store result
115
+ * - console: Limited console API (log, error, warn, info)
116
+ * - Safe libraries: Can require() packages from allowlist
117
+ * - Safe built-ins: JSON, Math, Date, Array, Object, String, Number, Boolean
118
+ *
119
+ * The code does NOT have access to:
120
+ * - File system (fs module is mocked)
121
+ * - Network (http, https, net, axios, etc. are blocked)
122
+ * - Process control (child_process, cluster blocked)
123
+ * - Dangerous APIs (eval, Function constructor are disabled)
124
+ *
125
+ * @private
126
+ */
127
+ private async executeJavaScript(
128
+ code: string,
129
+ inputData: any,
130
+ options: JavaScriptExecutionOptions
131
+ ): Promise<CodeExecutionResult> {
132
+ try {
133
+ // Dynamic import of vm2 (it may not be available in all environments)
134
+ let NodeVM: any;
135
+ try {
136
+ const vm2 = require('vm2');
137
+ NodeVM = vm2.NodeVM;
138
+ } catch (importError) {
139
+ return {
140
+ success: false,
141
+ errorType: 'RUNTIME_ERROR',
142
+ error: 'vm2 package is not installed. Run: npm install vm2'
143
+ };
144
+ }
145
+
146
+ const logs: string[] = [];
147
+
148
+ // Create sandbox context
149
+ const sandbox = {
150
+ input: inputData,
151
+ output: null,
152
+ console: {
153
+ log: (...args: any[]) => {
154
+ logs.push(args.map(arg => this.formatConsoleArg(arg)).join(' '));
155
+ },
156
+ error: (...args: any[]) => {
157
+ logs.push('ERROR: ' + args.map(arg => this.formatConsoleArg(arg)).join(' '));
158
+ },
159
+ warn: (...args: any[]) => {
160
+ logs.push('WARN: ' + args.map(arg => this.formatConsoleArg(arg)).join(' '));
161
+ },
162
+ info: (...args: any[]) => {
163
+ logs.push('INFO: ' + args.map(arg => this.formatConsoleArg(arg)).join(' '));
164
+ }
165
+ },
166
+ // Provide safe global objects
167
+ JSON,
168
+ Math,
169
+ Date,
170
+ Array,
171
+ Object,
172
+ String,
173
+ Number,
174
+ Boolean,
175
+ // Note: setTimeout, setInterval, etc. are not provided to prevent async abuse
176
+ };
177
+
178
+ // Create VM with security restrictions
179
+ const vm = new NodeVM({
180
+ timeout: options.timeout * 1000, // Convert to milliseconds
181
+ sandbox,
182
+
183
+ // Disable dangerous features
184
+ eval: false, // Disable eval()
185
+ wasm: false, // Disable WebAssembly
186
+ fixAsync: true, // Prevent async abuse
187
+
188
+ // Configure module imports
189
+ require: {
190
+ external: options.allowedLibraries || this.SAFE_LIBRARIES,
191
+ builtin: [], // No built-in Node modules (like fs, path, etc.)
192
+ root: './node_modules',
193
+
194
+ // Mock dangerous modules
195
+ mock: {
196
+ fs: {}, // Block filesystem
197
+ 'fs/promises': {}, // Block async filesystem
198
+ http: {}, // Block HTTP
199
+ https: {}, // Block HTTPS
200
+ net: {}, // Block raw network
201
+ dgram: {}, // Block UDP
202
+ child_process: {}, // Block process spawning
203
+ cluster: {}, // Block clustering
204
+ worker_threads: {}, // Block workers
205
+ os: {}, // Block OS info
206
+ process: {}, // Block process control
207
+ // Block popular HTTP clients
208
+ axios: {},
209
+ 'node-fetch': {},
210
+ got: {},
211
+ superagent: {},
212
+ request: {}
213
+ }
214
+ }
215
+ });
216
+
217
+ // Wrap code to properly capture output
218
+ // The code runs in module scope, so we need to export the output
219
+ const wrappedCode = `
220
+ module.exports = (function() {
221
+ ${code}
222
+ return output;
223
+ })();
224
+ `;
225
+
226
+ // Execute the code
227
+ const result = vm.run(wrappedCode, 'user-code.js');
228
+
229
+ return {
230
+ success: true,
231
+ output: result,
232
+ logs: logs.length > 0 ? logs : undefined
233
+ };
234
+
235
+ } catch (error: any) {
236
+ // Handle different types of errors
237
+ if (error.message?.includes('Script execution timed out')) {
238
+ return {
239
+ success: false,
240
+ errorType: 'TIMEOUT',
241
+ error: `Code execution exceeded ${options.timeout} second timeout`,
242
+ logs: []
243
+ };
244
+ }
245
+
246
+ if (error instanceof SyntaxError) {
247
+ return {
248
+ success: false,
249
+ errorType: 'SYNTAX_ERROR',
250
+ error: `Syntax error: ${error.message}`,
251
+ logs: []
252
+ };
253
+ }
254
+
255
+ // Check for security violations
256
+ if (error.message?.includes('not allowed') ||
257
+ error.message?.includes('access denied') ||
258
+ error.message?.includes('Cannot find module')) {
259
+ return {
260
+ success: false,
261
+ errorType: 'SECURITY_ERROR',
262
+ error: `Security violation: ${error.message}`,
263
+ logs: []
264
+ };
265
+ }
266
+
267
+ // Generic runtime error
268
+ LogError(`Code execution error: ${error.message}`, error);
269
+ return {
270
+ success: false,
271
+ errorType: 'RUNTIME_ERROR',
272
+ error: error.message || 'Unknown error during code execution',
273
+ logs: []
274
+ };
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Format console arguments for logging
280
+ * Handles objects, arrays, and primitives
281
+ *
282
+ * @private
283
+ */
284
+ private formatConsoleArg(arg: any): string {
285
+ if (arg === null) return 'null';
286
+ if (arg === undefined) return 'undefined';
287
+
288
+ if (typeof arg === 'object') {
289
+ try {
290
+ return JSON.stringify(arg, null, 2);
291
+ } catch {
292
+ return String(arg);
293
+ }
294
+ }
295
+
296
+ return String(arg);
297
+ }
298
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @module @memberjunction/code-execution
3
+ * @description Sandboxed code execution service for MemberJunction
4
+ */
5
+
6
+ export * from './CodeExecutionService';
7
+ export * from './types';
8
+ export * from './libraries';
@@ -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
+ }