Great Resig postĀ regarding JavaScriptās eval() statement:
Last week itĀ came outĀ that, in Firefox (and other Gecko-based browsers) you could dip into the private scope of a function using eval, like so:
// Getting "private" variables varĀ obj =Ā (function()Ā { Ā Ā varĀ a =Ā 21; Ā Ā returnĀ { Ā Ā Ā // public function must reference 'a' Ā Ā fn:Ā function()Ā {a;} Ā Ā }; })(); Ā varĀ foo; eval('foo=a', obj.fn); console.log(foo);Ā // 21I think the common response to seeing the above was something like: WUH!?!?
Iāll admit I had no idea that the eval() let you essentially peek into any arbitrary scope that you wanted to. What should otherwise be private members of a class or object are suddenly as public as any other. This means there are zero guaranteesĀ that your private data and code actually remain private in the JavaScript world.
Moral of the story? Donāt trust data in the browser! Weāve always known to validate any data that comes in to the server ā form validation just isnāt enough ā but now we know that we canāt necessarily trust our own private variables. If any 3rd party script runs on the same page as your scripts, youāre open to an āattackā of them reading and writing your private variables or functions! No private data or code is safe!
But what if ā what ifĀ ā you control 100% of the JavaScript that runs on a web page ā what then? Can you still trust the that your private variables and private functions havenāt been tampered with? Nope. Firefox plugins like GreaseMonkey let users run any bit of JavaScript on any page they want ā including your ā100% controlledā page.
Donāt get me wrong ā if you control 100% of the JavaScript on your page, thenĀ itās certainly not likelyĀ that youāre code will be tampered with, but it is possible, and IMO thatās equally scary.
Thereās no such thing as secure data or code in JavaScript.
The good news? Itās been fixed. So future versions of future browsers will one day not have this problem. In Firefox. Other browsers? No idea.