diff --git a/packages/server/src/utilities/scriptRunner.ts b/packages/server/src/utilities/scriptRunner.ts index b6e597cc55..c89d266b7e 100644 --- a/packages/server/src/utilities/scriptRunner.ts +++ b/packages/server/src/utilities/scriptRunner.ts @@ -1,63 +1,22 @@ -import ivm from "isolated-vm" +import env from "../environment" +import { IsolatedVM } from "../jsRunner/vm" const JS_TIMEOUT_MS = 1000 - class ScriptRunner { - vm: IsolatedVM + #code constructor(script: string, context: any) { - const code = `let fn = () => {\n${script}\n}; results.out = fn();` - this.vm = new IsolatedVM({ memoryLimit: 8 }) - this.vm.context = { - ...context, - results: { out: "" }, - } - this.vm.code = code + this.#code = `let fn = () => {\n${script}\n}; results.out = fn();` } execute() { - this.vm.runScript() - const results = this.vm.getValue("results") - return results.out - } -} - -class IsolatedVM { - isolate: ivm.Isolate - vm: ivm.Context - #jail: ivm.Reference - script: any - - constructor({ memoryLimit }: { memoryLimit: number }) { - this.isolate = new ivm.Isolate({ memoryLimit }) - this.vm = this.isolate.createContextSync() - this.#jail = this.vm.global - this.#jail.setSync("global", this.#jail.derefInto()) - } - - getValue(key: string) { - const ref = this.vm.global.getSync(key, { reference: true }) - const result = ref.copySync() - ref.release() + const vm = new IsolatedVM({ + memoryLimit: env.JS_RUNNER_MEMORY_LIMIT, + timeout: JS_TIMEOUT_MS, + }).withHelpers() + const result = vm.execute(this.#code) return result } - - set context(context: Record) { - for (let key in context) { - this.#jail.setSync(key, this.copyRefToVm(context[key])) - } - } - - set code(code: string) { - this.script = this.isolate.compileScriptSync(code) - } - - runScript() { - this.script.runSync(this.vm, { timeout: JS_TIMEOUT_MS }) - } - - copyRefToVm(value: Object): ivm.Copy { - return new ivm.ExternalCopy(value).copyInto({ release: true }) - } } + export default ScriptRunner