Recently Google's Lighthouse tool alerted me to the fact that I wasn't providing a Content Security Policy. However, when I try to add one (or at least one without the word "unsafe" in it), I wind up with a bunch of violations, seemingly coming from Next.js and Styled-Components.
Both libraries seem to use dynamic script/style tags which violate any sane CSP. But the only way I've found to work around them is to use a "nonce". However, that seems to require having an actual server running: if you're using Next to generate static files (to host on a static host like AWS S3), you can't provide nonces.
My question is simple: am I missing anything? Is there some non-nonce-based way, or a static-host-nonce-based way, to host a site on S3 using Next.js and Styled Components?
Or is it just impossible to use those libraries together with a strict CSP (without a server-generated nonce)?
CodePudding user response:
I hope you:
do not use inline styles like
<tag style='display:none;'>
or JS call ofelement.setAttribute('style', ...)
.do not use built-in inline event handlers like
<tag onclick='...'>
and JS-navigation like<a href='javascript:void(0)'>
because all of above require 'unsafe-inline'
in styles/scripts respectively since 'unsafe-hashes'
token is not supported by Safary and bugly supported by Firefox.
For Single Page Applications (SPA) (without server-side rendering), using 'nonce-value'
is not useful, because the SPA does not reload the page, but only partially updates its contents, but you must generate new nonce for each page loading.
For serverless apps (like static file hosting) and SPA apps you can use 'hash-value'
instead of 'nonce-value'
to allow inline scripts and styles.
If you use Webpack, it has some plugins, for instance, csp-html-webpack-plugin plugin will generate content for your Content Security Policy meta tag and input the correct data into your HTML template, generated by html-webpack-plugin
. All inline JS and CSS will be hashed, and inserted into the policy.