@novolobos/nodevm 3.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2014-2025 Patrik Simek and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,461 @@
1
+ # vm2 [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![License][license-image]][license-url] [![Node.js CI](https://github.com/patriksimek/vm2/actions/workflows/test.yml/badge.svg)](https://github.com/patriksimek/vm2/actions/workflows/test.yml) [![Known Vulnerabilities][snyk-image]][snyk-url]
2
+
3
+ vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules.
4
+
5
+ ## Important Security Disclaimer
6
+
7
+ **Before using vm2, you should understand how it works and its limitations.**
8
+
9
+ 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](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy) that intercept and mediate every interaction between the sandbox and the host environment.
10
+
11
+ ### The Fundamental Challenge
12
+
13
+ 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.
14
+
15
+ **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:
16
+
17
+ 1. **New bypasses will likely be discovered in the future.** Check our [security advisories](https://github.com/patriksimek/vm2/security/advisories) for known vulnerabilities.
18
+ 2. **You must keep vm2 updated** to benefit from the latest security fixes. Subscribe to security advisories and update promptly.
19
+ 3. **vm2 should not be your only line of defense.** Defense in depth is essential when running untrusted code.
20
+
21
+ ### More Robust Alternatives
22
+
23
+ If you require stronger isolation guarantees, consider these alternatives that provide **true process or hardware-level isolation**:
24
+
25
+ | Solution | Approach | Performance | Trade-offs |
26
+ |----------|----------|-------------|------------|
27
+ | **[isolated-vm](https://github.com/laverdet/isolated-vm)** | Separate V8 isolates (different V8 heap) | Fast | In maintenance mode; requires manual V8 updates |
28
+ | **Separate process / Worker** | `child_process` or Worker threads with limited permissions | Medium | Higher IPC overhead; data must be serialized |
29
+ | **Containers / VMs** | Docker, gVisor, Firecracker | Slow | Startup overhead; resource-heavy |
30
+ | **Managed services** | Cloud-based code execution (e.g., AWS Lambda, Cloudflare Workers) | Variable | Network latency; external dependency |
31
+
32
+ ### When vm2 May Still Be Appropriate
33
+
34
+ vm2 can be suitable when:
35
+ - You need tight integration with host objects and fast synchronous communication
36
+ - The untrusted code comes from a relatively trusted source (e.g., internal tools, plugin systems with vetted authors)
37
+ - You combine vm2 with other security layers (network isolation, filesystem restrictions, resource limits)
38
+ - You accept the risk and actively monitor for security updates
39
+
40
+ **If you're running code from completely untrusted sources (e.g., arbitrary user submissions), we strongly recommend using a solution with stronger isolation guarantees.**
41
+
42
+ ## Features
43
+
44
+ - Runs untrusted code securely in a single process with your code side by side
45
+ - Full control over the sandbox's console output
46
+ - The sandbox has limited access to the process's methods
47
+ - It is possible to require modules (built-in and external) from the sandbox
48
+ - You can limit access to certain (or all) built-in modules
49
+ - You can securely call methods and exchange data and callbacks between sandboxes
50
+ - Actively maintained with patches for known escape methods (see [Security Disclaimer](#important-security-disclaimer))
51
+ - Transpiler support
52
+
53
+ ## How does it work
54
+
55
+ - It uses the internal VM module to create a secure context.
56
+ - It uses [Proxies](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy) to prevent escaping from the sandbox.
57
+ - It overrides the built-in require to control access to modules.
58
+
59
+ For an in-depth look at vm2’s internals, see the [CONTRIBUTING.md](./CONTRIBUTING.md) file.
60
+
61
+ ## What is the difference between Node's vm and vm2?
62
+
63
+ Try it yourself:
64
+
65
+ ```js
66
+ import { runInNewContext } from "node:vm";
67
+
68
+ runInNewContext('this.constructor.constructor("return process")().exit()');
69
+ console.log('Never gets executed.');
70
+ ```
71
+
72
+ ```js
73
+ import { VM } from 'vm2';
74
+
75
+ new VM().run('this.constructor.constructor("return process")().exit()');
76
+ // Throws ReferenceError: process is not defined
77
+ ```
78
+
79
+ ## Installation
80
+
81
+ ```sh
82
+ npm install vm2
83
+ ```
84
+
85
+ ## Quick Examples
86
+
87
+ ```js
88
+ import { VM } from 'vm2';
89
+
90
+ const vm = new VM();
91
+ vm.run(`process.exit()`); // TypeError: process.exit is not a function
92
+ ```
93
+
94
+ ```js
95
+ import { NodeVM } from 'vm2';
96
+
97
+ const vm = new NodeVM({
98
+ require: {
99
+ external: true,
100
+ root: './',
101
+ },
102
+ });
103
+
104
+ vm.run(
105
+ `
106
+ var request = require('request');
107
+ request('http://www.google.com', function (error, response, body) {
108
+ console.error(error);
109
+ if (!error && response.statusCode == 200) {
110
+ console.log(body); // Show the HTML for the Google homepage.
111
+ }
112
+ });
113
+ `,
114
+ 'vm.js',
115
+ );
116
+ ```
117
+
118
+ ## Documentation
119
+
120
+ - [VM](#vm)
121
+ - [NodeVM](#nodevm)
122
+ - [VMScript](#vmscript)
123
+ - [Error handling](#error-handling)
124
+ - [Debugging a sandboxed code](#debugging-a-sandboxed-code)
125
+ - [Read-only objects](#read-only-objects-experimental)
126
+ - [Protected objects](#protected-objects-experimental)
127
+ - [Cross-sandbox relationships](#cross-sandbox-relationships)
128
+ - [CLI](#cli)
129
+ - [2.x to 3.x changes](https://github.com/patriksimek/vm2/wiki/2.x-to-3.x-changes)
130
+ - [1.x and 2.x docs](https://github.com/patriksimek/vm2/wiki/1.x-and-2.x-docs)
131
+ - [Contributing](https://github.com/patriksimek/vm2/wiki/Contributing)
132
+
133
+ ## VM
134
+
135
+ 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.
136
+
137
+ **Options:**
138
+
139
+ - `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.
140
+ - `sandbox` - VM's global object.
141
+ - `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`.
142
+ - `eval` - If set to `false` any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc.) will throw an `EvalError` (default: `true`).
143
+ - `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.
144
+ - `allowAsync` - If set to `false` any attempt to run code using `async` will throw a `VMError` (default: `true`).
145
+
146
+ **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](https://github.com/patriksimek/vm2/pull/244).
147
+
148
+ ```js
149
+ import { VM } from 'vm2';
150
+
151
+ const vm = new VM({
152
+ timeout: 1000,
153
+ allowAsync: false,
154
+ sandbox: {},
155
+ });
156
+
157
+ vm.run('process.exit()'); // throws ReferenceError: process is not defined
158
+ ```
159
+
160
+ You can also retrieve values from VM.
161
+
162
+ ```js
163
+ let number = vm.run('1337'); // returns 1337
164
+ ```
165
+
166
+ **TIP**: See tests for more usage examples.
167
+
168
+ ## NodeVM
169
+
170
+ Unlike `VM`, `NodeVM` allows you to require modules in the same way that you would in the regular Node's context.
171
+
172
+ **Options:**
173
+
174
+ - `console` - `inherit` to enable console, `redirect` to redirect to events, `off` to disable console (default: `inherit`).
175
+ - `sandbox` - VM's global object.
176
+ - `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`.
177
+ - `eval` - If set to `false` any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc.) will throw an `EvalError` (default: `true`).
178
+ - `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.
179
+ - `sourceExtensions` - Array of file extensions to treat as source code (default: `['js']`).
180
+ - `require` - `true`, an object or a Resolver to enable `require` method (default: `false`).
181
+ - `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.
182
+ - `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.
183
+ - `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.
184
+ - `require.builtin` - Array of allowed built-in modules, accepts ["\*"] for all (default: none). **WARNING**: "\*" can be dangerous as new built-ins can be added.
185
+ - `require.root` - Restricted path(s) where local modules can be required (default: every path).
186
+ - `require.mock` - Collection of mock modules (both external or built-in).
187
+ - `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.
188
+ - `require.import` - An array of modules to be loaded into NodeVM on start.
189
+ - `require.resolve` - An additional lookup function in case a module wasn't found in one of the traditional node lookup paths.
190
+ - `require.customRequire` - Use instead of the `require` function to load modules from the host.
191
+ - `require.strict` - `false` to not force strict mode on modules loaded by require (default: `true`).
192
+ - `require.fs` - Custom file system implementation.
193
+ - `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`).
194
+ - `wrapper` - `commonjs` (default) to wrap script into CommonJS wrapper, `none` to retrieve value returned by the script.
195
+ - `argv` - Array to be passed to `process.argv`.
196
+ - `env` - Object to be passed to `process.env`.
197
+ - `strict` - `true` to loaded modules in strict mode (default: `false`).
198
+
199
+ **IMPORTANT**: Timeout is not effective for NodeVM so it is not immune to `while (true) {}` or similar evil.
200
+
201
+ **REMEMBER**: The more modules you allow, the more fragile your sandbox becomes.
202
+
203
+ ```js
204
+ import { NodeVM } from 'vm2';
205
+
206
+ const vm = new NodeVM({
207
+ console: 'inherit',
208
+ sandbox: {},
209
+ require: {
210
+ external: true,
211
+ builtin: ['fs', 'path'],
212
+ root: './',
213
+ mock: {
214
+ fs: {
215
+ readFileSync: () => 'Nice try!',
216
+ },
217
+ },
218
+ },
219
+ });
220
+
221
+ // Sync
222
+
223
+ let functionInSandbox = vm.run('module.exports = function(who) { console.log("hello "+ who); }');
224
+ functionInSandbox('world');
225
+
226
+ // Async
227
+
228
+ let functionWithCallbackInSandbox = vm.run('module.exports = function(who, callback) { callback("hello "+ who); }');
229
+ functionWithCallbackInSandbox('world', greeting => {
230
+ console.log(greeting);
231
+ });
232
+ ```
233
+
234
+ When `wrapper` is set to `none`, `NodeVM` behaves more like `VM` for synchronous code.
235
+
236
+ ```js
237
+ assert.ok(vm.run('return true') === true);
238
+ ```
239
+
240
+ **TIP**: See tests for more usage examples.
241
+
242
+ ### Loading modules by relative path
243
+
244
+ 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.
245
+
246
+ ```js
247
+ vm.run('require("foobar")', '/data/myvmscript.js');
248
+ ```
249
+
250
+ If the script you are running is a VMScript, the path is given in the VMScript constructor.
251
+
252
+ ```js
253
+ const script = new VMScript('require("foobar")', { filename: '/data/myvmscript.js' });
254
+ vm.run(script);
255
+ ```
256
+
257
+ ### Resolver
258
+
259
+ 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.
260
+
261
+ ```js
262
+ const resolver = makeResolverFromLegacyOptions({
263
+ external: true,
264
+ builtin: ['fs', 'path'],
265
+ root: './',
266
+ mock: {
267
+ fs: {
268
+ readFileSync: () => 'Nice try!',
269
+ },
270
+ },
271
+ });
272
+ const vm = new NodeVM({
273
+ console: 'inherit',
274
+ sandbox: {},
275
+ require: resolver,
276
+ });
277
+ ```
278
+
279
+ ## VMScript
280
+
281
+ 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.
282
+
283
+ ```js
284
+ import { VM, VMScript } from 'vm2';
285
+
286
+ const vm = new VM();
287
+ const script = new VMScript('Math.random()');
288
+ console.log(vm.run(script));
289
+ console.log(vm.run(script));
290
+ ```
291
+
292
+ It works for both `VM` and `NodeVM`.
293
+
294
+ ```js
295
+ import { NodeVM, VMScript } from 'vm2';
296
+
297
+ const vm = new NodeVM();
298
+ const script = new VMScript('module.exports = Math.random()');
299
+ console.log(vm.run(script));
300
+ console.log(vm.run(script));
301
+ ```
302
+
303
+ 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.
304
+
305
+ ## Error handling
306
+
307
+ 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`.
308
+
309
+ ```js
310
+ try {
311
+ var script = new VMScript('Math.random()').compile();
312
+ } catch (err) {
313
+ console.error('Failed to compile script.', err);
314
+ }
315
+
316
+ try {
317
+ vm.run(script);
318
+ } catch (err) {
319
+ console.error('Failed to execute script.', err);
320
+ }
321
+
322
+ process.on('uncaughtException', err => {
323
+ console.error('Asynchronous error caught.', err);
324
+ });
325
+ ```
326
+
327
+ ## Debugging a sandboxed code
328
+
329
+ You can debug or inspect code running in the sandbox as if it was running in a normal process.
330
+
331
+ - You can use breakpoints (which requires you to specify a script file name)
332
+ - You can use `debugger` keyword.
333
+ - You can use step-in to step inside the code running in the sandbox.
334
+
335
+ ### Example
336
+
337
+ /tmp/main.js:
338
+
339
+ ```js
340
+ import { VM, VMScript } from 'vm2';
341
+ import { readFileSync } from 'node:fs';
342
+
343
+ const file = `${__dirname}/sandbox.js`;
344
+
345
+ // By providing a file name as second argument you enable breakpoints
346
+ const script = new VMScript(readFileSync(file), file);
347
+
348
+ new VM().run(script);
349
+ ```
350
+
351
+ /tmp/sandbox.js
352
+
353
+ ```js
354
+ const foo = 'ahoj';
355
+
356
+ // The debugger keyword works just fine everywhere.
357
+ // Even without specifying a file name to the VMScript object.
358
+ debugger;
359
+ ```
360
+
361
+ ## Read-only objects (experimental)
362
+
363
+ 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.
364
+
365
+ **Example without using `freeze`:**
366
+
367
+ ```js
368
+ const util = {
369
+ add: (a, b) => a + b,
370
+ };
371
+
372
+ const vm = new VM({
373
+ sandbox: { util },
374
+ });
375
+
376
+ vm.run('util.add = (a, b) => a - b');
377
+ console.log(util.add(1, 1)); // returns 0
378
+ ```
379
+
380
+ **Example with using `freeze`:**
381
+
382
+ ```js
383
+ const vm = new VM(); // Objects specified in the sandbox cannot be frozen.
384
+ vm.freeze(util, 'util'); // Second argument adds object to global.
385
+
386
+ vm.run('util.add = (a, b) => a - b'); // Fails silently when not in strict mode.
387
+ console.log(util.add(1, 1)); // returns 2
388
+ ```
389
+
390
+ **IMPORTANT:** It is not possible to freeze objects that have already been proxied to the VM.
391
+
392
+ ## Protected objects (experimental)
393
+
394
+ 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`.
395
+
396
+ **IMPORTANT:** It is not possible to protect objects that have already been proxied to the VM.
397
+
398
+ ## Cross-sandbox relationships
399
+
400
+ ```js
401
+ const assert = require('assert');
402
+ const { VM } = require('vm2');
403
+
404
+ const sandbox = {
405
+ object: new Object(),
406
+ func: new Function(),
407
+ buffer: new Buffer([0x01, 0x05]),
408
+ };
409
+
410
+ const vm = new VM({ sandbox });
411
+
412
+ assert.ok(vm.run(`object`) === sandbox.object);
413
+ assert.ok(vm.run(`object instanceof Object`));
414
+ assert.ok(vm.run(`object`) instanceof Object);
415
+ assert.ok(vm.run(`object.__proto__ === Object.prototype`));
416
+ assert.ok(vm.run(`object`).__proto__ === Object.prototype);
417
+
418
+ assert.ok(vm.run(`func`) === sandbox.func);
419
+ assert.ok(vm.run(`func instanceof Function`));
420
+ assert.ok(vm.run(`func`) instanceof Function);
421
+ assert.ok(vm.run(`func.__proto__ === Function.prototype`));
422
+ assert.ok(vm.run(`func`).__proto__ === Function.prototype);
423
+
424
+ assert.ok(vm.run(`new func() instanceof func`));
425
+ assert.ok(vm.run(`new func()`) instanceof sandbox.func);
426
+ assert.ok(vm.run(`new func().__proto__ === func.prototype`));
427
+ assert.ok(vm.run(`new func()`).__proto__ === sandbox.func.prototype);
428
+
429
+ assert.ok(vm.run(`buffer`) === sandbox.buffer);
430
+ assert.ok(vm.run(`buffer instanceof Buffer`));
431
+ assert.ok(vm.run(`buffer`) instanceof Buffer);
432
+ assert.ok(vm.run(`buffer.__proto__ === Buffer.prototype`));
433
+ assert.ok(vm.run(`buffer`).__proto__ === Buffer.prototype);
434
+ assert.ok(vm.run(`buffer.slice(0, 1) instanceof Buffer`));
435
+ assert.ok(vm.run(`buffer.slice(0, 1)`) instanceof Buffer);
436
+ ```
437
+
438
+ ## CLI
439
+
440
+ Before you can use vm2 in the command line, install it globally with `npm install vm2 -g`.
441
+
442
+ ```sh
443
+ vm2 ./script.js
444
+ ```
445
+
446
+ ## Known Issues
447
+
448
+ - It is not possible to define a class that extends a proxied class. This includes using a proxied class in `Object.create`.
449
+ - Direct eval does not work.
450
+ - Logging sandbox arrays will repeat the array part in the properties.
451
+ - Source code transformations can result a different source string for a function.
452
+ - There are ways to crash the node process from inside the sandbox.
453
+
454
+ [npm-image]: https://img.shields.io/npm/v/vm2.svg
455
+ [npm-url]: https://www.npmjs.com/package/vm2
456
+ [license-image]: https://img.shields.io/npm/l/vm2.svg
457
+ [license-url]: https://github.com/patriksimek/vm2/blob/resurrection/LICENSE.md
458
+ [downloads-image]: https://img.shields.io/npm/dm/vm2.svg
459
+ [downloads-url]: https://www.npmjs.com/package/vm2
460
+ [snyk-image]: https://snyk.io/test/github/patriksimek/vm2/badge.svg
461
+ [snyk-url]: https://snyk.io/test/github/patriksimek/vm2
package/bin/vm2 ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+
3
+ require(__dirname +'/../lib/cli.js');