laverdet / isolated-vm

Secure & isolated JS environments for nodejs
ISC License
2.19k stars 154 forks source link

Cloning an async function into the isolate #399

Closed savoygrizzly closed 1 year ago

savoygrizzly commented 1 year ago

Is there any way to clone an async function into the context using setSync ?


 let setup = async function () {
        const isolate = new ivm.Isolate();
        const context = await isolate.createContext();
        const jail = context.global;
        jail.setSync("log", console.log);

        jail.setSync("hook", function (...args) {
          return hook.function();
        });
        const fn = "async function execute() { return await hook();}";
        const compiledFn = await isolate.compileScript(fn);
        await compiledFn.run(context);
        const fnReference = await context.global.get("execute", {
          reference: true,
        });
        const result = await fnReference.apply(undefined, [{ a: 20 }], {
          arguments: { copy: true },
          result: { promise: true, copy: true },
        });
        return result;
      };

      setup()
        .then((result) => {
          console.log(result);
        })
        .catch((err) => {
          console.log(err);
        });

Where hook is an async function like so


{
    function: async () => {
                                            //do async stuff 
                                            return "ok";
   }
}

So far I don't see a way.

I have tried everything I could find from online examples since the doc is.... lacking to say the least.

Thanks.

laverdet commented 1 year ago
        jail.setSync("hook", function (...args) {
          return hook.function();
        }, { reference: true });
        const fn = "async function execute() { return await hook.apply(undefined, [], { result: { promise: true } });}";