Skip to content

Commit

Permalink
fix: add style nonce to comply with content security policy
Browse files Browse the repository at this point in the history
  • Loading branch information
justin-tay committed Feb 22, 2023
1 parent 2556f88 commit 7f5be23
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,13 @@ export function updateStyle(id: string, content: string): void {
style.setAttribute('data-vite-dev-id', id)
style.textContent = content

const cspNonce = document.querySelector<HTMLMetaElement>(
'meta[property=csp-nonce]',
)?.content
if (cspNonce) {
style.setAttribute('nonce', cspNonce)
}

if (!lastInsertedStyle) {
document.head.appendChild(style)

Expand Down
5 changes: 5 additions & 0 deletions playground/css/__tests__/css.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -518,3 +518,8 @@ test('async css order with css modules', async () => {
expect(await getColor('.modules-pink')).toMatchInlineSnapshot('"pink"')
}, true)
})

test.runIf(isServe)('style csp nonce', async () => {
const cspNonce = await page.getAttribute('style', 'nonce')
expect(cspNonce).toBe('random')
})
2 changes: 2 additions & 0 deletions playground/css/index.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<meta property="csp-nonce" content="random" />

<link rel="stylesheet" href="./linked.css" />

<div class="wrapper">
Expand Down

0 comments on commit 7f5be23

Please sign in to comment.