Setting policies/headers not working

Hi. I want to Implement content security policy, referrer policy and permission policy by using Cloudflare workers. But the script I am using is not working. Can anyone help me out with this. I will attach the script i am using.

let securityHeaders = {
“Content-Security-Policy” : “upgrade-insecure-requests”,
“Strict-Transport-Security” : "max-age=31536000 ",
“X-Xss-Protection” : “1; mode=block”,
“X-Frame-Options” : “DENY”,
“X-Content-Type-Options” : “nosniff”,
“Referrer-Policy” : “strict-origin-when-cross-origin”,
“Permissions-Policy” : “geolocation=(self “site url”), microphone=()”,

}

let sanitiseHeaders = {
“Server” : “My New Server Header!!!”,
}

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
})

}

Thanks is advance .

That looks like Scott Helme’s script. I’ve used it and know it works.

Can you be more specific? Did you add a route for it?

1 Like

I’ve used the same script with some modifications before so I also know it works.

Are you sure you added all the routes you want it to trigger on?

Also a recommendation, join the below Discord server (It’s a great place to hang out and get help to workers related questions)

1 Like