Skip to content

Commit 5c6618f

Browse files
committed
fix: avoid TrustedHTML sink for style injection
1 parent d1045f4 commit 5c6618f

2 files changed

Lines changed: 38 additions & 3 deletions

File tree

‎src/Dom/dynamicCSS.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export function injectCSS(css: string, option: Options = {}) {
7676
if (csp?.nonce) {
7777
styleNode.nonce = csp?.nonce;
7878
}
79-
styleNode.innerHTML = css;
79+
styleNode.textContent = css;
8080

8181
const container = getContainer(option);
8282
const { firstChild } = container;
@@ -177,8 +177,8 @@ export function updateCSS(
177177
existNode.nonce = option.csp?.nonce;
178178
}
179179

180-
if (existNode.innerHTML !== css) {
181-
existNode.innerHTML = css;
180+
if (existNode.textContent !== css) {
181+
existNode.textContent = css;
182182
}
183183

184184
return existNode;

‎tests/dynamicCSS.test.tsx‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,41 @@ describe('dynamicCSS', () => {
3434
expect(document.querySelector('style').nonce).toEqual('light');
3535
});
3636

37+
it('does not assign CSS through the innerHTML sink', () => {
38+
const innerHTMLDescriptor = Object.getOwnPropertyDescriptor(
39+
HTMLStyleElement.prototype,
40+
'innerHTML',
41+
);
42+
43+
Object.defineProperty(HTMLStyleElement.prototype, 'innerHTML', {
44+
configurable: true,
45+
set() {
46+
throw new TypeError(
47+
"This document requires 'TrustedHTML' assignment.",
48+
);
49+
},
50+
});
51+
52+
try {
53+
const style = injectCSS(TEST_STYLE);
54+
const managedStyle = updateCSS(TEST_STYLE, 'trusted-types');
55+
56+
expect(style.textContent).toEqual(TEST_STYLE);
57+
expect(() => updateCSS('.light {}', 'trusted-types')).not.toThrow();
58+
expect(managedStyle.textContent).toEqual('.light {}');
59+
} finally {
60+
if (innerHTMLDescriptor) {
61+
Object.defineProperty(
62+
HTMLStyleElement.prototype,
63+
'innerHTML',
64+
innerHTMLDescriptor,
65+
);
66+
} else {
67+
delete HTMLStyleElement.prototype.innerHTML;
68+
}
69+
}
70+
});
71+
3772
describe('prepend', () => {
3873
function testPrepend() {
3974
const head = document.querySelector('head');

0 commit comments

Comments
 (0)