mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
fix(parsers): HTML a browser reads differently is refused before it is rewritten (#8760)
* fix(parsers): HTML a browser reads differently is refused before it is rewritten * fix(parsers): the HTML check walks the tree once and publishes only its own types * fix(parsers): the HTML check reads a page with no elements, and its package budget covers it * fix(parsers): reading a page no longer copies every template's content * refactor(parsers): keep the typing note on the function it describes
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -0,0 +1,51 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { bundleToSingleHtml } from "./htmlBundler";
|
||||
|
||||
const READ_UNLIKE_BROWSER = /can't be read the way a browser reads them/;
|
||||
|
||||
const ICON = "<svg><title><!-- </title><img src=x onerror=f()> --></title></svg>";
|
||||
const root = (body: string) =>
|
||||
`<!DOCTYPE html><html><head></head><body><div data-composition-id="main" data-width="320" data-height="180">${body}</div></body></html>`;
|
||||
|
||||
async function bundle(files: Record<string, string>): Promise<string> {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-foreign-text-"));
|
||||
try {
|
||||
for (const [path, html] of Object.entries(files)) {
|
||||
mkdirSync(join(dir, path, ".."), { recursive: true });
|
||||
writeFileSync(join(dir, path), html);
|
||||
}
|
||||
return await bundleToSingleHtml(dir);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// fails without the fix: the preview and render bundle served the title's hidden img as a live element.
|
||||
describe("bundleToSingleHtml with markup hidden in an svg title", () => {
|
||||
it("refuses it in the root composition", async () => {
|
||||
await expect(bundle({ "index.html": root(`<div class="clip">${ICON}</div>`) })).rejects.toThrow(
|
||||
READ_UNLIKE_BROWSER,
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses it in a sub-composition", async () => {
|
||||
const sub = `<template><div data-composition-id="sub" data-width="320" data-height="180">${ICON}</div></template>`;
|
||||
const host =
|
||||
'<div data-composition-id="sub" data-composition-src="compositions/sub.html" data-start="0" data-duration="1"></div>';
|
||||
await expect(
|
||||
bundle({ "index.html": root(host), "compositions/sub.html": sub }),
|
||||
).rejects.toThrow(READ_UNLIKE_BROWSER);
|
||||
});
|
||||
|
||||
it("still bundles an svg whose title is plain text", async () => {
|
||||
const html = await bundle({
|
||||
"index.html": root(
|
||||
'<svg viewBox="0 0 4 4"><title>Icon 1 < 2</title><circle r="2"></circle></svg>',
|
||||
),
|
||||
});
|
||||
expect(html).toContain("<title>Icon 1 < 2</title>");
|
||||
});
|
||||
});
|
||||
@@ -35,15 +35,78 @@ function escapeTextOnWrite(): void {
|
||||
}
|
||||
}
|
||||
|
||||
// Typed with the DOM's own types: published declarations that name linkedom's fail a strict consumer.
|
||||
export function parseHTML(html: string, globals?: unknown): Window & typeof globalThis {
|
||||
escapeTextOnWrite();
|
||||
return linkedomParseHTML(html, globals);
|
||||
// linkedom reads these as plain text even inside svg or math, where a browser reads their markup.
|
||||
const READ_AS_TEXT = new Set(["title", "style", "script", "textarea", "xmp"]);
|
||||
const FOREIGN = new Set(["svg", "math"]);
|
||||
const BACK_TO_HTML = new Set(["foreignobject", "desc"]);
|
||||
const TAG_OR_COMMENT = /<[A-Za-z!/?]/;
|
||||
const CDATA = /<!\[CDATA\[[\s\S]*?\]\]>/g;
|
||||
|
||||
export class HtmlReadUnlikeBrowserError extends Error {
|
||||
constructor() {
|
||||
super(
|
||||
"This HTML has tags or comments inside an SVG or MathML title, style, script, textarea or xmp element, which can't be read the way a browser reads them.",
|
||||
);
|
||||
this.name = "HtmlReadUnlikeBrowserError";
|
||||
}
|
||||
}
|
||||
|
||||
function insideForeign(element: Element): boolean {
|
||||
for (let up = element.parentElement; up; up = up.parentElement) {
|
||||
const name = up.localName.toLowerCase();
|
||||
if (BACK_TO_HTML.has(name)) return false;
|
||||
if (FOREIGN.has(name)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function readAsTextUnlikeBrowser(element: Element): boolean {
|
||||
return (
|
||||
READ_AS_TEXT.has(element.localName.toLowerCase()) &&
|
||||
insideForeign(element) &&
|
||||
TAG_OR_COMMENT.test((element.textContent ?? "").replace(CDATA, ""))
|
||||
);
|
||||
}
|
||||
|
||||
function nextInDocumentOrder(element: Element): Element | null {
|
||||
if (element.firstElementChild) return element.firstElementChild;
|
||||
for (let at: Element | null = element; at; at = at.parentElement)
|
||||
if (at.nextElementSibling) return at.nextElementSibling;
|
||||
return null;
|
||||
}
|
||||
|
||||
// One pass in document order: linkedom keeps the tree as a list, so asking each element for its children is quadratic.
|
||||
// A parsed template's children are in that list; its `content` is a deep copy linkedom makes and keeps on first read.
|
||||
function readsUnlikeBrowser(root: ParentNode): boolean {
|
||||
for (let element = root.firstElementChild; element; element = nextInDocumentOrder(element))
|
||||
if (readAsTextUnlikeBrowser(element)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Typed with the DOM's own types: published declarations that name linkedom's fail a strict consumer.
|
||||
/** linkedom's `parseHTML`, refusing HTML that a browser would read as a different tree. */
|
||||
export function parseHTML(html: string, globals?: unknown): Window & typeof globalThis {
|
||||
escapeTextOnWrite();
|
||||
const parsed = linkedomParseHTML(html, globals) as Window & typeof globalThis;
|
||||
if (readsUnlikeBrowser(parsed.document)) throw new HtmlReadUnlikeBrowserError();
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** linkedom's `DOMParser`, with the same refusal for `text/html`. */
|
||||
export const DOMParser = class extends LinkedomDOMParser {
|
||||
constructor() {
|
||||
super();
|
||||
escapeTextOnWrite();
|
||||
}
|
||||
|
||||
override parseFromString<Mime extends Parameters<LinkedomDOMParser["parseFromString"]>[1]>(
|
||||
markup: string,
|
||||
mimeType: Mime,
|
||||
globals?: unknown,
|
||||
) {
|
||||
const parsed = super.parseFromString(markup, mimeType, globals);
|
||||
if (mimeType === "text/html" && readsUnlikeBrowser(parsed as unknown as Document))
|
||||
throw new HtmlReadUnlikeBrowserError();
|
||||
return parsed;
|
||||
}
|
||||
} as unknown as { new (): globalThis.DOMParser };
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DOMParser, parseHTML } from "./linkedom.js";
|
||||
|
||||
const READ_UNLIKE_BROWSER = /can't be read the way a browser reads them/;
|
||||
|
||||
const HIDDEN = "<svg><title><!-- </title><img src=x onerror=f()> --></title></svg>";
|
||||
const page = (body: string) => `<!DOCTYPE html><html><head></head><body>${body}</body></html>`;
|
||||
|
||||
// fails without the fix: linkedom ended the title inside its comment, so a browser's inert comment became a live img.
|
||||
describe("parseHTML", () => {
|
||||
it.each([
|
||||
HIDDEN,
|
||||
"<svg><style><!-- </style><img src=x onerror=f()> --></style></svg>",
|
||||
"<math><title><!-- </title><img src=x onerror=f()> --></title></math>",
|
||||
"<svg><style><![CDATA[ a{} ]]><!-- </style><img src=x onerror=f()> --></style></svg>",
|
||||
`<template><div>${HIDDEN}</div></template>`,
|
||||
])("refuses %s, which a browser reads differently", (body) => {
|
||||
expect(() => parseHTML(page(body))).toThrow(READ_UNLIKE_BROWSER);
|
||||
expect(() => new DOMParser().parseFromString(page(body), "text/html")).toThrow(
|
||||
READ_UNLIKE_BROWSER,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'<svg viewBox="0 0 4 4"><title>Icon 1 < 2 & 3</title><circle r="2"></circle></svg>',
|
||||
"<title>Page</title><style>a > b { color: red }</style>",
|
||||
"<p><!-- </title><img> --></p>",
|
||||
'<head><meta name="description" content="x"></head>',
|
||||
"<template></template>",
|
||||
"<svg><foreignObject><title>a <b> c</title></foreignObject></svg>",
|
||||
'<svg><style><![CDATA[ a::after { content: "<b>" } ]]></style></svg>',
|
||||
])("reads %s as linkedom does", (body) => {
|
||||
const { document } = parseHTML(page(body));
|
||||
expect(document.querySelectorAll("img")).toHaveLength(0);
|
||||
});
|
||||
|
||||
// fails without the fix: the check read each template's content, so linkedom copied every mounted scene and kept
|
||||
// the copy, and a later edit to the template never reached its content.
|
||||
it("leaves a template's content to be made from its children when it is first read", () => {
|
||||
const { document } = parseHTML(page("<template><p>before</p></template>"));
|
||||
const template = document.querySelector("template") as HTMLTemplateElement;
|
||||
template.querySelector("p")!.textContent = "after";
|
||||
expect(template.content.firstChild?.textContent).toBe("after");
|
||||
});
|
||||
|
||||
it("reads a page that is only a comment", () => {
|
||||
expect(() => parseHTML("<!-- <template><div></div></template> -->")).not.toThrow();
|
||||
});
|
||||
|
||||
it("leaves svg read as XML to linkedom", () => {
|
||||
const doc = new DOMParser().parseFromString(HIDDEN, "image/svg+xml");
|
||||
expect(doc.querySelectorAll("img")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
|
||||
import { duplicateElementInHtml } from "./duplicateElement.js";
|
||||
import { parseSourceDocument } from "./sourceMutation.js";
|
||||
|
||||
const READ_UNLIKE_BROWSER = /can't be read the way a browser reads them/;
|
||||
|
||||
describe("duplicateElementInHtml", () => {
|
||||
it("ripples a following natural-duration video by the resolved source clip length", () => {
|
||||
const source = `<div>
|
||||
@@ -91,4 +93,13 @@ describe("duplicateElementInHtml", () => {
|
||||
expect(result.html).toContain('id="scene-copy" data-composition-id="scene-split"');
|
||||
expect(result.html.match(/data-composition-id="scene"/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
// fails without the fix: the copy and the original were written with the title's hidden img live.
|
||||
it("refuses a file a browser would read differently, writing nothing", () => {
|
||||
const source =
|
||||
'<div id="icon" data-start="0" data-duration="1"><svg><title><!-- </title><img src=x onerror=f()> --></title></svg></div>';
|
||||
expect(() => duplicateElementInHtml(source, { id: "icon" }, "icon-copy", 1)).toThrow(
|
||||
READ_UNLIKE_BROWSER,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -248,11 +248,9 @@ it("writes nothing the server serves as running code, from the live copy or a sa
|
||||
);
|
||||
expect(saved.clipboard().handleCopy()).toBe(true);
|
||||
await saved.clipboard().handlePaste();
|
||||
// The saved file is read through linkedom, which ends the title early: its handler shows, so the paste is refused.
|
||||
// linkedom would end the title early in the saved file, so that file is refused before anything is read from it.
|
||||
expect(saved.writes).toEqual([]);
|
||||
expect(saved.toasts).toContain(
|
||||
"Couldn't paste: the copied element holds markup that can't be pasted here.",
|
||||
);
|
||||
expect(saved.toasts.join("\n")).toMatch(/can't be read the way a browser reads them/);
|
||||
});
|
||||
|
||||
// fails without the fix: markup the copy found in another file was taken as saved and pasted unchecked.
|
||||
|
||||
@@ -232,10 +232,9 @@ describe("a paste is checked as the preview server serves the file", () => {
|
||||
});
|
||||
|
||||
it("still pastes an svg whose title is plain text", () => {
|
||||
const icon =
|
||||
'<svg viewBox="0 0 4 4"><title>Icon </title></title><circle r="2"></circle></svg>';
|
||||
const icon = '<svg viewBox="0 0 4 4"><title>Icon 1 < 2</title><circle r="2"></circle></svg>';
|
||||
const file = pasteElementHtml(FILE, { html: icon, readFrom: null }, false, "index.html");
|
||||
expect(file).toMatch(/<title [^>]*>Icon <\/title><\/title><circle /);
|
||||
expect(file).toMatch(/<title [^>]*>Icon 1 < 2<\/title><circle /);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user