Last active
April 19, 2023 12:20
-
-
Save diegoparrilla/d7996da7fecb0491c179c150009f565e to your computer and use it in GitHub Desktop.
Using Cloudflare Workers and https://Apility.io API add to the request headers information of the blacklists of abusers that contains the IP address of the client.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener('fetch', event => { | |
event.respondWith(fetchAndCheckOrigin(event.request)) | |
}) | |
async function fetchAndCheckOrigin(req) { | |
try { | |
startTime = new Date(); | |
const body = await req.body; | |
const ip = req.headers.get('cf-connecting-ip'); | |
const es = req.headers.get('cf-ipcountry'); | |
const apilityio = await fetch('http://api.apility.net/badip/' + ip + '?token=APILITYIO_API_KEY', { headers: {'Accept': 'application/json'}} ); | |
const status = await apilityio.status; | |
var blacklists = 'ERROR'; | |
if (status == 404) { | |
// The IP has not been found in any blacklist | |
blacklists = ''; | |
} | |
if (status == 200) { | |
// The IP has been found in any blacklist | |
blacklists = (await apilityio.json())['response']; | |
} | |
if (status == 429) { | |
// Quota Exceeded. Too many requests. | |
blacklists = 'QUOTA_EXCEEDED'; | |
} | |
var endTime = new Date(); | |
let newHdrs = new Headers(req.headers) | |
newHdrs.set('Apilityio-Badip', blacklists) | |
newHdrs.set('Apilityio-Elapsed-Time', endTime - startTime); | |
if ((req.method == 'GET') || (req.method == 'HEAD')) { | |
const init = { | |
method: req.method, | |
headers: newHdrs, | |
}; | |
return await fetch(req.url, init); | |
} | |
else { | |
const init = { | |
method: req.method, | |
headers: newHdrs, | |
body: body | |
}; | |
return await fetch(req.url, init); | |
} | |
} catch (err) { | |
console.log(err); | |
return new Response('Internal Error') | |
} | |
return await fetch(req) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment