vm2-process
Run untrusted code via vm2, but inside a separate process which has additional restrictions:
- Limit how much of a CPU can be used
- Limit how much memory can be used
- Limit how much time it can take (even if blocked by sync code)
Installation
npm install --save vm2-process
API
The createVm2Pool
(default export) accepts the following options:
Title | Key | Default |
---|
Min Threads | min | - |
Max Threads | max | - |
CPU | cpu | 100 percent |
Memory | memory | 2000 megabytes |
Execution Time | time | 1000 milliseconds |
It will return a run
function that takes two arguments: run(code, scope)
code
is a string of JavaScript code.
scope
is an object, of which will be globally accessible during execution.
Note: Communication is done via a unix socket, and therefore the scope,
and result from the execution needs to be JSON serializable.
Usage
Simple usage with only code
import createVm2Pool from 'vm2-process';
const { run, drain } = createVm2Pool({ min: 1, max: 3 });
const result = await run('1 + 1');
console.log(result)
drain();
Simple usage with some scope
import createVm2Pool from 'vm2-process';
const { run, drain } = createVm2Pool({ min: 1, max: 3 });
const result = await run('1 + a', { a: 2 })
console.log(result)
drain();
Simple usage with some limits
import createVm2Pool from 'vm2-process';
const { run, drain } = createVm2Pool({
min: 1,
max: 3,
cpu: 100,
memory: 2000,
time: 1000
});
const result = await run('while (true) {}', null);
drain();