vite icon indicating copy to clipboard operation
vite copied to clipboard

nonce tag in __vitePreload (CSP)

Open vinicius73 opened this issue 4 years ago • 24 comments

Description

I am trying to migrate or default tooling from Webpack to Vite.

The main issue is nonce security police.

Actually, we handle it using __webpack_nonce__

https://webpack.js.org/guides/csp/

I can't interact with the preload function to change it.

https://github.com/vitejs/vite/blob/05712323b292492e9161a6ff7b20bfce43097dfb/packages/vite/src/node/plugins/importAnalysisBuild.ts#L58-L103

I'm already injecting the preload tags manually, JavaScript and CSS files.

Suggested solution

A way to inject nonce value simular to webpack.

Alternative

No response

Additional context

Example Application

https://github.com/nextcloud/text/blob/48b21b6e524c4aef78a1046e1f19a2bbd85837c4/src/main.js#L3-L4

Nextcloud apps

Nextcloud is modular, and allow the users to install a variety of apps. These apps can inject scripts in many parts of nextcloud.

For secure reasons, we use CSP to prevent malicious script injections.

Content-Security-Policy: default-src 'none';base-uri 'none';manifest-src 'self';script-src 'nonce-cHQ...bz0=';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-src 'self';frame-ancestors 'self';form-action 'self'

Validations

vinicius73 avatar Aug 17 '22 22:08 vinicius73

discussion related: https://github.com/vitejs/vite/discussions/5218

vinicius73 avatar Aug 23 '22 13:08 vinicius73

I have this problem also

dagda1 avatar Sep 26 '22 14:09 dagda1

We're also facing this issue, coming from CRA/webpack. It would be awesome to have CSP nonce support in vite.

VincentvD avatar Sep 28 '22 09:09 VincentvD

We are also facing this problem. ATM it makes verifying a CSP is correct very hard. We are forced to set unsafe-inline during development.

kmcc049 avatar Oct 09 '22 19:10 kmcc049

I'm just now running into this as well. I converted our apps to Vite a few months ago and I love using it, it's SO FAST.

I've done a little googling trying to figure out if there is a plugin that will do this and I haven't found anything.

Do we have any updates on this issue?

seth-seikosoft avatar Nov 16 '22 23:11 seth-seikosoft

Running into this issue too. I'm disabling all the dynamic import because I could not set the nonce token on the generated tags. Waiting for a solution

Carminepo2 avatar Nov 19 '22 13:11 Carminepo2

Please address this, it is impossible to use a sane CSP without it.

krossekrabbe avatar Dec 27 '22 11:12 krossekrabbe

We ended up doing this:

in vite.config.ts

plugins: [
            {
                name: "html-inject-nonce-into-script-tag",
                enforce: "post",
                transformIndexHtml(html: string) {
                    const regex = /<script(.*?)/gi;
                    const replacement = '<script nonce="{SERVER-GENERATED-NONCE}"$1';
                    return html.replace(regex, replacement);
                },
            },
        ],

All bundled script tags now get the placeholder {SERVER-GENERATED-NONCE} which is replaced with a random value by the server on each request.

tonymcneil avatar Feb 21 '23 03:02 tonymcneil

@tonymcneil Thanks for this, I also got it working for script tags. However, i tried the same trick for style tags, but it does not work. Do you know how to get this working also for style tags?

ottopaulsen avatar Mar 20 '23 08:03 ottopaulsen

@tonymcneil Thanks for this, I also got it working for script tags. However, i tried the same trick for style tags, but it does not work. Do you know how to get this working also for style tags?

@ottopaulsen You can just go about it the same as for the script tags. Generic extendable example:

plugins: [{
    name: "html-inject-data-preload-attr",
    enforce: "post",
    transformIndexHtml(html) {
        const regex = /<(link|style|script)/gi;
        const replacement = '<$1 data-preload="true"';

        return html.replace(regex, replacement);
    },
}]

patrickglueck avatar May 05 '23 07:05 patrickglueck

const replacement = '<$1 data-preload="true"';

@patrickglueck Building custom AD B2C layouts are we? 😅

ulken avatar May 16 '23 08:05 ulken

@ulken That is absolutely correct :D

patrickglueck avatar May 16 '23 08:05 patrickglueck

If you want an extendable example that only adds nonces on the appropriate tags, I modified the above examples to:

  plugins: [
    {
      name: 'html-inject-data',
      enforce: 'post',
      transformIndexHtml(html) {
        const regex = /<(style|script|link) (.*)>/gi;
        const replacer = (_, p1, p2) => {
          // add nonce?
          if (
            p1 === 'style' ||
            p1 === 'script' ||
            // if link, only nonce for stylesheet
            (p1 === 'link' && p2.includes('rel="stylesheet"'))
          ) {
            p2 = `nonce="{SERVER-CSP-NONCE}" ${p2}`;
          }

          return `<${p1} data-preload="true" ${p2}>`;
        };

        return html.replace(regex, replacer);
      },
    },
  ],

Preload tag is added to all style, script, and link tags but nonce is only added to style, script, and rel="stylesheet" links.

gregtwallace avatar Oct 21 '23 02:10 gregtwallace

If you want an extendable example that only adds nonces on the appropriate tags, I modified the above examples to:

  plugins: [
    {
      name: 'html-inject-data',
      enforce: 'post',
      transformIndexHtml(html) {
        const regex = /<(style|script|link) (.*)>/gi;
        const replacer = (_, p1, p2) => {
          // add nonce?
          if (
            p1 === 'style' ||
            p1 === 'script' ||
            // if link, only nonce for stylesheet
            (p1 === 'link' && p2.includes('rel="stylesheet"'))
          ) {
            p2 = `nonce="{SERVER-CSP-NONCE}" ${p2}`;
          }

          return `<${p1} data-preload="true" ${p2}>`;
        };

        return html.replace(regex, replacer);
      },
    },
  ],

Preload tag is added to all style, script, and link tags but nonce is only added to style, script, and rel="stylesheet" links.

does this work for vite react?i cant make it work for static file.

q7314568 avatar Oct 26 '23 15:10 q7314568

I am using it with Vite and React, yes:

https://github.com/gregtwallace/legocerthub-frontend/blob/master/vite.config.js

The snipet I posted doesn’t include any other plugins like react().

gregtwallace avatar Oct 26 '23 21:10 gregtwallace

I am using it with Vite and React, yes:

https://github.com/gregtwallace/legocerthub-frontend/blob/master/vite.config.js

The snipet I posted doesn’t include any other plugins like react().

Thanks for reply!

I try to run your repo,but didnt find where is the csp tag,

I put csp like the following:

`

`

and even with the setting in vite.config,the emotion and react/fontawsome still throw the error.

q7314568 avatar Oct 27 '23 00:10 q7314568

The script only injects the nonce into what’s in the html. Emotion injects styles using js which is not yet supported in Vite. For now I’m using unsafe-inline for styles.

gregtwallace avatar Oct 29 '23 02:10 gregtwallace

The script only injects the nonce into what’s in the html. Emotion injects styles using js which is not yet supported in Vite. For now I’m using unsafe-inline for styles.

Finally i found a way to inject nonce value for emotion.js,thanks for your reply anyway.

q7314568 avatar Oct 29 '23 08:10 q7314568

The script only injects the nonce into what’s in the html. Emotion injects styles using js which is not yet supported in Vite. For now I’m using unsafe-inline for styles.

Finally i found a way to inject nonce value for emotion.js,thanks for your reply anyway.

Mind sharing what you did @q7314568 ? Facing a similar problem with a different library and curious how you solved it.

tvongaza avatar Oct 29 '23 17:10 tvongaza

I'm interested in your workaround too.

The only remotely sane way I've found is to add the emotion cache (https://emotion.sh/docs/@emotion/cache) with a placeholder string for nonce and then inline everything using https://github.com/richardtallent/vite-plugin-singlefile. Then the backend can replace the placeholder string in the inlined js inside index.html.

This is bad for a number of reasons and I've chosen to leave my app as unsafe-inline until Vite provides proper support to precompile the css and do a stylesheet import.

gregtwallace avatar Oct 30 '23 22:10 gregtwallace