I have a javascript file that reads another file which may contain javascript fragments that need to be eval()-ed. The script fragments are supposed to conform to a strict s
Here's an idea. What if you used a static analyzer (something you could build with esprima, for example) to determine which outside variables the eval'd code uses, and alias them. By "outside code" i mean variables the eval'd code uses but does not declare. Here's an example:
eval(safeEval(
"var x = window.theX;"
+"y = Math.random();"
+"eval('window.z = 500;');"))
where safeEval returns the javascript string modified with a context that blocks access to outside variables:
";(function(y, Math, window) {"
+"var x = window.theX;"
+"y = Math.random();"
+"eval(safeEval('window.z = 500;');"
"})();"
There are a couple things you can do now with this:
undefined as the function arguments, or not passing arguments). Or you could simply throw an exception in cases where variables are being unsafely accessed.Note that the use of eval is a special case, since by its nature, it effectively can't be wrapped in another function (which is why we have to do eval(safeEval(...))).
Of course, doing all this work may slow down your code, but there are certainly places where the hit won't matter. Hope this helps someone. And if anyone creates a proof of concept, I'd love to see a link to it here ; )