How to really obfuscate your JavaScript code with more magic and annoy a poor succeeding programmer
Working on bad legacy code damages your brain. Encountering too many global variables without any use made me think about how an evil person (not me, of course) could make the life of his fellow programmers into hell.
I think I found an especially mean-spirited way.
Suppose you’ve inherited an inscrutable mess of code that you are expected to modify. While trying to make sense of it, you encounter lots of global variables; some of them are used (although you’re not sure why your predecessor chose to do it that way), but one of them is not.
Let’s say you encounter
more_magic = 42;
and more_magic
is used nowhere in the code. You do a global search for that string, and it turns up nowhere else. So you simply comment it out …
… and the code stops working. How is that possible?
Well, here is my suggestion, and it’s mean-spirited; however, it’s only possible because of JavaScript’s idiosyncrasies.
First, we don’t want for more_magic
to appear anywhere else in the code. Therefore, we encode it as npsf`nbhjd
(each character code increased by one) and supply a decode function:
function decode(inp) {
var i, out = '';
for (i = 0; i < inp.length; i++) {
out += String.fromCharCode(inp.charCodeAt(i)-1);
}
return out;
}
Next, given a string, we can access any global variable via the global object window
, like so (and this is JavaScript’s fault):
function pure_evil() {
var prop = decode('npsf`nbhjd');
(window[prop]) ? do_something() : halt_and_catch_fire();
}
And that’s it. Of course, we wouldn’t name those functions decode
and pure_evil
, but instead we’d choose inconspicuous names. And we’d bury them deep in other code. Thread that magic value through many function calls, and blow up late in the game.
Please, please, please: don’t try this at work!
(And yes, this is inspired by the old
Story About Magic
; it sounds funny, until it happens to you.)