Validate that request is coming from Github Webhook range


#1
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})


async function handleRequest(request) {
  const ip = request.headers.get('cf-connecting-ip');
  const ghHeaders = new Headers();
  ghHeaders.append("User-agent", "Cloudflare")
  response = await fetch('https://api.github.com/meta', {headers: ghHeaders}).then(function(response) {
    return response.json()
  }).then(async function(ranges) {
    isValid = ranges.hooks.some(function(range) {
      return validateIpRange(range, ip);
    })
    if (isValid) {
      response = await fetch(request);
      return response;
    } else {
      return new Response("Access Denied - Not From Github", {status: 403})
    }
  })
  return response;
}

function validateIpRange(cidrRange, ip) {
  [network, mask] = cidrRange.split("/")
  
  function convertIp(ipDottedQuad) {
    octets = ipDottedQuad.split(".")
    converted = (+octets[0]<<24) + (+octets[1]<<16) + (+octets[2]<<8) + (+octets[3])
    return converted;
  }

  function convertMask(mask) {
      return -1<<(32-mask)
  }

  return (convertIp(ip) & convertMask(mask)) == convertIp(network)
}```

#2

Should be filed under recipies?