diff --git a/packages/core/src/runtime/entry.ts b/packages/core/src/runtime/entry.ts index 3e08a28736..7b00153df0 100644 --- a/packages/core/src/runtime/entry.ts +++ b/packages/core/src/runtime/entry.ts @@ -20,6 +20,7 @@ import { createFilmBridge } from "./filmBridge"; import { trackAcceleratedCanvases } from "./captureMotionBlur"; import { parkFarScenesAtBoot } from "./sceneWindow"; import { installPausedVideoCallbacks } from "./pausedVideoCallbacks"; +import { corsForSealedMedia } from "./sealedMediaCors"; type HyperframeWindow = Window & { __hyperframeRuntimeBootstrapped?: boolean; @@ -46,6 +47,7 @@ type HyperframeWindow = Window & { // at script evaluation time, while the document is still parsing. installAuthoredOpacityCapture(); installAuthoredMediaCapture(); +corsForSealedMedia(); installPausedVideoCallbacks(); installFlatGsapTransforms(); trackAcceleratedCanvases(); diff --git a/packages/core/src/runtime/sealedMediaCors.test.ts b/packages/core/src/runtime/sealedMediaCors.test.ts new file mode 100644 index 0000000000..54e19b0209 --- /dev/null +++ b/packages/core/src/runtime/sealedMediaCors.test.ts @@ -0,0 +1,114 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { corsForSealedMedia } from "./sealedMediaCors"; + +const PREVIEW = "http://localhost:4817/api/projects/demo/preview/~token/"; +let observer: MutationObserver | null = null; + +// MutationObserver callbacks run as a microtask after the insertion. +const settled = () => Promise.resolve(); + +function add(html: string): Element { + const host = document.createElement("div"); + host.innerHTML = html; + document.body.append(host); + return host; +} + +beforeEach(() => { + document.head.innerHTML = ``; + document.body.innerHTML = ""; +}); + +afterEach(() => { + observer?.disconnect(); + observer = null; + vi.unstubAllGlobals(); +}); + +describe("corsForSealedMedia", () => { + it("opts the preview's own video and audio into CORS in a sealed document", async () => { + vi.stubGlobal("origin", "null"); + observer = corsForSealedMedia(); + const host = add( + ``, + ); + await settled(); + const crossOrigins = [...host.querySelectorAll("video, audio")].map((el) => + el.getAttribute("crossorigin"), + ); + expect(crossOrigins).toEqual(["anonymous", "anonymous"]); + }); + + it("leaves media from another host as authored, since that host may not answer CORS", async () => { + vi.stubGlobal("origin", "null"); + observer = corsForSealedMedia(); + const host = add( + `` + + ``, + ); + await settled(); + expect([...host.querySelectorAll("video")].map((el) => el.hasAttribute("crossorigin"))).toEqual( + [false, false], + ); + }); + + it("opts in a video whose arrives after it", async () => { + vi.stubGlobal("origin", "null"); + observer = corsForSealedMedia(); + const host = add(``); + await settled(); + const video = host.querySelector("video")!; + expect(video.hasAttribute("crossorigin")).toBe(false); + const source = document.createElement("source"); + source.setAttribute("src", "media/late.mp4"); + video.append(source); + await settled(); + expect(video.getAttribute("crossorigin")).toBe("anonymous"); + }); + + it("opts in a video whose src a script sets after inserting it", async () => { + vi.stubGlobal("origin", "null"); + observer = corsForSealedMedia(); + const video = add(``).querySelector("video")!; + await settled(); + video.src = "media/later.mp4"; + await settled(); + expect(video.getAttribute("crossorigin")).toBe("anonymous"); + }); + + it("takes back only its own crossorigin when a script moves a video to another host", async () => { + vi.stubGlobal("origin", "null"); + observer = corsForSealedMedia(); + const host = add( + ``, + ); + await settled(); + const [ours, authored] = host.querySelectorAll("video"); + ours.src = "https://cdn.example.com/a.mp4"; + authored.src = "https://cdn.example.com/b.mp4"; + await settled(); + expect([ours.hasAttribute("crossorigin"), authored.getAttribute("crossorigin")]).toEqual([ + false, + "anonymous", + ]); + }); + + it("covers media already in the page when it starts, and keeps an authored crossorigin", async () => { + const host = add( + ``, + ); + vi.stubGlobal("origin", "null"); + observer = corsForSealedMedia(); + expect([...host.querySelectorAll("video")].map((el) => el.getAttribute("crossorigin"))).toEqual( + ["anonymous", "use-credentials"], + ); + }); + + it("changes nothing in a document with its own origin", async () => { + observer = corsForSealedMedia(); + const host = add(``); + await settled(); + expect(observer).toBeNull(); + expect(host.querySelector("video")!.hasAttribute("crossorigin")).toBe(false); + }); +}); diff --git a/packages/core/src/runtime/sealedMediaCors.ts b/packages/core/src/runtime/sealedMediaCors.ts new file mode 100644 index 0000000000..777f249cf2 --- /dev/null +++ b/packages/core/src/runtime/sealedMediaCors.ts @@ -0,0 +1,75 @@ +// A sealed preview's document has an opaque origin, so its own server's media is cross-origin to it. Without +// `crossorigin` the browser loads that media in no-cors mode: WebGL and canvases refuse its frames, Web Audio treats it +// as foreign. The preview server answers CORS loads from an opaque origin, so its own media opts in; other hosts don't. + +const isMedia = (el: Element): el is HTMLMediaElement => + el.localName === "video" || el.localName === "audio"; + +function servedHere(media: HTMLMediaElement, home: string): boolean { + const urls = [media, ...media.querySelectorAll("source")] + .map((el) => el.getAttribute("src")) + .filter((src): src is string => Boolean(src)); + const own = originOf(home, home); + return urls.length > 0 && urls.every((src) => originOf(src, home) === own); +} + +function originOf(url: string, base: string): string | null { + try { + return new URL(url, base).origin; + } catch { + return null; + } +} + +// Only a crossorigin added here is taken back when a src moves to a host that may not answer CORS. +const optedIn = new WeakSet(); + +function sync(media: HTMLMediaElement, home: string): void { + const own = servedHere(media, home); + if (own && !media.hasAttribute("crossorigin")) { + media.setAttribute("crossorigin", "anonymous"); + optedIn.add(media); + } else if (!own && optedIn.delete(media)) { + media.removeAttribute("crossorigin"); + } +} + +// The parser can add a after its media element, and a script can change either's src. +function mediaOf(el: Element): HTMLMediaElement | null { + if (isMedia(el)) return el; + const parent = el.localName === "source" ? el.parentElement : null; + return parent && isMedia(parent) ? parent : null; +} + +function visit(node: Node, home: string): void { + if (node.nodeType !== 1) return; + const el = node as Element; + const media = mediaOf(el); + if (media) sync(media, home); + for (const inner of el.querySelectorAll("video, audio")) sync(inner as HTMLMediaElement, home); +} + +/** In a sealed document, opts the preview server's own media into CORS as it parses or changes src, before it loads. */ +export function corsForSealedMedia(): MutationObserver | null { + if ( + typeof MutationObserver === "undefined" || + typeof document === "undefined" || + window.origin !== "null" + ) + return null; + const home = document.baseURI; + visit(document.documentElement, home); + const observer = new MutationObserver((records) => { + for (const record of records) { + if (record.type === "attributes") visit(record.target, home); + else record.addedNodes.forEach((node) => visit(node, home)); + } + }); + observer.observe(document.documentElement, { + childList: true, + subtree: true, + attributes: true, + attributeFilter: ["src"], + }); + return observer; +}