Skip to content

Instantly share code, notes, and snippets.

@bitbybit
Last active November 13, 2023 18:42
Show Gist options
  • Save bitbybit/6f30814d955bfdc71b235fc897372c74 to your computer and use it in GitHub Desktop.
Save bitbybit/6f30814d955bfdc71b235fc897372c74 to your computer and use it in GitHub Desktop.
const cloudflareIpURLv4 = 'https://www.cloudflare.com/ips-v4'
const cloudflareIpURLv6 = 'https://www.cloudflare.com/ips-v6'
addEventListener('fetch', (event) => {
return event.respondWith(handleRequest())
})
/**
*
* @param url
*/
async function handleRequest (url = cloudflareIpURLv4) {
const response = await fetch(url)
const text = await gatherResponse(response)
const result = createRules({
url,
source: text
})
return new Response(result)
}
/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/
async function gatherResponse (response) {
const { headers } = response
const contentType = headers.get('content-type') || ''
if (contentType.includes('application/json')) {
return JSON.stringify(await response.json())
}
if (contentType.includes('application/text')) {
return await response.text()
}
if (contentType.includes('text/html')) {
return await response.text()
}
return await response.text()
}
/**
*
* @param root0
* @param root0.url
* @param root0.source
* @param root0.listNameV6
* @param root0.listNameV4
*/
function createRules ({
url,
source,
listNameV4 = 'cloudflare-ips',
listNameV6 = 'cloudflare-ips-v6'
}) {
let result = ''
const isV6 = url.toLowerCase().includes('v6')
const listName = isV6 ? listNameV6 : listNameV4
const addresses = source.split('\n')
addresses.forEach((address) => {
if (isV6) {
result += '/ipv6'
} else {
result += '/ip'
}
result += ` firewall address-list add list=${listName} address=${address}\n`
})
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment