@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.
- package/.turbo/turbo-build.log +4 -0
- package/CHANGELOG.md +8 -0
- package/README.md +312 -0
- package/dist/CodeExecutionService.d.ts +44 -0
- package/dist/CodeExecutionService.d.ts.map +1 -0
- package/dist/CodeExecutionService.js +253 -0
- package/dist/CodeExecutionService.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/dist/libraries/index.d.ts +27 -0
- package/dist/libraries/index.d.ts.map +1 -0
- package/dist/libraries/index.js +355 -0
- package/dist/libraries/index.js.map +1 -0
- package/dist/types/index.d.ts +95 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +3 -0
- package/dist/types/index.js.map +1 -0
- package/package.json +39 -0
- package/security-research.md +226 -0
- package/src/CodeExecutionService.ts +267 -0
- package/src/CodeExecutionService.ts.backup +298 -0
- package/src/index.ts +8 -0
- package/src/libraries/index.ts +359 -0
- package/src/types/index.ts +110 -0
- package/tsconfig.json +25 -0
package/CHANGELOG.md
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
# @memberjunction/code-execution
|
|
2
|
+
|
|
3
|
+
Sandboxed JavaScript code execution service for MemberJunction AI agents and workflows.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
This package provides secure, isolated execution of JavaScript code in a sandboxed environment using vm2. It's designed to enable AI agents to generate and run code for data analysis, transformations, and calculations without compromising system security.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- **Secure Sandboxing**: Executes code in isolated VM with no filesystem or network access
|
|
12
|
+
- **Timeout Protection**: Configurable execution timeouts (default: 30 seconds)
|
|
13
|
+
- **Safe Library Access**: Curated allowlist of npm packages for data manipulation
|
|
14
|
+
- **Console Logging**: Captures console output for debugging
|
|
15
|
+
- **Type Safety**: Full TypeScript support with comprehensive interfaces
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @memberjunction/code-execution
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
### Direct TypeScript Usage
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
import { CodeExecutionService } from '@memberjunction/code-execution';
|
|
29
|
+
|
|
30
|
+
const service = new CodeExecutionService();
|
|
31
|
+
|
|
32
|
+
const result = await service.execute({
|
|
33
|
+
code: `
|
|
34
|
+
const sum = input.values.reduce((a, b) => a + b, 0);
|
|
35
|
+
const average = sum / input.values.length;
|
|
36
|
+
output = { sum, average };
|
|
37
|
+
`,
|
|
38
|
+
language: 'javascript',
|
|
39
|
+
inputData: { values: [10, 20, 30, 40, 50] }
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
if (result.success) {
|
|
43
|
+
console.log(result.output); // { sum: 150, average: 30 }
|
|
44
|
+
console.log(result.logs); // Any console.log output from the code
|
|
45
|
+
} else {
|
|
46
|
+
console.error(result.error);
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### With Actions (for AI Agents)
|
|
51
|
+
|
|
52
|
+
Agents use the "Execute Code" action:
|
|
53
|
+
|
|
54
|
+
```json
|
|
55
|
+
{
|
|
56
|
+
"type": "Action",
|
|
57
|
+
"action": {
|
|
58
|
+
"name": "Execute Code",
|
|
59
|
+
"params": {
|
|
60
|
+
"code": "const total = input.prices.reduce((sum, p) => sum + p, 0); output = total;",
|
|
61
|
+
"language": "javascript",
|
|
62
|
+
"inputData": "{\"prices\": [10, 20, 30]}"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Supported Libraries
|
|
69
|
+
|
|
70
|
+
The sandbox includes these pre-approved npm packages:
|
|
71
|
+
|
|
72
|
+
- **lodash** - Data manipulation and utilities
|
|
73
|
+
- **date-fns** - Modern date library
|
|
74
|
+
- **mathjs** - Advanced mathematics
|
|
75
|
+
- **papaparse** - CSV parsing
|
|
76
|
+
- **uuid** - UUID generation
|
|
77
|
+
- **validator** - String validation and sanitization
|
|
78
|
+
|
|
79
|
+
### Using Libraries in Code
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
const result = await service.execute({
|
|
83
|
+
code: `
|
|
84
|
+
const _ = require('lodash');
|
|
85
|
+
const { format, addDays } = require('date-fns');
|
|
86
|
+
const math = require('mathjs');
|
|
87
|
+
|
|
88
|
+
// Group data by category
|
|
89
|
+
const grouped = _.groupBy(input.data, 'category');
|
|
90
|
+
|
|
91
|
+
// Calculate statistics
|
|
92
|
+
const stats = {};
|
|
93
|
+
for (const [category, items] of Object.entries(grouped)) {
|
|
94
|
+
const values = items.map(i => i.value);
|
|
95
|
+
stats[category] = {
|
|
96
|
+
mean: math.mean(values),
|
|
97
|
+
median: math.median(values),
|
|
98
|
+
total: math.sum(values)
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
output = stats;
|
|
103
|
+
`,
|
|
104
|
+
language: 'javascript',
|
|
105
|
+
inputData: {
|
|
106
|
+
data: [
|
|
107
|
+
{ category: 'A', value: 10 },
|
|
108
|
+
{ category: 'B', value: 20 },
|
|
109
|
+
{ category: 'A', value: 15 }
|
|
110
|
+
]
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Security Model
|
|
116
|
+
|
|
117
|
+
### What Code CAN Do
|
|
118
|
+
|
|
119
|
+
- Access input data via `input` variable
|
|
120
|
+
- Set output data via `output` variable
|
|
121
|
+
- Use console methods (log, error, warn, info)
|
|
122
|
+
- Require allowed npm packages
|
|
123
|
+
- Perform calculations and data transformations
|
|
124
|
+
- Use safe built-in objects (JSON, Math, Date, Array, Object, String, Number, Boolean)
|
|
125
|
+
|
|
126
|
+
### What Code CANNOT Do
|
|
127
|
+
|
|
128
|
+
- Access filesystem (`fs` module is mocked)
|
|
129
|
+
- Make network requests (`http`, `https`, `net`, `axios` are blocked)
|
|
130
|
+
- Spawn processes (`child_process` is blocked)
|
|
131
|
+
- Access environment variables
|
|
132
|
+
- Use `eval()` or `Function` constructor
|
|
133
|
+
- Run indefinitely (timeout enforced)
|
|
134
|
+
|
|
135
|
+
## API Reference
|
|
136
|
+
|
|
137
|
+
### CodeExecutionService
|
|
138
|
+
|
|
139
|
+
#### `execute(params: CodeExecutionParams): Promise<CodeExecutionResult>`
|
|
140
|
+
|
|
141
|
+
Executes code in a sandboxed environment.
|
|
142
|
+
|
|
143
|
+
**Parameters:**
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
interface CodeExecutionParams {
|
|
147
|
+
code: string; // JavaScript code to execute
|
|
148
|
+
language: 'javascript'; // Currently only 'javascript' supported
|
|
149
|
+
inputData?: any; // Data available as 'input' variable
|
|
150
|
+
timeoutSeconds?: number; // Execution timeout (default: 30)
|
|
151
|
+
memoryLimitMB?: number; // Memory limit (default: 128)
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
**Returns:**
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
interface CodeExecutionResult {
|
|
159
|
+
success: boolean; // Whether execution succeeded
|
|
160
|
+
output?: any; // Value of 'output' variable
|
|
161
|
+
logs?: string[]; // Console output
|
|
162
|
+
error?: string; // Error message if failed
|
|
163
|
+
errorType?: 'TIMEOUT' | 'MEMORY_LIMIT' | 'SYNTAX_ERROR' | 'RUNTIME_ERROR' | 'SECURITY_ERROR';
|
|
164
|
+
executionTimeMs?: number; // Execution duration
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## Error Handling
|
|
169
|
+
|
|
170
|
+
The service handles various error conditions gracefully:
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
const result = await service.execute({
|
|
174
|
+
code: 'invalid syntax here',
|
|
175
|
+
language: 'javascript'
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
if (!result.success) {
|
|
179
|
+
switch (result.errorType) {
|
|
180
|
+
case 'SYNTAX_ERROR':
|
|
181
|
+
console.error('Code has syntax errors:', result.error);
|
|
182
|
+
break;
|
|
183
|
+
case 'TIMEOUT':
|
|
184
|
+
console.error('Code execution timed out');
|
|
185
|
+
break;
|
|
186
|
+
case 'RUNTIME_ERROR':
|
|
187
|
+
console.error('Runtime error:', result.error);
|
|
188
|
+
break;
|
|
189
|
+
case 'SECURITY_ERROR':
|
|
190
|
+
console.error('Security violation:', result.error);
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
## Examples
|
|
197
|
+
|
|
198
|
+
### Data Analysis
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
const result = await service.execute({
|
|
202
|
+
code: `
|
|
203
|
+
const _ = require('lodash');
|
|
204
|
+
|
|
205
|
+
// Calculate key metrics
|
|
206
|
+
const metrics = {
|
|
207
|
+
totalSales: _.sumBy(input.sales, 'amount'),
|
|
208
|
+
avgSale: _.meanBy(input.sales, 'amount'),
|
|
209
|
+
topProducts: _.chain(input.sales)
|
|
210
|
+
.groupBy('product')
|
|
211
|
+
.map((items, product) => ({
|
|
212
|
+
product,
|
|
213
|
+
revenue: _.sumBy(items, 'amount')
|
|
214
|
+
}))
|
|
215
|
+
.orderBy('revenue', 'desc')
|
|
216
|
+
.take(5)
|
|
217
|
+
.value()
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
output = metrics;
|
|
221
|
+
`,
|
|
222
|
+
language: 'javascript',
|
|
223
|
+
inputData: {
|
|
224
|
+
sales: [
|
|
225
|
+
{ product: 'Widget', amount: 100 },
|
|
226
|
+
{ product: 'Gadget', amount: 200 },
|
|
227
|
+
// ... more sales
|
|
228
|
+
]
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### Date Manipulation
|
|
234
|
+
|
|
235
|
+
```typescript
|
|
236
|
+
const result = await service.execute({
|
|
237
|
+
code: `
|
|
238
|
+
const { format, addDays, differenceInDays } = require('date-fns');
|
|
239
|
+
|
|
240
|
+
const start = new Date(input.startDate);
|
|
241
|
+
const end = new Date(input.endDate);
|
|
242
|
+
|
|
243
|
+
output = {
|
|
244
|
+
duration: differenceInDays(end, start),
|
|
245
|
+
milestones: [
|
|
246
|
+
format(addDays(start, 30), 'yyyy-MM-dd'),
|
|
247
|
+
format(addDays(start, 60), 'yyyy-MM-dd'),
|
|
248
|
+
format(addDays(start, 90), 'yyyy-MM-dd')
|
|
249
|
+
]
|
|
250
|
+
};
|
|
251
|
+
`,
|
|
252
|
+
language: 'javascript',
|
|
253
|
+
inputData: {
|
|
254
|
+
startDate: '2025-01-01',
|
|
255
|
+
endDate: '2025-12-31'
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
### CSV Processing
|
|
261
|
+
|
|
262
|
+
```typescript
|
|
263
|
+
const result = await service.execute({
|
|
264
|
+
code: `
|
|
265
|
+
const Papa = require('papaparse');
|
|
266
|
+
|
|
267
|
+
const parsed = Papa.parse(input.csvData, {
|
|
268
|
+
header: true,
|
|
269
|
+
dynamicTyping: true
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
// Filter and transform
|
|
273
|
+
const processed = parsed.data
|
|
274
|
+
.filter(row => row.status === 'active')
|
|
275
|
+
.map(row => ({
|
|
276
|
+
id: row.id,
|
|
277
|
+
name: row.name,
|
|
278
|
+
value: row.value * 1.1 // 10% markup
|
|
279
|
+
}));
|
|
280
|
+
|
|
281
|
+
output = processed;
|
|
282
|
+
`,
|
|
283
|
+
language: 'javascript',
|
|
284
|
+
inputData: {
|
|
285
|
+
csvData: 'id,name,value,status\n1,Item A,100,active\n2,Item B,200,inactive'
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
## Best Practices
|
|
291
|
+
|
|
292
|
+
1. **Set Appropriate Timeouts**: Adjust `timeoutSeconds` based on expected workload
|
|
293
|
+
2. **Validate Input Data**: Ensure input data is in expected format before execution
|
|
294
|
+
3. **Handle Errors Gracefully**: Always check `result.success` before using `result.output`
|
|
295
|
+
4. **Use Console Logging**: Add `console.log()` statements for debugging
|
|
296
|
+
5. **Leverage Libraries**: Use lodash, mathjs, etc. instead of reinventing the wheel
|
|
297
|
+
6. **Keep Code Focused**: Break complex logic into smaller execution chunks
|
|
298
|
+
|
|
299
|
+
## Limitations
|
|
300
|
+
|
|
301
|
+
- **Language Support**: Currently only JavaScript (Python may be added in future)
|
|
302
|
+
- **Async Code**: No support for `async/await` or Promises (synchronous code only)
|
|
303
|
+
- **Memory**: No hard memory limits enforced (relies on Node.js process limits)
|
|
304
|
+
- **Library Expansion**: New libraries require code changes (not configurable at runtime)
|
|
305
|
+
|
|
306
|
+
## Contributing
|
|
307
|
+
|
|
308
|
+
This package is part of the MemberJunction project. See the main repository for contribution guidelines.
|
|
309
|
+
|
|
310
|
+
## License
|
|
311
|
+
|
|
312
|
+
ISC
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Code Execution Service
|
|
3
|
+
*
|
|
4
|
+
* Provides secure, sandboxed execution of JavaScript code using isolated-vm.
|
|
5
|
+
* This service enables AI agents and workflows to generate and run code safely
|
|
6
|
+
* without compromising system security.
|
|
7
|
+
*
|
|
8
|
+
* Security Model:
|
|
9
|
+
* - Uses isolated-vm for true V8 isolate separation
|
|
10
|
+
* - No filesystem access (fs module blocked)
|
|
11
|
+
* - No network access (http/https/net modules blocked)
|
|
12
|
+
* - Configurable timeout and memory limits
|
|
13
|
+
* - Curated allowlist of safe npm packages
|
|
14
|
+
*
|
|
15
|
+
* @module @memberjunction/code-execution
|
|
16
|
+
*/
|
|
17
|
+
import { CodeExecutionParams, CodeExecutionResult } from './types';
|
|
18
|
+
/**
|
|
19
|
+
* Service for executing JavaScript code in a secure sandbox
|
|
20
|
+
*/
|
|
21
|
+
export declare class CodeExecutionService {
|
|
22
|
+
/**
|
|
23
|
+
* Cache of loaded modules per isolate
|
|
24
|
+
*/
|
|
25
|
+
private moduleCache;
|
|
26
|
+
/**
|
|
27
|
+
* Execute JavaScript code in a sandboxed environment
|
|
28
|
+
*
|
|
29
|
+
* @param params - Execution parameters (code, language, input data, limits)
|
|
30
|
+
* @returns Execution result with output, logs, or error
|
|
31
|
+
*/
|
|
32
|
+
execute(params: CodeExecutionParams): Promise<CodeExecutionResult>;
|
|
33
|
+
/**
|
|
34
|
+
* Execute JavaScript code using isolated-vm
|
|
35
|
+
* @private
|
|
36
|
+
*/
|
|
37
|
+
private executeJavaScript;
|
|
38
|
+
/**
|
|
39
|
+
* Format console arguments for logging
|
|
40
|
+
* @private
|
|
41
|
+
*/
|
|
42
|
+
private formatConsoleArg;
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=CodeExecutionService.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CodeExecutionService.d.ts","sourceRoot":"","sources":["../src/CodeExecutionService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAGnE;;GAEG;AACH,qBAAa,oBAAoB;IAC7B;;OAEG;IACH,OAAO,CAAC,WAAW,CAA+B;IAClD;;;;;OAKG;IACG,OAAO,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAgCxE;;;OAGG;YACW,iBAAiB;IAmL/B;;;OAGG;IACH,OAAO,CAAC,gBAAgB;CAY3B"}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Code Execution Service
|
|
4
|
+
*
|
|
5
|
+
* Provides secure, sandboxed execution of JavaScript code using isolated-vm.
|
|
6
|
+
* This service enables AI agents and workflows to generate and run code safely
|
|
7
|
+
* without compromising system security.
|
|
8
|
+
*
|
|
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
|
|
15
|
+
*
|
|
16
|
+
* @module @memberjunction/code-execution
|
|
17
|
+
*/
|
|
18
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
19
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
20
|
+
};
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.CodeExecutionService = void 0;
|
|
23
|
+
const isolated_vm_1 = __importDefault(require("isolated-vm"));
|
|
24
|
+
const libraries_1 = require("./libraries");
|
|
25
|
+
/**
|
|
26
|
+
* Service for executing JavaScript code in a secure sandbox
|
|
27
|
+
*/
|
|
28
|
+
class CodeExecutionService {
|
|
29
|
+
/**
|
|
30
|
+
* Cache of loaded modules per isolate
|
|
31
|
+
*/
|
|
32
|
+
moduleCache = new Map();
|
|
33
|
+
/**
|
|
34
|
+
* Execute JavaScript code in a sandboxed environment
|
|
35
|
+
*
|
|
36
|
+
* @param params - Execution parameters (code, language, input data, limits)
|
|
37
|
+
* @returns Execution result with output, logs, or error
|
|
38
|
+
*/
|
|
39
|
+
async execute(params) {
|
|
40
|
+
const startTime = Date.now();
|
|
41
|
+
// Validate parameters
|
|
42
|
+
if (!params.code || typeof params.code !== 'string') {
|
|
43
|
+
return {
|
|
44
|
+
success: false,
|
|
45
|
+
error: 'Code parameter is required and must be a string',
|
|
46
|
+
errorType: 'RUNTIME_ERROR'
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (params.language !== 'javascript') {
|
|
50
|
+
return {
|
|
51
|
+
success: false,
|
|
52
|
+
error: `Unsupported language: ${params.language}. Only 'javascript' is currently supported.`,
|
|
53
|
+
errorType: 'RUNTIME_ERROR'
|
|
54
|
+
};
|
|
55
|
+
}
|
|
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
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Execute JavaScript code using isolated-vm
|
|
70
|
+
* @private
|
|
71
|
+
*/
|
|
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
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Format console arguments for logging
|
|
233
|
+
* @private
|
|
234
|
+
*/
|
|
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);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
exports.CodeExecutionService = CodeExecutionService;
|
|
253
|
+
//# sourceMappingURL=CodeExecutionService.js.map
|
|
@@ -0,0 +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,CAAC,MAA2B;QACrC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAE7B,sBAAsB;QACtB,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAClD,OAAO;gBACH,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,iDAAiD;gBACxD,SAAS,EAAE,eAAe;aAC7B,CAAC;QACN,CAAC;QAED,IAAI,MAAM,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;YACnC,OAAO;gBACH,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,yBAAyB,MAAM,CAAC,Q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AC;gBACV,OAAO,CAAC,OAAO,EAAE,CAAC;YACtB,CAAC;YACD,IAAI,OAAO,EAAE,CAAC;gBACV,OAAO,CAAC,OAAO,EAAE,CAAC;YACtB,CAAC;QACL,CAAC;IACL,CAAC;IAED;;;OAGG;IACK,gBAAgB,CAAC,GAAQ;QAC7B,IAAI,GAAG,KAAK,IAAI;YAAE,OAAO,MAAM,CAAC;QAChC,IAAI,GAAG,KAAK,SAAS;YAAE,OAAO,WAAW,CAAC;QAC1C,IAAI,OAAO,GAAG,KAAK,QAAQ;YAAE,OAAO,GAAG,CAAC;QACxC,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,OAAO,GAAG,KAAK,SAAS;YAAE,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;QAE5E,IAAI,CAAC;YACD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACxC,CAAC;QAAC,MAAM,CAAC;YACL,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;QACvB,CAAC;IACL,CAAC;CACJ;AAlPD,oDAkPC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,wBAAwB,CAAC;AACvC,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @module @memberjunction/code-execution
|
|
4
|
+
* @description Sandboxed code execution service for MemberJunction
|
|
5
|
+
*/
|
|
6
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
7
|
+
if (k2 === undefined) k2 = k;
|
|
8
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
9
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
10
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
11
|
+
}
|
|
12
|
+
Object.defineProperty(o, k2, desc);
|
|
13
|
+
}) : (function(o, m, k, k2) {
|
|
14
|
+
if (k2 === undefined) k2 = k;
|
|
15
|
+
o[k2] = m[k];
|
|
16
|
+
}));
|
|
17
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
18
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
19
|
+
};
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
__exportStar(require("./CodeExecutionService"), exports);
|
|
22
|
+
__exportStar(require("./types"), exports);
|
|
23
|
+
__exportStar(require("./libraries"), exports);
|
|
24
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;;;;AAEH,yDAAuC;AACvC,0CAAwB;AACxB,8CAA4B"}
|