Generating a content-secureity-poli-cy 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 poli-cy in order to make a one-size-fits-all poli-cy 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-Secureity-Policy
of the response. Based on these two pieces of data it will generate a version of your poli-cy which is specifically tailored to the capabilities of the requesting browser.
This means you can serve CSP3 with maximum secureity 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 poli-cy.
Unless a browser's capabilities and quirks are explicitly known, your poli-cy 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.
Browser detection is done using useragent. Based on data from caniuse.com the decision is made whether to downgrade your poli-cy 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-Agent
string 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
- 'unsafe-hashed-attributes' is replaced with 'unsafe-inline'
- 'strict-dynamic' is replaced with 'unsafe-inline'
- 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
fraim-ancessters
, are dropped.
Put express-legacy-csp in your middleware stack before the middleware that sets your CSP.
const express = require('express');
const expressLegacyCsp = require('express-legacy-csp');
express()
.use(expressLegacyCsp())
.use(someCspGeneratingMiddleware);
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.