Ben Muircroft Ben Muircroft - 2 months ago 7
Javascript Question

Is hiding code inside null like this safe?

Can you get the key after it's injected?

var outside=[];

var NULL=(function(){
var key='';
console.log("Hi, I'm null!");
window.injectkey=function(k){
window.injectkey=null;
key=k;
return;
};
window.askmeforkey=function(){return "nope! I could use my key for stuff though...";}
setTimeout(function(){
outside.push("I still exist and can alter things outside but you can't see me!");
console.log(outside);
},1000);
})();
NULL=null;
console.log('NULL=='+NULL); // prints NULL==null


After try

console.dir(NULL); // prints null

injectkey('xyz');


And again

injectkey('abc'); // Uncaught TypeError: injectkey is not a function(…)

askmeforkey() // nope


Possible use: (Say the key might be an encryption key thats not hard coded anywhere)

injectkey
could be done many ways via some secure encrypted messaging

Answer

key is entirely private to the anonymous function. Note that there's no need for NULL here at all, this does the exact same thing:

var outside=[];

(function(){
    var key='';
    console.log("Hi, I'm null!");
    window.injectkey=function(k){
        window.injectkey=null;
        key=k;
        return;
        };
    window.askmeforkey=function(){return "nope! I could use my key for stuff though...";}
    setTimeout(function(){
        outside.push("I still exist and can alter things outside but you can't see me!");
        console.log(outside);
        },1000);
    })();

This is a common pattern for avoiding exposing variables more widely than is necessary.