webpack-contrib / mini-css-extract-plugin

Lightweight CSS extraction plugin
MIT License
4.65k stars 390 forks source link

Dynamic loaded styles does not includes nonce when __webpack_nonce__ is set #1081

Closed PepeBotella25 closed 4 months ago

PepeBotella25 commented 4 months ago

Bug report

Dynamic loaded styles does not includes nonce when __webpack_nonce__ is set.

createStylesheet method, which creates the link tag, does not add the nonce (__webpack_require__.nc is not used at all).

Current workaround is to set the nonce through insert option.

runtimeOptions: {
    insert(linkTag) {
        linkTag.nonce = __webpack_require__.nc;
        document.head.appendChild(linkTag);
    }
}

Actual Behavior

Nonce is missing in dynamically loaded styles when __webpack_nonce__ was set

Expected Behavior

Dynamically added link tag should contain the nonce

I'd expect createStylesheet to do something like:

`if (${RuntimeGlobals.scriptNonce}) {`,
Template.indent(
    `linkTag.nonce = ${RuntimeGlobals.scriptNonce};`
),
"}"

That's what webpack's script loader (webpack/lib/runtime/LoadScriptRuntimeModule.js) does for instance.

How Do We Reproduce?

Set __webpack_nonce__

Please paste the results of npx webpack-cli info here, and mention other relevant information

System: OS: Windows 11 10.0.22631 CPU: (16) x64 11th Gen Intel(R) Core(TM) i7-11850H @ 2.50GHz Memory: 35.53 GB / 63.20 GB Binaries: Node: 20.11.1 - C:\Users\dpelaez\AppData\Roaming\nvm\v20.11.1\node.EXE npm: 10.2.4 - C:\Users\dpelaez\AppData\Roaming\nvm\v20.11.1\npm.CMD Browsers: Edge: Chromium (121.0.2277.128) Internet Explorer: 11.0.22621.1 Packages: sass-loader: 12.6.0 => 12.6.0 webpack-dev-middleware: 7.0.0 => 7.0.0 webpack-hot-middleware: 2.26.1 => 2.26.1

alexander-akait commented 4 months ago

Sorry I don't undestand your problem

PepeBotella25 commented 4 months ago

If you want to have a CSP style-src nonce-<something> you need link/style html tags to set the nonce attr, otherwise the browser won't load the resource.

Webpack provides a way to do that by defining __webpack_nonce__. By setting it, when a script or style is loaded dynamically it will have the nonce attr, but that's not the case when you use mini-css-extract-plugin therefore the styles loaded dynamically are rejected by the browser

alexander-akait commented 4 months ago

I see, feel free to send a PR

PepeBotella25 commented 4 months ago

@alexander-akait Here's the PR