ElMassimo / ElMassimo/vite_ruby
Content security policy for development not working when nonces enabled
- Dominant language
- Ruby
- Stars
- 1.6k
- Forks
- 149
- Avg merge
- 5h 13m
- Merged PRs (30d)
- 2
Description
- [x] I have tried upgrading by running `bundle update vite_ruby`.
- [x] I have read the __[troubleshooting section]__ before opening an issue.
### Description π
With the following in the Rails content_security_policy.rb:
```ruby
Rails.application.configure do
config.content_security_policy_nonce_generator = ->(_request) { SecureRandom.base64(16) }
config.content_security_policy do |policy|
[SNIP]
if Rails.env.development?
policy.style_src(*policy.style_src, :unsafe_inline)
policy.script_src(*policy.script_src, :unsafe_eval, "http://#{ViteRuby.config.host_with_port}")
policy.connect_src(*policy.connect_src, "ws://#{ViteRuby.config.host_with_port}")
end
end
end
```
styles are broken in development. Getting the following browser console errore:
```
Content-Security-Policy: Ignoring β'unsafe-inline'β within style-src: nonce-source or hash-source specified
```
```
Content-Security-Policy: The pageβs settings blocked an inline style (style-src-elem) from being applied because it violates the following directive: βstyle-src 'self' https: 'unsafe-inline' 'nonce-hlKBeGISpbxAy7igRiyz2w=='β
```
It appears that, if the CSP contains a nonce, then unsafe-* declarations are ignored. And because of this, all the tags that vite is injecting are not able to load.
When I comment out `content_security_policy_nonce_generator`, then everything works as expected.
### Reproduction π
_Please provide a link to a repo that can reproduce the problem you ran into._
<details>
<summary>Vite Ruby Info</summary>
_Run `bin/rake vite:info` and provide the output:_
```
bin/vite present?: true
vite_ruby: 3.9.2
vite_rails: 3.0.19
rails: 8.0.2
ruby: ruby 3.4.2 (2025-02-15 revision d2930f8e7a) +PRISM [arm64-darwin24]
node: v22.14.0
yarn: 4.8.1
installed packages:
work@ /Volumes/Work
βββ¬ @storybook/svelte-vite@8.6.12
β βββ¬ @storybook/builder-vite@8.6.12
β β βββ vite@5.4.18 deduped
β βββ vite@5.4.18 deduped
βββ¬ @sveltejs/vite-plugin-svelte@3.1.2
β βββ¬ @sveltejs/vite-plugin-svelte-inspector@2.1.0
β β βββ vite@5.4.18 deduped
β βββ vite@5.4.18 deduped
β βββ¬ vitefu@0.2.5
β βββ vite@5.4.18 deduped
βββ¬ @testing-library/svelte@5.2.7
β βββ vite@5.4.18 deduped
βββ¬ vite-plugin-ruby@5.1.1
β βββ vite@5.4.18 deduped
βββ vite@5.4.18
βββ¬ vitest@3.1.1
βββ¬ @vitest/mocker@3.1.1
β βββ vite@6.2.6 deduped
βββ¬ vite-node@3.1.1
β βββ vite@6.2.6
βββ vite@6.2.6
```
</details>
Contributor guide
Assessment
This issue has not been assessed yet.