I have a function that runs before every API request to check if the request is from a valid origin.
I have an array of valid origins
const whitelist = [ 'a.com', 'b.co.uk' ]
const validOrigin = str => {
const url = new URL( str )
return whitelist.includes( url.host )
}
console.log(validOrigin('https://www.a.com'))
It returns false because of the www. I dont want to just add a copy with www. to the array of valid origins. I would like a way that covers this and everything else thats unexpected.
Keeping in mind that, by the rules, www.example.com and example.com are different origins:
If you want to match any origin on the same domain or a subdomain of the domains in the whitelist, then you need to:
. followed by the string (to stop third-party-hacker-a.com matching)So something like:
const validOrigin = str => {
const url = new URL( str )
const host = url.host;
return whitelist.some( element => {
if (element === host) return true;
return element.endsWith(`.${host}`);
} )
}
The Array.prototype.includes function only accepts the value to search for, and looks for an exact match.
You would need to use a function that accepts a callback to test the elements - for example, the Array.prototype.findIndex function.
As you mention in the comments, you'll also need to change the whitelist so that you can exclude domains whose name ends with one of your valid domains.
const whitelist = [ /(^|\.)a\.com$/i, /(^|\.)b\.co\.uk$/i ];
const validOrigin = str => {
const url = new URL(str);
const index = whitelist.findIndex(el => el.test(url.host));
return index !== -1;
};
document.querySelectorAll("#tests > li").forEach(li => {
const str = li.dataset.value;
const result = validOrigin(str);
li.textContent = `${str} = ${result}`;
});
<ul id="tests">
<li data-value="http://a.com/foo"></li>
<li data-value="http://www.a.com/foo"></li>
<li data-value="http://dev.a.com/foo"></li>
<li data-value="http://banana.com/foo"></li>
<li data-value="http://a.com.b.ru/foo"></li>
</ul>
you can try something like this
str = str.replace( new RegExp("((http)(s)?:\/\/)?(www.)?","gm"),"")
this will delete the first part of the url