mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-26 00:57:05 +00:00
fix(studio): paste and duplicate write only allowed markup unless it comes from the same file (#8483)
* refactor(core): keep the SVG element and attribute allowlist in its own module * test(studio): clipboard writes refuse markup a scripting preview reads differently * fix(studio): paste and duplicate write only allowed markup unless it comes from the same file * test(core): inline SVG with its namespace declarations pastes from another file * fix(core): paste keeps SVG namespace declarations and checks xlink:href as a link * chore(cli): regenerate the media-use SVG sanitizer from its moved allowlist
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -3,211 +3,10 @@
|
||||
* as dangerous, so a new SVG feature can't reopen a class of bug the way regex denylisting did.
|
||||
*/
|
||||
import { DOMParser } from "linkedom";
|
||||
|
||||
const SAFE_ELEMENTS = new Set([
|
||||
"svg",
|
||||
"g",
|
||||
"defs",
|
||||
"symbol",
|
||||
"use",
|
||||
"image",
|
||||
"a",
|
||||
"switch",
|
||||
"rect",
|
||||
"circle",
|
||||
"ellipse",
|
||||
"line",
|
||||
"polyline",
|
||||
"polygon",
|
||||
"path",
|
||||
"text",
|
||||
"tspan",
|
||||
"textPath",
|
||||
"linearGradient",
|
||||
"radialGradient",
|
||||
"stop",
|
||||
"pattern",
|
||||
"mask",
|
||||
"clipPath",
|
||||
"marker",
|
||||
"filter",
|
||||
"feBlend",
|
||||
"feColorMatrix",
|
||||
"feComponentTransfer",
|
||||
"feComposite",
|
||||
"feConvolveMatrix",
|
||||
"feDiffuseLighting",
|
||||
"feDisplacementMap",
|
||||
"feDistantLight",
|
||||
"feDropShadow",
|
||||
"feFlood",
|
||||
"feFuncA",
|
||||
"feFuncB",
|
||||
"feFuncG",
|
||||
"feFuncR",
|
||||
"feGaussianBlur",
|
||||
"feImage",
|
||||
"feMerge",
|
||||
"feMergeNode",
|
||||
"feMorphology",
|
||||
"feOffset",
|
||||
"fePointLight",
|
||||
"feSpecularLighting",
|
||||
"feSpotLight",
|
||||
"feTile",
|
||||
"feTurbulence",
|
||||
"title",
|
||||
"desc",
|
||||
"metadata",
|
||||
"style",
|
||||
]);
|
||||
|
||||
// Local names only — a namespace prefix (xlink:href, x:href, ...) is stripped before this
|
||||
// lookup, so it doesn't matter which prefix an attacker aliases onto a real or fake namespace.
|
||||
const SAFE_ATTRIBUTES = new Set([
|
||||
"id",
|
||||
"class",
|
||||
"style",
|
||||
"transform",
|
||||
"viewBox",
|
||||
"width",
|
||||
"height",
|
||||
"x",
|
||||
"y",
|
||||
"x1",
|
||||
"y1",
|
||||
"x2",
|
||||
"y2",
|
||||
"cx",
|
||||
"cy",
|
||||
"r",
|
||||
"rx",
|
||||
"ry",
|
||||
"fx",
|
||||
"fy",
|
||||
"points",
|
||||
"d",
|
||||
"offset",
|
||||
"enable-background",
|
||||
"gradientUnits",
|
||||
"gradientTransform",
|
||||
"spreadMethod",
|
||||
"patternUnits",
|
||||
"patternContentUnits",
|
||||
"patternTransform",
|
||||
"maskUnits",
|
||||
"maskContentUnits",
|
||||
"clipPathUnits",
|
||||
"clip-rule",
|
||||
"filterUnits",
|
||||
"primitiveUnits",
|
||||
"preserveAspectRatio",
|
||||
"space",
|
||||
"lang",
|
||||
"role",
|
||||
"focusable",
|
||||
"tabindex",
|
||||
"version",
|
||||
"baseProfile",
|
||||
"fill",
|
||||
"fill-opacity",
|
||||
"fill-rule",
|
||||
"stroke",
|
||||
"stroke-width",
|
||||
"stroke-opacity",
|
||||
"stroke-linecap",
|
||||
"stroke-linejoin",
|
||||
"stroke-miterlimit",
|
||||
"stroke-dasharray",
|
||||
"stroke-dashoffset",
|
||||
"opacity",
|
||||
"color",
|
||||
"stop-color",
|
||||
"stop-opacity",
|
||||
"font-family",
|
||||
"font-size",
|
||||
"font-weight",
|
||||
"font-style",
|
||||
"text-anchor",
|
||||
"dominant-baseline",
|
||||
"alignment-baseline",
|
||||
"letter-spacing",
|
||||
"word-spacing",
|
||||
"text-decoration",
|
||||
"clip-path",
|
||||
"mask",
|
||||
"filter",
|
||||
"marker-start",
|
||||
"marker-mid",
|
||||
"marker-end",
|
||||
"marker",
|
||||
"cursor",
|
||||
"pointer-events",
|
||||
"visibility",
|
||||
"display",
|
||||
"overflow",
|
||||
"vector-effect",
|
||||
"paint-order",
|
||||
"color-interpolation",
|
||||
"color-interpolation-filters",
|
||||
"isolation",
|
||||
"mix-blend-mode",
|
||||
"startOffset",
|
||||
"method",
|
||||
"spacing",
|
||||
"side",
|
||||
"textLength",
|
||||
"lengthAdjust",
|
||||
"in",
|
||||
"in2",
|
||||
"result",
|
||||
"mode",
|
||||
"type",
|
||||
"values",
|
||||
"dx",
|
||||
"dy",
|
||||
"stdDeviation",
|
||||
"edgeMode",
|
||||
"k1",
|
||||
"k2",
|
||||
"k3",
|
||||
"k4",
|
||||
"operator",
|
||||
"radius",
|
||||
"scale",
|
||||
"xChannelSelector",
|
||||
"yChannelSelector",
|
||||
"baseFrequency",
|
||||
"numOctaves",
|
||||
"seed",
|
||||
"stitchTiles",
|
||||
"tableValues",
|
||||
"slope",
|
||||
"intercept",
|
||||
"amplitude",
|
||||
"exponent",
|
||||
"order",
|
||||
"divisor",
|
||||
"bias",
|
||||
"targetX",
|
||||
"targetY",
|
||||
"kernelMatrix",
|
||||
"preserveAlpha",
|
||||
"kernelUnitLength",
|
||||
"surfaceScale",
|
||||
"diffuseConstant",
|
||||
"specularConstant",
|
||||
"specularExponent",
|
||||
"lighting-color",
|
||||
"flood-color",
|
||||
"flood-opacity",
|
||||
"azimuth",
|
||||
"elevation",
|
||||
"pointsAtX",
|
||||
"pointsAtY",
|
||||
"pointsAtZ",
|
||||
"limitingConeAngle",
|
||||
]);
|
||||
import {
|
||||
SVG_ATTRIBUTES as SAFE_ATTRIBUTES,
|
||||
SVG_ELEMENTS as SAFE_ELEMENTS,
|
||||
} from "../utils/svgAllowlist";
|
||||
|
||||
function localName(name: string): string {
|
||||
const i = name.lastIndexOf(":");
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { JSDOM } from "jsdom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { markupOutsideAllowlist } from "./htmlAttrSafety";
|
||||
|
||||
/** `html` as a parser reads it with scripting off (what the check sees) or on (what a preview or render runs). jsdom
|
||||
* parses with scripting on only under "dangerously"; it loads no resources, so no handler here ever fires. */
|
||||
const parse = (html: string, scripting: boolean) =>
|
||||
new JSDOM(html, scripting ? { runScripts: "dangerously" } : {}).window.document;
|
||||
|
||||
const tagsOf = (doc: Document) =>
|
||||
Array.from(doc.querySelectorAll("*"), (el) => [
|
||||
el.localName,
|
||||
...Array.from(el.attributes, (a) => a.name),
|
||||
]);
|
||||
const runsCode = (doc: Document) =>
|
||||
Array.from(doc.querySelectorAll("*")).some(
|
||||
(el) =>
|
||||
["script", "base"].includes(el.localName) ||
|
||||
Array.from(el.attributes).some((a) => a.name.toLowerCase().startsWith("on")),
|
||||
);
|
||||
|
||||
const ALLOWED = [
|
||||
'<div id="card" class="clip" data-start="1" data-duration="2" style="left: 4px"><h1>Title</h1></div>',
|
||||
'<video id="v" class="clip" src="clip.mp4" muted playsinline data-start="0" data-duration="3"></video>',
|
||||
'<div class="clip"><svg viewBox="0 0 10 10"><path d="M0 0L10 10" fill="red"></path></svg></div>',
|
||||
'<div class="clip"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><use xlink:href="#a"></use></svg></div>',
|
||||
];
|
||||
|
||||
// fails without the fix: each of these passed the old denylist, and the first runs a handler once scripting is on.
|
||||
const REFUSED = [
|
||||
'<div class="clip"><noscript><p title="</noscript><img src=x onerror=alert(1)>"></p></noscript></div>',
|
||||
'<div class="clip"><style>p{}</style><p>Made</p></div>',
|
||||
'<div class="clip"><textarea><img src=x onerror=alert(1)></textarea></div>',
|
||||
'<div class="clip"><base href="https://elsewhere.example/"></div>',
|
||||
'<div class="clip"><meta http-equiv="refresh" content="0;url=x"></div>',
|
||||
'<div class="clip"><link rel="stylesheet" href="https://elsewhere.example/a.css"></div>',
|
||||
'<div class="clip"><template><img src=x onerror=alert(1)></template></div>',
|
||||
'<div class="clip"><form action="https://elsewhere.example/"><button>Go</button></form></div>',
|
||||
];
|
||||
|
||||
describe("markupOutsideAllowlist", () => {
|
||||
it("passes clip markup that parses to the same inert tree with scripting on as in the check", () => {
|
||||
for (const html of ALLOWED) {
|
||||
const checked = parse(html, false);
|
||||
expect(markupOutsideAllowlist(checked.documentElement)).toEqual([]);
|
||||
const run = parse(html, true);
|
||||
expect(tagsOf(run)).toEqual(tagsOf(checked));
|
||||
expect(runsCode(run)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses markup a scripting parser could read differently, or that loads or points elsewhere", () => {
|
||||
for (const html of REFUSED)
|
||||
expect(markupOutsideAllowlist(parse(html, false).documentElement), html).not.toEqual([]);
|
||||
});
|
||||
|
||||
it("shows why: a noscript the check reads as inert runs a handler once scripting is on", () => {
|
||||
const html = REFUSED[0]!;
|
||||
expect(runsCode(parse(html, false))).toBe(false);
|
||||
expect(runsCode(parse(html, true))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isSafeAttributeValue, unsafeMarkup } from "./htmlAttrSafety";
|
||||
import { isSafeAttributeValue, markupOutsideAllowlist } from "./htmlAttrSafety";
|
||||
|
||||
const root = (html: string) => {
|
||||
const holder = document.createElement("template");
|
||||
@@ -8,33 +8,51 @@ const root = (html: string) => {
|
||||
return holder.content.firstElementChild!;
|
||||
};
|
||||
|
||||
describe("unsafeMarkup", () => {
|
||||
describe("markupOutsideAllowlist", () => {
|
||||
it("names each handler and script link anywhere in the tree", () => {
|
||||
const tree = root(
|
||||
`<div onclick="a()"><a href=" javascript:b()">x</a><img src="data:text/html,c" onerror="d()"></div>`,
|
||||
);
|
||||
expect(unsafeMarkup(tree)).toEqual(["div[onclick]", "a[href]", "img[src]", "img[onerror]"]);
|
||||
expect(markupOutsideAllowlist(tree)).toEqual([
|
||||
"div[onclick]",
|
||||
"a[href]",
|
||||
"img[src]",
|
||||
"img[onerror]",
|
||||
]);
|
||||
});
|
||||
|
||||
it("names elements that carry code, wherever they sit, a template's content included", () => {
|
||||
const tree = root(
|
||||
`<div><script>a()</script><iframe srcdoc="<b>x</b>"></iframe><object data="x"></object><embed src="y"><template><p><script>b()</script></p></template></div>`,
|
||||
);
|
||||
expect(unsafeMarkup(tree)).toEqual(["script", "iframe[srcdoc]", "object", "embed", "script"]);
|
||||
expect(markupOutsideAllowlist(tree)).toEqual(
|
||||
expect.arrayContaining(["script", "iframe", "iframe[srcdoc]", "object", "embed"]),
|
||||
);
|
||||
expect(markupOutsideAllowlist(tree).filter((found) => found === "script")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("names an SVG animation that sets a script link", () => {
|
||||
it("names an SVG animation that sets a script link, and a script link in xlink:href", () => {
|
||||
const tree = root(
|
||||
`<svg><a><set attributeName="href" to="javascript:a()"/><animate attributeName="xlink:href" values="x.svg;javascript:b()"/></a></svg>`,
|
||||
`<svg><a><set attributeName="href" to="javascript:a()"/><use xlink:href="javascript:b()"/></a></svg>`,
|
||||
);
|
||||
expect(unsafeMarkup(tree)).toEqual(["set[to]", "animate[values]"]);
|
||||
expect(markupOutsideAllowlist(tree)).toEqual([
|
||||
"set",
|
||||
"set[attributeName]",
|
||||
"set[to]",
|
||||
"use[xlink:href]",
|
||||
]);
|
||||
});
|
||||
|
||||
it("names nothing in ordinary markup", () => {
|
||||
it("names nothing in ordinary markup, inline SVG with its namespace declarations included", () => {
|
||||
const tree = root(
|
||||
`<section id="s" data-start="1" style="color: red"><video src="clip.mp4" poster="p.png" playsinline></video><iframe src="https://example.com/"></iframe><svg viewBox="0 0 1 1"><path d="M0 0"/><animate attributeName="opacity" values="0;1"/></svg></section>`,
|
||||
`<section id="s" data-start="1" style="color: red"><video src="clip.mp4" poster="p.png" playsinline></video><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1 1"><path d="M0 0"/><use xlink:href="#p"/></svg></section>`,
|
||||
);
|
||||
expect(unsafeMarkup(tree)).toEqual([]);
|
||||
expect(markupOutsideAllowlist(tree)).toEqual([]);
|
||||
});
|
||||
|
||||
it("names a namespace declaration that holds anything but its own namespace", () => {
|
||||
const tree = root(`<svg xmlns:xlink="http://example.com/"><path d="M0 0"/></svg>`);
|
||||
expect(markupOutsideAllowlist(tree)).toEqual(["svg[xmlns:xlink]"]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
* used by sourceMutation (core), sdkCutover (studio), and mutate (sdk).
|
||||
*/
|
||||
|
||||
import { SVG_ATTRIBUTES, SVG_ELEMENTS } from "./svgAllowlist";
|
||||
|
||||
export const ALLOWED_HTML_ATTRS = new Set([
|
||||
"id",
|
||||
"class",
|
||||
@@ -105,54 +107,50 @@ export function isSafeAttributeValue(name: string, value: string): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
const CODE_ELEMENTS = new Set(["script", "object", "embed"]);
|
||||
const INLINE_DOCUMENT_FRAMES = new Set(["iframe", "frame"]);
|
||||
const LINK_ANIMATIONS = new Set(["set", "animate"]);
|
||||
const ANIMATED_LINKS = new Set(["href", "xlink:href"]);
|
||||
const ANIMATED_VALUES = ["to", "from", "by", "values"];
|
||||
|
||||
function kindFindings(element: Element, tag: string): string[] {
|
||||
if (CODE_ELEMENTS.has(tag)) return [tag];
|
||||
return INLINE_DOCUMENT_FRAMES.has(tag) && element.hasAttribute("srcdoc")
|
||||
? [`${tag}[srcdoc]`]
|
||||
: [];
|
||||
}
|
||||
|
||||
const runsCode = (name: string, value: string) =>
|
||||
name.toLowerCase().startsWith("on") || !isSafeAttributeValue(name, value);
|
||||
|
||||
function attributeFindings(element: Element, tag: string): string[] {
|
||||
return Array.from(element.attributes)
|
||||
.filter(({ name, value }) => runsCode(name, value))
|
||||
.map(({ name }) => `${tag}[${name}]`);
|
||||
}
|
||||
|
||||
const animatesLink = (element: Element, tag: string) =>
|
||||
LINK_ANIMATIONS.has(tag) &&
|
||||
ANIMATED_LINKS.has(element.getAttribute("attributeName")?.toLowerCase() ?? "");
|
||||
|
||||
function animationFindings(element: Element, tag: string): string[] {
|
||||
if (!animatesLink(element, tag)) return [];
|
||||
return ANIMATED_VALUES.filter((name) =>
|
||||
(element.getAttribute(name)?.split(";") ?? []).some((v) => !isSafeAttributeValue("href", v)),
|
||||
).map((name) => `${tag}[${name}]`);
|
||||
}
|
||||
|
||||
function childrenOf(element: Element, tag: string): Element[] {
|
||||
const content = tag === "template" ? (element as HTMLTemplateElement).content : null;
|
||||
return [...Array.from(element.children), ...Array.from(content?.children ?? [])];
|
||||
}
|
||||
|
||||
function unsafeIn(element: Element, found: string[]): void {
|
||||
const tag = element.localName;
|
||||
found.push(...kindFindings(element, tag));
|
||||
found.push(...attributeFindings(element, tag));
|
||||
found.push(...animationFindings(element, tag));
|
||||
for (const child of childrenOf(element, tag)) unsafeIn(child, found);
|
||||
const ELEMENTS_PARSED_ALIKE_WITH_SCRIPTING_ON = new Set(
|
||||
(
|
||||
"html head body div span p a abbr address article aside b bdi bdo blockquote br button caption cite code col " +
|
||||
"colgroup data dd del details dfn dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hgroup hr i img " +
|
||||
"ins kbd label li main mark nav ol picture pre q rp rt ruby s samp section small source strong sub summary sup " +
|
||||
"table tbody td template tfoot th thead time tr track u ul var video audio canvas wbr"
|
||||
).split(" "),
|
||||
);
|
||||
const SVG_NS = "http://www.w3.org/2000/svg";
|
||||
const isSvg = (element: Element) => element.namespaceURI === SVG_NS;
|
||||
const FIXED_NAMESPACES = new Map([
|
||||
["xmlns", SVG_NS],
|
||||
["xmlns:xlink", "http://www.w3.org/1999/xlink"],
|
||||
]);
|
||||
|
||||
function elementAllowed(element: Element, tag: string): boolean {
|
||||
if (isSvg(element)) return tag !== "style" && SVG_ELEMENTS.has(element.tagName);
|
||||
return ELEMENTS_PARSED_ALIKE_WITH_SCRIPTING_ON.has(tag) || /^hf-[a-z0-9-]+$/.test(tag);
|
||||
}
|
||||
|
||||
export function unsafeMarkup(root: Element): string[] {
|
||||
function attributeAllowed(element: Element, name: string, value: string): boolean {
|
||||
if (!isSafeAttributeValue(name, value) || name.toLowerCase().startsWith("on")) return false;
|
||||
if (isAllowedHtmlAttribute(name)) return true;
|
||||
if (!isSvg(element)) return false;
|
||||
const namespace = FIXED_NAMESPACES.get(name);
|
||||
if (namespace) return value === namespace;
|
||||
return name === "xlink:href" || SVG_ATTRIBUTES.has(name.replace(/^[^:]*:/, ""));
|
||||
}
|
||||
|
||||
function outsideIn(element: Element, found: string[]): void {
|
||||
const tag = element.localName;
|
||||
if (!elementAllowed(element, tag)) found.push(tag);
|
||||
for (const { name, value } of Array.from(element.attributes))
|
||||
if (!attributeAllowed(element, name, value)) found.push(`${tag}[${name}]`);
|
||||
for (const child of childrenOf(element, tag)) outsideIn(child, found);
|
||||
}
|
||||
|
||||
export function markupOutsideAllowlist(root: Element): string[] {
|
||||
const found: string[] = [];
|
||||
unsafeIn(root, found);
|
||||
outsideIn(root, found);
|
||||
return found;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
/** The SVG elements and attributes sanitizeSvg keeps and the clipboard accepts; anything else is dropped or refused. */
|
||||
export const SVG_ELEMENTS = new Set([
|
||||
"svg",
|
||||
"g",
|
||||
"defs",
|
||||
"symbol",
|
||||
"use",
|
||||
"image",
|
||||
"a",
|
||||
"switch",
|
||||
"rect",
|
||||
"circle",
|
||||
"ellipse",
|
||||
"line",
|
||||
"polyline",
|
||||
"polygon",
|
||||
"path",
|
||||
"text",
|
||||
"tspan",
|
||||
"textPath",
|
||||
"linearGradient",
|
||||
"radialGradient",
|
||||
"stop",
|
||||
"pattern",
|
||||
"mask",
|
||||
"clipPath",
|
||||
"marker",
|
||||
"filter",
|
||||
"feBlend",
|
||||
"feColorMatrix",
|
||||
"feComponentTransfer",
|
||||
"feComposite",
|
||||
"feConvolveMatrix",
|
||||
"feDiffuseLighting",
|
||||
"feDisplacementMap",
|
||||
"feDistantLight",
|
||||
"feDropShadow",
|
||||
"feFlood",
|
||||
"feFuncA",
|
||||
"feFuncB",
|
||||
"feFuncG",
|
||||
"feFuncR",
|
||||
"feGaussianBlur",
|
||||
"feImage",
|
||||
"feMerge",
|
||||
"feMergeNode",
|
||||
"feMorphology",
|
||||
"feOffset",
|
||||
"fePointLight",
|
||||
"feSpecularLighting",
|
||||
"feSpotLight",
|
||||
"feTile",
|
||||
"feTurbulence",
|
||||
"title",
|
||||
"desc",
|
||||
"metadata",
|
||||
"style",
|
||||
]);
|
||||
|
||||
// Local names only — a namespace prefix (xlink:href, x:href, ...) is stripped before this
|
||||
// lookup, so it doesn't matter which prefix an attacker aliases onto a real or fake namespace.
|
||||
export const SVG_ATTRIBUTES = new Set([
|
||||
"id",
|
||||
"class",
|
||||
"style",
|
||||
"transform",
|
||||
"viewBox",
|
||||
"width",
|
||||
"height",
|
||||
"x",
|
||||
"y",
|
||||
"x1",
|
||||
"y1",
|
||||
"x2",
|
||||
"y2",
|
||||
"cx",
|
||||
"cy",
|
||||
"r",
|
||||
"rx",
|
||||
"ry",
|
||||
"fx",
|
||||
"fy",
|
||||
"points",
|
||||
"d",
|
||||
"offset",
|
||||
"enable-background",
|
||||
"gradientUnits",
|
||||
"gradientTransform",
|
||||
"spreadMethod",
|
||||
"patternUnits",
|
||||
"patternContentUnits",
|
||||
"patternTransform",
|
||||
"maskUnits",
|
||||
"maskContentUnits",
|
||||
"clipPathUnits",
|
||||
"clip-rule",
|
||||
"filterUnits",
|
||||
"primitiveUnits",
|
||||
"preserveAspectRatio",
|
||||
"space",
|
||||
"lang",
|
||||
"role",
|
||||
"focusable",
|
||||
"tabindex",
|
||||
"version",
|
||||
"baseProfile",
|
||||
"fill",
|
||||
"fill-opacity",
|
||||
"fill-rule",
|
||||
"stroke",
|
||||
"stroke-width",
|
||||
"stroke-opacity",
|
||||
"stroke-linecap",
|
||||
"stroke-linejoin",
|
||||
"stroke-miterlimit",
|
||||
"stroke-dasharray",
|
||||
"stroke-dashoffset",
|
||||
"opacity",
|
||||
"color",
|
||||
"stop-color",
|
||||
"stop-opacity",
|
||||
"font-family",
|
||||
"font-size",
|
||||
"font-weight",
|
||||
"font-style",
|
||||
"text-anchor",
|
||||
"dominant-baseline",
|
||||
"alignment-baseline",
|
||||
"letter-spacing",
|
||||
"word-spacing",
|
||||
"text-decoration",
|
||||
"clip-path",
|
||||
"mask",
|
||||
"filter",
|
||||
"marker-start",
|
||||
"marker-mid",
|
||||
"marker-end",
|
||||
"marker",
|
||||
"cursor",
|
||||
"pointer-events",
|
||||
"visibility",
|
||||
"display",
|
||||
"overflow",
|
||||
"vector-effect",
|
||||
"paint-order",
|
||||
"color-interpolation",
|
||||
"color-interpolation-filters",
|
||||
"isolation",
|
||||
"mix-blend-mode",
|
||||
"startOffset",
|
||||
"method",
|
||||
"spacing",
|
||||
"side",
|
||||
"textLength",
|
||||
"lengthAdjust",
|
||||
"in",
|
||||
"in2",
|
||||
"result",
|
||||
"mode",
|
||||
"type",
|
||||
"values",
|
||||
"dx",
|
||||
"dy",
|
||||
"stdDeviation",
|
||||
"edgeMode",
|
||||
"k1",
|
||||
"k2",
|
||||
"k3",
|
||||
"k4",
|
||||
"operator",
|
||||
"radius",
|
||||
"scale",
|
||||
"xChannelSelector",
|
||||
"yChannelSelector",
|
||||
"baseFrequency",
|
||||
"numOctaves",
|
||||
"seed",
|
||||
"stitchTiles",
|
||||
"tableValues",
|
||||
"slope",
|
||||
"intercept",
|
||||
"amplitude",
|
||||
"exponent",
|
||||
"order",
|
||||
"divisor",
|
||||
"bias",
|
||||
"targetX",
|
||||
"targetY",
|
||||
"kernelMatrix",
|
||||
"preserveAlpha",
|
||||
"kernelUnitLength",
|
||||
"surfaceScale",
|
||||
"diffuseConstant",
|
||||
"specularConstant",
|
||||
"specularExponent",
|
||||
"lighting-color",
|
||||
"flood-color",
|
||||
"flood-opacity",
|
||||
"azimuth",
|
||||
"elevation",
|
||||
"pointsAtX",
|
||||
"pointsAtY",
|
||||
"pointsAtZ",
|
||||
"limitingConeAngle",
|
||||
]);
|
||||
@@ -26,14 +26,24 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
/** A sealed preview of SAVED, with the runtime's hide on the clip, and the saved file served. */
|
||||
function sealedClipboard(domSelection: DomEditSelection | null, scriptMade = "", saved = SAVED) {
|
||||
function sealedClipboard(
|
||||
domSelection: DomEditSelection | null,
|
||||
scriptMade = "",
|
||||
saved = SAVED,
|
||||
otherFiles: Record<string, string> = {},
|
||||
) {
|
||||
const preview = new DOMParser().parseFromString(ensureHfIds(saved), "text/html");
|
||||
document.body.innerHTML = preview.body.innerHTML;
|
||||
document.querySelector("[data-composition-id]")!.insertAdjacentHTML("beforeend", scriptMade);
|
||||
document.getElementById("title")!.style.cssText = "visibility: hidden; display: none";
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => new Response(JSON.stringify({ content: saved }))),
|
||||
vi.fn(async (url: string) => {
|
||||
const other = Object.keys(otherFiles).find((path) =>
|
||||
decodeURIComponent(String(url)).endsWith(`/files/${path}`),
|
||||
);
|
||||
return new Response(JSON.stringify({ content: other ? otherFiles[other] : saved }));
|
||||
}),
|
||||
);
|
||||
const { iframe } = sealedPreviewFrame();
|
||||
const writes: string[] = [];
|
||||
@@ -130,6 +140,18 @@ const SCRIPT_MADE = [
|
||||
['<a id="made" class="clip" href="javascript:alert(1)">Made</a>', true],
|
||||
['<div id="made" class="clip"><script>alert(1)</script>Made</div>', true],
|
||||
['<iframe id="made" class="clip" srcdoc="<b>x</b>"></iframe>', true],
|
||||
// fails without the fix: inert in the check's scripting-off parse, live in a preview that runs scripts.
|
||||
[
|
||||
'<div id="made" class="clip"><noscript><p title="</noscript><img src=x onerror=alert(1)>"></p></noscript></div>',
|
||||
true,
|
||||
],
|
||||
['<div id="made" class="clip"><base href="https://elsewhere.example/"></div>', true],
|
||||
['<div id="made" class="clip"><meta http-equiv="refresh" content="0;url=x"></div>', true],
|
||||
[
|
||||
'<div id="made" class="clip"><link rel="stylesheet" href="https://elsewhere.example/a.css"></div>',
|
||||
true,
|
||||
],
|
||||
['<div id="made" class="clip"><style>p{}</style><p>Made</p></div>', true],
|
||||
['<video id="made" class="clip" src="clip.mp4" data-start="1" data-duration="2"></video>', false],
|
||||
] as const;
|
||||
|
||||
@@ -154,6 +176,28 @@ it("pastes a sealed preview's own element only when its markup runs no code", as
|
||||
}
|
||||
});
|
||||
|
||||
// fails without the fix: markup the copy found in another file was taken as saved and pasted unchecked.
|
||||
it("checks a saved element read from another file before pasting it into this one", async () => {
|
||||
const received = `<!doctype html><html><body><div data-composition-id="recv" data-start="0" data-duration="5">
|
||||
<button id="go" class="clip" onclick="steal()" data-start="1" data-duration="1" data-track-index="2">Go</button>
|
||||
</div></body></html>`;
|
||||
const selection = {
|
||||
id: "go",
|
||||
selector: "#go",
|
||||
sourceFile: "compositions/recv.html",
|
||||
} as DomEditSelection;
|
||||
// The frame shows one of the person's own clips under the received element's file and id.
|
||||
const relabelled =
|
||||
'<div data-composition-file="compositions/recv.html"><button id="go" class="clip">Go</button></div>';
|
||||
const { clipboard, writes, toasts } = sealedClipboard(selection, relabelled, SAVED, {
|
||||
"compositions/recv.html": received,
|
||||
});
|
||||
expect(clipboard().handleCopy()).toBe(true);
|
||||
await clipboard().handlePaste();
|
||||
expect(writes).toEqual([]);
|
||||
expect(toasts.at(-1)).toMatch(/^Couldn't paste/);
|
||||
});
|
||||
|
||||
it("pastes and duplicates a saved element with its own handler, as saved", async () => {
|
||||
const saved = SAVED.replace(
|
||||
"</div></body>",
|
||||
|
||||
@@ -229,14 +229,19 @@ describe("pasteTimelineClips", () => {
|
||||
it("still strips data-hf-id from a tag the HTML parser hoists out of body (e.g. title)", () => {
|
||||
// A <title> never reaches DOMParser's body, so remintHfIds's DOM walk sees
|
||||
// no root element here -- this exercises the regex fallback, not the walk.
|
||||
// Only an in-file copy gets that far: from anywhere else a <title> is refused.
|
||||
const hoisted: TimelineClipboardClip = {
|
||||
html: '<title data-hf-id="hf-leak">x</title>',
|
||||
readFrom: "index.html",
|
||||
start: 0,
|
||||
duration: 1,
|
||||
track: 0,
|
||||
};
|
||||
const { content } = pasteTimelineClips(ROOT, [hoisted], 0, []);
|
||||
const { content } = pasteTimelineClips(ROOT, [hoisted], 0, [], true, "index.html");
|
||||
expect(content).not.toContain("data-hf-id");
|
||||
expect(() => pasteTimelineClips(ROOT, [{ ...hoisted, readFrom: null }], 0, [])).toThrow(
|
||||
/^Couldn't paste/,
|
||||
);
|
||||
});
|
||||
|
||||
it("captures the root's own id, not a data-id that happens to precede it", () => {
|
||||
@@ -293,10 +298,15 @@ describe("pasteTimelineClips + extendRootDurationInSource", () => {
|
||||
});
|
||||
|
||||
describe("pasteElementHtml", () => {
|
||||
it("refuses code the parser hoists out of the body unless the markup came from the saved file", () => {
|
||||
it("refuses code the parser hoists out of the body unless Studio read it from the file it writes to", () => {
|
||||
const html = "<script>alert(1)</script>";
|
||||
expect(() => pasteElementHtml(ROOT, { html })).toThrow(/^Couldn't paste/);
|
||||
expect(pasteElementHtml(ROOT, { html, saved: true })).toContain(html);
|
||||
expect(() =>
|
||||
pasteElementHtml(ROOT, { html, readFrom: "other.html" }, false, "index.html"),
|
||||
).toThrow(/^Couldn't paste/);
|
||||
expect(pasteElementHtml(ROOT, { html, readFrom: "index.html" }, false, "index.html")).toContain(
|
||||
html,
|
||||
);
|
||||
});
|
||||
|
||||
it("gives a pasted element and its children ids of their own, so an edit to the copy stays on it", () => {
|
||||
@@ -304,7 +314,12 @@ describe("pasteElementHtml", () => {
|
||||
ROOT.replace("</div>", '<p id="title" class="t">Hello <b>there</b></p></div>'),
|
||||
);
|
||||
const copied = stamped.match(/<p[^>]*id="title"[^>]*>.*?<\/p>/)![0];
|
||||
const content = pasteElementHtml(stamped, { html: copied, saved: true }, true);
|
||||
const content = pasteElementHtml(
|
||||
stamped,
|
||||
{ html: copied, readFrom: "index.html" },
|
||||
true,
|
||||
"index.html",
|
||||
);
|
||||
expect(content.indexOf("</p>") + 4).toBe(content.indexOf("\n<p"));
|
||||
const ids = hfIdsIn(content);
|
||||
expect(ids).toHaveLength(hfIdsIn(stamped).length + 2);
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
savedMarkupElseLive,
|
||||
} from "../utils/authoredSource";
|
||||
import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
|
||||
import { unsafeMarkup } from "@hyperframes/core/html-attr-safety";
|
||||
import { refuseUnlistedMarkup } from "../utils/clipboardMarkup";
|
||||
|
||||
type InPlace = { inPlace?: boolean };
|
||||
|
||||
@@ -158,20 +158,17 @@ export function resolveFreeTrack(preferred: PlacedClip, taken: readonly PlacedCl
|
||||
return maxTrack + 1;
|
||||
}
|
||||
|
||||
function refuseRunningCode(doc: Document, saved = false): void {
|
||||
if (!saved && unsafeMarkup(doc.documentElement).length > 0) {
|
||||
throw new Error(
|
||||
"Couldn't paste: the copied element runs code (a script, an event handler or a script link)",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Gives a clone's root and every descendant a fresh data-hf-id, clear of `taken`. Minted here,
|
||||
* inside the edit, or the server stamps them on the next preview load, behind undo's back.
|
||||
* DOMParser, not a regex, so a `>` inside an attribute value can't defeat it. */
|
||||
function remintHfIds(html: string, parser: DOMParser, taken: Set<string>, saved = false): string {
|
||||
function remintHfIds(
|
||||
html: string,
|
||||
parser: DOMParser,
|
||||
taken: Set<string>,
|
||||
check: (doc: Document) => void,
|
||||
): string {
|
||||
const doc = parser.parseFromString(html, "text/html");
|
||||
refuseRunningCode(doc, saved);
|
||||
check(doc);
|
||||
const root = doc.body.firstElementChild;
|
||||
if (!root) {
|
||||
// A tag the HTML parser hoists out of <body> (title/meta/style/base/link)
|
||||
@@ -195,14 +192,16 @@ const hfIdsInFile = (content: string) =>
|
||||
|
||||
export function pasteElementHtml(
|
||||
content: string,
|
||||
payload: { html: string; saved?: boolean },
|
||||
payload: { html: string; readFrom?: string | null },
|
||||
fromThisFile = false,
|
||||
writeTo: string | null = null,
|
||||
): string {
|
||||
const parser = new DOMParser();
|
||||
const reminted = remintHfIds(payload.html, parser, hfIdsInFile(content), payload.saved);
|
||||
const check = (doc: Document) => refuseUnlistedMarkup(doc, payload.readFrom, writeTo);
|
||||
const reminted = remintHfIds(payload.html, parser, hfIdsInFile(content), check);
|
||||
const deduped = deduplicateIds(reminted, collectHtmlIds(content));
|
||||
const anchorFromThisFile =
|
||||
fromThisFile && payload.saved
|
||||
fromThisFile && !!payload.readFrom && payload.readFrom === writeTo
|
||||
? parser
|
||||
.parseFromString(payload.html, "text/html")
|
||||
.body.firstElementChild?.getAttribute("data-hf-id")
|
||||
@@ -221,6 +220,7 @@ export function pasteTimelineClips(
|
||||
anchorTime: number,
|
||||
liveElements: readonly TimelineElement[],
|
||||
fromThisFile = false,
|
||||
writeTo: string | null = null,
|
||||
): { content: string; ids: string[]; requiredEnd: number } {
|
||||
const groupMinStart = Math.min(...clips.map((c) => c.start));
|
||||
let existingIds = collectHtmlIds(content);
|
||||
@@ -235,7 +235,8 @@ export function pasteTimelineClips(
|
||||
const domParser = new DOMParser();
|
||||
const takenHfIds = hfIdsInFile(content);
|
||||
for (const clip of clips) {
|
||||
const reminted = remintHfIds(clip.html, domParser, takenHfIds, clip.saved);
|
||||
const check = (doc: Document) => refuseUnlistedMarkup(doc, clip.readFrom, writeTo);
|
||||
const reminted = remintHfIds(clip.html, domParser, takenHfIds, check);
|
||||
const deduped = deduplicateIds(reminted, existingIds);
|
||||
existingIds = existingIds.concat(collectHtmlIds(deduped));
|
||||
const newStart = anchorTime + (clip.start - groupMinStart);
|
||||
@@ -255,7 +256,7 @@ export function pasteTimelineClips(
|
||||
.replace(/data-start="[^"]*"/, `data-start="${formatTimelineAttributeNumber(newStart)}"`)
|
||||
.replace(/data-track-index="[^"]*"/, `data-track-index="${newTrack}"`);
|
||||
const withPatched = patchedRootTag + deduped.slice(rootTagEnd + 1);
|
||||
refuseRunningCode(domParser.parseFromString(withPatched, "text/html"), clip.saved);
|
||||
check(domParser.parseFromString(withPatched, "text/html"));
|
||||
result = insertTimelineAssetIntoSource(result, withPatched);
|
||||
if (fromThisFile) {
|
||||
const authored = Number(rootTag.match(/data-start="([^"]*)"/)?.[1]);
|
||||
@@ -428,9 +429,10 @@ export function useClipboard({
|
||||
try {
|
||||
let pastedIds: string[] = [];
|
||||
const fromThisFile = payload.sourceFile === targetPath && payload.projectId === pid;
|
||||
const writeTo = payload.projectId === pid ? targetPath : null;
|
||||
const paste = (originalContent: string) => {
|
||||
if (payload.kind !== "timeline-clip")
|
||||
return pasteElementHtml(originalContent, payload, fromThisFile);
|
||||
return pasteElementHtml(originalContent, payload, fromThisFile, writeTo);
|
||||
const { currentTime, elements } = usePlayerStore.getState();
|
||||
const pasted = pasteTimelineClips(
|
||||
originalContent,
|
||||
@@ -438,6 +440,7 @@ export function useClipboard({
|
||||
pasteStart(payload, targetPath, currentTime, options),
|
||||
elements,
|
||||
fromThisFile,
|
||||
writeTo,
|
||||
);
|
||||
pastedIds = pasted.ids;
|
||||
// A clip pasted past the current composition end would exist in the
|
||||
@@ -507,7 +510,14 @@ export function useClipboard({
|
||||
.getState()
|
||||
.elements.filter((el) => pathOf(el) === targetPath)
|
||||
.map((el) => ({ ...el, start: toAuthoredStart(el, el.start) }));
|
||||
const pasted = pasteTimelineClips(originalContent, clips, anchorTime, liveElements, true);
|
||||
const pasted = pasteTimelineClips(
|
||||
originalContent,
|
||||
clips,
|
||||
anchorTime,
|
||||
liveElements,
|
||||
true,
|
||||
targetPath,
|
||||
);
|
||||
ids = pasted.ids;
|
||||
return extendRootDurationInSource(pasted.content, pasted.requiredEnd);
|
||||
};
|
||||
|
||||
@@ -7,9 +7,9 @@ vi.mock("@hyperframes/core/html-attr-safety", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@hyperframes/core/html-attr-safety")>();
|
||||
return {
|
||||
...actual,
|
||||
unsafeMarkup: (root: Element) => {
|
||||
markupOutsideAllowlist: (root: Element) => {
|
||||
checked.push(root.outerHTML);
|
||||
return actual.unsafeMarkup(root);
|
||||
return actual.markupOutsideAllowlist(root);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -150,7 +150,7 @@ export function liveMarkupWithoutPreviewMarks(live: Element): string {
|
||||
return copy.outerHTML;
|
||||
}
|
||||
|
||||
export type MarkedMarkup = { html: string; saved: boolean };
|
||||
export type MarkedMarkup = { html: string; readFrom: string | null };
|
||||
|
||||
export function savedMarkupElseLive(
|
||||
saved: Document,
|
||||
@@ -159,8 +159,8 @@ export function savedMarkupElseLive(
|
||||
): MarkedMarkup {
|
||||
const authored = findAuthoredElement(saved, live) ?? findAuthoredElementById(saved, live);
|
||||
return authored
|
||||
? { html: authoredMarkup(authored, live, sourceFile), saved: true }
|
||||
: { html: liveMarkupWithoutPreviewMarks(live), saved: false };
|
||||
? { html: authoredMarkup(authored, live, sourceFile), readFrom: sourceFile }
|
||||
: { html: liveMarkupWithoutPreviewMarks(live), readFrom: null };
|
||||
}
|
||||
|
||||
export async function readSavedMarkup(
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { markupOutsideAllowlist } from "@hyperframes/core/html-attr-safety";
|
||||
|
||||
/** Every clipboard write: only markup Studio itself read from the file it writes to skips the allowlist. */
|
||||
export function refuseUnlistedMarkup(
|
||||
doc: Document,
|
||||
readFrom: string | null | undefined,
|
||||
writeTo: string | null,
|
||||
): void {
|
||||
if (readFrom && readFrom === writeTo) return;
|
||||
if (markupOutsideAllowlist(doc.documentElement).length > 0) {
|
||||
throw new Error("Couldn't paste: the copied element holds markup that can't be pasted here.");
|
||||
}
|
||||
}
|
||||
@@ -87,12 +87,12 @@ describe("serializeClipboardPayload / deserializeClipboardPayload", () => {
|
||||
expect(parsed).toEqual(payload);
|
||||
});
|
||||
|
||||
it("drops a 'saved' mark that arrives in clipboard text, for an element and for each clip", () => {
|
||||
it("drops a 'readFrom' mark that arrives in clipboard text, for an element and for each clip", () => {
|
||||
const element = deserializeClipboardPayload(
|
||||
serializeClipboardPayload({
|
||||
kind: "dom-element",
|
||||
html: '<div onclick="x()"></div>',
|
||||
saved: true,
|
||||
readFrom: "index.html",
|
||||
sourceFile: "index.html",
|
||||
}),
|
||||
);
|
||||
@@ -100,13 +100,19 @@ describe("serializeClipboardPayload / deserializeClipboardPayload", () => {
|
||||
serializeClipboardPayload({
|
||||
kind: "timeline-clip",
|
||||
clips: [
|
||||
{ html: '<div onclick="x()"></div>', saved: true, start: 0, duration: 1, track: 0 },
|
||||
{
|
||||
html: '<div onclick="x()"></div>',
|
||||
readFrom: "index.html",
|
||||
start: 0,
|
||||
duration: 1,
|
||||
track: 0,
|
||||
},
|
||||
],
|
||||
sourceFile: "index.html",
|
||||
}),
|
||||
);
|
||||
expect(element).toMatchObject({ kind: "dom-element", html: '<div onclick="x()"></div>' });
|
||||
expect(element).not.toHaveProperty("saved");
|
||||
expect(element).not.toHaveProperty("readFrom");
|
||||
expect(clips?.kind === "timeline-clip" && clips.clips[0]).toEqual({
|
||||
html: '<div onclick="x()"></div>',
|
||||
start: 0,
|
||||
|
||||
@@ -9,7 +9,7 @@ const CLIPBOARD_MARKER = "hyperframes-clipboard:v1";
|
||||
* relative offsets and tracks across a group paste. */
|
||||
export interface TimelineClipboardClip {
|
||||
html: string;
|
||||
saved?: boolean;
|
||||
readFrom?: string | null;
|
||||
start: number;
|
||||
duration: number;
|
||||
track: number;
|
||||
@@ -26,7 +26,7 @@ export type ClipboardPayload =
|
||||
| {
|
||||
kind: "dom-element";
|
||||
html: string;
|
||||
saved?: boolean;
|
||||
readFrom?: string | null;
|
||||
sourceFile: string;
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user