Skip to content

Instantly share code, notes, and snippets.

Forked from line-o/SandBox.js
Created October 7, 2012 10:53
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Is it possible to sandbox JS code
function sandbox(script, context){
context.window = {};
for (var key in context){
context.window[key] = context[key];
} = context.window;
eval("with (context){~function(){'use strict';" + script + "}()}");
// ~115 bytes:
// function(e,t,n,r){r={};for(n in t)r[n]=t[n];,eval("with(t)~function(){'use strict';"+e+"}()")}
var NOT_ALLOWED = function(name){
return function(){
console.warn(name + "(); is not allowed.");
return function(){};
var scope = {
"alert": function(message){ console.log(message); },
"Function": NOT_ALLOWED("Function"),
"eval": NOT_ALLOWED("eval")
function test(script){
try {
sandbox(script, scope);
} catch (e) {
var samples = [
"alert('good try');",
"~new Function('alert(4)')();",
"(function(){this.eval('good try');}).apply(null)",
"(function(){return this;})().alert(6)"
Copy link

aemkei commented Oct 7, 2012

This should work in the browser and Node.js.

Copy link

aemkei commented Oct 7, 2012

// This will fail:
sandbox("(function(){this.eval('good try');}).apply(null)", scope);

Copy link

aemkei commented Oct 9, 2012

Okay, 'use strict' might fix that.

Copy link

"console.log(this, window, self, top, frames, document, parent, document.defaultView);" // should also be protected.
// could be done in line 8: = context.self = = context.frames = context.parent = context.window;

"setTimeout(function () { console.log(this, window); }, 100);" // "this" will be the global object.
// this might work (to be set in the scope object): "setTimeout": function (fn, time) { setTimeout(~function () { fn(); }.call(scope), time); }
"onclick=function () { console.log(this, window); };" // same here.
// how could we protect these cases? Not allowing event handlers and timeouts at all seems a little too strict.

Copy link

This one break your jail:
'new (function(){}).constructor('alert("good try")')()'

Copy link


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment