Open stereobooster opened 6 years ago
I'll share my experiences so far.
I'm assuming that snapshotted apps will be running straight off a bare web-server, like nginx. This makes the nonce approach unsuitable. CSP can either be specified as headers or as meta tags. Headers are kinda a PITA - every new build will require changing the web-server config and doing a restart, both of which likely need root privileges. This makes the meta tags approach appealing.
We also need to let the user specify their own CSP directives. I think the solution is to add hashes to user-specified directives during the snapshot process.
Also, since react-snap
generates quite a few script tags, there will be a lot of hashes to add to CSP directives, which gets very verbose. I'd suggest that the snapshot process should only inject one script tag in the page. So, there's only ever one hash on the page.
If it's too troublesome to change CSP directives during build time, it might be worth considering keeping the hash static. This would mean that the injected script tags need to be the same every time, character for character. This has the benefit of not needing to change nginx config with every build, which means that setting CSP via headers is not off the table in this scenario. However, it means that we'd have to move the dynamic parts of the script contents to some other type of in-DOM storage. Things like data-attributes and template tags are possible locations to store dynamic content without CSP complaining.
If I had to pick between meta tags and headers, I'd choose meta tags though. Headers seem to be the recommended approach, but it seems like the meta tag approach would lead to fewer hassles during deployment, since all hashes are contained within the built bundle, and doesn't need modifications of web-server config.
Also, puppeteer has some issues with CSP, but I'm hoping this will be fixed soon. https://github.com/GoogleChrome/puppeteer/issues/1229
It would be awesome if we could take advantage of the performance gains from react-snap while easily implementing a strict CSP. @rakeshpai's suggestions are great!
@stereobooster Do you have any interest in changing react-snap to work with a CSP? I'm sure it's not simple.
It is possible to generate hashes for each inline script and expose them the same way as http2-push-manifest.
See: