tusen-ai / naive-ui

A Vue 3 Component Library. Fairly Complete. Theme Customizable. Uses TypeScript. Fast.
https://www.naiveui.com
MIT License
16.25k stars 1.68k forks source link

当Content-Security-Policy设置不允许Unsafe-inline时报错无法正常使用组件 #6356

Open linwh203 opened 2 months ago

linwh203 commented 2 months ago

描述错误

当对应用有安全性需求的时候,CSP不允许使用unsafe-inline。 在vite5中可以通过配置 html.cspNonce 给页面所有script和style加上Nonce满足CSP的要求。 但naiveUI似乎并不适用,打开页面后控制台报错,且UI库的组件均无法正常使用。

截屏2024-09-14 15 52 24

复现步骤

  1. create a new vue3 project with vite 5
  2. add html.cspNonce (value:12345) to vite config
  3. add CSP in html file:
    <meta
      http-equiv="Content-Security-Policy"
      content="default-src 'self' 'nonce-12345'; style-src 'self' 'nonce-12345' ; base-uri 'self'; "
    />
  4. install naive-ui and import naive-ui in .vue file
  5. use naive-ui in .vue file:
    <n-config-provider :theme="theme">
      <n-card>
        <n-space>
          <n-button @click="theme = darkTheme"> 深色 </n-button>
          <n-button @click="theme = null"> 浅色 </n-button>
        </n-space>
      </n-card>
    </n-config-provider>
  6. Lauch dev-server and open Chrome, naive-ui is not work and errors in console:
    Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' 'nonce-12345'". Either the 'unsafe-inline' keyword, a hash ('sha256-fZjflqFcROvJ0PG4AlqR1f+YzoVYVuh3bUA02kwtbIw='), or a nonce ('nonce-...') is required to enable inline execution.

最小复现链接

https://github.com/linwh203/csp-naive

系统信息

System:
    OS: macOS 14.6.1
    CPU: (10) arm64 Apple M1 Pro
    Memory: 87.61 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.12.2 - ~/.nvm/versions/node/v20.12.2/bin/node
    Yarn: 1.22.15 - /usr/local/bin/yarn
    npm: 10.5.0 - ~/.nvm/versions/node/v20.12.2/bin/npm
    pnpm: 6.11.0 - /usr/local/bin/pnpm
  Browsers:
    Chrome: 128.0.6613.138
    Edge: 128.0.2739.79
    Safari: 17.6
  npmPackages:
    naive-ui: ^2.39.0 => 2.39.0
    vue: ^3.4.18 => 3.5.5

使用的包管理器

npm

验证

getCryptoAddress commented 2 weeks ago

https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP#fetch_directives and https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce

CSP is already becoming very common. I'm looking forward to nonce support

getCryptoAddress commented 2 weeks ago

Example: https://primevue.org/configuration/#csp

Primevue provides the ability to set a nonce