Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 133 ยท Projects

Project: Online Code Runner with child_process

Build a code runner in Node.js with child_process. Run untrusted code with timeouts, output caps, the permission model and a job queue, and learn honestly where child processes stop being a sandbox.

Playgrounds, coding-interview sites, autograders and "try it" boxes in documentation all do the same thing: take code written by a stranger and run it on your machine. That is one of the most dangerous things a server can do, and one of the most instructive Node.js projects. You will use child_process to run code in a separate process, and you will learn which protections Node itself can give you (time limits, output limits, memory limits, the permission model) and which it cannot (a real security boundary).

The runner you build has four layers:

  1. runJs(code): starts a fresh node process with a locked-down environment, feeds it input, collects output, and returns a plain result object. It enforces a timeout and an output cap and cleans up afterwards.
  2. Permission flags: Node's permission model (--permission) denies file access, child processes and worker threads to the guest code.
  3. A job queue that runs at most N programs at a time, because ten parallel infinite loops would stall a small server.
  4. An HTTP API with validation, so a web page can call it.

This site's own runner works in the same spirit. The Java, C++ and other "Run" buttons post code to a server that runs it inside Docker with real isolation (see the Piston notes in the project documentation). That server is what you would use for many languages. Here you see the Node.js-level building blocks.

A child process is not a sandbox. It protects your main program from crashes and infinite loops in the guest, but the guest still runs as the same operating system user, on the same machine, usually with the same network. Never expose a runner like this to the internet without real isolation underneath: a container with no network and a read-only file system, a virtual machine, or a dedicated service such as Piston, gVisor or Firecracker. The permission model is a useful extra layer, not a replacement. Everything below runs inside the lesson's own sandbox, but do not treat the code as production-ready security.

Stage 1: run one program and collect everything

The simplest way to run code is execFile or spawn with the code as an argument. We write the code to a temporary file in a private folder instead, because it is more flexible (ES modules, longer programs) and avoids command-line length limits and quoting problems. Never build a shell command string from user input: spawn with an argument array and no shell means there is nothing to inject into (Child Processes).

Our runJs function does these things, in this order:

  • Create a fresh temp directory and write main.mjs into it.
  • Start process.execPath (the same Node binary that runs your server) with a few safety flags, cwd set to the temp folder and an empty environment (env: {}), so the guest cannot read your DATABASE_URL or API keys from process.env.
  • Send the optional input to the child's stdin.
  • Collect stdout and stderr as they arrive. If the total passes the limit, kill the child: otherwise while (true) console.log('x') fills your memory with output faster than anything else.
  • Start a timer. If the program has not finished in time, kill it with SIGKILL, which cannot be caught or ignored.
  • When the child closes, clear the timer, delete the temp folder and return { exitCode, signal, timedOut, truncated, stdout, stderr, ms }.

The flags are --permission with --allow-fs-read=<temp folder> (the guest may read only its own folder, nothing else), and --max-old-space-size=64, which limits the JavaScript heap to 64 MB. Without --allow-child-process, --allow-worker and --allow-addons, the guest cannot spawn processes, start threads or load native addons.

Node.js runJs: timeout, output cap, permission model and a clean environment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the verdicts. The infinite loop was killed by the timer (timedOut: true, signal SIGKILL). The flood stopped at the 2,000-byte cap. Reading /etc/passwd failed with a permission error (ERR_ACCESS_DENIED), spawning a command did too, and the environment is empty, so there are no secrets to steal. Reading the program's own standard input works, because file descriptor 0 is not a path.

Two details matter in production. First, child.kill('SIGKILL') kills only that process; if the guest could start children of its own, they would survive. The permission model blocks that here, and in other designs you start the child with detached: true and kill the whole process group with process.kill(-child.pid, 'SIGKILL') (on Linux and macOS). Second, the temp folder is removed in finally, so even a crash of your own code path leaves nothing behind.

The permission model restricts file system access, child processes, worker threads, native addons and WASI. It does not restrict the network, CPU time, or the number of file descriptors, and it does not protect against bugs in Node or V8 itself. A guest program can still open outgoing connections, so network isolation has to come from the operating system (a container with no network, or a firewall rule). Memory limits from --max-old-space-size cover the JavaScript heap only; typed arrays and buffers live outside it. Use cgroup limits (docker run --memory) for a hard cap.

Stage 2: a job queue that limits concurrency

If twenty users press "Run" at once, twenty Node processes start, each using a CPU core and tens of megabytes. A small server falls over. The fix is a queue with a concurrency limit: only limit programs run at the same time; the rest wait in line, and each caller still simply awaits its result. We also cap the queue length: when the line is too long, answer "busy, try again" at once instead of letting requests pile up for minutes.

Node.js RunnerPool: at most N programs at a time, a bounded waiting line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Jobs a and b started immediately, c and d waited and ran as soon as a slot freed up, and e, f and g were rejected because the waiting line was full. The peak concurrency never exceeded the limit of two. Rejecting early is a feature: the website can show "busy" immediately, instead of a spinner that ends in a timeout. In an HTTP server this maps to status 429 Too Many Requests or 503 Service Unavailable with a Retry-After header.

For a production pool, base the limit on CPU cores and memory (os.availableParallelism()), not on a guess, and count the time spent waiting separately from the time spent running, so you can see when you need more capacity.

Stage 3: an HTTP API around the pool

Finally, put an HTTP interface on top: POST /run with a JSON body { "code": "...", "stdin": "..." }. The handler validates everything before any process starts, because the cheapest attack on a runner is a huge or malformed request. It enforces these rules:

  • Only POST, only JSON, request bodies up to 20 KB (read with a size limit, as in Request Bodies).
  • code is a non-empty string up to 5,000 characters, and stdin an optional string up to 1,000 characters.
  • Per-client rate limit: here 3 runs per window per IP, kept in a Map. For a real service use the techniques from Rate Limiting and API Protection.
  • Results are plain JSON with a verdict; the temp path is stripped from error messages so the server's directory layout is not leaked.
Node.js POST /run: validation, rate limit, queue and results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The API returns a status for every outcome: ok, error (with the first error line, without the server's temp path), time-limit and output-limit for a runaway program, plus clear HTTP errors for bad input (400, 405, 413), for a client that runs too often (429) and for a full queue (503).

Hardening checklist for real deployments

  • Isolation. Run each job in a throwaway container or microVM with no network, a read-only root file system, a tiny writable temp directory, CPU and memory cgroup limits, a PID limit (stops fork bombs) and a non-root user. Piston, Judge0, gVisor and Firecracker exist for this.
  • Time. Limit CPU time as well as wall-clock time (a program that sleeps uses no CPU but still holds a slot). Linux ulimit -t or cgroup cpu.max do that.
  • Disk. Limit the size of files the guest can write, and delete the working directory afterwards.
  • No secrets nearby. The runner host must hold no credentials the guest could reach, and should not be on a network that contains internal services.
  • Output. Treat output as untrusted text: escape it when you show it in a page, or you create a cross-site scripting hole (Web Security).
  • Abuse. Authenticate users, rate limit per user and per IP, and watch for crypto miners and outbound attack traffic.
  • Observability. Log job id, duration, verdict and resource use (never the program itself in plain logs if it may contain personal data).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does runJs start the child with env: {}?

    By default a child inherits the parent's environment variables. A guest could print them. An empty environment hands over nothing.
  2. 2. Why kill with SIGKILL when the time limit is reached?

    SIGTERM can be handled by the guest. SIGKILL is enforced by the operating system.
  3. 3. What does --permission without --allow-child-process prevent the guest from doing?

    The permission model denies APIs such as spawn and exec unless explicitly allowed, along with file access outside the allowed paths, workers and native addons.
  4. 4. Why does the pool reject new jobs when the waiting line is full instead of queueing without limit?

    Back-pressure protects the server. Answering 503 immediately is better than a long wait that ends in a timeout.
  5. 5. Is a child process with the permission model enough to safely run code from anonymous users on the internet?

    The permission model does not limit the network, CPU time or kernel attack surface. Treat it as one layer among several, under real isolation.

Summary

  • Run guest code in a separate process with spawn, an argument array (never a shell string), an empty environment and a private temp directory that you always delete.
  • Enforce a timeout with SIGKILL, cap the output while it streams, and report outcomes as data: ok, error, time-limit, output-limit.
  • Node's permission model blocks file access, child processes, workers and addons, but not the network or CPU use; --max-old-space-size limits only the JavaScript heap.
  • Limit concurrency with a pool, bound its waiting line and answer 503 or 429 early.
  • Validate every request, rate limit, strip server paths from errors, and for real use put the whole thing inside container or microVM isolation.

Next: Project: Document and Report Generator