Skip to content

Instantly share code, notes, and snippets.

@pd12bbf7608ae1
Created December 24, 2022 08:17
Show Gist options
  • Save pd12bbf7608ae1/0bb2f7d84cd3058785af698408fe47d0 to your computer and use it in GitHub Desktop.
Save pd12bbf7608ae1/0bb2f7d84cd3058785af698408fe47d0 to your computer and use it in GitHub Desktop.
CF Workers Proxy
// Var apiAuthorization as key
// Header apihost
// Header apiAuthorization as key
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const defaultPage = '<!DOCTYPE html><html><head><title>Welcome to nginx!</title><style>body{width:35em;margin:0 auto;font-family:Tahoma,Verdana,Arial,sans-serif}</style></head><body><h1>Welcome to nginx!</h1><p>If you see this page,the nginx web server is successfully installed and working.Further configuration is required.</p><p>For online documentation and support please refer to<a href="http://nginx.org/">nginx.org</a>.<br/>Commercial support is available at<a href="http://nginx.com/">nginx.com</a>.</p><p><em>Thank you for using nginx.</em></p></body></html>';
const defaultInit = {
status: 200,
headers: {
'Content-Type': 'text/html;charset=UTF-8'
}
}
const allowMethods = new Array('GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS');
const removeHeaders = new Array('apihost','apiauthorization','host','cf-connecting-ip','cf-ipcountry','cf-ray','cf-visitor','x-real-ip');
function checkPermission(headers) {
if (!headers.has('apihost'))
{
return false;
}
if (headers.get('apiAuthorization') === apiAuthorization)
{
return true;
} else {
return false;
}
}
function genURL(originalRequest) {
const url = new URL(originalRequest.url);
url.host = originalRequest.headers.get('apihost');
return url;
}
async function handleRequest(request) {
if (!checkPermission(request.headers))
{
return new Response(defaultPage,defaultInit);
}
if (!allowMethods.includes(request.method))
{
return new Response(defaultPage,defaultInit);
}
const reqUrl = genURL(request);
const reqHeaders = new Headers(request.headers);
removeHeaders.forEach(element => reqHeaders.delete(element));
let reqInit = {
method: request.method,
headers: reqHeaders,
redirect: 'follow',
body: request.body,
};
return await fetch(reqUrl,reqInit);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment