Skip to content

Instantly share code, notes, and snippets.

@pascalandy
Last active June 16, 2021 22:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pascalandy/9c2ae76555655af35fc18ddc20e51afd to your computer and use it in GitHub Desktop.
Save pascalandy/9c2ae76555655af35fc18ddc20e51afd to your computer and use it in GitHub Desktop.
let securityHeaders = {
"Content-Security-Policy" : "upgrade-insecure-requests",
"Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload",
"X-Xss-Protection" : "1; mode=block",
"X-Frame-Options" : "DENY",
"X-Content-Type-Options" : "nosniff",
"Referrer-Policy" : "strict-origin-when-cross-origin",
"Feature-Policy" : "accelerometer 'none' ; ambient-light-sensor 'none' ; autoplay 'self' ; camera 'none' ; encrypted-media 'none' ; fullscreen 'self' ; geolocation 'none' ; gyroscope 'none' ; magnetometer 'none' ; microphone 'none' ; midi 'none' ; payment 'self' ; picture-in-picture * ; speaker 'self' ; sync-xhr 'none' ; usb 'none' ; notifications 'self' ; vibrate 'self' ; push 'self' ; vr 'none'",
"Cache-Control" : "public, max-age=0, must-revalidate",
"Content-Type" : "text/html; charset=UTF-8",
}
let sanitiseHeaders = {
"Server" : "headers override",
}
let removeHeaders = [
"Public-Key-Pins",
"X-Powered-By",
"X-AspNet-Version",
]
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
})
}
@pascalandy
Copy link
Author

@pascalandy
Copy link
Author

@dapovoa
Copy link

dapovoa commented Nov 5, 2019

Excellent coding skills!

@sbwcws
Copy link

sbwcws commented Jan 21, 2020

Does this affect google to not cache your page?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment