fix(player): a sealed player fails a cross-site film without the runtime as unsealed does (#8558)

* feat(player): a composition can no longer read the page that embeds the player

BREAKING CHANGE: the player's composition frame no longer shares the embedding page's origin
by default. Add sandbox-origin="same-origin" to keep reading the composition's DOM or runtime
directly (editors, recorders, custom timelines), only for compositions you trust.

* chore(skills): refresh the slideshow skill's manifest hash

* fix(player): a sealed player's timeout says how to play a composition without the runtime

A sealed player cannot add the runtime to a composition, so one with a GSAP timeline and no runtime never became
ready and failed with a bare timeout. The timeout now names the two fixes, the README says a sealed composition
brings its own runtime, and a browser test covers the sealed, trusted and runtime-bundled paths.

* test(player): the heavy-films bench embeds the trusted player, since it reads the film from inside

* test(player): the bench host stays sealed; only the bench that reads the film asks for trust

* test(player): the perf server answers CORS, so a sealed player's film loads its own media

* test(player): a sealed film on a host without CORS must still play its videos

* test(core): a sealed video whose CORS load fails loads again once without crossorigin

* fix(core): a sealed film's video loads once more without CORS when its host refuses CORS

* fix(core): the sealed media fallback reads its event target without a realm-bound instanceof

* fix(player): keep the player's origin sharing as today; sealing stays opt-in with sandbox-origin

* test(core): a failed sealed media source spares its siblings; a refused URL drops the helper's CORS

* fix(core): a sealed film tries every CORS source before falling back and drops CORS for refused URLs

* fix(cli): the play page shares its origin as today; docs say sealing is opt-in

* refactor(core): split the sealed media fallback into small steps

* test(player): sealed media decides CORS per element in Chrome; probe advice follows the policy

* fix(core): each sealed media element owns its CORS choice; probe advice follows the policy

* test(player): a sealed player's late timeline expects the sealed advice; media cases await each read

* test(player): sealed media rows for a skipped first source, author writes and a recovered URL

* fix(core): sealed media falls back only when the browser has no source left, once per URL

* test(player): the skipped-source row's loads are never cached, so each one is counted

* test(player): the skipped-source row bounds the video's load attempts as well as its requests

* test(player): sealed media rows for a mismatched-source reload, an outage and two refusing sources

* fix(core): a sealed media element owns one fallback state; only a played fallback is remembered

* test(player): a generated table of sealed media edits, each element checked on its own

* fix(core): sealed media CORS is decided per element and chosen source, with no shared cache

* test(player): the media table counts the runtime's loads against other selections

* fix(core): a sealed media element guesses the source it last played

* test(player): the media table attributes loads exactly and lets a failing host stay down

* test: sealed media rows check per-element CORS; the generated table replaces the hand-picked ones

* fix(core): a media element's own src counts as the source that failed

* fix(core): starting sealed media CORS twice adds no second set of listeners

* test(player): judge the sealed media table against frames without the runtime

* test(player): compare the sealed media table with the same film unsealed

* test(player): run the unsealed control film before the sealed one in one tab

* test(player): judge an authored crossorigin only on the composition's value

* test(player): an all-own list returning to an upgraded URL keeps its pixels

* test(player): source and playback against the sealed film with the helper off

* test(player): count every runtime load of a table video, net of the film without the helper

* test(player): the all-own return row plays the other clip alone before the URL comes back

* test(player): judge every round of the sealed media table, not only the end

* fix(core): sealed media keeps the browser's source choice and its playback across our reloads

* test(player): the table plays a video only after the runtime has bound it

* fix(core): a sealed video drops a stale crossorigin its source already refused

* test(player): the table exempts foreign hosts from pixels and allows a range request per load

* test(core): unit rows for the source choice, down hosts and playback across reloads

* refactor(core): sealed media restores time through the media clock, and its failure path is split

* test(player): the table compares play() outcomes, recovers a down host, and reads a seek at seeked

* test(player): the table judges a seek by where it settles and lets a composition pause on rejection

* test(player): the table holds the helper to a play() the film without it resolved

* test(player): pin the generated sequences that found the recovery and play() faults

* test(player): a slow host keeps the composition's play() pending when its source fails

* test(player): pin the sequences that find the play() and recovery faults with the slow host

* test(player): the table can start its generated sequences at any seed

* test(player): pin the generated sequences that find the recovered source skipped

* test(player): keep the pinned sequences that are red in every run in both browsers

* test(player): a looping video starting over is not a seek after the composition's

* fix(core): a sealed video retries a recovered source and keeps the composition's play() alive

* test(core): the playback row watches the play() the runtime's retry makes

* test(player): a slow host delays its first answer only; the composition's own abort is skipped

* test(player): a loop restart is told from a seek by where the seek began

* test(player): restarts are read at metadata, and a buffering control judges no playback

* test(player): the table counts and limits the comparisons it skips

* test(player): our restore after a composition seek stays within a frame; all selections count

* test(player): a playhead counts as moving if it moves within a second

* fix(core): only the composition's own load() makes a sealed video retry a down source

* fix(core): a sealed video's down source stays down through the runtime's preload load

* test(player): judge sealed media rows by what each step makes possible, not page timing

* test(player): print sealed and unsealed seek landings each sealed media run

* test(player): read a looping clip after its loop restart in every film alike

* fix(core): the runtime's preload loads a media element once per source list

* fix(core): the runtime's prefetch shares the preload's one load per source list

* test(player): a table step interrupts the CORS handling's own reload, not the runtime's preload

* test(core): an undo puts a clip's colour grade back in a sealed preview in place

* fix(core): an undo of a colour grade applies in place in a sealed preview

* test(player): a second table seek lands during the CORS reload of a playing clip

* test(core): an undo in a sealed preview keeps the media attributes the runtime added

* fix(core): an undo in a sealed preview keeps the media attributes the runtime added

* test(player): the playing-clip seek row plays a clip that starts past 0, as a trimmed one does

* test(player): the playing-clip seek is armed with its video, before the play step waits

* test(player): the down-then-back row reloads again, so every film's control has a frame

* test(player): the playing-clip seek row's host answers late, so the clip plays before its reload

* fix(player): a sealed player plays a same-site composition with the runtime it ships

* fix(player): a switch to video unloads a sealed composition shown as srcdoc

* test(core): the runtime's preload mid-selection keeps a down source's mark

* fix(core): a sealed film's down source keeps its mark through the runtime's own loads

* chore(player): fallow reads the cjs and iife runtime file as an entry

* fix(core): declare the html-tokens subpath where package exports are generated

* fix(player): a sealed composition that brings its runtime loads by src under its own headers

* test(player): expect the sealed player's own timeout message in the late-runtime tests

* test(core): a grade undo on a far clip whose length is loading applies in place

* fix(core): a far clip's length probe records the preload it sets, so a grade undo applies

* fix(player): a sealed film shown as srcdoc keeps its URL, so its sound still plays

* test(player): the late-timeline switch uses a film from another origin, which must still fail

* fix(player): a sealed Studio preview keeps its own runtime and loads by src

* fix(player): the player package carries the runtime once, and Studio none

* fix(core): a sealed video reads its own source's pixels in a list that names another host

* fix(player): a sealed player with no bundler still gets the runtime, only when it needs it

* fix(core): keep the mixed-list change within the comment budget

* fix(core): opt a mixed list in only when its first source plays, so a reload keeps that video

* fix(core): a CORS reload keeps the source that was playing

* fix(core): the composition's own load() picks from its full source list again

* fix(core): a reload's pin keeps a source type the composition wrote meanwhile

* fix(core): a reload's pin stops at the source the browser picked, not a skipped copy of its URL

* fix(core): a reload's pin stops at the source element that played, not the first copy of its URL

* fix(core): a reload's pin keeps the source element that played or refused

* style(core): format the source pin

* style(player): keep the runtime source comment under the line limit

* fix(player): only a real </script> closing tag ends a script in the runtime check

* test(player): count the sealed helper's loads by the crossorigin they change

* fix(player): a sealed player fails a cross-site film without the runtime exactly as unsealed

* fix(core): a sealed video asks its host once before treating a failed CORS load as a refusal

* test(player): the sealed table expects pixels from a host that answers CORS after a failed load

* docs(player): the README's timeout sentence matches the shared error

* test(core): each refusal row waits for the CORS question it starts

* test(player): the sealed media table waits on each clip's own events

* fix(player): a film from another site that times out names the fix, in both modes

* fix(player): the no-listener warning tracks listeners by capture and drops once and aborted ones

* refactor(core): a pinned-out source's error gets its own check in the sealed media helper

* test(player): the loop restart wait keeps its two-second window

* fix(player): warn only when no error listener ran, and leave the source URL out

* fix(player): an error listener of null is passed through, as the DOM accepts it

* style(player): format the table's event wait

* fix(player): an onerror handler that clears itself still counts as heard

* chore(fallow): resolve workspace exports to source as bun does, so no false package cycle

* refactor(player): read script tag attributes in small steps, the same result

* refactor(player): the shader loading attribute reads its words from one table

* refactor(player): the attribute helpers' names say what their comments did

* fix(core): the CORS question never follows a redirect, and stays quiet while it waits

* style(core): format the CORS question's rows

* test(player): a sealed same-site page keeps its own policy; a stuck fetch reports the limit

* fix(player): a sealed same-site page keeps its own policy, and a stuck fetch ends at the limit

* fix(player): a sealed page whose headers can't all be read, as after a redirect, loads by src

* style(player): format the sealed player and name the probe's preparation state

* test(player): the listener waits run past the load limit, as the cross-site wait does

* fix(player): a sealed player that couldn't read its page names the runtime fix again

* fix(player): a same-site page still being fetched keeps the plain timeout

* test(player): a sealed player with no film gets the plain timeout
This commit is contained in:
Miguel Ángel
2026-11-25 03:54:38 +00:00
committed by GitHub
parent 32618ac514
commit fbdfd188c4
11 changed files with 366 additions and 70 deletions
+1 -1
View File
@@ -145,7 +145,7 @@ player.addEventListener("timeupdate", (event) => {
| `ratechange` | — | Playback rate changed |
| `volumechange` | — | Volume or muted state changed |
| `scenes` | `{ scenes }` | The runtime reported its scene list |
| `error` | `{ message }` | Load or runtime error, or no timeline within the load limit (Windows 90 s, Linux 30 s, other systems 120 s). The player keeps listening, so a timeline that comes later still fires `ready`. A video adds its `MediaError` `code` |
| `error` | `{ message }` | Load or runtime error, or no timeline within the load limit (Windows 90 s, Linux 30 s, other systems 120 s). The player keeps listening, so a timeline that comes later still fires `ready`. A video adds its `MediaError` `code`. With no listener and no `onerror`, it is also a console warning |
| `playbackerror` | `{ source, error }` | The browser blocked playback, for example unmuted autoplay |
## Custom icons and loading mark
+1 -1
View File
@@ -356,7 +356,7 @@ The `width` and `height` attributes define the composition's native resolution f
## How it works
The player renders compositions in a sandboxed `<iframe>` inside a Shadow DOM. It communicates with the HyperFrames runtime via `postMessage`. If the composition has GSAP timelines (`window.__timelines`) but no runtime, the player auto-injects it from CDN. An opaque player adds the runtime only to a composition from its own site that sets no security policy of its own; any other composition must load the runtime script itself, or the player fires `error` at the load limit with a message naming both fixes.
The player renders compositions in a sandboxed `<iframe>` inside a Shadow DOM. It communicates with the HyperFrames runtime via `postMessage`. If the composition has GSAP timelines (`window.__timelines`) but no runtime, the player auto-injects it from CDN. An opaque player adds the runtime only to a composition from its own site that sets no security policy of its own; any other composition must load the runtime script itself, or the player fires `error` at the load limit, sealed or not. For a composition from another site, the message also says to include the runtime script in it. An `error` with no listener and no `onerror` is also written to the console as a `[hyperframes-player]` warning.
## Distribution
+7 -8
View File
@@ -26,13 +26,12 @@ import {
import { RUNTIME_CDN_URL, runtimeCdnUrlForVersion } from "./runtime-url.js";
const SEALED_RUNTIME_HINT =
". A sealed player adds the HyperFrames runtime only to a composition from its own site: " +
"include the runtime script in a composition from another site, or play a composition you trust without sandbox-origin.";
const ANOTHER_SITE_FIX =
"A player can't add the HyperFrames runtime to a composition from another site: include the runtime script in it.";
export function timelineNotFound(limitMs: number, sealed: boolean): string {
export function timelineNotFound(limitMs: number, runtimeOutOfReach = false): string {
const message = `Composition timeline not found after ${limitMs / 1000}s`;
return sealed ? message + SEALED_RUNTIME_HINT : message;
return runtimeOutOfReach ? `${message}. ${ANOTHER_SITE_FIX}` : message;
}
export { runtimeCdnUrlForVersion };
@@ -51,7 +50,7 @@ export interface ProbeCallbacks {
onRuntimeInjected?: () => void;
resolveRuntimeUrl?: () => string;
hostOwnsDeadline?: () => boolean;
unreadSealedLoad?: () => boolean;
runtimeOutOfReach?: () => boolean;
}
/**
@@ -168,7 +167,7 @@ export class CompositionProbe {
if (!this._navigationPending || this._callbacks.hostOwnsDeadline?.()) return;
this._limitReportedBeforeLoad = true;
this._callbacks.onError(
timelineNotFound(this._limitMs, this._callbacks.unreadSealedLoad?.() === true),
timelineNotFound(this._limitMs, this._callbacks.runtimeOutOfReach?.() === true),
);
}
@@ -239,7 +238,7 @@ export class CompositionProbe {
this._interval = setInterval(tick, LATE_POLL_MS);
this._failure = { document: this._iframe.contentDocument, deadline: true };
this._callbacks.onError(
timelineNotFound(this._limitMs, this._callbacks.unreadSealedLoad?.() === true),
timelineNotFound(this._limitMs, this._callbacks.runtimeOutOfReach?.() === true),
);
}
@@ -131,30 +131,15 @@ describe("composition probe readiness", () => {
vi.advanceTimersByTime(LIMIT);
expect(onError).toHaveBeenCalledOnce();
});
const unreadable = (sealed: boolean) => {
const { iframe, onError } = mount(
'<div data-composition-id="main"></div>',
{},
{ unreadSealedLoad: () => sealed },
);
it("gives a frame it can't read the plain timeout, sealed or not", () => {
const { iframe, onError } = mount('<div data-composition-id="main"></div>');
Object.defineProperty(iframe, "contentWindow", {
get: () => {
throw new DOMException("Blocked a frame with origin", "SecurityError");
},
});
vi.advanceTimersByTime(LIMIT);
return onError;
};
it("names the runtime script and sandbox-origin when a sealed frame never shows a timeline", () => {
const sealedTimeout = timelineNotFound(LIMIT, true);
expect(unreadable(true)).toHaveBeenCalledExactlyOnceWith(sealedTimeout);
expect(sealedTimeout).toContain("without sandbox-origin");
expect(sealedTimeout).toContain("runtime script");
});
it("gives an unsealed player whose composition is on another origin the plain timeout", () => {
expect(unreadable(false)).toHaveBeenCalledExactlyOnceWith(TIMED_OUT);
expect(onError).toHaveBeenCalledExactlyOnceWith(TIMED_OUT);
});
it("does not invent duration for an unresolved document", () => {
const { onReady, onError } = mount('<div data-composition-id="main"></div>');
+88 -6
View File
@@ -44,6 +44,9 @@ import {
// timeline itself respects. Clamping here also shields the native
// HTMLMediaElement.playbackRate setter, which throws for extreme values in
// production browsers.
const capturing = (options?: boolean | EventListenerOptions): boolean =>
typeof options === "boolean" ? options : options?.capture === true;
function parseUrl(src: string): URL | null {
try {
return new URL(src, document.baseURI);
@@ -159,6 +162,8 @@ class HyperframesPlayer extends HTMLElement {
/** The URL a sealed srcdoc was fetched from, so its media resolve as they would by `src`. */
private _srcdocUrl: string | null = null;
private _pageRead = false;
/** A sealed player's fetch answered a page it can't read (opaque, or carrying its own policy). */
private _pageUnreadable = false;
private _readyBeforeRuntime = false;
private _readyDocument: Document | null = null;
private _awaitingLoad = false;
@@ -185,6 +190,12 @@ class HyperframesPlayer extends HTMLElement {
private _compositionWidth = 1920;
private _compositionHeight = 1080;
private _rescaleWarned = false;
private _errorHeard = false;
private readonly _errorStandIns = new WeakMap<
EventListenerOrEventListenerObject,
Map<boolean, EventListener>
>();
private readonly _errorStandInSet = new WeakSet<EventListenerOrEventListenerObject>();
private _directTimelineAdapter: DirectTimelineAdapter | null = null;
private _directTimelineClock: DirectTimelineClock;
private _parentTickRaf: number | null = null;
@@ -249,9 +260,12 @@ class HyperframesPlayer extends HTMLElement {
this.probe = new CompositionProbe(this.iframe, {
resolveRuntimeUrl: () => runtimeSrcFromElement(this),
hostOwnsDeadline: () => this.hasAttribute("no-load-timeout"),
unreadSealedLoad: () => this.hasAttribute(SANDBOX_ORIGIN_ATTR) && !this._pageRead,
// No player adds the runtime to a page it didn't read from another site, or to one its fetch couldn't read; a
// same-site page still being fetched or answering an error gets the plain timeout.
runtimeOutOfReach: () =>
!this._pageRead && (this._filmFromAnotherSite() || this._pageUnreadable),
onReady: (result) => this._onProbeReady(result),
onError: (message) => this._emit(new CustomEvent("error", { detail: { message } })),
onError: (message) => this._emitError({ message }),
});
this.addEventListener("click", (event) => {
@@ -1140,6 +1154,7 @@ class HyperframesPlayer extends HTMLElement {
private _writeFrame(to: FrameTarget): void {
this.probe.frameWritten();
this._pageRead = !("src" in to) || to.read === true;
this._pageUnreadable = false;
if (!("srcdoc" in to)) this.iframe.src = to.src;
else if (to.srcdoc === null) this.iframe.removeAttribute("srcdoc");
else this.iframe.srcdoc = to.srcdoc;
@@ -1168,7 +1183,7 @@ class HyperframesPlayer extends HTMLElement {
() => {
if (load !== this._documentLoad) return;
this.probe.endNavigation();
this._emit(new CustomEvent("error", { detail: { message: SEALED_RUNTIME_LOAD_FAILED } }));
this._emitError({ message: SEALED_RUNTIME_LOAD_FAILED });
},
);
}
@@ -1194,8 +1209,10 @@ class HyperframesPlayer extends HTMLElement {
.then(
(page) => {
if (load !== this._documentLoad) return;
if (page.bySrc) this._writeSrcOverSrcdoc(src, page.read);
else this._showSealedDocument(page.html, page.url, load);
if (page.bySrc) {
this._writeSrcOverSrcdoc(src, page.read);
this._pageUnreadable = !page.read;
} else this._showSealedDocument(page.html, page.url, load);
},
() => {
if (load === this._documentLoad) this._writeSrcOverSrcdoc(src);
@@ -1222,7 +1239,7 @@ class HyperframesPlayer extends HTMLElement {
},
onError: (message, code) => {
if (!this._paused) this.pause();
this._emit(new CustomEvent("error", { detail: { message, code } }));
this._emitError({ message, code });
},
onPlayRejected: (error) => this._onVideoPlayRejected(error),
});
@@ -1752,6 +1769,71 @@ class HyperframesPlayer extends HTMLElement {
this._afterEvents(() => this.dispatchEvent(event));
}
private _emitError(detail: { message: string; code?: number | null }): void {
this._afterEvents(() => {
this._errorHeard = false;
// The DOM calls the onerror handler set when the error dispatches, which may clear itself.
const handler = this.onerror;
this.dispatchEvent(new CustomEvent("error", { detail }));
if (!this._errorHeard && !handler) {
console.warn(`[hyperframes-player] error with no listener: ${detail.message}`);
}
});
}
override addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions,
): void {
super.addEventListener(
type,
type === "error" && listener ? this._heardBy(listener, capturing(options)) : listener,
options,
);
}
override removeEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions,
): void {
super.removeEventListener(
type,
type === "error" && listener ? this._heardBy(listener, capturing(options)) : listener,
options,
);
}
/** The one stand-in the DOM holds for an error listener: it marks the error heard, and leaves once, signal
* and capture to the browser. */
private _heardBy(
listener: EventListenerOrEventListenerObject,
capture: boolean,
): EventListenerOrEventListenerObject {
if (this._errorStandInSet.has(listener)) return listener;
const byCapture = this._errorStandIns.get(listener) ?? new Map<boolean, EventListener>();
this._errorStandIns.set(listener, byCapture);
let standIn = byCapture.get(capture);
if (!standIn) {
standIn = (event: Event) => {
this._errorHeard = true;
if (typeof listener === "function") listener.call(this, event);
else listener.handleEvent(event);
};
byCapture.set(capture, standIn);
this._errorStandInSet.add(standIn);
}
return standIn;
}
/** A composition from another origin than the page's: no player, sealed or not, can add the runtime to it. */
private _filmFromAnotherSite(): boolean {
if (this.hasAttribute("srcdoc")) return false;
const url = parseUrl(this.getAttribute("src") ?? "");
return url !== null && url.origin !== location.origin;
}
private _rescale() {
const applied = scaleIframeToFit(
this,
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { loadLimitMs, timelineNotFound } from "./composition-probe.js";
const LIMIT = loadLimitMs();
const TIMED_OUT = `error ${timelineNotFound(LIMIT, true)}`;
const TIMED_OUT = `error ${timelineNotFound(LIMIT)}`;
type Player = HTMLElement & {
ready: boolean;
@@ -57,7 +57,7 @@ describe("an error a sealed frame's preview records", () => {
const { events, postError } = sealedPlayer();
postError(THROWN, window);
vi.advanceTimersByTime(LIMIT);
expect(events).toEqual([`error ${timelineNotFound(LIMIT, true)}`]);
expect(events).toEqual([`error ${timelineNotFound(LIMIT)}`]);
});
it("ignores an error once the film is ready", () => {
@@ -76,7 +76,7 @@ describe("an error a sealed frame's preview records", () => {
const { events, postError } = sealedPlayer();
postError(message);
vi.advanceTimersByTime(LIMIT);
expect(events).toEqual([`error ${timelineNotFound(LIMIT, true)}`]);
expect(events).toEqual([`error ${timelineNotFound(LIMIT)}`]);
});
it("keeps the first 1000 characters of a longer text, as plain text", () => {
+1 -1
View File
@@ -226,7 +226,7 @@ describe("a sealed player brings its own runtime", () => {
await vi.advanceTimersByTimeAsync(LIMIT - 1);
expect(errors).toEqual([]);
await vi.advanceTimersByTimeAsync(1);
expect(errors).toEqual([timelineNotFound(LIMIT, true)]);
expect(errors).toEqual([timelineNotFound(LIMIT)]);
answer(siteResponse(page()));
await vi.advanceTimersByTimeAsync(0);
@@ -77,7 +77,7 @@ describe("a sealed film whose runtime boots late", () => {
const { player, events, postStatic } = framedPlayer();
postStatic(over);
vi.advanceTimersByTime(LIMIT);
expect(events).toEqual([`error ${timelineNotFound(LIMIT, true)}`]);
expect(events).toEqual([`error ${timelineNotFound(LIMIT)}`]);
expect(player.ready).toBe(false);
});
@@ -85,7 +85,7 @@ describe("a sealed film whose runtime boots late", () => {
const { player, events, postStatic } = framedPlayer();
postStatic({}, window);
vi.advanceTimersByTime(LIMIT);
expect(events).toEqual([`error ${timelineNotFound(LIMIT, true)}`]);
expect(events).toEqual([`error ${timelineNotFound(LIMIT)}`]);
expect(player.ready).toBe(false);
});
+130
View File
@@ -0,0 +1,130 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { loadLimitMs, timelineNotFound } from "./composition-probe.js";
type Player = HTMLElement & { iframeElement: HTMLIFrameElement; _onIframeLoad(): void };
const LIMIT = loadLimitMs();
const PLAIN = timelineNotFound(LIMIT);
const HINTED = timelineNotFound(LIMIT, true);
const unheard = (warn: { mock: { calls: unknown[][] } }) =>
warn.mock.calls.filter(([text]) => String(text).includes("error with no listener")).length;
/** A player whose film's frame can't be read, as a frame from another site, or a sealed one, can't be. */
function load(src: string, { sealed, listen = true }: { sealed: boolean; listen?: boolean }) {
const player = document.createElement("hyperframes-player") as Player;
if (sealed) player.setAttribute("sandbox-origin", "");
player.setAttribute("src", src);
document.body.appendChild(player);
Object.defineProperty(player.iframeElement, "contentDocument", {
value: null,
configurable: true,
});
const errors: string[] = [];
if (listen) {
player.addEventListener("error", (event: Event) =>
errors.push((event as CustomEvent<{ message: string }>).detail.message),
);
}
player._onIframeLoad();
return { player, errors };
}
describe("the timeline timeout", () => {
beforeEach(async () => {
vi.useFakeTimers();
await import("./hyperframes-player.js");
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
document.body.innerHTML = "";
});
// fails without the fix: the error said only that no timeline was found, not that the film must bring the runtime.
it.each([true, false])(
"names the fix for a film from another site, the same sealed or not (sealed: %s)",
(sealed) => {
const { errors } = load("https://films.example/film.html", { sealed });
vi.advanceTimersByTime(LIMIT);
expect(errors).toEqual([HINTED]);
},
);
it.each([true, false])(
"keeps the plain timeout for a film from the page's own site (sealed: %s)",
(sealed) => {
const { errors } = load(`${location.origin}/film.html`, { sealed });
vi.advanceTimersByTime(LIMIT);
expect(errors).toEqual([PLAIN]);
},
);
// fails without the fix: an error nobody listened for left the console silent.
it.each([true, false])(
"warns in the console when nothing listens for the error (sealed: %s)",
(sealed) => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
load("https://films.example/film.html", { sealed, listen: false });
vi.advanceTimersByTime(LIMIT);
// The composition URL can carry a signed query, so the warning names only the error.
expect(warn).toHaveBeenCalledWith(`[hyperframes-player] error with no listener: ${HINTED}`);
},
);
it("warns for the next error once a once-listener has heard one", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { player } = load("https://films.example/film.html", { sealed: true, listen: false });
player.addEventListener("error", () => {}, { once: true });
vi.advanceTimersByTime(LIMIT);
expect(unheard(warn)).toBe(0);
player._onIframeLoad();
vi.advanceTimersByTime(LIMIT);
expect(unheard(warn)).toBe(1);
});
it("keeps a listener added with and without capture until both are removed", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { player } = load("https://films.example/film.html", { sealed: true, listen: false });
const heard = vi.fn();
player.addEventListener("error", heard, true);
player.addEventListener("error", heard);
player.removeEventListener("error", heard);
vi.advanceTimersByTime(LIMIT);
expect(heard).toHaveBeenCalledOnce();
expect(unheard(warn)).toBe(0);
});
it("warns once the signal that added the only listener aborts", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { player } = load("https://films.example/film.html", { sealed: true, listen: false });
const added = new AbortController();
player.addEventListener("error", () => {}, { signal: added.signal });
added.abort();
vi.advanceTimersByTime(LIMIT);
expect(unheard(warn)).toBe(1);
});
it("does not warn when an onerror handler hears the error and clears itself", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { player } = load("https://films.example/film.html", { sealed: true, listen: false });
const handled = vi.fn(() => (player.onerror = null));
player.onerror = handled;
vi.advanceTimersByTime(LIMIT);
expect(handled).toHaveBeenCalledOnce();
expect(unheard(warn)).toBe(0);
});
it.each([
["an error listener", (player: Player) => player.addEventListener("error", () => {})],
["onerror", (player: Player) => (player.onerror = () => {})],
])("does not warn when the page handles the error with %s", (_name, handle) => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { player } = load("https://films.example/film.html", { sealed: true, listen: false });
handle(player);
vi.advanceTimersByTime(LIMIT);
expect(
warn.mock.calls.filter(([text]) => String(text).includes("error with no listener")),
).toEqual([]);
});
});
+130 -30
View File
@@ -3,6 +3,8 @@ import assert from "node:assert/strict";
import { launchBrowser } from "../perf/runner.js";
import { startServer } from "../perf/server.js";
// Linux's 30 s load limit, as on CI, plus slack: every wait for an error that comes at the limit.
const PAST_LOAD_LIMIT_MS = 36_000;
const server = startServer();
const browser = await launchBrowser();
@@ -47,47 +49,145 @@ try {
true,
"removing the policy must reload into the documented trusted mode",
);
// A sealed player adds the runtime to a composition from its own site, so the missing-runtime
// error belongs to one from another origin (localhost against 127.0.0.1).
const direct = await browser.newPage();
await direct.goto(`${server.origin}/host.html?fixture=direct-timeline&sealed=1`, {
waitUntil: "domcontentloaded",
});
await direct.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
await direct.evaluate(
(url) => {
document.querySelector("hyperframes-player")!.setAttribute("src", url);
},
`${server.origin.replace("127.0.0.1", "localhost")}/fixtures/direct-timeline/index.html`,
// fails without the fix: a sealed player told a cross-site film without the runtime more than an unsealed one.
const crossSiteFilm = async (sealed: boolean) => {
const page = await browser.newPage();
await page.goto(
`${server.origin}/host.html?fixture=direct-timeline${sealed ? "&sealed=1" : ""}`,
{
waitUntil: "domcontentloaded",
},
);
await page.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
await page.evaluate(
(url) => {
const player = document.querySelector("hyperframes-player")!;
const events: string[] = [];
(window as { __events?: string[] }).__events = events;
for (const type of ["ready", "error", "durationchange", "play"])
player.addEventListener(type, () => events.push(type));
window.__playerError = undefined;
player.setAttribute("src", url);
},
`${server.origin.replace("127.0.0.1", "localhost")}/fixtures/direct-timeline/index.html`,
);
await page.waitForFunction(() => window.__playerError !== undefined, {
timeout: PAST_LOAD_LIMIT_MS,
});
return page.evaluate(() => ({
error: String(window.__playerError),
events: (window as { __events?: string[] }).__events,
}));
};
const sealedCrossSite = await crossSiteFilm(true);
const openCrossSite = await crossSiteFilm(false);
assert.deepEqual(
sealedCrossSite,
openCrossSite,
"a cross-site film without the runtime fails sealed exactly as unsealed",
);
// Linux's 30 s load limit, as on CI, plus slack.
await direct.waitForFunction(() => window.__playerError !== undefined, { timeout: 36_000 });
const sealedError = String(await direct.evaluate(() => window.__playerError));
assert.match(
sealedError,
/include the runtime script/,
"a sealed timeout must name the runtime script",
openCrossSite.error,
/^Composition timeline not found after \d+s\. A player can't add the HyperFrames runtime to a composition from another site: include the runtime script in it\.$/,
);
assert.match(sealedError, /without sandbox-origin/, "a sealed timeout must name the trusted way");
const elsewhere = await browser.newPage();
await elsewhere.goto(`${server.origin}/host.html?fixture=direct-timeline`, {
// fails without the fix: Chrome drops a once or aborted listener without calling removeEventListener, so the
// player kept counting it and the next unheard error reached no one.
const listenerPage = await browser.newPage();
const unheard: string[] = [];
listenerPage.on("console", (message) => {
if (message.text().includes("error with no listener")) unheard.push(message.text());
});
await listenerPage.goto(`${server.origin}/host.html?fixture=direct-timeline&sealed=1`, {
waitUntil: "domcontentloaded",
});
await elsewhere.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
await elsewhere.evaluate(
await listenerPage.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
await listenerPage.evaluate(
(url) => {
document.querySelector("hyperframes-player")!.setAttribute("src", url);
const heard: string[] = [];
Object.assign(window, { __heard: heard });
const once = document.createElement("hyperframes-player");
once.setAttribute("sandbox-origin", "");
once.addEventListener("error", () => heard.push("once"), { once: true });
once.setAttribute("src", url);
document.body.appendChild(once);
const aborted = document.createElement("hyperframes-player");
aborted.setAttribute("sandbox-origin", "");
const added = new AbortController();
aborted.addEventListener("error", () => heard.push("aborted"), { signal: added.signal });
added.abort();
aborted.setAttribute("src", url);
document.body.appendChild(aborted);
// A once-listener that installs the next one while the first error dispatches: the second error is heard.
const replaced = document.createElement("hyperframes-player");
replaced.setAttribute("sandbox-origin", "");
replaced.addEventListener(
"error",
() => {
heard.push("first");
replaced.addEventListener("error", () => heard.push("second"), { once: true });
},
{ once: true },
);
replaced.setAttribute("src", url);
document.body.appendChild(replaced);
// A callback removed and added again, then the first registration's signal aborts. Engines differ on whether
// that drops the new registration; either way the error reaches it or warns.
const readded = document.createElement("hyperframes-player");
readded.setAttribute("sandbox-origin", "");
const first = new AbortController();
const listen = () => heard.push("readded");
readded.addEventListener("error", listen, { signal: first.signal });
readded.removeEventListener("error", listen);
readded.addEventListener("error", listen);
first.abort();
readded.setAttribute("src", url);
document.body.appendChild(readded);
Object.assign(window, {
__again: () => {
once.setAttribute("src", `${url}?again`);
replaced.setAttribute("src", `${url}?again`);
},
});
},
`${server.origin.replace("127.0.0.1", "localhost")}/fixtures/direct-timeline/index.html`,
);
// Linux's 30 s load limit, as on CI, plus slack.
await elsewhere.waitForFunction(() => window.__playerError !== undefined, { timeout: 36_000 });
assert.doesNotMatch(
String(await elsewhere.evaluate(() => window.__playerError)),
/sandbox-origin/,
"a default player with a composition on another origin is not told it is sealed",
const heardAll = (...names: string[]) =>
listenerPage
.waitForFunction(
(wanted: string[]) =>
wanted.every((name) => (window as { __heard?: string[] }).__heard?.includes(name)),
{ timeout: PAST_LOAD_LIMIT_MS },
names,
)
.catch(async (error: unknown) => {
const heard = await listenerPage.evaluate(() => (window as { __heard?: string[] }).__heard);
throw new Error(
`waited for ${names.join(", ")}; heard ${JSON.stringify(heard)}, warned ${unheard.length}`,
{
cause: error,
},
);
});
await heardAll("once", "first");
await listenerPage.evaluate(() => (window as { __again?: () => void }).__again?.());
await heardAll("second");
for (let waited = 0; unheard.length < 2 && waited < 15_000; waited += 250)
await new Promise((resolve) => setTimeout(resolve, 250));
await new Promise((resolve) => setTimeout(resolve, 1500));
const heard =
(await listenerPage.evaluate(() => (window as { __heard?: string[] }).__heard)) ?? [];
assert.equal(
unheard.length,
heard.includes("readded") ? 2 : 3,
"every error either reached a listener or warned, never both",
);
assert.deepEqual(heard.filter((name) => name !== "readded").sort(), ["first", "once", "second"]);
assert.ok(
unheard.every((text) => !text.includes("index.html")),
"the warning carries no composition URL",
);
await listenerPage.close();
const trusted = await browser.newPage();
await trusted.goto(`${server.origin}/host.html?fixture=direct-timeline`, {