Sandboxed / Scoped function

There are a lot of hacks and workarounds regarding safe, sandboxed code execution in the browser (I've seen the dreaded "with" being used for example). If ES could provide some kind of way to execute functions without access to the global scope it would be great. Here's my idea on how to do it.

A keyword like "scoped" or "sandboxed" could be used to declare a sandboxed function. This function, when executed has no access to the global scope (window etc.) and only a very limited number of built-in types (arrays, functions, primitives, objects, etc..). Scope could be given via Function.bind, "this" would take the place of the global scope in this case. The only I/O happens through this ("global" scope), arguments and return value.

var doSth = sandboxed function (arg1, arg2) {
  return document;
}
doSth(); //undefined
var doOther = doSth.bind({document});
doOther(); //returns the document object

Scopes are lexical, so that would only affect the function being ran - if you tried to run a function that was defined elsewhere in there, it wouldn’t be sandboxed.

Do you mean a function declared outside of this "sandboxed" function? You shouldn't have access to those.

If you mean a function declared in the sandboxed function - it should of course inherit the scope in some way so that an escape isn't possible

The use cases I’m aware of for sandboxing are about running untrusted code safely - as such, that code might, say, be passed in as a function argument - not about restricting code that you’ve authored. A lexical declaration wouldn’t seem to be able to effect code declared elsewhere.

You're right, maybe I didn't think this through all the way. Still, some kind of sandboxing as well as changing scope would be useful to have in my opinion.

Maybe implement the first as a kind of extension to eval and the second as a function similar to .bind?

(Also I still see use for my original idea, but in a context that hasn't been explored by browsers yet, so that doesn't really apply here)

slightly off-topic, but there are production-scenarios where you want to deploy a single, rolled-up js-file, rather than multiple es-module files.

some way to sandbox es-modules so you can roll them up into a single-file would be useful.

I haven't looked too much in to it but I think the Realms proposal might cover this.

1 Like

As @AshleyScirra says, the Realms proposal is the place to go. Controlling access to the global scope is one of the primary drivers of this proposal.