nonce tag in __vitePreload (CSP)
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
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guidelines.
- [X] Read the docs.
- [X] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
discussion related: https://github.com/vitejs/vite/discussions/5218
I have this problem also
We're also facing this issue, coming from CRA/webpack. It would be awesome to have CSP nonce support in vite.
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.
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?
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
Please address this, it is impossible to use a sane CSP without it.
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 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?
@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);
},
}]
const replacement = '<$1 data-preload="true"';
@patrickglueck Building custom AD B2C layouts are we? 😅
@ulken That is absolutely correct :D
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.
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.
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().
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.
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.
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.
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.
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.