fix: propagate CSP nonce to dynamically injected style elements

When Svelte components inject `<style>` elements at runtime via
`append_styles`, these elements now inherit the CSP nonce from any
existing nonce-bearing element on the page. This allows them to pass
CSP checks when a `style-src 'nonce-...'` policy is in effect.

Browsers expose `element.nonce` to JavaScript while hiding it from CSS
selectors, so querying `[nonce]` and reading `.nonce` is safe and
works correctly.

Fixes #14270

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
pull/17776/head
Your Name 5 days ago
parent 69e6c4cdbb
commit 53e5fa491a

@ -23,6 +23,13 @@ export function append_styles(anchor, css) {
style.id = css.hash;
style.textContent = css.code;
// Propagate nonce to the style element for CSP compliance.
// Browsers allow reading `element.nonce` from JS but hide it from CSS selectors,
// so we can find a nonce from any existing script/style element on the page.
var doc = /** @type {Document} */ (/** @type {ShadowRoot} */ (root).host ? root.ownerDocument : root);
var nonce = /** @type {HTMLElement | null} */ (doc?.querySelector('[nonce]'))?.nonce;
if (nonce) style.nonce = nonce;
target.appendChild(style);
if (DEV) {

Loading…
Cancel
Save