
Research
/Security News
Miasma Mini Shai-Hulud Hits ImmobiliareLabs npm Packages
Miasma Mini Shai-Hulud hits @immobiliarelabs Backstage plugins, targeting GitLab and LDAP auth packages on npm.
vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules.
vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules.
Before using vm2, you should understand how it works and its limitations.
vm2 attempts to sandbox untrusted JavaScript code within the same Node.js process as your application. It does this through a complex network of Proxies that intercept and mediate every interaction between the sandbox and the host environment.
JavaScript is an extraordinarily dynamic language. Objects can be accessed through prototype chains, constructors can be reached via error objects, symbols provide protocol hooks, and async execution creates timing windows. The sheer number of ways to traverse from one object to another in JavaScript makes building an airtight in-process sandbox extremely difficult.
We are honest about this reality: Despite our best efforts, researchers and security professionals continuously discover new ways to escape the vm2 sandbox. We actively patch these vulnerabilities as they are reported, but the cat-and-mouse nature of in-process sandboxing means that:
If you require stronger isolation guarantees, consider these alternatives that provide true process or hardware-level isolation:
| Solution | Approach | Performance | Trade-offs |
|---|---|---|---|
| isolated-vm | Separate V8 isolates (different V8 heap) | Fast | In maintenance mode; requires manual V8 updates |
| Separate process / Worker | child_process or Worker threads with limited permissions | Medium | Higher IPC overhead; data must be serialized |
| Containers / VMs | Docker, gVisor, Firecracker | Slow | Startup overhead; resource-heavy |
| Managed services | Cloud-based code execution (e.g., AWS Lambda, Cloudflare Workers) | Variable | Network latency; external dependency |
vm2 can be suitable when:
If you're running code from completely untrusted sources (e.g., arbitrary user submissions), we strongly recommend using a solution with stronger isolation guarantees.
For an in-depth look at vm2’s internals, see the CONTRIBUTING.md file.
Try it yourself:
import { runInNewContext } from "node:vm";
runInNewContext('this.constructor.constructor("return process")().exit()');
console.log('Never gets executed.');
import { VM } from 'vm2';
new VM().run('this.constructor.constructor("return process")().exit()');
// Throws ReferenceError: process is not defined
npm install vm2
import { VM } from 'vm2';
const vm = new VM();
vm.run(`process.exit()`); // TypeError: process.exit is not a function
import { NodeVM } from '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',
);
VM is a simple sandbox to synchronously run untrusted code without the require feature. Only JavaScript built-in objects and Node's Buffer are available. Scheduling functions (setInterval, setTimeout and setImmediate) are not available by default.
Options:
timeout - Script timeout in milliseconds. WARNING: You might want to use this option together with allowAsync=false. Further, operating on returned objects from the sandbox can run arbitrary code and circumvent the timeout. One should test if the returned object is a primitive with typeof and fully discard it (doing logging or creating error messages with such an object might also run arbitrary code again) in the other case.sandbox - VM's global object.compiler - javascript (default), typescript, coffeescript or custom compiler function. The library expects you to have compiler pre-installed if the value is set to typescript or coffeescript.eval - If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc.) will throw an EvalError (default: true).wasm - If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError (default: true). Note: WebAssembly.JSTag is removed inside the sandbox for security reasons, so wasm code cannot catch JavaScript exceptions.allowAsync - If set to false any attempt to run code using async will throw a VMError (default: true).bufferAllocLimit - Maximum size in bytes for a single Buffer.alloc / Buffer.allocUnsafe / Buffer.allocUnsafeSlow / Buffer(N) / new Buffer(N) request from inside the sandbox. Requests that exceed this cap throw a RangeError synchronously without performing the host allocation. Default: Infinity (no cap, fully backwards-compatible). Embedders running untrusted code in memory-constrained environments (Docker / Kubernetes / Lambda / serverless) should opt into a finite cap (e.g. 32 * 1024 * 1024) as part of layered DoS defense, the same way they opt into timeout. See Hardening recommendations below.IMPORTANT: Timeout is only effective on synchronous code that you run through run. Timeout does NOT work on any method returned by VM. There are some situations when timeout doesn't work - see #244.
import { VM } from 'vm2';
const vm = new VM({
timeout: 1000,
allowAsync: false,
sandbox: {},
});
vm.run('process.exit()'); // throws ReferenceError: process is not defined
You can also retrieve values from VM.
let number = vm.run('1337'); // returns 1337
TIP: See tests for more usage examples.
Unlike VM, NodeVM allows you to require modules in the same way that you would in the regular Node's context.
Options:
console - inherit to enable console, redirect to redirect to events, off to disable console (default: inherit).sandbox - VM's global object.compiler - javascript (default), typescript, coffeescript or custom compiler function (which receives the code, and it's file path). The library expects you to have compiler pre-installed if the value is set to typescript or coffeescript.eval - If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc.) will throw an EvalError (default: true).wasm - If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError (default: true). Note: WebAssembly.JSTag is removed inside the sandbox for security reasons, so wasm code cannot catch JavaScript exceptions.bufferAllocLimit - Same semantics as on VM — maximum size in bytes for a single Buffer.alloc family request from inside the sandbox. Default: Infinity. See Hardening recommendations.sourceExtensions - Array of file extensions to treat as source code (default: ['js']).require - true, an object or a Resolver to enable require method (default: false).require.external - Values can be true, an array of allowed external modules, or an object (default: false). All paths matching /node_modules/${any_allowed_external_module}/(?!/node_modules/) are allowed to be required.require.external.modules - Array of allowed external modules. Also supports wildcards, so specifying ['@scope/*-ver-??], for instance, will allow using all modules having a name of the form @scope/something-ver-aa, @scope/other-ver-11, etc. The * wildcard does not match path separators.require.external.transitive - Boolean which indicates if transitive dependencies of external modules are allowed (default: false). WARNING: When a module is required transitively, any module is then able to require it normally, even if this was not possible before it was loaded.require.builtin - Array of allowed built-in modules, accepts ["*"] for all (default: none). WARNING: "*" can be dangerous as new built-ins can be added.require.root - Restricted path(s) where local modules can be required (default: every path).require.mock - Collection of mock modules (both external or built-in).require.context - host (default) to require modules in the host and proxy them into the sandbox. sandbox to load, compile, and require modules in the sandbox. callback(moduleFilename, ext) to dynamically choose a context per module. The default will be sandbox is nothing is specified. Except for events, built-in modules are always required in the host and proxied into the sandbox.require.import - An array of modules to be loaded into NodeVM on start.require.resolve - An additional lookup function in case a module wasn't found in one of the traditional node lookup paths.require.customRequire - Use instead of the require function to load modules from the host.require.strict - false to not force strict mode on modules loaded by require (default: true).require.fs - Custom file system implementation.nesting - WARNING: Allowing this is a security risk as scripts can create a NodeVM which can require any host module. true to enable VMs nesting (default: false).wrapper - commonjs (default) to wrap script into CommonJS wrapper, none to retrieve value returned by the script.argv - Array to be passed to process.argv.env - Object to be passed to process.env.strict - true to loaded modules in strict mode (default: false).IMPORTANT: Timeout is not effective for NodeVM so it is not immune to while (true) {} or similar evil.
REMEMBER: The more modules you allow, the more fragile your sandbox becomes.
import { NodeVM } from 'vm2';
const vm = new NodeVM({
console: 'inherit',
sandbox: {},
require: {
external: true,
builtin: ['fs', 'path'],
root: './',
mock: {
fs: {
readFileSync: () => 'Nice try!',
},
},
},
});
// Sync
let functionInSandbox = vm.run('module.exports = function(who) { console.log("hello "+ who); }');
functionInSandbox('world');
// Async
let functionWithCallbackInSandbox = vm.run('module.exports = function(who, callback) { callback("hello "+ who); }');
functionWithCallbackInSandbox('world', greeting => {
console.log(greeting);
});
When wrapper is set to none, NodeVM behaves more like VM for synchronous code.
assert.ok(vm.run('return true') === true);
TIP: See tests for more usage examples.
To load modules by relative path, you must pass the full path of the script you're running as a second argument to vm's run method if the script is a string. The filename is then displayed in any stack traces generated by the script.
vm.run('require("foobar")', '/data/myvmscript.js');
If the script you are running is a VMScript, the path is given in the VMScript constructor.
const script = new VMScript('require("foobar")', { filename: '/data/myvmscript.js' });
vm.run(script);
A resolver can be created via makeResolverFromLegacyOptions and be used for multiple NodeVM instances allowing to share compiled module code potentially speeding up load times. The first example of NodeVM can be rewritten using makeResolverFromLegacyOptions as follows.
const resolver = makeResolverFromLegacyOptions({
external: true,
builtin: ['fs', 'path'],
root: './',
mock: {
fs: {
readFileSync: () => 'Nice try!',
},
},
});
const vm = new NodeVM({
console: 'inherit',
sandbox: {},
require: resolver,
});
You can increase performance by using precompiled scripts. The precompiled VMScript can be run multiple times. It is important to note that the code is not bound to any VM (context); rather, it is bound before each run, just for that run.
import { VM, VMScript } from 'vm2';
const vm = new VM();
const script = new VMScript('Math.random()');
console.log(vm.run(script));
console.log(vm.run(script));
It works for both VM and NodeVM.
import { NodeVM, VMScript } from 'vm2';
const vm = new NodeVM();
const script = new VMScript('module.exports = Math.random()');
console.log(vm.run(script));
console.log(vm.run(script));
Code is compiled automatically the first time it runs. One can compile the code anytime with script.compile(). Once the code is compiled, the method has no effect.
Errors in code compilation and synchronous code execution can be handled by try-catch. Errors in asynchronous code execution can be handled by attaching uncaughtException event handler to Node's process.
try {
var script = new VMScript('Math.random()').compile();
} catch (err) {
console.error('Failed to compile script.', err);
}
try {
vm.run(script);
} catch (err) {
console.error('Failed to execute script.', err);
}
process.on('uncaughtException', err => {
console.error('Asynchronous error caught.', err);
});
You can debug or inspect code running in the sandbox as if it was running in a normal process.
debugger keyword./tmp/main.js:
import { VM, VMScript } from 'vm2';
import { readFileSync } from 'node:fs';
const file = `${__dirname}/sandbox.js`;
// By providing a file name as second argument you enable breakpoints
const script = new VMScript(readFileSync(file), file);
new VM().run(script);
/tmp/sandbox.js
const foo = 'ahoj';
// The debugger keyword works just fine everywhere.
// Even without specifying a file name to the VMScript object.
debugger;
To prevent sandboxed scripts from adding, changing, or deleting properties from the proxied objects, you can use freeze methods to make the object read-only. This is only effective inside VM. Frozen objects are affected deeply. Primitive types cannot be frozen.
Example without using freeze:
const util = {
add: (a, b) => a + b,
};
const vm = new VM({
sandbox: { util },
});
vm.run('util.add = (a, b) => a - b');
console.log(util.add(1, 1)); // returns 0
Example with using freeze:
const vm = new VM(); // Objects specified in the sandbox cannot be frozen.
vm.freeze(util, 'util'); // Second argument adds object to global.
vm.run('util.add = (a, b) => a - b'); // Fails silently when not in strict mode.
console.log(util.add(1, 1)); // returns 2
IMPORTANT: It is not possible to freeze objects that have already been proxied to the VM.
Unlike freeze, this method allows sandboxed scripts to add, change, or delete properties on objects, with one exception - it is not possible to attach functions. Sandboxed scripts are therefore not able to modify methods like toJSON, toString or inspect.
IMPORTANT: It is not possible to protect objects that have already been proxied to the VM.
const assert = require('assert');
const { VM } = require('vm2');
const sandbox = {
object: new Object(),
func: new Function(),
buffer: new Buffer([0x01, 0x05]),
};
const vm = new VM({ sandbox });
assert.ok(vm.run(`object`) === sandbox.object);
assert.ok(vm.run(`object instanceof Object`));
assert.ok(vm.run(`object`) instanceof Object);
assert.ok(vm.run(`object.__proto__ === Object.prototype`));
assert.ok(vm.run(`object`).__proto__ === Object.prototype);
assert.ok(vm.run(`func`) === sandbox.func);
assert.ok(vm.run(`func instanceof Function`));
assert.ok(vm.run(`func`) instanceof Function);
assert.ok(vm.run(`func.__proto__ === Function.prototype`));
assert.ok(vm.run(`func`).__proto__ === Function.prototype);
assert.ok(vm.run(`new func() instanceof func`));
assert.ok(vm.run(`new func()`) instanceof sandbox.func);
assert.ok(vm.run(`new func().__proto__ === func.prototype`));
assert.ok(vm.run(`new func()`).__proto__ === sandbox.func.prototype);
assert.ok(vm.run(`buffer`) === sandbox.buffer);
assert.ok(vm.run(`buffer instanceof Buffer`));
assert.ok(vm.run(`buffer`) instanceof Buffer);
assert.ok(vm.run(`buffer.__proto__ === Buffer.prototype`));
assert.ok(vm.run(`buffer`).__proto__ === Buffer.prototype);
assert.ok(vm.run(`buffer.slice(0, 1) instanceof Buffer`));
assert.ok(vm.run(`buffer.slice(0, 1)`) instanceof Buffer);
Before you can use vm2 in the command line, install it globally with npm install vm2 -g.
vm2 ./script.js
vm2 prevents sandbox escapes (untrusted code obtaining host realm access). It does not, by itself, prevent every form of resource exhaustion or denial-of-service. Embedders running untrusted code should add the following layered defenses around the sandbox.
bufferAllocLimitA single Buffer.alloc(N) call with attacker-controlled N runs as one synchronous host C++ allocation that V8's timeout cannot interrupt. In memory-constrained environments a ~100-byte sandbox payload can drive a 100 MB+ host RSS jump and crash the host process via OOM. Set bufferAllocLimit (e.g. 32 * 1024 * 1024) to cap individual allocations:
const vm = new VM({
timeout: 1000,
bufferAllocLimit: 32 * 1024 * 1024,
allowAsync: false,
});
The cap also applies to the deprecated Buffer(N) and new Buffer(N) paths. Note that aggregate exhaustion (many small allocations, Buffer.concat, Uint8Array, String.repeat, Array(n).fill(), etc.) is not covered by this cap — combine with a host-side memory limit (--max-old-space-size, container limit, cgroup) for full coverage.
unhandledRejection handlerA class of host-process abort DoS exists where sandbox code creates an async function, async function*, or await using whose body throws a value that triggers a host-realm error during stack formatting (e.g. e.name = Symbol(); e.stack). V8 creates the rejection promise via the realm's intrinsic Promise, which bypasses vm2's Promise subclass wrap, so the rejection escapes to the host as unhandledRejection. On Node 15+ the default behavior is to terminate the process.
Closing this requires changing observable host behavior, so vm2 does not ship a fix by default. Embedders should install a process-level handler that swallows (or logs) sandbox-originating rejections:
// Recommended: filter rejections that originated inside vm2 and swallow them,
// while letting your own host-side rejections propagate.
process.on('unhandledRejection', (reason, promise) => {
// Heuristic: rejections from the sandbox frequently surface as values
// without proper Error semantics, or with stacks pointing at vm.js.
// Adjust the predicate to match your application.
if (looksLikeSandboxOrigin(reason)) {
return; // swallow — don't terminate the process
}
// Otherwise: handle (or rethrow) as normal for your host code.
yourLogger.error('unhandled rejection', reason);
});
If your application has no other source of unhandled rejections, a blanket swallow + log is acceptable:
process.on('unhandledRejection', reason => {
yourLogger.warn('swallowed sandbox rejection', reason);
});
A scoped fix may ship behind an opt-in swallowSandboxUnhandledRejections flag in a future minor release; until then, the host-side handler is the recommended mitigation.
Even with bufferAllocLimit set, run the host process with --max-old-space-size (or an equivalent container memory limit) sized for the workload. The cap protects against the single-allocation primitive; the OS-level limit protects against aggregate exhaustion and against any future allocation primitive vm2 hasn't yet capped.
require.builtin: ['*'] as a non-sandbox configurationThe '*' wildcard expands to most Node built-ins, including child_process, fs, dgram, net, http, and dns. These are full host-capability primitives — require('child_process').execSync('id') is reachable from the sandbox under '*'. vm2's '*' semantics are intentional (some embedders run trusted-but-isolated code), but it should not be used as a default for untrusted code. Prefer an explicit allowlist of the smallest set of modules your sandbox actually needs.
nesting: true is an escape hatchnesting: true lets sandbox code require('vm2') and construct nested NodeVMs. The nested VM's require config is chosen by the sandbox code that constructs it, not constrained by the outer VM. Concretely:
const vm = new NodeVM({ nesting: true, require: { builtin: [] } });
vm.run(`
const { NodeVM: NVM } = require('vm2');
// Inner VM's config is whatever the sandbox writes here:
const inner = new NVM({ require: { builtin: ['child_process'] } });
inner.run('require("child_process").execSync("id")'); // RCE
`);
If you set nesting: true, you have effectively granted the sandbox the same trust level you have. Do not enable nesting: true for untrusted code. Use it only when you trust the sandboxed code itself but want VM-style execution semantics (fresh global, controlled timeouts) for non-security reasons.
nesting: true requires an explicit require config object (e.g. require: { builtin: [] } or require: {}). Any other shape — require: false, require: undefined, require: null, or omitting require entirely — throws VMError at construction (GHSA-m4wx-m65x-ghrr, supersedes GHSA-8hg8-63c5-gwmx). All of those shapes produce a NESTING_OVERRIDE-only resolver: the sandbox can require('vm2') but nothing else, which is a pure escape primitive with no legitimate use. To deny all requires, remove nesting: true. To allow nested VMs, provide an explicit require config so the trade-off is visible at the call site.
Object.create.The 'sandboxed-module' package is similar to vm2 in that it allows for the execution of code in a sandboxed environment. However, it focuses more on requiring modules in a sandbox rather than executing arbitrary code. It does not provide as strong isolation as vm2.
The 'secure-vm' package is another alternative that provides a sandbox for executing code. It is similar to vm2 but has a different API and may not offer the same level of customization and security features as vm2.
FAQs
vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules.
The npm package vm2 receives a total of 992,733 weekly downloads. As such, vm2 popularity was classified as popular.
We found that vm2 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Research
/Security News
Miasma Mini Shai-Hulud hits @immobiliarelabs Backstage plugins, targeting GitLab and LDAP auth packages on npm.

Security News
Rolldown paused Rust React Compiler integration after a 5MB binary size increase raised concerns about shipping React-specific code to all Vite users.

Security News
/Research
Mini Shai-Hulud expands into the Go ecosystem after hitting LeoPlatform npm packages and targeting GitHub Actions workflows.