|
| 1 | +import pkg from "isolated-vm"; |
| 2 | +const { Isolate } = pkg; |
| 3 | + |
| 4 | +const MEMORY_LIMIT_MB = 256; |
| 5 | +// Current svgdom bundle is large and slow, so we need to give it more time to solve |
| 6 | +// TODO: Reduce once performance improved |
| 7 | +const TIMEOUT_MS = 2000; |
| 8 | + |
| 9 | +export class UserError extends Error { |
| 10 | + userStack = []; |
| 11 | +} |
| 12 | + |
| 13 | +export function runInSandbox({ userCode, resultCode, params }) { |
| 14 | + const isolate = new Isolate({ memoryLimit: MEMORY_LIMIT_MB }); |
| 15 | + const context = isolate.createContextSync(); |
| 16 | + const jail = context.global; |
| 17 | + jail.setSync("global", jail.derefInto()); |
| 18 | + // Example of exposing a custom function on the context's global: |
| 19 | + /* |
| 20 | + jail.setSync("log", function (...args) { |
| 21 | + console.log(...args); |
| 22 | + }); |
| 23 | + */ |
| 24 | + |
| 25 | + // Evaluate untrusted user code in isolated context |
| 26 | + try { |
| 27 | + context.evalSync(userCode, { |
| 28 | + timeout: TIMEOUT_MS, |
| 29 | + filename: "user.js", |
| 30 | + }); |
| 31 | + |
| 32 | + return context.evalClosureSync(resultCode, params, { |
| 33 | + timeout: TIMEOUT_MS, |
| 34 | + arguments: { copy: true }, |
| 35 | + result: { copy: true }, |
| 36 | + }); |
| 37 | + } catch (ex) { |
| 38 | + throw handleUserError(ex); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +function handleUserError(ex) { |
| 43 | + const userError = new UserError(`${ex.name}: ${ex.message}`); |
| 44 | + if (ex.stack) { |
| 45 | + userError.userStack = ex.stack.split("\n").filter((line) => line.match(/^ at .*user\.js/)); |
| 46 | + } |
| 47 | + return userError; |
| 48 | +} |
0 commit comments