diff --git a/packages/studio/src/hooks/useClipboard.sealed.test.ts b/packages/studio/src/hooks/useClipboard.sealed.test.ts
index 4023cad5c5..728aa00bc2 100644
--- a/packages/studio/src/hooks/useClipboard.sealed.test.ts
+++ b/packages/studio/src/hooks/useClipboard.sealed.test.ts
@@ -8,6 +8,7 @@ import { usePlayerStore, type TimelineElement } from "../player";
import type { DomEditSelection } from "../components/editor/domEditing";
import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers";
import { setCompositionSourceMap } from "../components/editor/domEditingDom";
+import { parseHTMLContent } from "@hyperframes/core/compiler/html-document";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -178,6 +179,75 @@ it("pastes a sealed preview's own element only when its markup runs no code", as
}
});
+// The sealed path to the writes useClipboard.written.test.ts fails main on; jsdom keeps CSS escapes, so this one holds.
+it("writes no running code when a sealed preview's own element hides markup in a comment", async () => {
+ const hidden = [
+ '
Made
',
+ ];
+ for (const markup of hidden) {
+ const selection = {
+ id: "made",
+ selector: "#made",
+ sourceFile: "index.html",
+ } as DomEditSelection;
+ const { clipboard, writes } = sealedClipboard(
+ selection,
+ markup,
+ SAVED.replace("", ""),
+ );
+ expect(clipboard().handleCopy()).toBe(true);
+ await clipboard().handlePaste();
+ for (const written of writes) {
+ const parsed = new DOMParser().parseFromString(written, "text/html");
+ const handlers = Array.from(parsed.querySelectorAll("*")).flatMap((el) =>
+ el.getAttributeNames().filter((name) => name.startsWith("on")),
+ );
+ expect(handlers).toEqual([]);
+ }
+ act(() => root?.unmount());
+ root = null;
+ }
+});
+
+/** Handlers in a written file, read as saved and as the preview server serves it. */
+function handlersServed(written: string): string[] {
+ return [written, parseHTMLContent(written).toString()].flatMap((html) =>
+ Array.from(new DOMParser().parseFromString(html, "text/html").querySelectorAll("*")).flatMap(
+ (el) => el.getAttributeNames().filter((name) => name.startsWith("on")),
+ ),
+ );
+}
+
+// fails without the fix: a comment in an svg passed the check, and the server's parser serves it as markup.
+it("writes nothing the server serves as running code, from the live copy or a saved one", async () => {
+ const svg = "";
+ const live = sealedClipboard(
+ { id: "made", selector: "#made", sourceFile: "index.html" } as DomEditSelection,
+ `
`,
+ SAVED,
+ { "compositions/recv.html": received },
+ );
+ expect(saved.clipboard().handleCopy()).toBe(true);
+ await saved.clipboard().handlePaste();
+ for (const file of saved.writes) expect(handlersServed(file)).toEqual([]);
+});
+
// 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 = `
diff --git a/packages/studio/src/hooks/useClipboard.test.ts b/packages/studio/src/hooks/useClipboard.test.ts
index a165aa0d1b..738306287f 100644
--- a/packages/studio/src/hooks/useClipboard.test.ts
+++ b/packages/studio/src/hooks/useClipboard.test.ts
@@ -215,20 +215,17 @@ describe("pasteTimelineClips", () => {
expect(hfIdsIn(content)).toHaveLength(1);
});
- it("still strips data-hf-id from bare text with no element root", () => {
+ it("refuses bare text with no element root", () => {
const noRoot: TimelineClipboardClip = {
html: 'text mentioning data-hf-id="hf-leak" with no tag at all',
start: 0,
duration: 1,
track: 0,
};
- const { content } = pasteTimelineClips(ROOT, [noRoot], 0, []);
- expect(content).not.toContain("data-hf-id");
+ expect(() => pasteTimelineClips(ROOT, [noRoot], 0, [])).toThrow(/^Couldn't paste/);
});
- it("still strips data-hf-id from a tag the HTML parser hoists out of body (e.g. title)", () => {
- // A never reaches DOMParser's body, so remintHfIds's DOM walk sees
- // no root element here -- this exercises the regex fallback, not the walk.
+ it("gives a tag a document would hoist out of body (e.g. title) a fresh data-hf-id, never the copied one", () => {
// Only an in-file copy gets that far: from anywhere else a is refused.
const hoisted: TimelineClipboardClip = {
html: 'x',
@@ -238,7 +235,7 @@ describe("pasteTimelineClips", () => {
track: 0,
};
const { content } = pasteTimelineClips(ROOT, [hoisted], 0, [], true, "index.html");
- expect(content).not.toContain("data-hf-id");
+ expect(content).not.toContain("hf-leak");
expect(() => pasteTimelineClips(ROOT, [{ ...hoisted, readFrom: null }], 0, [])).toThrow(
/^Couldn't paste/,
);
diff --git a/packages/studio/src/hooks/useClipboard.ts b/packages/studio/src/hooks/useClipboard.ts
index 443d803ec2..7ae2872545 100644
--- a/packages/studio/src/hooks/useClipboard.ts
+++ b/packages/studio/src/hooks/useClipboard.ts
@@ -1,5 +1,4 @@
import { useCallback, useRef } from "react";
-import { EXCLUDED_TAGS, mintHfId, walkCompositionDescendants } from "@hyperframes/parsers/hf-ids";
import type { TimelineElement } from "../player";
import { usePlayerStore } from "../player";
import { toAuthoredStart } from "../player/store/timelineElement";
@@ -7,13 +6,10 @@ import type { DomEditSelection } from "../components/editor/domEditing";
import {
type ClipboardPayload,
type TimelineClipboardClip,
- ID_ATTR_RE,
- deduplicateIds,
insertAsSibling,
} from "../utils/clipboardPayload";
-import { carryLook, renamedIds } from "../utils/clipboardLook";
-import { collectHtmlIds } from "../utils/studioHelpers";
-import { insertTimelineAssetIntoSource, writtenTrackIndex } from "../utils/timelineAssetDrop";
+import { carryLook } from "../utils/clipboardLook";
+import { placeUnderCompositionRoot, writtenTrackIndex } from "../utils/timelineAssetDrop";
import { extendRootDurationInSource } from "../utils/rootDuration";
import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
@@ -29,7 +25,7 @@ import {
savedMarkupElseLive,
} from "../utils/authoredSource";
import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
-import { copiedFile, refuseUnlistedMarkup } from "../utils/clipboardMarkup";
+import { copiedFile, idsInFile, prepareCopy, refuseAddedMarkup } from "../utils/clipboardMarkup";
import { knownCompositionFile } from "../components/editor/domEditingDom";
type InPlace = { inPlace?: boolean };
@@ -159,61 +155,28 @@ export function resolveFreeTrack(preferred: PlacedClip, taken: readonly PlacedCl
return maxTrack + 1;
}
-/** 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,
- check: (doc: Document) => void,
-): string {
- const doc = parser.parseFromString(html, "text/html");
- check(doc);
- const root = doc.body.firstElementChild;
- if (!root) {
- // A tag the HTML parser hoists out of (title/meta/style/base/link)
- // never reaches the walk above — fall back to a direct strip so
- // data-hf-id still can't survive, even though no real clip root is one
- // of these tags today.
- return html.replace(/\sdata-hf-id=("[^"]*"|'[^']*')/g, "");
- }
- const elements = [root];
- walkCompositionDescendants(root, (el) => elements.push(el));
- for (const el of elements) {
- if (EXCLUDED_TAGS.has(el.tagName.toLowerCase())) el.removeAttribute("data-hf-id");
- else el.setAttribute("data-hf-id", mintHfId(el, taken));
- }
- return root.outerHTML;
-}
-
-const HF_ID_ATTR_RE = /\bdata-hf-id\s*=\s*["']?([^"'\s>]+)/gi;
-const hfIdsInFile = (content: string) =>
- new Set(Array.from(content.matchAll(HF_ID_ATTR_RE), (match) => match[1]));
-
export function pasteElementHtml(
content: string,
payload: { html: string; readFrom?: string | null },
fromThisFile = false,
writeTo: string | null = null,
): string {
- const parser = new DOMParser();
- 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.readFrom && payload.readFrom === writeTo
- ? parser
- .parseFromString(payload.html, "text/html")
- .body.firstElementChild?.getAttribute("data-hf-id")
- : null;
- const result = insertAsSibling(content, deduped, anchorFromThisFile ?? undefined);
- return fromThisFile ? carryLook(result, renamedIds(reminted, deduped), 0) : result;
+ const taken = idsInFile(content);
+ const copy = prepareCopy(payload.html, taken.hfIds, taken.ids);
+ const fromItsFile = fromThisFile && !!payload.readFrom && payload.readFrom === writeTo;
+ const inserted = insertAsSibling(
+ content,
+ copy.html,
+ (fromItsFile && copy.originalHfId) || undefined,
+ );
+ const result = fromThisFile ? carryLook(inserted, copy.renames, 0) : inserted;
+ refuseAddedMarkup(content, result, [{ html: copy.html, readFrom: payload.readFrom }], writeTo);
+ return result;
}
/** Shared insertion path for paste and duplicate, anchored at the playhead or the selection's end. Returns the
- * final ids so the caller can select what it placed, and the furthest end any clip lands at so it can grow the
- * root duration to cover it. `fromThisFile`: the clips came from `content`, so a renamed copy takes its
+ * final ids so the caller can select what it placed; the root's data-duration grows to the furthest end, since a
+ * clip past it never plays or exports. `fromThisFile`: the clips came from `content`, so a renamed copy takes its
* original's look. */
export function pasteTimelineClips(
content: string,
@@ -224,22 +187,14 @@ export function pasteTimelineClips(
writeTo: string | null = null,
): { content: string; ids: string[]; requiredEnd: number } {
const groupMinStart = Math.min(...clips.map((c) => c.start));
- let existingIds = collectHtmlIds(content);
const taken: PlacedClip[] = liveElements.map((el) => ({
track: writtenTrackIndex(el.authoredTrack ?? el.track),
start: el.start,
duration: el.duration,
}));
- const ids: string[] = [];
- let result = content;
+ const { hfIds: takenHfIds, ids: takenIds } = idsInFile(content);
let requiredEnd = 0;
- const domParser = new DOMParser();
- const takenHfIds = hfIdsInFile(content);
- for (const clip of clips) {
- 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 placed = clips.map((clip) => {
const newStart = anchorTime + (clip.start - groupMinStart);
const newTrack = resolveFreeTrack(
{ track: writtenTrackIndex(clip.track), start: newStart, duration: clip.duration },
@@ -247,27 +202,28 @@ export function pasteTimelineClips(
);
taken.push({ track: newTrack, start: newStart, duration: clip.duration });
requiredEnd = Math.max(requiredEnd, newStart + clip.duration);
-
- // Only rewrite the outermost opening tag. The non-global regex matches
- // the first occurrence, which is always in the root tag since outerHTML
- // starts with it. Nested clips keep their own timing and track.
- const rootTagEnd = deduped.indexOf(">");
- const rootTag = rootTagEnd >= 0 ? deduped.slice(0, rootTagEnd + 1) : deduped;
- const patchedRootTag = rootTag
- .replace(/data-start="[^"]*"/, `data-start="${formatTimelineAttributeNumber(newStart)}"`)
- .replace(/data-track-index="[^"]*"/, `data-track-index="${newTrack}"`);
- const withPatched = patchedRootTag + deduped.slice(rootTagEnd + 1);
- check(domParser.parseFromString(withPatched, "text/html"));
- result = insertTimelineAssetIntoSource(result, withPatched);
- if (fromThisFile) {
- const authored = Number(rootTag.match(/data-start="([^"]*)"/)?.[1]);
- const authoredStart = Number.isFinite(authored) ? authored : clip.start;
- result = carryLook(result, renamedIds(reminted, deduped), newStart - authoredStart);
- }
-
- const id = patchedRootTag.match(ID_ATTR_RE)?.[1];
- if (id) ids.push(id);
- }
+ let authoredStart = clip.start;
+ // Only the root moves: nested clips keep their own timing and track.
+ const copy = prepareCopy(clip.html, takenHfIds, takenIds, (root) => {
+ const authored = Number(root.getAttribute("data-start"));
+ if (root.hasAttribute("data-start") && Number.isFinite(authored)) authoredStart = authored;
+ if (root.hasAttribute("data-start"))
+ root.setAttribute("data-start", formatTimelineAttributeNumber(newStart));
+ if (root.hasAttribute("data-track-index"))
+ root.setAttribute("data-track-index", String(newTrack));
+ });
+ return { copy, readFrom: clip.readFrom, delta: newStart - authoredStart };
+ });
+ const base = extendRootDurationInSource(content, requiredEnd);
+ let result = base;
+ const written = placed.map(({ copy, readFrom, delta }) => {
+ const { insertAt, written: html } = placeUnderCompositionRoot(result, copy.html);
+ result = result.slice(0, insertAt) + html + result.slice(insertAt);
+ if (fromThisFile) result = carryLook(result, copy.renames, delta);
+ return { html, readFrom };
+ });
+ refuseAddedMarkup(base, result, written, writeTo);
+ const ids = placed.flatMap(({ copy }) => copy.root.getAttribute("id") ?? []);
return { content: result, ids, requiredEnd };
}
@@ -443,10 +399,7 @@ export function useClipboard({
writeTo,
);
pastedIds = pasted.ids;
- // A clip pasted past the current composition end would exist in the
- // file but never appear on the timeline or in playback/export (the
- // root's data-duration is what actually bounds the render).
- return extendRootDurationInSource(pasted.content, pasted.requiredEnd);
+ return pasted.content;
};
const { label, toast } = pasteWords(payload);
@@ -519,7 +472,7 @@ export function useClipboard({
targetPath,
);
ids = pasted.ids;
- return extendRootDurationInSource(pasted.content, pasted.requiredEnd);
+ return pasted.content;
};
await saveProjectFilesWithHistory({
diff --git a/packages/studio/src/hooks/useClipboard.written.test.ts b/packages/studio/src/hooks/useClipboard.written.test.ts
new file mode 100644
index 0000000000..87f37ee638
--- /dev/null
+++ b/packages/studio/src/hooks/useClipboard.written.test.ts
@@ -0,0 +1,238 @@
+// @vitest-environment jsdom
+import { describe, expect, it, vi } from "vitest";
+import { pasteElementHtml, pasteTimelineClips } from "./useClipboard";
+import { parseHTMLContent } from "@hyperframes/core/compiler/html-document";
+import { prepareCopy, refuseAddedMarkup } from "../utils/clipboardMarkup";
+
+const FILE = `
+
Card
+
`;
+
+/** Every handler in `html` as saved and as the preview server serves it: what no paste may add. */
+function runningCode(html: string): string[] {
+ return [html, parseHTMLContent(html).toString()].flatMap(handlersIn);
+}
+
+function handlersIn(html: string): string[] {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ return Array.from(doc.querySelectorAll("*")).flatMap((el) =>
+ el
+ .getAttributeNames()
+ .filter((name) => name.toLowerCase().startsWith("on"))
+ .map((name) => `${el.localName}[${name}]`),
+ );
+}
+
+/** The paste's own file, or nothing when it was refused. */
+function written(paste: () => string): string {
+ try {
+ return paste();
+ } catch (error) {
+ expect(String(error)).toMatch(/Couldn't paste/);
+ return FILE;
+ }
+}
+
+// fails without the fix: a comment that loses its data-hf-id text after the check closes early, and what followed it
+// in the comment is written as markup.
+describe("markup a paste writes is the markup it checked", () => {
+ const SPLIT_COMMENTS = ['"', "'"].flatMap((q) => [
+ `
';
+
+ it("writes no running code when an element is pasted into its own file", () => {
+ const file = written(() =>
+ pasteElementHtml(FILE, { html: COMMENTED_STYLE, readFrom: null }, true, "index.html"),
+ );
+ expect(runningCode(file)).toEqual([]);
+ });
+
+ it("writes no running code when a clip is duplicated in its own file", () => {
+ const clip = { html: COMMENTED_STYLE, readFrom: null, start: 0, duration: 2, track: 1 };
+ const file = written(() => pasteTimelineClips(FILE, [clip], 2, [], true, "index.html").content);
+ expect(runningCode(file)).toEqual([]);
+ });
+
+ it("still gives a pasted copy its original's look", () => {
+ const html =
+ '
Copy
';
+ const file = pasteElementHtml(FILE, { html, readFrom: "index.html" }, true, "index.html");
+ expect(file).toMatch(/#card-2\s*\{\s*color: red;?\s*\}/);
+ });
+});
+
+describe("prepareCopy", () => {
+ it("renames each taken id on the copy's elements and leaves every other attribute as it was", () => {
+ const html =
+ '
x
y
';
+ const copy = prepareCopy(html, new Set(), new Set(["hero", "hero-2"]));
+ expect(copy.root.getAttribute("id")).toBe("hero-3");
+ expect(copy.root.getAttribute("data-composition-id")).toBe("hero");
+ expect(copy.html).toContain('id="hero-2-2" data-id="hero"');
+ expect(copy.html).toContain('id="free"');
+ expect([...copy.renames]).toEqual([
+ ["hero", "hero-3"],
+ ["hero-2", "hero-2-2"],
+ ]);
+ });
+});
+
+// fails without the fix: the check compared attribute names only and ran the allowlist on the copy, not on the file.
+describe("the final check reads what the saved file holds", () => {
+ const copy = 'Go';
+ const before = FILE;
+ const inserted = (html: string) => before.replace('
{
+ const after = inserted('Go');
+ expect(() =>
+ refuseAddedMarkup(before, after, [{ html: copy, readFrom: null }], "index.html"),
+ ).toThrow(/Couldn't paste/);
+ });
+
+ it("refuses a changed link even for a copy Studio read from this very file", () => {
+ const after = inserted('Go');
+ expect(() =>
+ refuseAddedMarkup(before, after, [{ html: copy, readFrom: "index.html" }], "index.html"),
+ ).toThrow(/Couldn't paste/);
+ });
+
+ it("refuses a saved copy whose elements moved to other parents in the same order", () => {
+ const nested = '
Caption
';
+ const after = inserted('
Caption
');
+ expect(() =>
+ refuseAddedMarkup(before, after, [{ html: nested, readFrom: "index.html" }], "index.html"),
+ ).toThrow(/Couldn't paste/);
+ });
+
+ it("accepts the saved copy when it is the copy that was checked", () => {
+ expect(() =>
+ refuseAddedMarkup(before, inserted(copy), [{ html: copy, readFrom: null }], "index.html"),
+ ).not.toThrow();
+ });
+});
+
+// fails without the fix: the file's ids were read as raw text, so an entity-escaped id never matched the copy's.
+it("renames a pasted id the file already holds written with entities", () => {
+ const file = FILE.replace('
L\n
R', readFrom: null },
+ false,
+ "index.html",
+ );
+ const ids = Array.from(
+ new DOMParser().parseFromString(pasted, "text/html").querySelectorAll("span"),
+ (el) => el.id,
+ );
+ expect(ids.sort()).toEqual(["left&right", "left&right-2"]);
+});
+
+// fails without the fix: an svg element named template has no template content, and reading the file's ids threw.
+it("pastes into a file holding an svg element named template", () => {
+ const file = FILE.replace(
+ '
';
+ const { content } = pasteTimelineClips(
+ FILE,
+ [{ html, readFrom: null, start: 0, duration: 1, track: 1 }],
+ 0,
+ [],
+ false,
+ "index.html",
+ );
+ expect(content).toContain('id="multi"');
+});
+
+// fails without the fix: the check read a comment in an svg as a comment, and the preview server's parser
+// ends the title inside it, serving what follows as markup.
+describe("a paste is checked as the preview server serves the file", () => {
+ const svgClip =
+ '