import { config } from '../app/config-handler' ; const urlParts = /^(https?:\/\/)?([^/]*@)?(.+?)(:\d{2,5})?([/?].*)?$/ ; const dot = /\./g ; interface IURLObject { tld : string ; domain : string ; subdomain : string ; } export class WhitelistHandler { param url { String } returns { boolean } public isWhitelisted ( url ) { const { whitelistUrl } = config . getConfigFields ( [ 'whitelistUrl' ] ) ; return this . checkWhitelist ( url , whitelistUrl ) ; } param url return { { tld : string | * , domain : string | * , subdomain : string } } public parseDomain ( url ) { let urlSplit = url . match ( urlParts ) ; let domain = urlSplit [ 3 ] ; const tld = domain . slice ( domain . lastIndexOf ( '.' ) ) ; urlSplit = domain . slice ( 0 , - tld . length ) . split ( dot ) ; domain = urlSplit . pop ( ) ; const subdomain = urlSplit . join ( '.' ) ; return { tld : tld . trim ( ) , domain : domain . trim ( ) , subdomain : subdomain . trim ( ) , } ; } param url { String } param whitelistUrl { String } returns { boolean } private checkWhitelist ( url , whitelistUrl ) { const whitelistArray = whitelistUrl . split ( ',' ) ; const parsedUrl = this . parseDomain ( url ) ; if ( ! parsedUrl ) { return false ; } if ( ! whitelistUrl ) { return false ; } if ( ! whitelistArray . length || whitelistArray . indexOf ( '*' ) !== - 1 ) { return true ; } return whitelistArray . some ( ( whitelistHost ) => { const parsedWhitelist = this . parseDomain ( whitelistHost ) ; if ( ! parsedWhitelist ) { return false ; } return this . matchDomains ( parsedUrl , parsedWhitelist ) ; } ) ; } param parsedUrl { Object } param parsedWhitelist { Object } returns { boolean } private matchDomains ( parsedUrl , parsedWhitelist ) { if ( ! parsedUrl || ! parsedWhitelist ) { return false ; } if ( parsedUrl . subdomain === parsedWhitelist . subdomain && parsedUrl . domain === parsedWhitelist . domain && parsedUrl . tld === parsedWhitelist . tld ) { return true ; } const hostNameFromUrl = parsedUrl . domain + parsedUrl . tld ; const hostNameFromWhitelist = parsedWhitelist . domain + parsedWhitelist . tld ; if ( ! parsedWhitelist . subdomain ) { return hostNameFromUrl === hostNameFromWhitelist ; } return ( hostNameFromUrl === hostNameFromWhitelist && this . matchSubDomains ( parsedUrl . subdomain , parsedWhitelist . subdomain ) ) ; } param subDomainUrl { String } param subDomainWhitelist { String } returns { boolean } private matchSubDomains ( subDomainUrl , subDomainWhitelist ) { if ( subDomainUrl === subDomainWhitelist ) { return true ; } const subDomainUrlArray = subDomainUrl . split ( '.' ) ; const lastCharSubDomainUrl = subDomainUrlArray [ subDomainUrlArray . length - 1 ] ; const subDomainWhitelistArray = subDomainWhitelist . split ( '.' ) ; const lastCharWhitelist = subDomainWhitelistArray [ subDomainWhitelistArray . length - 1 ] ; return lastCharSubDomainUrl === lastCharWhitelist ; } } const whitelistHandler = new WhitelistHandler ( ) ; export { whitelistHandler } ;