Skip to content

Commit

Permalink
fix(cspNonce): don't overwrite existing nonce values
Browse files Browse the repository at this point in the history
  • Loading branch information
thebanjomatic committed Apr 12, 2024
1 parent 6c323d5 commit 3eef719
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1180,6 +1180,13 @@ export function injectNonceAttributeTagHook(
return
}

const alreadyContainsNonce = !!node.attrs.find(
(attr) => attr.name === 'nonce',
)
if (alreadyContainsNonce) {
return
}

if (
node.nodeName === 'script' ||
(node.nodeName === 'link' &&
Expand Down
7 changes: 7 additions & 0 deletions playground/csp/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@
color: green;
}
</style>
<script nonce="#$NONCE$#">
// nonce above verifies that this script is allowed to run with nonce
// but also verifies that we don't write two nonces as a result of
// setting html.cspNonce in the vite.config.jsg
document.querySelector('.inline-js').textContent = 'inline-js: ok'
</script>
<script type="module" src="./index.js"></script>
<p class="linked">direct</p>
<p class="inline">inline</p>
<p class="from-js">from-js</p>
<p class="dynamic">dynamic</p>
<p class="js">js: error</p>
<p class="dynamic-js">dynamic-js: error</p>
<p class="inline-js">inline-js: error</p>
3 changes: 3 additions & 0 deletions playground/csp/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ const createMiddleware = (file, transform) => async (req, res) => {
}

export default defineConfig({
html: {
cspNonce: noncePlaceholder,
},
plugins: [
{
name: 'nonce-inject',
Expand Down

0 comments on commit 3eef719

Please sign in to comment.