Sandbox untrusted code in a worker
Run untrusted code in a worker thread with limited memory and a kill timeout, and know what a worker does not isolate.
A worker thread gives you a separate JavaScript heap and the ability to stop it. That is useful to contain a runaway script, but it is not a security sandbox.
import { Worker } from 'node:worker_threads';
function runLimited(file, ms) {
return new Promise((resolve, reject) => {
const worker = new Worker(file, { resourceLimits: { maxOldGenerationSizeMb: 64 } });
const timer = setTimeout(() => worker.terminate(), ms);
worker.once('message', resolve);
worker.once('error', reject);
worker.once('exit', (code) => {
clearTimeout(timer);
if (code !== 0) reject(new Error(`worker stopped with code ${code}`));
});
});
}
await runLimited('./loop-forever.js', 500).catch((e) => console.log(e.message));worker stopped with code 1resourceLimits caps the old generation heap, so a script that allocates without end fails alone, and terminate() stops a loop that never yields. The main thread stays responsive. See the worker_threads documentation.
A worker still shares the process: it can require modules, read files and use the network unless you also apply the permission model. For hostile code use a separate process in a container, or isolated-vm.