Sandboxing and parsing jQuery in 100ms

Wednesday, 7 November 2012

I’ve been on a mission to create a reliable JavaScript sandbox. I started off writing one with regular expressions which was flawed because of the inability to match whole expressions and matching characters. That sandbox was called JSReg, it was broken by the very best js hackers (Alexey Silin, Jonas Magazinius, Mario Heiderich, Eduardo Vela, David Lindsay, Stefano Di Paola, Soroush Dalili, Giorgio Maone). After their work testing I decided to make a new parser called MentalJS, this time I didn’t let the browser handle syntax I parsed it and corrected it myself.

Today I feel a moment of satisfaction in that I think I’ve achieved my goal that I set myself. MentalJS now parses and sandboxes jQuery in 100ms and it’s actually usable within a sandboxed environment. The sandboxed environment is quite restrictive since I haven’t had chance to add a complete emulated DOM api but I don’t care about that right now. My goal was to create a perfect js parser and sandbox that you can’t escape from and I think I’ve done that.

Thanks again to Jonas Magazinius who helped me improve my parsing technique by providing very good test cases.

Sure, by sandboxing I mean the javascript input will be whitelisted to allow only a limited amount of functions. I then add sandboxed functions such as eval that converts code through the sandbox again. For example:

alert(1)
// converted to->
$alert$(1)

You can choose if you allow alert to be a function or not. Stuff like ”.constructor.constructor will return a sandboxed function.

The environment is protected against accessing harmful stuff like “location”, “document.cookie” etc but still allowing document.body.style.color or whatever you decide.

It could be used to share javascript code between users and allow users to build site functionality.