vite_ruby icon indicating copy to clipboard operation
vite_ruby copied to clipboard

Add nonce to `vite_react_refresh_tag` Rails tag helper

Open renchap opened this issue 2 years ago • 1 comments

Description 📖

When using a Content Security Policy that does not allow unsafe-inline scripts, vite_react_refresh_tag does not work as inline JS is not allowed. The solution is to enable CSP nonces (Rails has a way to do it), but then the nonce is not added to the generated <script> tag and the tag is ignored.

Note that this is quite common policy using nonces or script hashes, needed for the legacy plugin for example

Solution 💡

I see 2 solutions here, and I can try a PR to implement the one you prefer:

  • Probably best solution: update react_refresh_preamble to only return the JS content, and wrap it into the framework specific tag for each framework, allowing to pass framework options as needed (for example vite_react_refresh_tag(nonce: true))
  • update vite_react_refresh_tag and react_refresh_preamble to accept a nonce argument, and add it to the generated HTML

What do you think?

renchap avatar Sep 05 '22 14:09 renchap

Hi Renaud, thanks for reporting.

Ideally, we add a new react_preamble_code method in ViteRuby::Manifest to preserve backwards compatibility, keeping react_refresh_preamble, and then extend vite_rails to use javascript_tag with nonce: true, type: :module.

PRs are welcome!

ElMassimo avatar Sep 05 '22 14:09 ElMassimo

Hey, just wondering if there's been any progress on this. We're looking to get CSP enabled and this is obviously blocking the more advanced CSP cases.

mikecx avatar Mar 31 '23 21:03 mikecx

This only affects development, where you can make an exception if needed.

PRs are welcome!

ElMassimo avatar Apr 01 '23 01:04 ElMassimo