javascript / expert
Snippet
Isolated Script Execution Sandboxing using Node.js VM Contexts
The node:vm module provides APIs for compiling and running code within isolated V8 context scopes. By binding a null-prototype object as the global proxy and defining explicit execution timeouts, developers can restrict untrusted script capabilities and halt CPU-bound loops.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import vm from 'node:vm';function executeInSandbox(untrustedCode, contextGlobals) {const sandbox = vm.createContext(Object.create(null, {...Object.getOwnPropertyDescriptors(contextGlobals),Math: { value: Math, writable: false, configurable: false }}));const script = new vm.Script(untrustedCode, { filename: 'sandbox.vm.js' });return script.runInContext(sandbox, {timeout: 100,breakOnSigint: true});}const result = executeInSandbox('x * 2 + Math.PI', { x: 10 });
nodejs
Breakdown
1
const sandbox = vm.createContext(Object.create(null, {
Creates a fresh V8 execution context detached from standard Object prototype properties for isolation.
2
Math: { value: Math, writable: false, configurable: false }
Injects read-only built-in primitives using explicit property descriptors.
3
const script = new vm.Script(untrustedCode, { filename: 'sandbox.vm.js' });
Compiles code string into a reusable V8 script instance ahead of context execution.
4
timeout: 100,
Enforces a strict CPU wall-clock limit in milliseconds, throwing an error if execution exceeds the threshold.