Created
August 31, 2021 09:36
-
-
Save repalash/b1e778dbe3ac2e7149831c530a6535f9 to your computer and use it in GitHub Desktop.
Cloudflare worker to query headers of remote urls from client where CORS is enabled
This file contains 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
// Sample usage: | |
// https://header-inspector.repalash.workers.dev/?apiurl=https://example.com&headers=* | |
// ?apiurl=https://example.com&headers=etag,content-type | |
// ?apiurl=https://example.com&headers=x-frame-options,access-control-allow-origin | |
//Related: check for x-frame-options before displaying in iframe: https://stackoverflow.com/questions/15273042/catch-error-if-iframe-src-fails-to-load-error-refused-to-display-http | |
async function handleRequest(request, filters) { | |
let response = await fetch(request) | |
const url = new URL(request.url) | |
let allHeaders = filters.headers.includes('*') | |
const data = { | |
url: request.url, | |
origin: url.origin, | |
method: request.method, | |
headers: Object.fromEntries( | |
[...response.headers.entries()] | |
.filter(v=> | |
(allHeaders || filters.headers.includes(v[0].toLowerCase())) | |
) | |
) | |
} | |
const json = JSON.stringify(data, null, 2); | |
console.log(json) | |
return new Response(json, { | |
headers: { | |
"content-type": "application/json;charset=UTF-8", | |
"X-Frame-Options": "*", | |
"Access-Control-Allow-Origin": "*", | |
"Access-Control-Allow-Methods": "HEAD", | |
"Access-Control-Max-Age": "86400", | |
} | |
}); | |
} | |
addEventListener("fetch", event => { | |
const url = new URL(event.request.url) | |
let apiUrl = url.searchParams.get("apiurl") || 'https://example.com/' | |
let headers = (url.searchParams.get("headers") || '').toLowerCase().split(',') | |
// const request = new Request(apiUrl, event.request) | |
const request = new Request(apiUrl, {method: "HEAD"}) | |
request.headers.set("Origin", new URL(apiUrl).origin) | |
return event.respondWith(handleRequest(request, {headers})) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment