Thursday, June 25th, 2009
JavaScript sandbox using Web Workers
We have been sandboxing JavaScript in iframes for a long time. The Web Worker API has the nice property that it doesn't have access to objects like document and the like, and just runs code that you can pass over to it.
With this, Elijah Grey has created an experimental jsandbox API that gives you an eval function that you pass in some code, and optionally input data, callback for results, and an onerror callback.
Code looks like this:
-
-
jsandbox
-
.eval({
-
code : "x=1;Math.round(Math.pow(input, ++x))",
-
input : 36.565010597564445,
-
callback: function(n) {
-
console.log("number: ", n); // number: 1337
-
}
-
}).eval({
-
code : "][];.]\\ (*# ($(! ~",
-
onerror: function(ex) {
-
console.log("syntax error: ", ex); // syntax error: [error object]
-
}
-
}).eval({
-
code : '"foo"+input',
-
input : "bar",
-
callback: function(str) {
-
console.log("string: ", str); // string: foobar
-
}
-
}).eval({
-
code : "({q:1, w:2})",
-
callback: function(obj) {
-
console.log("object: ", obj); // object: object q=1 w=2
-
}
-
}).eval({
-
code : "[1, 2, 3].concat(input)",
-
input : [4, 5, 6],
-
callback: function(arr) {
-
console.log("array: ", arr); // array: [1, 2, 3, 4, 5, 6]
-
}
-
}).eval({
-
code : "function x(z){this.y=z;};new x(input)",
-
input : 4,
-
callback: function(x) {
-
console.log("new x: ", x); // new x: object y=4
-
}
-
});
-












Dean Edwards’ “sandboxing” script doesn’t do any sandboxing. It just evals code in the context an iframe, which is completely insecure. The “sandboxed” code could still access the parent window. For example,
sandbox.eval("parent.doWhatever()").Dean’s code can be simplified to to just using
iframe.contentWindow.eval. Nothing special there.@EliGrey I think you are being a bit harsh on Dean’s approach. He popularized/discovered the iframe approach that allows devs to access/use/extend native objects that are separate from the normal documents without using eval or function decompilation via toString(). Iframes, while still buggy in areas (IE https, Safari 2), also offer support for more than just Firefox 3.5, Chrome 2, and Safari 4. I think there is plenty of things “special” there.
@EliGrey Try reading the post before posting comments. Code running in the sandbox does not have access to parent/window/etc. It’s a web worker thread, which does not run in the context of the web page.
@randomrandom I never said anything about jsandbox. I was talking about Dean Edwards’ insecure attempt at making a sandbox. I’m the guy who wrote jsandbox.