Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save timelf123/8fe74dfb08ad768d681a9b8a6e05a222 to your computer and use it in GitHub Desktop.
Save timelf123/8fe74dfb08ad768d681a9b8a6e05a222 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.
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