feat(security): add nonce support for injected style tags
Problem
When trying to enforce strict rules about which content is allowed on a specific page, a Content Security Policy (CSP) is the way to go.
The Stitches library currently injects all of their style scripts as an inline style to the DOM. For this to function, a CSP would need to contain style-src: unsafe-inline for the app/library to function properly. As the attribute name implies, this is unsafe and not the recommended way of building a secure app.
There is the concept of nonce attributes that allows inline style/script tags to be executed if the nonce matches the CSP header. The rule would look something like this style-src: 'self' 'nonce-<injected-id>' If Stitches checks for and sets this nonce, security minded apps can get rid of the unsafe-inline setting and consume this library.
Solution
Luckily, WebPack is already supporting the concept of a global __webpack_nonce__ variable. Once set, all dynamically injected code created by WebPack will have a nonce attribute with the correct value. Some apps may not be using WebPack and may prefer to set the nonce in a different property on window.
If the __webpack_nonce__ or window.nonce variable is set, pass the value to every generated style tag inside the nonce attribute of the style tag. All the magic happens in the new createSheet function I created that simply checks for a nonce existence and adds the nonce attribute with value if it exists.
I have tested this in a private repo and confirm it works as intended. See below that the global theme style tag now has the nonce attribute set on the inline style tag.

Further readings:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP https://developers.google.com/web/fundamentals/security/csp/ https://csp.withgoogle.com/docs/index.html
This pull request is automatically built and testable in CodeSandbox.
To see build info of the built libraries, click here or the icon next to each commit SHA.
Latest deployment of this branch, based on commit c1e90fee8405bad7f7208c5867882a5a4de81352:
| Sandbox | Source |
|---|---|
| Stitches CI: CRA | Configuration |
| Stitches CI: Next.js | Configuration |
TIL! Thanks for this. Over to the Stitches core team 🚀
Any progress/ETA on this? I'm currently deploying to production without SSR support because we can't change our CSP.