fix(studio): paste refuses an element with an event handler or a script link (#8298)

* test(studio): pasting a preview's own element keeps only markup that runs no code

* fix(studio): paste refuses an element with an event handler or a script link

* fix(studio): paste checks only markup that is not in the saved file

* test(studio): paste refuses code in elements and in links spelled to slip past

* fix(studio): paste refuses scripts, inline frames and links a browser would read as script

* refactor(studio): one owner for markup safety and the saved-or-live copy plumbing

* refactor(studio): keep the saved-markup helpers private to their module

* test(studio): clipboard text cannot mark a pasted clip as saved

* fix(studio): clipboard text cannot mark a pasted clip as saved
This commit is contained in:
Miguel Ángel
2026-11-20 19:06:46 +00:00
committed by GitHub
parent 99fcdfb5c1
commit 7b2c6dc1ad
11 changed files with 280 additions and 143 deletions
@@ -0,0 +1,53 @@
// @vitest-environment happy-dom
import { describe, expect, it } from "vitest";
import { isSafeAttributeValue, unsafeMarkup } from "./htmlAttrSafety";
const root = (html: string) => {
const holder = document.createElement("template");
holder.innerHTML = html;
return holder.content.firstElementChild!;
};
describe("unsafeMarkup", () => {
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]"]);
});
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"]);
});
it("names an SVG animation that sets a script link", () => {
const tree = root(
`<svg><a><set attributeName="href" to="javascript:a()"/><animate attributeName="xlink:href" values="x.svg;javascript:b()"/></a></svg>`,
);
expect(unsafeMarkup(tree)).toEqual(["set[to]", "animate[values]"]);
});
it("names nothing in ordinary markup", () => {
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>`,
);
expect(unsafeMarkup(tree)).toEqual([]);
});
});
describe("isSafeAttributeValue", () => {
it("reads a link the way a browser does: no tab, newline or leading control character hides its scheme", () => {
for (const link of [
"java\tscript:a()",
"\njavascript:a()",
"\u0001 javascript:a()",
"JAVA\r\nSCRIPT:a()",
])
expect(isSafeAttributeValue("href", link)).toBe(false);
expect(isSafeAttributeValue("data", "javascript:a()")).toBe(false);
expect(isSafeAttributeValue("href", "https://example.com/java\tscript")).toBe(true);
});
});
+63 -1
View File
@@ -66,6 +66,7 @@ export const ALLOWED_HTML_ATTRS = new Set([
export const URI_BEARING_ATTRS = new Set([
"src",
"data",
"href",
"action",
"formaction",
@@ -86,11 +87,72 @@ export function isAllowedHtmlAttribute(name: string): boolean {
return false;
}
// The URL spec's own clean-up before it reads a scheme: no C0 control or space at either end, no tab or newline at all.
function linkAsBrowsersReadIt(value: string): string {
let start = 0;
let end = value.length;
while (start < end && value.charCodeAt(start) <= 0x20) start++;
while (end > start && value.charCodeAt(end - 1) <= 0x20) end--;
return value.slice(start, end).replace(/[\t\n\r]/g, "");
}
export function isSafeAttributeValue(name: string, value: string): boolean {
if (URI_BEARING_ATTRS.has(name.toLowerCase())) {
const trimmed = value.trim();
const trimmed = linkAsBrowsersReadIt(value);
if (DANGEROUS_URI_SCHEMES.test(trimmed)) return false;
if (DANGEROUS_DATA_URI.test(trimmed)) return false;
}
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);
}
export function unsafeMarkup(root: Element): string[] {
const found: string[] = [];
unsafeIn(root, found);
return found;
}
@@ -26,17 +26,19 @@ afterEach(() => {
});
/** A sealed preview of SAVED, with the runtime's hide on the clip, and the saved file served. */
function sealedClipboard(domSelection: DomEditSelection | null) {
const preview = new DOMParser().parseFromString(ensureHfIds(SAVED), "text/html");
function sealedClipboard(domSelection: DomEditSelection | null, scriptMade = "", saved = SAVED) {
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 () => new Response(JSON.stringify({ content: saved }))),
);
const { iframe } = sealedPreviewFrame();
const writes: string[] = [];
const deleted: string[] = [];
const toasts: string[] = [];
const view = { projectId: "p" };
let api: ReturnType<typeof useClipboard> | null = null;
function Harness() {
@@ -44,7 +46,7 @@ function sealedClipboard(domSelection: DomEditSelection | null) {
projectId: view.projectId,
activeCompPath: "index.html",
domEditSelectionRef: { current: domSelection },
showToast: () => {},
showToast: (message: string) => void toasts.push(message),
writeProjectFile: async (_path: string, content: string) => void writes.push(content),
recordEdit: async () => {},
reloadPreview: () => {},
@@ -62,7 +64,13 @@ function sealedClipboard(domSelection: DomEditSelection | null) {
view.projectId = projectId;
act(() => root?.render(React.createElement(Harness)));
};
return { clipboard: () => api as ReturnType<typeof useClipboard>, writes, deleted, openProject };
return {
clipboard: () => api as ReturnType<typeof useClipboard>,
writes,
deleted,
toasts,
openProject,
};
}
const clipOf = (id: string, tag: string, start: number, track: number): TimelineElement => ({
@@ -116,6 +124,56 @@ it("copies a canvas selection from a sealed preview, as saved", async () => {
expect(writes[0]).not.toContain("display: none");
});
// Elements the preview's own script made: not in the saved file, so a copy takes the preview's markup.
const SCRIPT_MADE = [
['<div id="made" class="clip" onclick="alert(1)">Made</div>', true],
['<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],
['<video id="made" class="clip" src="clip.mp4" data-start="1" data-duration="2"></video>', false],
] as const;
it("pastes a sealed preview's own element only when its markup runs no code", async () => {
for (const [markup, refused] of SCRIPT_MADE) {
const selection = {
id: "made",
selector: "#made",
sourceFile: "index.html",
} as DomEditSelection;
const { clipboard, writes, toasts } = sealedClipboard(selection, markup);
expect(clipboard().handleCopy()).toBe(true);
await clipboard().handlePaste();
if (refused) {
expect(writes).toEqual([]);
expect(toasts.at(-1)).toMatch(/^Couldn't paste/);
} else {
expect(writes[0]).toContain('src="clip.mp4"');
}
act(() => root?.unmount());
root = null;
}
});
it("pastes and duplicates a saved element with its own handler, as saved", async () => {
const saved = SAVED.replace(
"</div></body>",
'<button id="go" class="clip" onclick="next()" data-start="1" data-duration="1" data-track-index="2">Go</button>\n</div></body>',
);
const selection = { id: "go", selector: "#go", sourceFile: "index.html" } as DomEditSelection;
const pasted = sealedClipboard(selection, "", saved);
expect(pasted.clipboard().handleCopy()).toBe(true);
await pasted.clipboard().handlePaste();
expect(pasted.writes[0]?.match(/onclick="next\(\)"/g)).toHaveLength(2);
act(() => root?.unmount());
root = null;
usePlayerStore.setState({ elements: [clipOf("go", "button", 1, 2)] });
selectClip("go");
const duplicated = sealedClipboard(null, "", saved);
expect(await duplicated.clipboard().handleDuplicate()).toBe(true);
expect(duplicated.writes[0]?.match(/onclick="next\(\)"/g)).toHaveLength(2);
});
it("leaves the clipboard as it was when a sealed preview lacks the element", async () => {
const selection = { id: "gone", selector: "#gone", sourceFile: "index.html" } as DomEditSelection;
const { clipboard, writes } = sealedClipboard(selection);
@@ -279,6 +279,12 @@ describe("pasteTimelineClips + extendRootDurationInSource", () => {
});
describe("pasteElementHtml", () => {
it("refuses code the parser hoists out of the body unless the markup came from the saved file", () => {
const html = "<script>alert(1)</script>";
expect(() => pasteElementHtml(ROOT, { html })).toThrow(/^Couldn't paste/);
expect(pasteElementHtml(ROOT, { html, saved: true })).toContain(html);
});
it("gives a pasted element and its children ids of their own, so an edit to the copy stays on it", () => {
const stamped = ensureHfIds(
ROOT.replace("</div>", '<p id="title" class="t">Hello <b>there</b></p></div>'),
+17 -33
View File
@@ -23,13 +23,13 @@ import { previewDocumentCopy, previewFrameOpaque } from "../player/lib/previewCh
import { buildTimelineElementKey } from "../player/lib/timelineElementHelpers";
import { timeRangesOverlap } from "../player/components/timelineCollision";
import {
authoredMarkup,
findAuthoredElement,
findAuthoredElementById,
liveMarkupWithoutPreviewMarks,
type MarkedMarkup,
parseSavedSource,
readSavedMarkup,
savedMarkupElseLive,
} from "../utils/authoredSource";
import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
import { unsafeMarkup } from "@hyperframes/core/html-attr-safety";
type InPlace = { inPlace?: boolean };
@@ -137,28 +137,6 @@ function copyFound<T>(
return target === null ? null : copy(target);
}
function savedMarkupElseLive(saved: Document, live: Element, sourceFile: string): string {
const authored = findAuthoredElement(saved, live) ?? findAuthoredElementById(saved, live);
return authored
? authoredMarkup(authored, live, sourceFile)
: liveMarkupWithoutPreviewMarks(live);
}
async function readSavedMarkup(
readSaved: (path: string) => Promise<string>,
paths: string[],
lives: Element[],
): Promise<string[]> {
const sources = new Map<string, Promise<Document>>();
return Promise.all(
paths.map(async (path, index) => {
if (!sources.has(path)) sources.set(path, readSaved(path).then(parseSavedSource));
const saved = await (sources.get(path) as Promise<Document>);
return savedMarkupElseLive(saved, lives[index] as Element, path);
}),
);
}
export interface PlacedClip {
track: number;
start: number;
@@ -183,8 +161,14 @@ export function resolveFreeTrack(preferred: PlacedClip, taken: readonly PlacedCl
/** 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>): string {
const root = parser.parseFromString(html, "text/html").body.firstElementChild;
function remintHfIds(html: string, parser: DOMParser, taken: Set<string>, saved = false): string {
const doc = parser.parseFromString(html, "text/html");
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)",
);
}
const root = doc.body.firstElementChild;
if (!root) {
// A tag the HTML parser hoists out of <body> (title/meta/style/base/link)
// never reaches the walk above — fall back to a direct strip so
@@ -207,10 +191,10 @@ const hfIdsInFile = (content: string) =>
export function pasteElementHtml(
content: string,
payload: { html: string; originSelector?: string; originSelectorIndex?: number },
payload: { html: string; saved?: boolean; originSelector?: string; originSelectorIndex?: number },
fromThisFile = false,
): string {
const reminted = remintHfIds(payload.html, new DOMParser(), hfIdsInFile(content));
const reminted = remintHfIds(payload.html, new DOMParser(), hfIdsInFile(content), payload.saved);
const deduped = deduplicateIds(reminted, collectHtmlIds(content));
const result = insertAsSibling(
content,
@@ -245,7 +229,7 @@ export function pasteTimelineClips(
const domParser = new DOMParser();
const takenHfIds = hfIdsInFile(content);
for (const clip of clips) {
const reminted = remintHfIds(clip.html, domParser, takenHfIds);
const reminted = remintHfIds(clip.html, domParser, takenHfIds, clip.saved);
const deduped = deduplicateIds(reminted, existingIds);
existingIds = existingIds.concat(collectHtmlIds(deduped));
const newStart = anchorTime + (clip.start - groupMinStart);
@@ -336,7 +320,7 @@ export function useClipboard({
const paths = targets.elements.map((el) => el.sourceFile || activeCompPath || "index.html");
const markup = await readSavedMarkup((path) => readSaved(path, pid), paths, targets.lives);
return targets.elements.map((element, index) => ({
html: markup[index] as string,
...(markup[index] as MarkedMarkup),
start: element.start,
duration: element.duration,
// authoredTrack, not track: `track` can be a display-lane number
@@ -384,7 +368,7 @@ export function useClipboard({
showToast("Copied element", "info");
return {
kind: "dom-element",
html: savedMarkupElseLive(parseSavedSource(content), live, sourceFile),
...savedMarkupElseLive(parseSavedSource(content), live, sourceFile),
sourceFile,
projectId: pid ?? undefined,
originSelector: domSelection.selector,
+30 -2
View File
@@ -79,7 +79,7 @@ export function savedTiming(html: string): SavedTiming {
return timing;
}
export function findAuthoredElementById(doc: Document, live: Element): Element | null {
function findAuthoredElementById(doc: Document, live: Element): Element | null {
return live.id ? findByAttribute(doc, "id", live.id) : null;
}
@@ -110,7 +110,7 @@ function livePathsOf(live: Element): Set<string> {
// The preview inlines a sub-composition with its relative asset paths rebased to the project
// root (rewriteAssetPath in @hyperframes/parsers, which is not browser-safe); copy does the same.
export function authoredMarkup(authored: Element, live: Element, sourceFile: string): string {
function authoredMarkup(authored: Element, live: Element, sourceFile: string): string {
if (!sourceFile.includes("/")) return authored.outerHTML;
const livePaths = livePathsOf(live);
const rebase = (path: string): string => {
@@ -149,3 +149,31 @@ export function liveMarkupWithoutPreviewMarks(live: Element): string {
}
return copy.outerHTML;
}
export type MarkedMarkup = { html: string; saved: boolean };
export function savedMarkupElseLive(
saved: Document,
live: Element,
sourceFile: string,
): MarkedMarkup {
const authored = findAuthoredElement(saved, live) ?? findAuthoredElementById(saved, live);
return authored
? { html: authoredMarkup(authored, live, sourceFile), saved: true }
: { html: liveMarkupWithoutPreviewMarks(live), saved: false };
}
export async function readSavedMarkup(
readSaved: (path: string) => Promise<string>,
paths: string[],
lives: Element[],
): Promise<MarkedMarkup[]> {
const sources = new Map<string, Promise<Document>>();
return Promise.all(
paths.map(async (path, index) => {
if (!sources.has(path)) sources.set(path, readSaved(path).then(parseSavedSource));
const saved = await (sources.get(path) as Promise<Document>);
return savedMarkupElseLive(saved, lives[index] as Element, path);
}),
);
}
@@ -86,6 +86,34 @@ describe("serializeClipboardPayload / deserializeClipboardPayload", () => {
expect(parsed).toEqual(payload);
});
it("drops a 'saved' 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,
sourceFile: "index.html",
}),
);
const clips = deserializeClipboardPayload(
serializeClipboardPayload({
kind: "timeline-clip",
clips: [
{ html: '<div onclick="x()"></div>', saved: true, 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(clips?.kind === "timeline-clip" && clips.clips[0]).toEqual({
html: '<div onclick="x()"></div>',
start: 0,
duration: 1,
track: 0,
});
});
it("returns null for invalid JSON", () => {
expect(deserializeClipboardPayload("not json")).toBeNull();
expect(deserializeClipboardPayload('{"kind":"unknown"}')).toBeNull();
+15 -11
View File
@@ -6,6 +6,7 @@ const CLIPBOARD_MARKER = "hyperframes-clipboard:v1";
* relative offsets and tracks across a group paste. */
export interface TimelineClipboardClip {
html: string;
saved?: boolean;
start: number;
duration: number;
track: number;
@@ -22,6 +23,7 @@ export type ClipboardPayload =
| {
kind: "dom-element";
html: string;
saved?: boolean;
sourceFile: string;
projectId?: string;
originSelector?: string;
@@ -51,17 +53,19 @@ export function deserializeClipboardPayload(json: string): ClipboardPayload | nu
if (typeof obj.sourceFile !== "string") return null;
if (obj.kind === "timeline-clip") {
if (!Array.isArray(obj.clips)) return null;
const clips = obj.clips.filter((c): c is TimelineClipboardClip => {
const clip = c as Partial<TimelineClipboardClip> | null;
return (
!!clip &&
typeof clip === "object" &&
typeof clip.html === "string" &&
typeof clip.start === "number" &&
typeof clip.duration === "number" &&
typeof clip.track === "number"
);
});
const clips = obj.clips
.filter((c): c is TimelineClipboardClip => {
const clip = c as Partial<TimelineClipboardClip> | null;
return (
!!clip &&
typeof clip === "object" &&
typeof clip.html === "string" &&
typeof clip.start === "number" &&
typeof clip.duration === "number" &&
typeof clip.track === "number"
);
})
.map(({ html, start, duration, track }) => ({ html, start, duration, track }));
if (clips.length === 0) return null;
const projectId = typeof obj.projectId === "string" ? obj.projectId : undefined;
const copiedInComposition =
@@ -1,90 +0,0 @@
// keep-in-sync-with: packages/core/src/utils/htmlAttrSafety.ts
const ALLOWED_HTML_ATTRS = new Set([
"id",
"class",
"style",
"title",
"name",
"for",
"type",
"lang",
"dir",
"translate",
"hidden",
"tabindex",
"draggable",
"contenteditable",
"role",
"slot",
"href",
"target",
"rel",
"src",
"srcset",
"sizes",
"alt",
"poster",
"loading",
"decoding",
"crossorigin",
"preload",
"autoplay",
"loop",
"muted",
"controls",
"playsinline",
"width",
"height",
"colspan",
"rowspan",
"scope",
"placeholder",
"value",
"min",
"max",
"step",
"pattern",
"required",
"disabled",
"readonly",
"checked",
"selected",
"multiple",
"accept",
"maxlength",
"minlength",
"rows",
"cols",
"wrap",
]);
const URI_BEARING_ATTRS = new Set([
"src",
"href",
"action",
"formaction",
"poster",
"srcset",
"xlink:href",
]);
const DANGEROUS_URI_SCHEMES = /^(?:javascript|vbscript):/i;
const DANGEROUS_DATA_URI = /^data\s*:\s*text\/html/i;
export function isAllowedHtmlAttribute(name: string): boolean {
const lower = name.toLowerCase();
if (lower.startsWith("on")) return false;
if (ALLOWED_HTML_ATTRS.has(lower)) return true;
if (lower.startsWith("data-")) return true;
if (lower.startsWith("aria-")) return true;
return false;
}
export function isSafeAttributeValue(name: string, value: string): boolean {
if (URI_BEARING_ATTRS.has(name.toLowerCase())) {
const trimmed = value.trim();
if (DANGEROUS_URI_SCHEMES.test(trimmed)) return false;
if (DANGEROUS_DATA_URI.test(trimmed)) return false;
}
return true;
}
@@ -6,7 +6,7 @@
*/
import type { Composition } from "@hyperframes/sdk";
import type { PatchOperation } from "./sourcePatcher";
import { isAllowedHtmlAttribute, isSafeAttributeValue } from "./htmlAttrSafety";
import { isAllowedHtmlAttribute, isSafeAttributeValue } from "@hyperframes/core/html-attr-safety";
import { resolveSnapshot } from "./sdkResolverShadow";
const CUTOVER_OP_TYPES = new Set<PatchOperation["type"]>([
+4
View File
@@ -2151,6 +2151,10 @@ export const ALLOWED_DELETIONS = new Map([
"packages/studio/src/utils/authoredOpacity.ts",
"its two authored-opacity helpers moved into core's colorGrading, which the frame's own tween patch now calls; Studio imports them from there",
],
[
"packages/studio/src/utils/htmlAttrSafety.ts",
"Studio's hand-synced copy of core's html-attr-safety rules; Studio imports core's now, one source",
],
]);
export function parseBase(argv, fallback = "origin/main") {