Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sumonst21
Forked from judge2020/Aworker.js
Created October 2, 2019 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumonst21/4e533a6be6f9e4725728685b14b3fa04 to your computer and use it in GitHub Desktop.
Save sumonst21/4e533a6be6f9e4725728685b14b3fa04 to your computer and use it in GitHub Desktop.
Cloudflare Workers: block proxy IPs
// Using a global variable so we aren't
// pulling from the proxy API on each
// and every subsequent request
// (note that the Workers billing still applies here)
//
// This could be "truly global" with KV but
// it's not really needed here unless the proxy list
// starts blocking CF ips.
//
//
var ips = [];
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Fetch and log a given request object
* @param {Request} request
*/
async function handleRequest(request) {
// check if the IP list is already populated
if(this.ips.length == 0) {
try {
const proxyResponse = await fetch("https://www.proxy-list.download/api/v0/get?l=en&t=https")
const proxyJson = await proxyResponse.json()
proxyJson[0]["LISTA"].forEach(proxyItem => {
this.ips.push(proxyItem["IP"])
})
}
catch(err) {
// don't break requsts if there is an error with
// the json or request failing
console.log(err)
}
}
if(this.ips.includes(request.headers.get("CF-Connecting-IP"))) {
// feel free to customize this
// you may want to error 400 or 401.
return new Response("An unknown error occured", {status: 500, statusText: "Internal Server Error"})
}
const response = await fetch(request)
return response
}

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment