Skip to content

Instantly share code, notes, and snippets.

@angrymouse
Created October 7, 2021 16:17
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 angrymouse/dadba9cda0b33a184615497541a8fe61 to your computer and use it in GitHub Desktop.
Save angrymouse/dadba9cda0b33a184615497541a8fe61 to your computer and use it in GitHub Desktop.
Cloudflare Workers reverse proxy by Angrymouse
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
}
const API_URL = "https://dev.server-discord.com"//
const PROXY_ENDPOINT = ""
async function JSONResponse(json) {
return new Response(JSON.stringify(json), {
headers: {
"content-type": "application/json;charset=UTF-8",
},
})
}
const DEFAULT_RESPONSE={ok:false,errors:["Invalid request to api"]}
async function handleRequest(realRequest) {
const url = new URL(realRequest.url)
let apiUrl = API_URL
// Rewrite request to point to API url. This also makes the request mutable
// so we can add the correct Origin header to make the API server think
// that this request isn't cross-site.
request = new Request(apiUrl+url.pathname.slice(PROXY_ENDPOINT.length), realRequest)
request.headers.set("Origin", new URL(apiUrl).origin)
request.headers.set('Authorization', 'Basic ' + btoa("pony:bebetter"));
let response = await fetch(request)
// Recreate the response so we can modify the headers
response = new Response(response.body, response)
// Set CORS headers
response.headers.set("Access-Control-Allow-Origin", url.origin)
// Append to/Add Vary header so browser will cache response correctly
response.headers.append("Vary", "Origin")
return response
}
function handleOptions(request) {
let headers = request.headers;
if (
headers.get("Origin") !== null &&
headers.get("Access-Control-Request-Method") !== null &&
headers.get("Access-Control-Request-Headers") !== null
){
let respHeaders = {
...corsHeaders,
"Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers"),
}
return new Response(null, {
headers: respHeaders,
})
}
else {
return new Response(null, {
headers: {
Allow: "GET, HEAD, POST, OPTIONS",
},
})
}
}
addEventListener("fetch",async function fetchFromDiscordAPI( event) {
const request = event.request
const url = new URL(request.url)
if(url.pathname.startsWith(PROXY_ENDPOINT)){
if (request.method === "OPTIONS") {
event.respondWith(handleOptions(request))
}
else if(
request.method === "GET" ||
request.method === "HEAD" ||
request.method === "POST"
){
event.respondWith(handleRequest(request))
}
else {
event.respondWith(
new Response(null, {
status: 405,
statusText: "Method Not Allowed",
}),
)
}
}
else {
event.respondWith(JSONResponse(DEFAULT_RESPONSE))
}
})
function sleep(ms){
return new Promise(resolve=>setTimeout(resolve,ms))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment