diff --git a/packages/core/src/utils/htmlAttrSafety.test.ts b/packages/core/src/utils/htmlAttrSafety.test.ts new file mode 100644 index 0000000000..a665d6cb05 --- /dev/null +++ b/packages/core/src/utils/htmlAttrSafety.test.ts @@ -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( + `
x
`, + ); + 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( + `
`, + ); + expect(unsafeMarkup(tree)).toEqual(["script", "iframe[srcdoc]", "object", "embed", "script"]); + }); + + it("names an SVG animation that sets a script link", () => { + const tree = root( + ``, + ); + expect(unsafeMarkup(tree)).toEqual(["set[to]", "animate[values]"]); + }); + + it("names nothing in ordinary markup", () => { + const tree = root( + `
`, + ); + 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); + }); +}); diff --git a/packages/core/src/utils/htmlAttrSafety.ts b/packages/core/src/utils/htmlAttrSafety.ts index 59bc764e7e..9166ede430 100644 --- a/packages/core/src/utils/htmlAttrSafety.ts +++ b/packages/core/src/utils/htmlAttrSafety.ts @@ -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; +} diff --git a/packages/studio/src/hooks/useClipboard.sealed.test.ts b/packages/studio/src/hooks/useClipboard.sealed.test.ts index e732699d6a..3042ffd768 100644 --- a/packages/studio/src/hooks/useClipboard.sealed.test.ts +++ b/packages/studio/src/hooks/useClipboard.sealed.test.ts @@ -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 | 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, writes, deleted, openProject }; + return { + clipboard: () => api as ReturnType, + 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 = [ + ['
Made
', true], + ['Made', true], + ['
Made
', true], + ['', true], + ['', 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( + "", + '\n', + ); + 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); diff --git a/packages/studio/src/hooks/useClipboard.test.ts b/packages/studio/src/hooks/useClipboard.test.ts index caedbea343..4a678a9150 100644 --- a/packages/studio/src/hooks/useClipboard.test.ts +++ b/packages/studio/src/hooks/useClipboard.test.ts @@ -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 = ""; + 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("", '

Hello there

'), diff --git a/packages/studio/src/hooks/useClipboard.ts b/packages/studio/src/hooks/useClipboard.ts index fa7ac05e4d..73cef1247e 100644 --- a/packages/studio/src/hooks/useClipboard.ts +++ b/packages/studio/src/hooks/useClipboard.ts @@ -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( 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, - paths: string[], - lives: Element[], -): Promise { - const sources = new Map>(); - 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); - 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 { - const root = parser.parseFromString(html, "text/html").body.firstElementChild; +function remintHfIds(html: string, parser: DOMParser, taken: Set, 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 (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, diff --git a/packages/studio/src/utils/authoredSource.ts b/packages/studio/src/utils/authoredSource.ts index a9873878d5..eb89f1b815 100644 --- a/packages/studio/src/utils/authoredSource.ts +++ b/packages/studio/src/utils/authoredSource.ts @@ -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 { // 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, + paths: string[], + lives: Element[], +): Promise { + const sources = new Map>(); + 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); + return savedMarkupElseLive(saved, lives[index] as Element, path); + }), + ); +} diff --git a/packages/studio/src/utils/clipboardPayload.test.ts b/packages/studio/src/utils/clipboardPayload.test.ts index b91c5eb806..d677328bf7 100644 --- a/packages/studio/src/utils/clipboardPayload.test.ts +++ b/packages/studio/src/utils/clipboardPayload.test.ts @@ -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: '
', + saved: true, + sourceFile: "index.html", + }), + ); + const clips = deserializeClipboardPayload( + serializeClipboardPayload({ + kind: "timeline-clip", + clips: [ + { html: '
', saved: true, start: 0, duration: 1, track: 0 }, + ], + sourceFile: "index.html", + }), + ); + expect(element).toMatchObject({ kind: "dom-element", html: '
' }); + expect(element).not.toHaveProperty("saved"); + expect(clips?.kind === "timeline-clip" && clips.clips[0]).toEqual({ + html: '
', + start: 0, + duration: 1, + track: 0, + }); + }); + it("returns null for invalid JSON", () => { expect(deserializeClipboardPayload("not json")).toBeNull(); expect(deserializeClipboardPayload('{"kind":"unknown"}')).toBeNull(); diff --git a/packages/studio/src/utils/clipboardPayload.ts b/packages/studio/src/utils/clipboardPayload.ts index 49c5198883..227505d1ee 100644 --- a/packages/studio/src/utils/clipboardPayload.ts +++ b/packages/studio/src/utils/clipboardPayload.ts @@ -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 | 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 | 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 = diff --git a/packages/studio/src/utils/htmlAttrSafety.ts b/packages/studio/src/utils/htmlAttrSafety.ts deleted file mode 100644 index be35f4deea..0000000000 --- a/packages/studio/src/utils/htmlAttrSafety.ts +++ /dev/null @@ -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; -} diff --git a/packages/studio/src/utils/sdkCutoverEligibility.ts b/packages/studio/src/utils/sdkCutoverEligibility.ts index 1e57bc9dca..d998b82380 100644 --- a/packages/studio/src/utils/sdkCutoverEligibility.ts +++ b/packages/studio/src/utils/sdkCutoverEligibility.ts @@ -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([ diff --git a/scripts/check-no-main-deletions.mjs b/scripts/check-no-main-deletions.mjs index 8d2c391ae1..1852d8be6a 100644 --- a/scripts/check-no-main-deletions.mjs +++ b/scripts/check-no-main-deletions.mjs @@ -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") {