How to run a JavaScript function in a sandbox environment?

I have an application server written in JavaScript(node.js) . I accept a JS function code as an input from the web browser. Now I want to be able to run this function on server without affecting anything else.

I want to make sure that all the variables this function is modifying are local to the function and not affecting any other vars on server.

Also I would like to somehow avoid infinite loops or recursions and any other unforseen problems.

Mostly I would like the user to be able to trigger some code as a function to be run before I take some action.

Any ideas ?

You cannot programmatically determine if arbitrary code will run indefinitely or terminate.

This is called The Halting Problem.

You might be able to prevent arbitrary JS code from modifying variables other than the ones it creates by sandboxing in a separate process.

Either way, accepting arbitrary code for execution on a server is opening a huge security risk on your system. Think carefully about how you can avoid it.

Sandbox is a node module that according to the README;

  • Can be used to execute untrusted code
  • Support for timeouts (e.g. prevent infinite loops)
  • Restricted code (cannot access node.js methods)

The Halting Problem as @maerics wrote about can be solved by setting a timeout for the code although you can not do that in the same process, because for example while(1) will block it. Sandbox addresses this issue by using a child process.

The variable problem should therefore also be solved because Sandbox is in a child process and not the main process.

As mentioned before, if possible, you should avoid users to run arbitrary code on your server because it comes with an huge security risk. Even through the module provides this restrictions you should run at least the child processes with an as unprivileged user as possible.