Skip to content

Commit 76b0efb

Browse files
committed
fix(cspNonce): don't overwrite existing nonce values
Fixes: #16414
1 parent 6c323d5 commit 76b0efb

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

packages/vite/src/node/plugins/html.ts

+7
Original file line numberDiff line numberDiff line change
@@ -1189,6 +1189,13 @@ export function injectNonceAttributeTagHook(
11891189
parseRelAttr(attr.value).some((a) => processRelType.has(a)),
11901190
))
11911191
) {
1192+
const alreadyContainsNonce = node.attrs.some(
1193+
({ name }) => name === 'nonce',
1194+
)
1195+
if (alreadyContainsNonce) {
1196+
return
1197+
}
1198+
11921199
// if the closing of the start tag includes a `/`, the offset should be 2 so the nonce
11931200
// is appended prior to the `/`
11941201
const appendOffset =

playground/csp/__tests__/csp.spec.ts

+14
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,20 @@ test('dynamic js', async () => {
2727
)
2828
})
2929

30+
test('inline js', async () => {
31+
await expectWithRetry(() => page.textContent('.inline-js')).toBe(
32+
'inline-js: ok',
33+
)
34+
})
35+
36+
test('nonce attributes are not repeated', async () => {
37+
const htmlSource = await page.content()
38+
expect(htmlSource).not.toContain(/nonce=""[^>]*nonce=""/)
39+
await expectWithRetry(() => page.textContent('.double-nonce-js')).toBe(
40+
'double-nonce-js: ok',
41+
)
42+
})
43+
3044
test('meta[property=csp-nonce] is injected', async () => {
3145
const meta = await page.$('meta[property=csp-nonce]')
3246
expect(await (await meta.getProperty('nonce')).jsonValue()).not.toBe('')

playground/csp/index.html

+10
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,13 @@
1111
<p class="dynamic">dynamic</p>
1212
<p class="js">js: error</p>
1313
<p class="dynamic-js">dynamic-js: error</p>
14+
<p class="inline-js">inline-js: error</p>
15+
<p class="double-nonce-js">double-nonce-js: error</p>
16+
<script>
17+
document.querySelector('.inline-js').textContent = 'inline-js: ok'
18+
</script>
19+
<script nonce="#$NONCE$#">
20+
// this test case is to ensure that the nonce isn't being
21+
// double-applied if an existing attribute is present.
22+
document.querySelector('.double-nonce-js').textContent = 'double-nonce-js: ok'
23+
</script>

0 commit comments

Comments
 (0)