laverdet / isolated-vm

Secure & isolated JS environments for nodejs
ISC License
2.12k stars 151 forks source link

#<Promise> could not be cloned. #461

Closed dashng closed 6 months ago

dashng commented 6 months ago
const http = require('http');
const ivm  = require('isolated-vm');

// Create a server instance
const server = http.createServer((req, res) => {
  // Allow only POST requests
  if (req.method === 'POST') {
    let data = '';

    // Receive data from the request
    req.on('data', chunk => {
      data += chunk;
    });

    // When request ends
    req.on('end', async () => {
      try {
        // Parse JSON payload
        const payload = JSON.parse(data);

        // Define a custom fetch function in the VM context
        // const vm = new VM({
        //   sandbox: {
        //     fetch: fetch
        //   }
        // });

        // Execute JavaScript code
        // const result = await vm.run(payload.code);

        const isolate = new ivm.Isolate({ memoryLimit: 128 });
        const context = isolate.createContextSync();
        const jail = context.global;
        jail.setSync('global', jail.derefInto());
        jail.setSync('log', function (...args) {
          console.log(...args);
        });

        jail.setSync('fetch', async function (...args) {
          let data  = await fetch(...args);
          return data;
        });

        const result = await context.eval(payload.code);

        // const hostile = isolate.compileScriptSync(payload.code)
        // const result  = await hostile.run(context);
        // Send the result back
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ result }));
      } catch (err) {
        // If any error occurs during execution
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: err.message }));
      }
    });
  } else {
    // Respond with a 404 for non-POST requests
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

// Start the server and listen on port 3000
server.listen(3030, () => {
  console.log('Server running on port 3000');
});

I am trying to run manual js string code within isolated-vm, but blocked by http query. JS script is for deltect / monitoring 3rd service health by restful api. So the http is mandatory to be supported. Is there any one can help me on this to point out if isolated-vm support async call?

dashng commented 6 months ago
If you want to perform operations on files, network, native modules, etc then you will need to set up some kind of shim delegate which can perform the operation within nodejs and pass the result back to your isolate. 

I think I got the answer, it doesnot support network http query.

dashng commented 6 months ago

Thanks