Last active
February 18, 2023 05:49
-
-
Save umonaca/79ea9b740f9a7a63a0ede370f5825c5f to your computer and use it in GitHub Desktop.
Cloudflare worker media proxy (for Mastodon)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DO Spaces isn't handling OPTIONS properly so I am manually setting them. It does not affect user experience, though. | |
// For DO Spaces, if Origin header is not set, DO won't return CORS headers at all. Must be set in the worker. | |
// Other references: | |
// https://community.cloudflare.com/t/injecting-cors-headers-in-response-larger-requests-fail/98479/7 | |
// https://www.digitalocean.com/community/questions/setting-access-control-allow-origin-in-my-space-doesn-t-work-with | |
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
async function handleRequest(request) { | |
if (request.method === "OPTIONS") { | |
return handleOptions(request) | |
} else if (request.method === "GET" || request.method == "HEAD") { | |
const parsedUrl = new URL(request.url) | |
let path = parsedUrl.pathname | |
const url = new URL("https://YOUR_BUCKET_NAME.YOUR_DATA_CENTER.digitaloceanspaces.com" + path) | |
const newRequest = new Request( | |
url.toString(), | |
new Request(request), | |
) | |
//Origin:https://YOUR_DOMAIN | |
newRequest.headers.set('Origin', 'https://YOUR_DOMAIN') | |
try { | |
return await fetch(newRequest) | |
} catch (e) { | |
return new Response(JSON.stringify({ error: e.message }), { status: 500 }) | |
} | |
} else { | |
return new Response(null, { | |
status: 405, | |
statusText: "Method Not Allowed", | |
}) | |
} | |
} | |
const corsHeaders = { | |
"Access-Control-Allow-Origin": "*", | |
"Access-Control-Allow-Methods": "GET, HEAD, OPTIONS", | |
"Access-Control-Allow-Headers": "Content-Type", | |
} | |
function handleOptions(request) { | |
if (request.headers.get("Origin") !== null && | |
request.headers.get("Access-Control-Request-Method") !== null && | |
request.headers.get("Access-Control-Request-Headers") !== null) { | |
// Handle CORS pre-flight request. | |
return new Response(null, { | |
headers: corsHeaders | |
}) | |
} else { | |
// Handle standard OPTIONS request. | |
return new Response(null, { | |
headers: { | |
"Allow": "GET, HEAD, OPTIONS", | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment