Skip to content

Instantly share code, notes, and snippets.

@kessl
Last active March 14, 2021 19:10
Show Gist options
  • Save kessl/d5ec24894833f7af5d10101128145b0d to your computer and use it in GitHub Desktop.
Save kessl/d5ec24894833f7af5d10101128145b0d to your computer and use it in GitHub Desktop.
Cloudflare custom headers worker
let securityHeaders = {
'Content-Security-Policy': "default-src 'self'; img-src 'self' https://t.bitgate.cz; upgrade-insecure-requests",
'Strict-Transport-Security': 'max-age=2592000',
'X-Xss-Protection': '1; mode=block',
'X-Frame-Options': 'DENY',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Feature-Policy': "autoplay 'none'",
'X-Clacks-Overhead': 'GNU Terry Pratchett',
}
let sanitiseHeaders = {}
let removeHeaders = ['Server', 'Public-Key-Pins', 'X-Powered-By']
addEventListener('fetch', event => {
event.respondWith(addHeaders(event.request))
})
async function addHeaders(req) {
let response = await fetch(req)
let newHdrs = new Headers(response.headers)
if (newHdrs.has('Content-Type') && !newHdrs.get('Content-Type').includes('text/html')) {
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHdrs,
})
}
Object.keys(securityHeaders).map(function (name, index) {
newHdrs.set(name, securityHeaders[name])
})
Object.keys(sanitiseHeaders).map(function (name, index) {
newHdrs.set(name, sanitiseHeaders[name])
})
removeHeaders.forEach(function (name) {
newHdrs.delete(name)
})
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHdrs,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment