Parcel 2.0+ plugin for generating Content Security Policy that also generates hashes for inline scripts.
npm install parcel-optimizer-csp
A Parcel 2.0+ plugin for generating and inserting a CSP based on a super simple JSON config.
It automatically calculates a hash for your inline scripts and appends that to the script-src in the CSP so that browsers will run it.
We have an inline script for Xchart.com that registers global error handlers. We do this as inline script, because if there's an error with loading a JS file required to run the app we want to know about it.
Another common reason would be inline scripts inserted for analytics.
BUT we're using a Content Security Policy (CSP) to prevent malicious scripts from being injected in any way.
CSP's script-src is one of the main reasons to use a CSP. It specifies _valid_ sources for JavaScript and so, can completely prevent XSS (Cross-site scripting).
But, one of the tricky things people quickly notice is that if you have an inline snippet in the HTML that you pass to Parcel, like this:
``html`
This code will not run when you've specified a script-src unless you've listed: 'unsafe-inline' which... kind of negates the whole point of setting a script-src to begin with.
If you're using CSP to prevent injected scripts, you can either specify a nonce or a hash of all the allowed scripts. A nonce is supposed to be unique from the server for each render, that doesn't work so well if you are building a PWA or static site (JAM Stack) when you may not have a server rendering on each request.
The other option is to calculate and specify a hash of each inline script that is allows to run: That's the main reason this plugin exists.
It's very important that this happens _last_ because if there's anything else that modifies the contents between the opening and closing