Skip to content
jshacks.dev
Security

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.

1 min read
Summarize in AI

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.

sandbox.jsJavaScript
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));
Text
worker stopped with code 1

resourceLimits 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.

Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.