vm2
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
acorn-walk | 8.3.2 | 9.29 kB | MIT | prod | |
acorn | 8.11.3 | 122.89 kB | MIT | prod |
Vm2 is a highly-secure sandbox in Node.js that allows you to run untrusted code safely. It provides built-in modules which have been whitelisted, ensuring that your code remains completely isolated and secure. This is achieved through various features such as controlled access to built-in modules, prevention from sandbox escape via Proxies and overriding the built-in require for module access control. Furthermore, it has built-in immunity against known attack methods.
Vm2 is quite straightforward to use. First, you need to install it via npm with npm install vm2
. After the installation, you can require and start using it in your Node.js application. Here's a basic example where we create a new VM and run a string of code in it:
const {VM} = require('vm2');
const vm = new VM();
vm.run(`process.exit()`); // TypeError: process.exit is not a function
In the example above, we see the VM2's security features in action. The sandboxed code attempts to call process.exit()
, which would normally end the process in the global Node.js context. But in this case, VM2 throws an error because it limits the access to process's methods.
To use external and built-in modules securely in VM2, you can use the NodeVM
class as shown in the example below:
const {NodeVM} = require('vm2');
const vm = new NodeVM({
require: {
external: true,
root: './'
}
});
vm.run(`
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.error(error);
if (!error && response.statusCode == 200) {
console.log(body); // Show the HTML for the Google homepage.
}
});
`, 'vm.js');
In this example, the sandbox has the ability to securely require modules (both built-in and external).
The documentation for all the features of VM2 is available in the README.md file on the vm2 GitHub page: https://github.com/patriksimek/vm2. You can expect to find information about different options you can use with VM2, how to handle different types of errors, and how to compile scripts among other things.