import { every } from 'lodash' ; import { parse } from 'url' ; interface NetworkPolicyRule { allow : boolean ; protocol ? : string ; host ? : string ; } export interface NetworkPolicy { enabled : boolean ; rules : NetworkPolicyRule [ ] ; } const isHostMatch = ( actualHost , ruleHost ) => { const hostParts = actualHost . split ( '.' ) . reverse ( ) ; const ruleParts = ruleHost . split ( '.' ) . reverse ( ) ; return every ( ruleParts , ( part , idx ) => part === hostParts [ idx ] ) ; } ; export function allowRequest ( url , rules ) { const parsed = parse ( url ) ; if ( ! rules . length ) { return true ; } const allowed = rules . reduce ( ( result , rule ) => { if ( typeof result === 'boolean' ) { return result ; } const hostMatch = rule . host ? isHostMatch ( parsed . host || '' , rule . host ) : true ; const protocolMatch = rule . protocol ? parsed . protocol === rule . protocol : true ; const isRuleMatch = hostMatch && protocolMatch ; return isRuleMatch ? rule . allow : undefined ; } , undefined ) ; return typeof allowed !== 'undefined' ? allowed : false ; }