Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions packages/cli/src/media-use/lib/svg-sanitize.mjs

Large diffs are not rendered by default.

28 changes: 28 additions & 0 deletions packages/core/src/compiler/htmlBundler.foreignText.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,31 @@ describe("bundleToSingleHtml with markup hidden in an svg title", () => {
expect(html).toContain("<title>Icon 1 &lt; 2</title>");
});
});

// fails without the fix: the build kept these marks as comment text, and the preview browser read them as elements.
describe("bundleToSingleHtml with a data-composition-file a scripting browser reads past a comment", () => {
const HIDDEN_MARKS = [
'<noscript><!-- </noscript><p data-composition-file="index.html">x</p> --></noscript>',
'<p><!-- --!><b data-composition-file="index.html">x</b> --></p>',
];

it.each(HIDDEN_MARKS)("refuses %s in the root composition", async (body) => {
await expect(bundle({ "index.html": root(body) })).rejects.toThrow(READ_UNLIKE_BROWSER);
});

it.each(HIDDEN_MARKS)("refuses %s in a sub-composition", async (body) => {
const sub = `<template><div data-composition-id="sub" data-width="320" data-height="180">${body}</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 a noscript fallback and comments", async () => {
const html = await bundle({
"index.html": root("<noscript><p>Turn on JavaScript</p></noscript><!-- a note -->"),
});
expect(html).toContain("<noscript><p>Turn on JavaScript</p></noscript>");
});
});
21 changes: 21 additions & 0 deletions packages/core/src/compiler/htmlBundler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4435,4 +4435,25 @@ describe("bundleToSingleHtml composition file marks", () => {
expect(document.getElementById("shout")?.getAttributeNames()).toEqual(["id"]);
expect(document.querySelectorAll("[data-composition-file]")).toHaveLength(1);
});

it("drops a mark authored inside a template, in the entry page or an inlined sub-composition", async () => {
const dir = makeTempProject({
"index.html": `<!doctype html><html><head></head><body>
<div data-composition-id="main" data-width="1920" data-height="1080">
<template id="tpl"><p id="intpl" data-composition-file="compositions/tpl.html">x</p>
<template><b data-composition-file="compositions/tpl.html">y</b></template></template>
<div data-composition-id="scene" data-composition-src="compositions/scene.html"
data-start="0" data-duration="5"></div>
</div>
</body></html>`,
"compositions/scene.html": `<template id="scene-template">
<div data-composition-id="scene" data-width="1920" data-height="1080">
<template id="later"><i data-composition-file="compositions/tpl.html">z</i></template>
</div>
</template>`,
});

const html = await bundleToSingleHtml(dir);
expect(html.match(/data-composition-file="compositions\/tpl[^"]*"/gi)).toBeNull();
});
});
35 changes: 35 additions & 0 deletions packages/core/src/compositionSource.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { describe, expect, it } from "vitest";
import { dropAuthoredCompositionFiles } from "./compositionSource";

// fails without the fix: linkedom's queries skip a template's children, so the drop cleaned only a copy of them.
describe("dropAuthoredCompositionFiles on a linkedom document", () => {
const page = (body: string) => `<!DOCTYPE html><html><head></head><body>${body}</body></html>`;

it("drops a mark inside a template at any depth", () => {
const { document } = parseHTML(
page(`<template><p data-composition-file="a.html">x</p>
<template><b DATA-Composition-File="a.html">y</b></template></template>`),
);
dropAuthoredCompositionFiles(document);
expect(document.toString()).not.toMatch(/data-composition-file/i);
});

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>"));
dropAuthoredCompositionFiles(document);
const template = document.querySelector("template") as HTMLTemplateElement;
template.querySelector("p")!.textContent = "after";
expect(template.content.firstChild?.textContent).toBe("after");
});

it("stops at the root it is given", () => {
const { document } = parseHTML(
page(
'<div id="r"><p data-composition-file="a.html">x</p></div><p id="out" data-composition-file="b.html">y</p>',
),
);
dropAuthoredCompositionFiles(document.getElementById("r")!);
expect(document.getElementById("out")?.getAttribute("data-composition-file")).toBe("b.html");
});
});
16 changes: 13 additions & 3 deletions packages/core/src/compositionSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,21 @@ export const COMPOSITION_ROOT_ATTRS = [
"data-hf-original-composition-id",
] as const;

function nextInDocumentOrder(element: Element, root: ParentNode): Element | null {
if (element.firstElementChild) return element.firstElementChild;
for (let at: Element | null = element; at && at !== root; at = at.parentElement)
if (at.nextElementSibling) return at.nextElementSibling;
return null;
}

export function dropAuthoredCompositionFiles(root: ParentNode): void {
for (const el of Array.from(root.querySelectorAll("*"))) {
for (let el = root.firstElementChild; el; el = nextInDocumentOrder(el, root)) {
for (const name of el.getAttributeNames())
if (name.toLowerCase() === COMPOSITION_FILE_ATTR) el.removeAttribute(name);
const content = (el as { content?: ParentNode | null }).content;
if (el.localName === "template" && content) dropAuthoredCompositionFiles(content);
const browserTemplateContent =
el.localName === "template" && !el.hasChildNodes()
? (el as { content?: ParentNode }).content
: null;
if (browserTemplateContent) dropAuthoredCompositionFiles(browserTemplateContent);
}
}
44 changes: 44 additions & 0 deletions packages/core/src/runtime/compositionLoader.noscript.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* @vitest-environment-options { "runScripts": "dangerously" }
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { loadCompositions } from "./compositionLoader";

beforeEach(() => {
(globalThis as { CSS?: { escape?: (value: string) => string } }).CSS ??= {};
CSS.escape ??= (value: string) => value.replace(/([^\w-])/g, "\\$1");
const base = document.createElement("base");
base.href = "https://example.com/";
document.head.prepend(base);
});

afterEach(() => {
vi.restoreAllMocks();
document.head.querySelectorAll("base").forEach((base) => base.remove());
document.body.innerHTML = "";
});

// Scripting is on here, as in the preview, so the page reads a noscript's contents as text.
// fails without the fix: the fallback mounted the fetched body as a string, which the page re-read with scripting on.
describe("loadCompositions with scripting on", () => {
it("mounts a fetched body without a mark hidden in a noscript comment", async () => {
const host = document.createElement("div");
host.setAttribute("data-composition-src", "https://example.com/comp.html");
host.setAttribute("data-composition-id", "scene-1");
document.body.appendChild(host);
const compositionHtml = `<html><body><p id="kept">Kept</p>
<noscript><!-- </noscript><p id="claim" data-composition-file="index.html">Hello</p> --></noscript>
</body></html>`;
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));

await loadCompositions({
injectedStyles: [],
injectedScripts: [],
injectedLinks: [],
parseDimensionPx: (value) => (value ? `${value}px` : null),
});

expect(host.querySelector("#kept")?.textContent).toBe("Kept");
expect(host.querySelectorAll("[data-composition-file]")).toHaveLength(0);
});
});
8 changes: 6 additions & 2 deletions packages/core/src/runtime/compositionLoader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2076,18 +2076,22 @@ describe("loadCompositions authored file marks", () => {

it("mounts a fetched file without the data-composition-file marks it authored", async () => {
const host = appendExternalHost("https://example.com/comp.html", "scene-1");
const compositionHtml = `<html><body>
const compositionHtml = `<html><body><template>
<div data-composition-id="scene-1" data-width="1920" data-height="1080">
<p id="claim" data-composition-file="index.html">Hello</p>
<section data-composition-file="index.html"><b id="deep">deep</b></section>
<template id="later"><i data-composition-file="index.html">later</i></template>
</div>
</body></html>`;
</template></body></html>`;
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(compositionHtml, { status: 200 }));

await loadFixture();

expect(host.querySelector("#claim")?.textContent).toBe("Hello");
expect(host.querySelector("#deep")?.textContent).toBe("deep");
expect(host.querySelectorAll("[data-composition-file]")).toHaveLength(0);
const later = host.querySelector<HTMLTemplateElement>("template#later")?.content;
expect(later?.querySelector("i")?.textContent).toBe("later");
expect(later?.querySelectorAll("[data-composition-file]")).toHaveLength(0);
});
});
11 changes: 5 additions & 6 deletions packages/core/src/runtime/compositionLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,6 @@ async function mountCompositionContent(params: {
hostCompositionSrc: string;
sourceNode: ParentNode;
hasTemplate: boolean;
fallbackBodyInnerHtml: string;
compositionUrl: URL | null;
injectedStyles: HTMLStyleElement[];
injectedScripts: HTMLScriptElement[];
Expand Down Expand Up @@ -617,8 +616,11 @@ async function mountCompositionContent(params: {
stripExtractedCompositionAssets(mountedContent);
params.host.appendChild(mountedContent);
} else {
params.host.innerHTML = params.fallbackBodyInnerHtml;
stripExtractedCompositionAssets(params.host);
const mountedContent = document.createDocumentFragment();
for (const node of Array.from(contentNode.childNodes))
mountedContent.appendChild(document.importNode(node, true));
stripExtractedCompositionAssets(mountedContent);
params.host.appendChild(mountedContent);
}
for (const el of plan.inertScriptsOutsideRoot)
params.host.appendChild(document.importNode(el, true));
Expand Down Expand Up @@ -735,7 +737,6 @@ async function mountInlineTemplateCompositions(
hostCompositionSrc: `template#${compId}-template`,
sourceNode,
hasTemplate: true,
fallbackBodyInnerHtml: "",
compositionUrl: null,
injectedStyles: params.injectedStyles,
injectedScripts: params.injectedScripts,
Expand Down Expand Up @@ -813,7 +814,6 @@ async function mountExternalCompositions(
hostCompositionSrc: src,
sourceNode: localContent,
hasTemplate: true,
fallbackBodyInnerHtml: "",
compositionUrl,
injectedStyles: params.injectedStyles,
injectedScripts: params.injectedScripts,
Expand Down Expand Up @@ -847,7 +847,6 @@ async function mountExternalCompositions(
hostCompositionSrc: src,
sourceNode,
hasTemplate: Boolean(content),
fallbackBodyInnerHtml: doc.body.innerHTML,
compositionUrl,
injectedStyles: params.injectedStyles,
injectedScripts: params.injectedScripts,
Expand Down
25 changes: 20 additions & 5 deletions packages/parsers/src/linkedom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,20 @@ 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 TEXT_UNTIL_ANY_END_TAG_IN_SCRIPTING_BROWSER = new Set([
"noscript",
"iframe",
"noembed",
"noframes",
]);
const COMMENT_END_ONLY_BROWSERS_READ = "--!>";
const SHOW_COMMENT = 0x80;
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 HTML has tags or comments inside an SVG or MathML title, style, script, textarea or xmp element, an end tag inside a comment or attribute of a noscript, iframe, noembed or noframes element, or a comment holding --!>, which can't be read the way a browser reads them.",
);
this.name = "HtmlReadUnlikeBrowserError";
}
Expand All @@ -61,8 +69,11 @@ function insideForeign(element: Element): boolean {
}

function readAsTextUnlikeBrowser(element: Element): boolean {
const name = element.localName.toLowerCase();
if (TEXT_UNTIL_ANY_END_TAG_IN_SCRIPTING_BROWSER.has(name))
return new RegExp(`</${name}[\\t\\n\\f\\r />]`, "i").test(element.innerHTML);
return (
READ_AS_TEXT.has(element.localName.toLowerCase()) &&
READ_AS_TEXT.has(name) &&
insideForeign(element) &&
TAG_OR_COMMENT.test((element.textContent ?? "").replace(CDATA, ""))
);
Expand All @@ -77,9 +88,13 @@ function nextInDocumentOrder(element: Element): Element | 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 {
function readsUnlikeBrowser(root: Document, html: string): boolean {
for (let element = root.firstElementChild; element; element = nextInDocumentOrder(element))
if (readAsTextUnlikeBrowser(element)) return true;
if (!html.includes(COMMENT_END_ONLY_BROWSERS_READ)) return false;
const comments = root.createTreeWalker(root, SHOW_COMMENT);
while (comments.nextNode())
if (comments.currentNode.nodeValue?.includes(COMMENT_END_ONLY_BROWSERS_READ)) return true;
return false;
}

Expand All @@ -88,7 +103,7 @@ function readsUnlikeBrowser(root: ParentNode): boolean {
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();
if (readsUnlikeBrowser(parsed.document, html)) throw new HtmlReadUnlikeBrowserError();
return parsed;
}

Expand All @@ -105,7 +120,7 @@ export const DOMParser = class extends LinkedomDOMParser {
globals?: unknown,
) {
const parsed = super.parseFromString(markup, mimeType, globals);
if (mimeType === "text/html" && readsUnlikeBrowser(parsed as unknown as Document))
if (mimeType === "text/html" && readsUnlikeBrowser(parsed as unknown as Document, markup))
throw new HtmlReadUnlikeBrowserError();
return parsed;
}
Expand Down
13 changes: 13 additions & 0 deletions packages/parsers/src/linkedomForeignText.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ describe("parseHTML", () => {
"<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>`,
"<noscript><!-- </noscript><img src=x onerror=f()> --></noscript>",
'<noscript><b title="</noscript><img src=x onerror=f()>"></b></noscript>',
"<NOSCRIPT><!-- </NOSCRIPT ><img src=x onerror=f()> --></NOSCRIPT>",
"<template><noscript><!-- </noscript/><img src=x onerror=f()> --></noscript></template>",
"<iframe><!-- </iframe><img src=x onerror=f()> --></iframe>",
"<noembed><!-- </noembed><img src=x onerror=f()> --></noembed>",
"<noframes><!-- </noframes><img src=x onerror=f()> --></noframes>",
"<p><!-- --!><img src=x onerror=f()> --></p>",
"<template><p><!-- --!><img src=x onerror=f()> --></p></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(
Expand All @@ -29,6 +38,10 @@ describe("parseHTML", () => {
"<template></template>",
"<svg><foreignObject><title>a <b> c</title></foreignObject></svg>",
'<svg><style><![CDATA[ a::after { content: "<b>" } ]]></style></svg>',
"<noscript><p>Turn on JavaScript</p><!-- a note --></noscript>",
'<iframe title="frame"></iframe><noscript>&lt;/noscript&gt;</noscript>',
"<noscript><!-- </noscripts> --></noscript>",
'<script>const end = "--!>";</script><p><!-- a -- b --></p>',
])("reads %s as linkedom does", (body) => {
const { document } = parseHTML(page(body));
expect(document.querySelectorAll("img")).toHaveLength(0);
Expand Down
25 changes: 25 additions & 0 deletions packages/studio-server/src/helpers/subComposition.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,31 @@ describe("buildSubCompositionHtml authored file marks", () => {
expect(document.querySelector("#claim")?.hasAttribute("data-composition-file")).toBe(false);
});

it("drops a mark written inside a template, at any depth", () => {
const dir = makeTempProject({
"index.html": "<!doctype html><html><head></head><body></body></html>",
"compositions/scene.html": `<div data-composition-id="scene">
<template><p data-composition-file="index.html">a</p><template><b data-composition-file="index.html">b</b></template></template>
</div>`,
});
const html = buildSubCompositionHtml(dir, "compositions/scene.html", "/runtime.js") ?? "";

expect(html).toContain("<p>a</p><template><b>b</b></template>");
expect(html).not.toContain('data-composition-file="index.html"');
});

it("refuses a mark hidden where a scripting browser reads past a comment", () => {
const dir = makeTempProject({
"index.html": "<!doctype html><html><head></head><body></body></html>",
"compositions/scene.html": `<div data-composition-id="scene">
<noscript><!-- </noscript><p data-composition-file="index.html">a</p> --></noscript>
</div>`,
});
expect(() => buildSubCompositionHtml(dir, "compositions/scene.html", "/runtime.js")).toThrow(
/can't be read the way a browser reads them/,
);
});

it("drops a mark a full document wrote on its <html> or <body>", () => {
const dir = makeTempProject({
"index.html": "<!doctype html><html><head></head><body></body></html>",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ afterEach(() => {

const entry = (mark: string) => `<html><head></head><body><div data-composition-id="main">
<p id="claim" ${mark}="scenes/other.html">Hi</p>
<template><b ${mark}="scenes/other.html">later</b></template>
</div></body></html>`;

function api(bundle: StudioApiAdapter["bundle"], mark: string) {
Expand Down
Loading
Loading