Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cloudflare Github Validation
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.