« Back to blog

Securing JS - "window.location" can we trust in it ?

We need a way to sell JS widgets and license these on a domain basis.

The idea is to provide a key which locks the widget to a given domain.

Basically we will be using window.location.host (and/or others similar like "hostname").

So, for instance  if we do

window.location.host == "mydomain.com"

we can lock the widget to this domain. Or can we ?

window.location.host = "localhost"

doesn't work cause the setter will cause the browser to navigate to "localhost". But what if we did (using Google Chrome):

window.location.__defineGetter__("host", function(){return "localhost";})

now window.location.host returns "localhost"!

The solution would be to use __lookupGetter__

window.location.__lookupGetter__("host")

If you call this before defining you own getter you get "undefined" but after defining the getter it returns a function. This way you can see if they tampered with the getter.

But what if they did

window.location.__lookupGetter__ = function(name){ return undefined;}

Now our previous method doesn't work!

We should do a 

/\[native code\]/.test(window.location.__lookupGetter__.toString())

 to make sure they haven't tampered with the __lookupGetter__ function.

Apparently Firefox doesn't provide __defineGetter__ and __lookupGetter__ for native objects like window.location so you can trust it....

We will be experimenting with this further but it just shows that JS is not to be trusted when it comes to securing your apps or widgets