/sandbox

A nifty JavaScript sandbox for Node.js

Primary LanguageJavaScriptISC LicenseISC

🏖️ sandbox

A nifty JavaScript sandbox for Node.js.
Latest Release Build Status

What is it?

It can...

  • Be used to execute untrusted code
  • Timeout long-running code and infinite loops
  • Handle errors gracefully
  • Run restricted code
  • Pass rich data structures back
  • Capture console output
const s = new Sandbox();

s.eval("const o = { answer: 4.2 }; o", function(err, res) {
  console.log("The answer is: %d", res.answer * 10); // The answer is: 42
});

Installation

npm install --save sandbox

By default the package will attempt to download the corresponding binary release for your platform. If you wish to skip this action you can set the SANDBOX_SKIP_DOWNLOAD environment variable:

env SANDBOX_SKIP_DOWNLOAD=1 npm install --save sandbox

Usage

NOTE: As it stands, only values that can be serialized to JSON may be returned.

About

sandbox is a tool to allow safe local execution of JavaScript.

The previous version of sandbox attempted to accomplish this by spawning a child process and running the untrusted code in a new Node.js context with known exploits patched. Unfortunately this didn't work well from a security standpoint and it became increasingly difficult to keep up with the whack-a-mole of security vulnerabilities. In fact, the previous version still has unaddressed vulnerabilities that are impossible to patch with that architecture.

The current version of sandbox takes a new approach—it embeds a JavaScript interpreter in the library which executes code in a separate context in another thread. This is made possible with the help of two incredible projects:

  • Boa - a JavaScript interpreter written in Rust
  • Neon - a library for interfacing with Node-API

The major drawback to this approach is that it either requires the user to build the sandbox locally from source (which requires the user to have the rust build tools onhand) or provide pre-built binaries for every platform would need to be provided. In order to make things a little more seamless for users, we've opted to provided pre-built binaries for the following platforms:

  • Linux x86_64
  • MacOS arm64
  • MacOS x86_64
  • Windows x86_64

Given these targets we should be able to meet the needs of most users.

Building

First, if you don't already have the rust toolchain installed you can follow the instructions for installing rustup:

Install rust.

Next, running npm run build will attempt to build the project with cargo and move the compiled binary to ./index.node.

At this point you should be able to work with sandbox and run the tests: npm test.

Learn More

To learn more about Neon, see the Neon documentation.

To learn more about Rust, see the Rust documentation.

To learn more about Node, see the Node documentation.