Generating a content-security-policy that works correctly in all the browsers you support is hard work.
Because of the different level of support of the CSP specifications, and some times even only partial implementations, you will run into situations where you will either need to drop older browser support or implement a less secure policy in order to make a one-size-fits-all policy that includes older browsers.
NOT ANY MORE!
express-legacy-csp is a middleware that sits at the top of your stack and analyses the user agent header and the
Content-Security-Policy of the response. Based on these two pieces of data it will generate a version of your policy which is specifically tailored to the capabilities of the requesting browser.
This means you can serve CSP3 with maximum security settings, but still support older versions of Chrome that only support CSP2, or even older browsers like Safari 6 with CSP1-support.
express-legacy-csp fixes other quirks in old implementations, like renaming the header that contains the policy.
Unless a browser's capabilities and quirks are explicitly known, your policy will pass through untouched.
There is a tiny performance bonus of sending fewer bytes over the wire when sending CSP1 instead of CSP2. We have not done any research on the performance improvements this results in. It's most likely that these are negligible.
How it worksBrowser detection is done using useragent. Based on data from caniuse.com the decision is made whether to downgrade your policy level or apply other changes.
A CSP version is only deemed supported if the the caniuse data has no notes attached. If the support is none or has notes, the CSP version will be dropped down one level. There is a specific exception for IE, where a non-standard header is needed to get even CSP1 support.
Resolutions that are cached for runtime performance in a production setup:
- Resolving a
User-Agentstring to a browser family and version
- Resolving a browser family and version to header name and CSP capabilities
- Downgrade of a unique CSP to corresponding lower version of the same CSP
CSP3 to CSP2 downgrade
- 'unsafe-hashed-attributes' is replaced with 'unsafe-inline'
- 'strict-dynamic' is replaced with 'unsafe-inline'
CSP2 to CSP1 downgrade
- All source-expressions have their paths stripped
- All nonces and hashes are replaced with 'unsafe-inline'
- Directives that would cause unsupported warnings in the Developer console, such as
frame-ancestors, are dropped.
UsagePut express-legacy-csp in your middleware stack before the middleware that sets your CSP.
const express = require('express');
const expressLegacyCsp = require('express-legacy-csp');
Both camelCased and kebab-cased directive names are supported, and you can supply the tokens to add as either a string or an array of strings.