diff --git a/packages/isomorphic/stringUtils.ts b/packages/isomorphic/stringUtils.ts index 4bddaffbda09f..1b7b130ae3da9 100644 --- a/packages/isomorphic/stringUtils.ts +++ b/packages/isomorphic/stringUtils.ts @@ -155,13 +155,52 @@ export function escapeRegExp(s: string) { } const escaped = { '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }; -export function escapeHTMLAttribute(s: string): string { +function escapeHTMLAttribute(s: string): string { return s.replace(/[&<>"']/ug, char => (escaped as any)[char]); } export function escapeHTML(s: string): string { return s.replace(/[&<]/ug, char => (escaped as any)[char]); } +// All trace-controlled data goes through this class, so escaping and name checks live in one place. +export class HtmlBuilder { + private _chunks: string[] = []; + + text(text: string) { + this._chunks.push(escapeHTML(text)); + } + + openTag(name: string): boolean { + if (!isSafeName(name)) + return false; + this._chunks.push('<', name); + return true; + } + + attribute(name: string, value: string) { + if (!isSafeName(name)) + return; + this._chunks.push(' ', name, '="', escapeHTMLAttribute(value), '"'); + } + + endOpenTag() { + this._chunks.push('>'); + } + + closeTag(name: string) { + this._chunks.push(''); + } + + toString() { + return this._chunks.join(''); + } +} + +// Reject names that would end the tag or attribute name early. Allow Unicode custom elements such as math-α. +function isSafeName(name: string): boolean { + return !!name && !/[\s=<>\/"']/.test(name); +} + export function longestCommonSubstring(s1: string, s2: string): string { const n = s1.length; const m = s2.length; diff --git a/packages/isomorphic/trace/snapshotRenderer.ts b/packages/isomorphic/trace/snapshotRenderer.ts index 8e5d24a3264fe..4edf3f742dce7 100644 --- a/packages/isomorphic/trace/snapshotRenderer.ts +++ b/packages/isomorphic/trace/snapshotRenderer.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { escapeHTMLAttribute, escapeHTML } from '../stringUtils'; +import { HtmlBuilder } from '../stringUtils'; import type { FrameSnapshot, NodeNameAttributesChildNodesSnapshot, NodeSnapshot, ResourceSnapshot, SubtreeReferenceSnapshot } from './trace'; import type { PageEntry } from './entries'; @@ -91,11 +91,11 @@ export class SnapshotRenderer { } render(): RenderedFrameSnapshot { - const result: string[] = []; + const result = new HtmlBuilder(); const visit = (n: NodeSnapshot, snapshotIndex: number, parentTag: string | undefined, parentAttrs: [string, string][] | undefined) => { // Text node. if (typeof n === 'string') { - result.push(escapeHTML(n)); + result.text(n); return; } @@ -114,17 +114,14 @@ export class SnapshotRenderer { // crafted trace file could include them to achieve XSS. if (name.toUpperCase() === 'SCRIPT') return; - // Reject names that would emit extra attributes (space, =, <, >, /). - // Allow Unicode custom elements such as math-α. - if (/[\s=<>\/]/.test(name)) - return; // Element node. // Note that