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 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 :
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.
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.
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 .
You can also retrieve values from VM.
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.
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.
When wrapper is set to none , NodeVM behaves more like VM for synchronous code.
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.
If the script you are running is a VMScript, the path is given in the VMScript constructor.
A resolver can be created via makeResolverFromLegacyOptions and be used for multiple NodeVM instances allowing to compiled module code potentially speeding up load times. The first example of NodeVM can be rewritten using makeResolverFromLegacyOptions as follows.
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.
It works for both VM and NodeVM .
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 .
You can debug or inspect code running in the sandbox as if it was running in a normal process.
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 :
Example with using freeze :
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.
Before you can use vm2 in the command line, install it globally with npm install vm2 -g .
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.
A 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:
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.
A 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:
If your application has no other source of unhandled rejections, a blanket swallow + log is acceptable:
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.
The '*' 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 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:
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.
The combination { nesting: true, require: false } throws VMError at construction (GHSA-8hg8-63c5-gwmx) because the pair is contradictory: nesting: true makes vm2 requireable regardless of require: false , so the deny-all expectation cannot be honored. To deny all requires, remove nesting: true . To allow nested VMs, replace require: false with an explicit config so the tradeoff is visible.
The full story
This article is one source in a clustered incident — the cluster page carries the summary, timeline and every other outlet covering it.
