Skip to content
9 changes: 8 additions & 1 deletion packages/isomorphic/trace/snapshotRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export class SnapshotRenderer {
// Best-effort Electron support: rewrite custom protocol in url() links in stylesheets.
// Old snapshotter was sending lower-case.
if (parentTag === 'STYLE' || parentTag === 'style')
result.push(escapeURLsInStyleSheet(rewriteURLsInStyleSheetForCustomProtocol(n)));
result.push(escapeClosingStyleTag(escapeURLsInStyleSheet(rewriteURLsInStyleSheetForCustomProtocol(n))));
Comment thread
yury-s marked this conversation as resolved.
Resolved
else
result.push(escapeHTML(n));
return;
Expand Down Expand Up @@ -680,4 +680,11 @@ function escapeURLsInStyleSheet(text: string): string {
return text.replace(urlToEscapeRegex1, replacer).replace(urlToEscapeRegex2, replacer);
}

// A literal "</style" closes the element, so the rest gets parsed as live markup.
// Break the sequence with a CSS backslash escape ("\/" is still "/" in CSS).
// HTML entities can't be used: they aren't decoded inside a <style> element.
function escapeClosingStyleTag(text: string): string {
return text.replace(/<\//g, '<\\/');
Comment thread
yury-s marked this conversation as resolved.
Resolved
}

export const blankSnapshotUrl = 'data:text/html;base64,' + btoa(`<body></body><style>body { color-scheme: light dark; background: light-dark(white, #333) }</style>`);
12 changes: 12 additions & 0 deletions tests/library/snapshot-renderer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ for (const [name, overrides] of [
});
}

test('snapshot renderer escapes closing style tag in style text', () => {
Comment thread
yury-s marked this conversation as resolved.
Resolved
const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
html: ['HTML', {}, ['BODY', {}, ['STYLE', {}, 'body::after{content:"</style><img src=x onerror=alert(1)>"}']]],
})], [], 0);
const { html } = renderer.render();
// The literal </style> must not survive - it would terminate the element and
// let the trailing markup be parsed as live HTML on the trace viewer origin.
expect(html).not.toContain('</style><img');
// It stays inside the stylesheet, neutralized with a CSS backslash escape.
expect(html).toContain('<\\/style><img src=x onerror=alert(1)>');
});

test('snapshot renderer strips event handler attributes', () => {
const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
html: ['HTML', {}, ['BODY', {}, ['IMG', { 'onerror': 'alert(1)', 'src': 'x' }]]],
Expand Down
Loading