1

I am running some sandboxed code in Node using vm2.

The code being run will be mostly asynchronous. It is untrusted code, and can not be relied upon to conform in any way- hence why I'm using vm2 to run it.

Does vm2 have a way of ending any code currently executing? The documentation is very limited. For example, if I were to have this code:

var code = 'setInterval(function(){ console.log("tick"); }, 1000);'
vm.run(code);

Is there any way I could run such the above, and halt it at some point in the future, without the controlling code having to know anything about the contents of code, and without code having to provide any specific features?

I cannot find a vm.stop() method or similar.

Community
  • 1
  • 1
Jodes
  • 14,118
  • 26
  • 97
  • 156

1 Answers1

8

Unfortunately, there isn't a way to interrupt execution of the code running in the VM. The vm2 library is based on Node's VM module which doesn't provide any method to interrupt code running in the sandbox. At least not at the moment of writing this.

The only thing you can limit is the duration of any synchronous execution.

Disclaimer: I'm the author vm2 library.

Patrik Šimek
  • 1,038
  • 10
  • 14
  • Can you set a timeout for its asynchronous callbacks? Or it just executes forever? – Gregory Magarshak Oct 01 '17 at 14:57
  • What would you recommend when it comes to running untrusted JS code with custom objects, and preventing it from doing setTimeout() recursively? – Gregory Magarshak Oct 01 '17 at 14:58
  • Perhaps I can append a setTimeout("alwaysrandomsecretvaluehere()") to the VM code, where context.alwaysrandomsecretvalue = process.exit? – Gregory Magarshak Oct 01 '17 at 15:00
  • @patrik Thanks for the answer. I am wondering if `process.on('uncaughtException')` caused by one vm2, breaks the others. I.e do the uncaught exceptions stay within the current context, or can bring the whole Node process down? – Dragomir Ivanov Jul 30 '18 at 22:02