Skip to content

Issue setting strict CSP in dev #11862

@justin-tay

Description

@justin-tay

Describe the bug

I am trying to set a strict CSP in dev so that developers don't inadvertently introduce changes that will break the application in production where a strict CSP is applied.

In this case the CSP avoids setting unsafe-inline for style-src

Content-Security-Policy: style-src 'nonce-random' 'self' etc

When running in dev client.ts in Chrome the following errors are seen in console

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'nonce-random' 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-J+3YsBcGEYMOe4DwBHZqef/THcqobccvabWv1wEouI4='), or a nonce ('nonce-...') is required to enable inline execution.
updateStyle | @ | client.ts:377

I will try to submit a PR for this issue. Since unlike webpack there is no convention of where to take the nonce value from like in window.__webpack_nonce__ I will likely get it from a meta tag like marco-prontera/vite-plugin-css-injected-by-js#64

Reproduction

https://github.com/justin-tay/vite-csp-issue.git

Steps to reproduce

Configure vite.config.ts with a strict CSP that disallows unsafe inline for style-src

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    headers: {
      'Content-Security-Policy': `style-src 'nonce-random' 'self'`,
    },
  },
  plugins: [react()],
})

Run npm run dev

System Info

System:
    OS: Windows 10 10.0.22621
    CPU: (8) x64 Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz
    Memory: 6.91 GB / 15.81 GB
  Binaries:
    Node: 18.13.0 - D:\dev\node\node.EXE
    Yarn: 1.22.19 - D:\dev\node\yarn.CMD
    npm: 8.19.3 - D:\dev\node\npm.CMD
  Browsers:
    Chrome: 109.0.5414.120
    Edge: Spartan (44.22621.1194.0), Chromium (109.0.1518.69)
    Internet Explorer: 11.0.22621.1

Used Package Manager

npm

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions