const ipLib = require('ip')
const unauthorized = require('boom').unauthorized
const pkg = require('../package')

exports.plugin = {
  name: pkg.name,
  version: pkg.version,
  pkg,
  register(server, options) {
    server.auth.scheme('ip-whitelist', ipWhitelistScheme)
  }
}

function ipWhitelistScheme(server, whitelisted) {
  return {
    authenticate(request, h) {
      const { remoteAddress } = request.info

      const list = whitelisted instanceof Array ? whitelisted : [whitelisted]

      if (list.some(ip => {
          const regularIP = (ipLib.isV4Format(ip) || ipLib.isV6Format(ip)) && ipLib.isEqual(ip, remoteAddress);
          const cidrIP = ip.includes("/") && ipLib.cidrSubnet(ip).contains(remoteAddress);

          return regularIP || cidrIP;
      })) {
          return h.authenticated({ credentials: remoteAddress })
      }

      throw unauthorized(`${remoteAddress} is not a valid IP`)
    }
  }
}

@@ -282,493 +282,517 @@
 ion 
-ipWhitelistScheme(server, whitelisted) %7B%0A  return %7B%0A    authenticate(request, h) %7B%0A      const %7B remoteAddress %7D = request.info%0A%0A      const list = whitelisted instanceof Array ? whitelisted : %5Bwhitelisted%5D%0A%0A      if (list.some(ip =%3E %7B%0A          const regularIP = (ipLib.isV4Format(ip) %7C%7C ipLib.isV6Format(ip)) && ipLib.isEqual(ip, remoteAddress);%0A          const cidrIP = ip.includes(%22/%22) && ipLib.cidrSubnet(ip).contains(remoteAddress);%0A%0A          return regularIP %7C%7C cidrIP;%0A      %7D
+matches(ip, remoteAddress) %7B%0A  if (ipLib.isV4Format(ip) %7C%7C ipLib.isV6Format(ip)) %7B%0A    return ipLib.isEqual(ip, remoteAddress);%0A  %7D%0A%0A  if (ip.includes(%22/%22)) %7B%0A    return ipLib.cidrSubnet(ip).contains(remoteAddress);%0A  %7D%0A%0A  return false;%0A%7D%0A%0Afunction ipWhitelistScheme(server, whitelisted) %7B%0A  return %7B%0A    authenticate(request, h) %7B%0A      const %7B remoteAddress %7D = request.info%0A%0A      const list = whitelisted instanceof Array ? whitelisted : %5Bwhitelisted%5D%0A%0A      if (list.some(ip =%3E matches(ip, remoteAddress)
 )) %7B

Refactor IP match check