Skip to content

Instantly share code, notes, and snippets.

@tounan
Last active August 4, 2023 15:07
Show Gist options
  • Save tounan/aea05977a4235fada443321887162724 to your computer and use it in GitHub Desktop.
Save tounan/aea05977a4235fada443321887162724 to your computer and use it in GitHub Desktop.
Proxy on cloudflare workers
// URI prefix
const token = TOKEN; // env, like 'https://<your worker domain>.workers.dev/'
const blocked_code = [
'US', 'UK', 'CA', 'AU', 'RU', 'FR', 'DE'
];
const blocked_hosts = [
'0.0.0.0',
'127.0.0.1',
'localhost'
];
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const region_code = request.headers.get('cf-ipcountry').toUpperCase();
const ip_address = request.headers.get('cf-connecting-ip');
if (blocked_code.includes(region_code)) {
return new Response('Deny', { status: 403 });
}
if (! request.url.startsWith(token)) {
return new Response('Bad request', { status: 400 });
}
let url = request.url.substr(token.length);
try {
url = new URL(url);
if (blocked_hosts.includes(url.hostname))
throw new Error('host is blocked');
} catch (e) {
return new Response('Bad request: ' + e.message, { status: 400 });
}
let reqhead = new Headers(request.headers);
// discard real ip
if (reqhead.has('x-real-ip')) reqhead.delete('x-real-ip');
for (let [key, val] of reqhead) {
if (key.startsWith('cf-') || key.startsWith('x-forwarded-'))
reqhead.delete(key);
}
reqhead.set('Host', url.hostname);
let response = await fetch(url.href, {
method: request.method,
headers: reqhead
});
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment