laverdet / isolated-vm

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

How to access proto methods of the returned reference? #476

Closed rakeshar3796 closed 5 months ago

rakeshar3796 commented 5 months ago

Hey folks, i've been playing around with this library for some time and i've a question here, in my code i've an async function to deal with requests and when once its made a request i've been trying to access json method, but i'm receiving a type error

Error

Error: TypeError: res.json is not a function
    at <isolated-vm>:3:104
    at async execute (<isolated-vm>:3:20)

Code

const ivm = require("isolated-vm");
const fetch = require("node-fetch");

const code = `
    async function execute() {
      let result = await makeRequest("https://jsonplaceholder.typicode.com/todos/1").then((res) => res.json());
      return new ivm.Reference(result.copySync()).deref();
    }
    execute();
`;

function makeRequest(url) {
  return fetch(url);
}

async function runScriptInIsolate() {
  // Create an isolate with a context
  const isolate = new ivm.Isolate({ memoryLimit: 128 /* MB */ });
  const context = await isolate.createContext();

  // Transfer the ivm module into the isolate
  const jail = context.global;
  await jail.set("ivm", ivm);

  context.evalClosureSync(
    `globalThis.makeRequest = (...args) => $0.apply(null, args, { arguments: { copy: true }, result: { promise: true } })`,
    [new ivm.Reference(makeRequest)]
  );

  // Execute the script in the isolate
  const script = await isolate.compileScriptSync(code);
  const result = await script.runSync(context, {
    promise: true,
    reference: true
  });

  // Dispose of the isolate
  //   isolate.dispose();

  // Return the result
  return result;
}

runScriptInIsolate()
  .then((result) => {
    console.log("Result:", result.copySync());
  })
  .catch((err) => {
    console.error("Error:", err);
  });

Can anyone help on this?

Node version - 18.20.3 OS version - MacOS 13.5

laverdet commented 5 months ago

This is covered under the "frequently asked question" section of the README

rakeshar3796 commented 5 months ago

@laverdet I've a question in general, in the above code example let's say fetch return response include prototype methods like json, text etc, and these methods i'm not getting inside the caller function, does copy excludes prototype methods by default?

Can you shed some light here on how to get these methods?

laverdet commented 5 months ago

The question doesn't make sense. The methods exist in a separate isolate. You might as well be asking how to copy res.json from Firefox into Edge.