From 3f67e0b74a28350f0896f5b2ede7d90f7c269e18 Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 00:03:48 +0200 Subject: [PATCH 1/4] feat(v2): open the EmulatorJS and js-dos launch views without a page load Play navigated to the EmulatorJS and js-dos launch views with a full document load, because only a directly loaded player URL carries the COOP/COEP headers nginx attaches to it, and only a cross-origin isolated document exposes the SharedArrayBuffer that threaded cores need. Every launch paid that reload, while only three cores (dosbox_pure, ppsspp, azahar) need threads, and js-dos 8.4.1 does not reference SharedArrayBuffer at all. Both views are now reached by SPA navigation with the cover morph, like the PICO-8 and Ruffle views. When a threaded core is booted without SharedArrayBuffer, useIsolatedLaunch keeps the pre-play selection in sessionStorage and reloads the view into the isolated document, where it boots straight away; a second miss reports the insecure context instead of looping. Adding a threaded core is one entry in areThreadsRequiredForEJSCore; another player that needs isolation uses the same composable. Leaving a player view is a full navigation whenever the document is isolated, since the rest of the app cannot embed third-party images under that policy (provider covers in Match ROM, see #4522), and whenever the EmulatorJS runtime was injected, which declares globals a second injection would clash with. usePlayerExit holds that rule for both views; js-dos also injects its runtime once per document. EmulatorJS closes the play session on pagehide as well, since the full navigation unmounts nothing. The Vite dev server mirrors the nginx header map for the player URLs. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01R1VFUvsR5wYK3axxR1gebc --- docs/FRONTEND_ARCHITECTURE.md | 11 ++ frontend/src/utils/index.ts | 4 +- .../components/GameActions/GameActionBtn.vue | 3 +- .../composables/useGameActions/index.test.ts | 55 ++------- .../v2/composables/useGameActions/index.ts | 32 ++---- .../useIsolatedLaunch/index.test.ts | 108 ++++++++++++++++++ .../v2/composables/useIsolatedLaunch/index.ts | 70 ++++++++++++ .../composables/usePlayerExit/index.test.ts | 105 +++++++++++++++++ .../src/v2/composables/usePlayerExit/index.ts | 49 ++++++++ frontend/src/v2/views/Player/EmulatorJS.vue | 102 ++++++++++++++--- frontend/src/v2/views/Player/JsDos.test.ts | 79 +++++++++++-- frontend/src/v2/views/Player/JsDos.vue | 11 +- .../src/v2/views/Player/launchIntent.test.ts | 39 +++++++ frontend/src/v2/views/Player/launchIntent.ts | 33 ++++++ frontend/vite.config.js | 22 ++++ 15 files changed, 620 insertions(+), 103 deletions(-) create mode 100644 frontend/src/v2/composables/useIsolatedLaunch/index.test.ts create mode 100644 frontend/src/v2/composables/useIsolatedLaunch/index.ts create mode 100644 frontend/src/v2/composables/usePlayerExit/index.test.ts create mode 100644 frontend/src/v2/composables/usePlayerExit/index.ts create mode 100644 frontend/src/v2/views/Player/launchIntent.test.ts create mode 100644 frontend/src/v2/views/Player/launchIntent.ts diff --git a/docs/FRONTEND_ARCHITECTURE.md b/docs/FRONTEND_ARCHITECTURE.md index 0ec63a741..c72588ad2 100644 --- a/docs/FRONTEND_ARCHITECTURE.md +++ b/docs/FRONTEND_ARCHITECTURE.md @@ -862,6 +862,17 @@ All synthesized with sine/noise blend, exponential envelopes, low-pass filter, a - Fullscreen support - Background color customization +### Cross-origin isolation (v2 players) + +Threaded EmulatorJS cores need `SharedArrayBuffer`, which browsers expose only in a cross-origin isolated document. Nginx attaches `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` to the player URLs alone (`docker/nginx/templates/default.conf.template`), because under that policy the rest of the app cannot embed third-party images (provider covers in Match ROM). + +A v2 player view is reached by SPA navigation, so it is not isolated on arrival. Two composables cover that: + +- `useIsolatedLaunch(player, romId, isIntent)` reloads the view into an isolated document when a launch needs it. The view defines the `Intent` the reload cannot carry in the URL, calls `relaunch(intent)` when `hasSharedArrayBuffer()` is false, and boots from `intent` on mount. `relaunch()` returns false when the view already came from such a reload: the context cannot be isolated (plain HTTP, or a proxy dropping the headers), so the view reports that instead of looping. +- `usePlayerExit(runtimeBound)` leaves the view by a full navigation when the document is isolated, or when the player's runtime cannot be injected twice (EmulatorJS declares globals), so the app resumes in a fresh document. Otherwise leaving is an SPA navigation. + +To add an EmulatorJS core that needs threads, add it to `areThreadsRequiredForEJSCore` in `utils/index.ts`; nothing else changes. To add a player that needs isolation, use both composables the way `v2/views/Player/EmulatorJS.vue` does. A player whose runtime needs no `SharedArrayBuffer` (js-dos) only needs `usePlayerExit()`. + ### Platform Detection `utils/index.ts` provides: diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts index 68aae2e08..60ec7c5ee 100644 --- a/frontend/src/utils/index.ts +++ b/frontend/src/utils/index.ts @@ -602,7 +602,9 @@ export function getSupportedEJSCores( } /** - * Check if a given EJS core requires threads enabled. + * Whether an EJS core ships only as a threaded build; a core added here gets + * the cross-origin isolated document it needs from the v2 launch view (see + * `useIsolatedLaunch`). * * @param core The core name. * @returns True if threads are required, false otherwise. diff --git a/frontend/src/v2/components/GameActions/GameActionBtn.vue b/frontend/src/v2/components/GameActions/GameActionBtn.vue index 2c1cad02e..4ab721c7a 100644 --- a/frontend/src/v2/components/GameActions/GameActionBtn.vue +++ b/frontend/src/v2/components/GameActions/GameActionBtn.vue @@ -354,7 +354,8 @@ function clearAllStatus() { } // Modified and non-primary clicks on a launch anchor stay with the browser -// (new tab); plain ones still go through `play()` for its full-document load. +// (new tab); plain ones still go through `play()` for its confirmation and +// cover morph. function onClick(e: MouseEvent) { if (props.action === "more" || props.action === "status") return; if (linkHref.value && (e.button !== 0 || opensInNewContext(e))) return; diff --git a/frontend/src/v2/composables/useGameActions/index.test.ts b/frontend/src/v2/composables/useGameActions/index.test.ts index bb8c69caa..89decddb2 100644 --- a/frontend/src/v2/composables/useGameActions/index.test.ts +++ b/frontend/src/v2/composables/useGameActions/index.test.ts @@ -1,19 +1,10 @@ -import { - afterAll, - beforeAll, - beforeEach, - describe, - expect, - it, - vi, -} from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import type { ActionKey } from "@/__generated__"; import type { SimpleRom } from "@/stores/roms"; import { useGameActions } from "./index"; // Controllable stubs shared with the mocked modules below. const push = vi.fn(); -const locationAssign = vi.fn(); const confirmFn = vi.fn(); const startScan = vi.fn(() => true); const snackbarInfo = vi.fn(); @@ -26,7 +17,6 @@ const streamContainer = { value: null as object | null }; const joinableSession = { value: null as { host_username: string | null } | null, }; -let originalLocation: Location; // Granted action keys — `null` means "everything" (the default). const grantedActions: { value: Set | null } = { value: null }; @@ -134,24 +124,8 @@ function makeRom(status: SimpleRom["rom_user"]["status"] = null): SimpleRom { } as unknown as SimpleRom; } -beforeAll(() => { - originalLocation = window.location; - Object.defineProperty(window, "location", { - configurable: true, - value: { ...originalLocation, assign: locationAssign }, - }); -}); - -afterAll(() => { - Object.defineProperty(window, "location", { - configurable: true, - value: originalLocation, - }); -}); - beforeEach(() => { push.mockClear(); - locationAssign.mockClear(); confirmFn.mockClear(); startScan.mockClear(); snackbarInfo.mockClear(); @@ -259,8 +233,7 @@ describe("useGameActions.play — launch confirmation", () => { const actions = useGameActions(() => makeRom(null)); await actions.play(); expect(confirmFn).not.toHaveBeenCalled(); - expect(locationAssign).toHaveBeenCalledWith("/rom/1/ejs"); - expect(push).not.toHaveBeenCalled(); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); }); it.each(["retired", "never_playing"] as const)( @@ -270,7 +243,6 @@ describe("useGameActions.play — launch confirmation", () => { const actions = useGameActions(() => makeRom(status)); await actions.play(); expect(confirmFn).toHaveBeenCalledTimes(1); - expect(locationAssign).not.toHaveBeenCalled(); expect(push).not.toHaveBeenCalled(); }, ); @@ -280,8 +252,7 @@ describe("useGameActions.play — launch confirmation", () => { const actions = useGameActions(() => makeRom("retired")); await actions.play(); expect(confirmFn).toHaveBeenCalledTimes(1); - expect(locationAssign).toHaveBeenCalledWith("/rom/1/ejs"); - expect(push).not.toHaveBeenCalled(); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); }); it("skips the prompt when the preference is disabled", async () => { @@ -289,8 +260,7 @@ describe("useGameActions.play — launch confirmation", () => { const actions = useGameActions(() => makeRom("never_playing")); await actions.play(); expect(confirmFn).not.toHaveBeenCalled(); - expect(locationAssign).toHaveBeenCalledWith("/rom/1/ejs"); - expect(push).not.toHaveBeenCalled(); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); }); it("prefers streaming over EmulatorJS", async () => { @@ -300,7 +270,6 @@ describe("useGameActions.play — launch confirmation", () => { await actions.play(); expect(push).toHaveBeenCalledWith("/rom/1/stream"); - expect(locationAssign).not.toHaveBeenCalled(); }); it("goes to EmulatorJS when asked for the local player, stream or not", async () => { @@ -311,8 +280,7 @@ describe("useGameActions.play — launch confirmation", () => { await actions.play("local"); - expect(locationAssign).toHaveBeenCalledWith("/rom/1/ejs"); - expect(push).not.toHaveBeenCalled(); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); }); it("goes to the stream when asked for it", async () => { @@ -322,7 +290,6 @@ describe("useGameActions.play — launch confirmation", () => { await actions.play("stream"); expect(push).toHaveBeenCalledWith("/rom/1/stream"); - expect(locationAssign).not.toHaveBeenCalled(); }); it("launches nothing when the asked-for player cannot run it", async () => { @@ -331,7 +298,6 @@ describe("useGameActions.play — launch confirmation", () => { await actions.play("stream"); expect(push).not.toHaveBeenCalled(); - expect(locationAssign).not.toHaveBeenCalled(); }); it("still confirms a shelved game whichever player is asked for", async () => { @@ -345,7 +311,7 @@ describe("useGameActions.play — launch confirmation", () => { expect(push).not.toHaveBeenCalled(); }); - it("keeps SPA navigation for Ruffle", async () => { + it("goes to Ruffle for a Flash rom", async () => { canPlayEJS.value = false; canPlayRuffle.value = true; const actions = useGameActions(() => makeRom()); @@ -353,10 +319,9 @@ describe("useGameActions.play — launch confirmation", () => { await actions.play(); expect(push).toHaveBeenCalledWith("/rom/1/ruffle"); - expect(locationAssign).not.toHaveBeenCalled(); }); - it("keeps SPA navigation for PICO-8", async () => { + it("goes to PICO-8 for a cartridge", async () => { canPlayEJS.value = false; canPlayPico8.value = true; const actions = useGameActions(() => makeRom()); @@ -364,17 +329,15 @@ describe("useGameActions.play — launch confirmation", () => { await actions.play(); expect(push).toHaveBeenCalledWith("/rom/1/pico8"); - expect(locationAssign).not.toHaveBeenCalled(); }); - it("full-loads js-dos ahead of EmulatorJS for its platforms", async () => { + it("prefers js-dos over EmulatorJS for its platforms", async () => { canPlayJsDos.value = true; const actions = useGameActions(() => makeRom()); await actions.play(); - expect(locationAssign).toHaveBeenCalledWith("/rom/1/jsdos"); - expect(push).not.toHaveBeenCalled(); + expect(push).toHaveBeenCalledWith("/rom/1/jsdos"); }); it("offers neither streaming nor download without a file behind the rom", () => { diff --git a/frontend/src/v2/composables/useGameActions/index.ts b/frontend/src/v2/composables/useGameActions/index.ts index ff4575c56..ee751d860 100644 --- a/frontend/src/v2/composables/useGameActions/index.ts +++ b/frontend/src/v2/composables/useGameActions/index.ts @@ -49,11 +49,6 @@ export type PlayTarget = "auto" | "local" | "stream"; type PlayerSlug = "stream" | "jsdos" | "ejs" | "pico8" | "ruffle"; -// EmulatorJS and js-dos need SharedArrayBuffer. Nginx only attaches the -// necessary COOP/COEP headers to the player document, so an SPA navigation -// cannot enable cross-origin isolation: these load the document directly. -const ISOLATED_PLAYERS: ReadonlySet = new Set(["jsdos", "ejs"]); - // Validate flashpoint game IDs are UUIDs const FLASHPOINT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -327,25 +322,20 @@ export function useGameActions( if (!ok) return; } - const launch = launchTarget(player); - if (!launch) return; - const target = launch.path; - if (ISOLATED_PLAYERS.has(launch.player)) { - window.location.assign(target); - return; - } + const target = playPath(player); + if (!target) return; // The launch "load" flourish (disc/cartridge insert) lives on the - // player view itself — see EmulatorJS's onPlay — so navigation is + // player view itself (see EmulatorJS's onPlay), so navigation is // immediate here. When the caller supplies a cover element (the gallery - // card / detail hero), morph it into the player's hero cover — same + // card / detail hero), morph it into the player's hero cover: the same // `rom-cover-` tag the player paints statically. Degrades to a plain // push where view transitions aren't available. const el = options.coverEl?.(); if (el) { // Await the push inside the transition so the browser snapshots the // player view *after* it has rendered its hero cover (which carries the - // same `rom-cover-` tag) — otherwise there's no element to morph to. + // same `rom-cover-` tag); otherwise there's no element to morph to. morphTransition({ el, name: `rom-cover-${rom.id}` }, async () => { await router.push(target); }); @@ -359,9 +349,8 @@ export function useGameActions( // container's own emulator and save library). The caller says which it // wants; "auto" keeps the single-button surfaces working by preferring // the stream, as they did before either could be asked for by name. - function launchTarget( - player: PlayTarget, - ): { player: PlayerSlug; path: string } | null { + /** Path `play(player)` opens; surfaces rendering the launch as a link point at it too. */ + function playPath(player: PlayTarget = "auto"): string | null { const rom = getRom(); if (!rom) return null; let slug: PlayerSlug | null = null; @@ -371,12 +360,7 @@ export function useGameActions( else if (canPlayEJS.value) slug = "ejs"; else if (canPlayPico8.value) slug = "pico8"; else if (canPlayRuffle.value) slug = "ruffle"; - return slug ? { player: slug, path: `/rom/${rom.id}/${slug}` } : null; - } - - /** Path `play(player)` would open, for surfaces that render the launch as a link. */ - function playPath(player: PlayTarget = "auto"): string | null { - return launchTarget(player)?.path ?? null; + return slug ? `/rom/${rom.id}/${slug}` : null; } // Joining is its own navigation: the stream view claims a container when it diff --git a/frontend/src/v2/composables/useIsolatedLaunch/index.test.ts b/frontend/src/v2/composables/useIsolatedLaunch/index.test.ts new file mode 100644 index 000000000..7ced43520 --- /dev/null +++ b/frontend/src/v2/composables/useIsolatedLaunch/index.test.ts @@ -0,0 +1,108 @@ +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { useIsolatedLaunch } from "./index"; + +interface Intent { + saveId: number | null; +} + +function isIntent(value: unknown): value is Intent { + return ( + typeof value === "object" && + value !== null && + "saveId" in value && + (value.saveId === null || typeof value.saveId === "number") + ); +} + +const KEY = "player:7:ejs:launch"; +const reload = vi.fn(); +let originalLocation: Location; + +beforeAll(() => { + originalLocation = window.location; + Object.defineProperty(window, "location", { + configurable: true, + value: { ...originalLocation, reload }, + }); +}); + +afterAll(() => { + Object.defineProperty(window, "location", { + configurable: true, + value: originalLocation, + }); +}); + +beforeEach(() => { + reload.mockClear(); + sessionStorage.clear(); +}); + +describe("useIsolatedLaunch", () => { + it("opens without an intent", () => { + const launch = useIsolatedLaunch("ejs", 7, isIntent); + + expect(launch.intent).toBeNull(); + expect(launch.relaunching.value).toBe(false); + }); + + it("keeps the intent and reloads the document", () => { + const launch = useIsolatedLaunch("ejs", 7, isIntent); + + expect(launch.relaunch({ saveId: 3 })).toBe(true); + + expect(launch.relaunching.value).toBe(true); + expect(reload).toHaveBeenCalledOnce(); + expect(sessionStorage.getItem(KEY)).toBe('{"saveId":3}'); + }); + + it("hands the intent to the reloaded view once", () => { + useIsolatedLaunch("ejs", 7, isIntent).relaunch({ saveId: 3 }); + + expect(useIsolatedLaunch("ejs", 7, isIntent).intent).toEqual({ + saveId: 3, + }); + expect(useIsolatedLaunch("ejs", 7, isIntent).intent).toBeNull(); + }); + + // A second reload could not isolate the document either, so the view is + // told to report the context instead of looping. + it("refuses to reload again from the reloaded view", () => { + useIsolatedLaunch("ejs", 7, isIntent).relaunch({ saveId: 3 }); + reload.mockClear(); + const reloaded = useIsolatedLaunch("ejs", 7, isIntent); + + expect(reloaded.relaunch({ saveId: 4 })).toBe(false); + + expect(reload).not.toHaveBeenCalled(); + expect(reloaded.relaunching.value).toBe(false); + }); + + it("keeps players and games apart", () => { + useIsolatedLaunch("ejs", 7, isIntent).relaunch({ saveId: 3 }); + + expect(useIsolatedLaunch("jsdos", 7, isIntent).intent).toBeNull(); + expect(useIsolatedLaunch("ejs", 8, isIntent).intent).toBeNull(); + expect(useIsolatedLaunch("ejs", 7, isIntent).intent).toEqual({ + saveId: 3, + }); + }); + + it.each([ + ["not JSON", "{"], + ["another shape", JSON.stringify({ core: "snes9x" })], + ])("drops a stored value that is %s", (_label, raw) => { + sessionStorage.setItem(KEY, raw); + + expect(useIsolatedLaunch("ejs", 7, isIntent).intent).toBeNull(); + expect(sessionStorage.getItem(KEY)).toBeNull(); + }); +}); diff --git a/frontend/src/v2/composables/useIsolatedLaunch/index.ts b/frontend/src/v2/composables/useIsolatedLaunch/index.ts new file mode 100644 index 000000000..dd993498d --- /dev/null +++ b/frontend/src/v2/composables/useIsolatedLaunch/index.ts @@ -0,0 +1,70 @@ +// useIsolatedLaunch: reloading a player view into a cross-origin isolated +// document. +// +// A runtime that needs SharedArrayBuffer only gets it in a cross-origin +// isolated document, and a view reached by SPA navigation is not one. Nginx +// attaches the COOP/COEP headers to the player URLs, so reloading the view is +// what isolates it. What the user had set up crosses the reload as an intent +// kept per tab, and the view boots from it on arrival. +// +// Usage, in a player whose runtime (or one of its cores) needs it: +// const { intent, relaunching, relaunch } = +// useIsolatedLaunch("myplayer", romId, isMyIntent); +// on Play: if (!hasSharedArrayBuffer()) { +// if (!relaunch(currentIntent())) reportInsecureContext(); +// return; +// } +// on mount: if (intent) { apply(intent); boot(); } +// Pair it with usePlayerExit, which drops the isolation again on the way out. +import { ref, type Ref } from "vue"; + +export function hasSharedArrayBuffer(): boolean { + return typeof window.SharedArrayBuffer === "function"; +} + +export function useIsolatedLaunch( + player: string, + romId: number, + isIntent: (value: unknown) => value is Intent, +): { + /** What the view stored before reloading, or null when it opened normally. */ + intent: Intent | null; + /** True once a reload is under way, so the Play control stays busy. */ + relaunching: Ref; + /** + * Keep `intent` and reload into the isolated document. False when this view + * already came from such a reload: the context cannot be isolated (plain + * HTTP, or a proxy dropping the headers), so the caller reports it instead. + */ + relaunch: (intent: Intent) => boolean; +} { + const key = `player:${romId}:${player}:launch`; + const intent = takeIntent(key, isIntent); + const relaunching = ref(false); + + function relaunch(next: Intent): boolean { + if (intent !== null) return false; + relaunching.value = true; + sessionStorage.setItem(key, JSON.stringify(next)); + window.location.reload(); + return true; + } + + return { intent, relaunching, relaunch }; +} + +/** The intent under `key`, cleared on read so it boots only once. */ +function takeIntent( + key: string, + isIntent: (value: unknown) => value is Intent, +): Intent | null { + const raw = sessionStorage.getItem(key); + if (raw === null) return null; + sessionStorage.removeItem(key); + try { + const parsed: unknown = JSON.parse(raw); + return isIntent(parsed) ? parsed : null; + } catch { + return null; + } +} diff --git a/frontend/src/v2/composables/usePlayerExit/index.test.ts b/frontend/src/v2/composables/usePlayerExit/index.test.ts new file mode 100644 index 000000000..d11abf8d8 --- /dev/null +++ b/frontend/src/v2/composables/usePlayerExit/index.test.ts @@ -0,0 +1,105 @@ +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from "vitest"; +import { usePlayerExit } from "./index"; + +const push = vi.fn(() => Promise.resolve()); +const locationReplace = vi.fn(); +let originalLocation: Location; + +vi.mock("vue-router", () => ({ + useRouter: () => ({ push }), +})); + +function setIsolated(isolated: boolean) { + Object.defineProperty(window, "crossOriginIsolated", { + configurable: true, + value: isolated, + }); +} + +beforeAll(() => { + originalLocation = window.location; + Object.defineProperty(window, "location", { + configurable: true, + value: { ...originalLocation, replace: locationReplace }, + }); +}); + +afterAll(() => { + Object.defineProperty(window, "location", { + configurable: true, + value: originalLocation, + }); +}); + +afterEach(() => { + push.mockClear(); + locationReplace.mockClear(); + setIsolated(false); +}); + +describe("usePlayerExit", () => { + it("leaves within the app when nothing binds the document", () => { + const exit = usePlayerExit(); + + exit.leave("/rom/1"); + + expect(push).toHaveBeenCalledWith("/rom/1"); + expect(locationReplace).not.toHaveBeenCalled(); + }); + + it("replaces the document when it is cross-origin isolated", () => { + setIsolated(true); + const exit = usePlayerExit(); + + exit.leave("/rom/1"); + + expect(locationReplace).toHaveBeenCalledWith("/rom/1"); + expect(push).not.toHaveBeenCalled(); + }); + + it("replaces the document once a runtime is bound to it", () => { + const exit = usePlayerExit(() => true); + + exit.leave("/rom/1"); + + expect(locationReplace).toHaveBeenCalledWith("/rom/1"); + expect(push).not.toHaveBeenCalled(); + }); + + it("lets a route departure through when nothing binds the document", () => { + const exit = usePlayerExit(); + + expect(exit.guard({ fullPath: "/platform/2" })).toBe(true); + expect(locationReplace).not.toHaveBeenCalled(); + }); + + it("turns a route departure into a full navigation when bound", () => { + setIsolated(true); + const exit = usePlayerExit(); + + expect(exit.guard({ fullPath: "/platform/2" })).toBe(false); + expect(locationReplace).toHaveBeenCalledWith("/platform/2"); + }); + + it("lets its own departure through", async () => { + let bound = false; + const exit = usePlayerExit(() => bound); + + exit.leave("/rom/1"); + // The runtime cannot bind between leave() and the guard, but a guard that + // re-checked the document would otherwise still be able to block the push. + bound = true; + expect(exit.guard({ fullPath: "/rom/1" })).toBe(true); + + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(exit.guard({ fullPath: "/rom/1" })).toBe(false); + }); +}); diff --git a/frontend/src/v2/composables/usePlayerExit/index.ts b/frontend/src/v2/composables/usePlayerExit/index.ts new file mode 100644 index 000000000..f346db57b --- /dev/null +++ b/frontend/src/v2/composables/usePlayerExit/index.ts @@ -0,0 +1,49 @@ +// usePlayerExit: how a player view hands the tab back to the app. +// +// Two things can bind a player to its document. A player URL opened directly +// carries the COOP/COEP headers nginx attaches to it, and the resulting +// cross-origin isolation outlives every SPA navigation after it, blocking the +// third-party images the app embeds elsewhere (provider covers in Match ROM). +// And a runtime that declares globals when injected (EmulatorJS) cannot be +// injected a second time. Either way the exit is a full navigation, so the +// app resumes in a fresh document; otherwise it is an SPA navigation. +import { useRouter, type RouteLocationNormalized } from "vue-router"; + +export function usePlayerExit( + /** True once the view injected a runtime the document cannot take twice. */ + runtimeBound: () => boolean = () => false, +): { + /** Whether leaving has to replace the document. */ + documentBound: () => boolean; + /** Go to `path`, by a full navigation when the document is bound. */ + leave: (path: string) => void; + /** `onBeforeRouteLeave` guard: lets a departure through unless bound. */ + guard: (to: Pick) => boolean; +} { + const router = useRouter(); + // Set by leave() so the guard lets its own push through. + let leaving = false; + + function documentBound(): boolean { + return window.crossOriginIsolated || runtimeBound(); + } + + function leave(path: string): void { + if (documentBound()) { + window.location.replace(path); + return; + } + leaving = true; + void router.push(path).finally(() => { + leaving = false; + }); + } + + function guard(to: Pick): boolean { + if (leaving || !documentBound()) return true; + window.location.replace(to.fullPath); + return false; + } + + return { documentBound, leave, guard }; +} diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index d2ff1dda3..f70857329 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -39,6 +39,7 @@ import { watch, } from "vue"; import { useI18n } from "vue-i18n"; +import { onBeforeRouteLeave } from "vue-router"; import type { FirmwareSchema, SaveSchema, StateSchema } from "@/__generated__"; import firmwareApi from "@/services/api/firmware"; import romApi from "@/services/api/rom"; @@ -61,7 +62,12 @@ import { useCoverArt } from "@/v2/composables/useCoverArt"; import { useFullscreenFallback } from "@/v2/composables/useFullscreenFallback"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; import { useInputModality } from "@/v2/composables/useInputModality"; +import { + hasSharedArrayBuffer, + useIsolatedLaunch, +} from "@/v2/composables/useIsolatedLaunch"; import { usePlaySession } from "@/v2/composables/usePlaySession"; +import { usePlayerExit } from "@/v2/composables/usePlayerExit"; import { usePlayerHero } from "@/v2/composables/usePlayerHero"; import { usePlayerNav } from "@/v2/composables/usePlayerNav"; import { useSnackbar } from "@/v2/composables/useSnackbar"; @@ -98,6 +104,7 @@ import { } from "@/v2/utils/saveSlots"; import { isJsResource, loadScript } from "@/v2/utils/scriptLoader"; import { rememberCore, resolveRememberedCore } from "./coreStorage"; +import { isLaunchIntent, type LaunchIntent } from "./launchIntent"; import { defaultResumeSelection, newerThanPick, @@ -147,10 +154,30 @@ const selectedCore = ref(null); const selectedFirmware = ref(null); const supportedCores = ref([]); const gameRunning = ref(false); +// A route departure while a game runs is deliberate, so the reload prompt +// stays quiet for the full navigation it turns into. +const departing = ref(false); +// Threaded cores need SharedArrayBuffer, so their launch may first have to +// reload the view into a cross-origin isolated document. +const { + intent: storedIntent, + relaunching, + relaunch: relaunchIsolated, +} = useIsolatedLaunch("ejs", romId, isLaunchIntent); -useUnloadGuard(gameRunning); +useUnloadGuard(() => gameRunning.value && !departing.value); useStageActive(gameRunning); +// The EmulatorJS loader declares globals and instantiates the emulator when +// injected, so a document that ran a game cannot host another launch. +const exit = usePlayerExit(() => window.EJS_emulator !== undefined); +onBeforeRouteLeave((to) => { + if (!exit.documentBound()) return true; + departing.value = true; + exit.leave(to.fullPath); + return false; +}); + // Stage-scoped so the non-passive listener never taxes touches elsewhere. const stageRef = ref(null); useEventListener(stageRef, "touchstart", suppressVirtualGamepadZoneTouch, { @@ -159,6 +186,15 @@ useEventListener(stageRef, "touchstart", suppressVirtualGamepadZoneTouch, { const presence = useActivityPresence(() => rom.value?.id); +function endSession() { + playSession.flush(); + presence.stopHeartbeat(); + presence.emitStop(); +} +// A full navigation out of the view unmounts nothing, so the session also +// closes on pagehide; flush() is idempotent, so no path records it twice. +useEventListener(window, "pagehide", endSession); + declare global { interface Navigator { keyboard: { @@ -235,14 +271,22 @@ useEventListener(document, "fullscreenchange", () => { }); async function onPlay() { - // Threaded cores need SharedArrayBuffer, which browsers only expose on a - // secure context (HTTPS or localhost), whatever headers the server sends. + if (rom.value) { + rememberCore(romId, rom.value.platform_slug, selectedCore.value); + rememberDisc(romId, selectedDisc.value); + } + + // Threaded cores need SharedArrayBuffer, which only a cross-origin isolated + // secure context exposes. A relaunch that still lacks it means the context + // itself is not secure. if ( selectedCore.value && areThreadsRequiredForEJSCore(selectedCore.value) && - typeof window.SharedArrayBuffer !== "function" + !hasSharedArrayBuffer() ) { - snackbar.error(t("play.https-required")); + if (!relaunchIsolated(currentIntent())) { + snackbar.error(t("play.https-required")); + } return; } @@ -254,10 +298,6 @@ async function onPlay() { await new Promise((resolve) => setTimeout(resolve, insertMs)); } - if (rom.value) { - rememberCore(rom.value.id, rom.value.platform_slug, selectedCore.value); - rememberDisc(rom.value.id, selectedDisc.value); - } gameRunning.value = true; window.EJS_fullscreenOnLoaded = fullscreenOnPlay.value; playing.value = true; @@ -292,6 +332,31 @@ async function onPlay() { } } +// What the reload cannot carry in the URL; the core and the disc are already +// remembered per game. +function currentIntent(): LaunchIntent { + return { + saveId: resume.value.save?.id ?? null, + stateId: resume.value.state?.id ?? null, + firmwareId: selectedFirmware.value?.id ?? null, + slot: slotChoice.value, + customSlot: customSlot.value, + }; +} + +// What the view had selected before the reload, re-applied over the defaults. +function applyLaunchIntent(intent: LaunchIntent, current: DetailedRom) { + const save = current.user_saves.find((s) => s.id === intent.saveId) ?? null; + const state = + compatibleStates.value.find((s) => s.id === intent.stateId) ?? null; + resume.value = { save, state }; + isSavesTabSelected.value = !state; + slotChoice.value = intent.slot; + customSlot.value = intent.customSlot; + selectedFirmware.value = + firmwareOptions.value.find((f) => f.id === intent.firmwareId) ?? null; +} + // A slotted save fixes the write slot, and it stays put for the session // even when a state later displaces the save. function selectSave(save: SaveSchema) { @@ -384,6 +449,13 @@ onMounted(async () => { configBiosFile: coreOptions["bios_file"], }); + if (storedIntent) { + applyLaunchIntent(storedIntent, romResponse.data); + await nextTick(); + void onPlay(); + return; + } + // Land gamepad/keyboard users on the primary action without an extra Tab. if ( shouldClaimFocusOnModality( @@ -415,9 +487,7 @@ watch(gameRunning, (running, prev) => { presence.start(); } if (prev && !running) { - playSession.flush(); - presence.stopHeartbeat(); - presence.emitStop(); + endSession(); nextTick(focusPlayButton); } }); @@ -434,9 +504,7 @@ onBeforeUnmount(() => { // Leaving the player (back nav / route change) ends the session even if // the user never exited the game to the config screen first. flush() is // idempotent, so an exit that already flushed via the watch is a no-op. - playSession.flush(); - presence.stopHeartbeat(); - presence.emitStop(); + endSession(); // Hand the keyboard and gamepad back to the UI; the flag otherwise // stays true and pad/hotkey navigation is dead until a reload. playing.value = false; @@ -577,8 +645,8 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value)); block prepend-icon="mdi-play" class="r-v2-ejs__play" - :loading="!rom" - :disabled="!rom" + :loading="!rom || relaunching" + :disabled="!rom || relaunching" @click="onPlay" > {{ t("play.play") }} diff --git a/frontend/src/v2/views/Player/JsDos.test.ts b/frontend/src/v2/views/Player/JsDos.test.ts index 09f874558..b1fdde14b 100644 --- a/frontend/src/v2/views/Player/JsDos.test.ts +++ b/frontend/src/v2/views/Player/JsDos.test.ts @@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({ getRom: vi.fn(), locationReplace: vi.fn(), playSessionStart: vi.fn(), - push: vi.fn(), + push: vi.fn(() => Promise.resolve()), confirm: vi.fn(), galleryRom: null as Record | null, routeLeaveGuard: null as ((to: { fullPath: string }) => unknown) | null, @@ -113,6 +113,13 @@ const rom = { let originalLocation: Location; +function setIsolated(isolated: boolean) { + Object.defineProperty(window, "crossOriginIsolated", { + configurable: true, + value: isolated, + }); +} + beforeAll(() => { originalLocation = window.location; Object.defineProperty(window, "location", { @@ -160,6 +167,7 @@ function injectedUrls(): string[] { beforeEach(() => { vi.clearAllMocks(); + setIsolated(false); stubRuntimeProbe("text/javascript"); mocks.galleryRom = null; mocks.routeLeaveGuard = null; @@ -187,12 +195,14 @@ function mountView(): VueWrapper { }); } +// The runtime script defines `Dos` once it has loaded, so the stub lands +// after the mount has injected it. async function mountPlayer(handle: JsDosProps): Promise { + const wrapper = mountView(); + await flushPromises(); window.Dos = vi.fn( (_element: HTMLDivElement, _options: Partial) => handle, ); - const wrapper = mountView(); - await flushPromises(); await wrapper.get(".r-v2-player__play").trigger("click"); await nextTick(); return wrapper; @@ -233,6 +243,14 @@ describe("JsDos runtime loading", () => { ); }); + it("injects the runtime once per document", async () => { + window.Dos = vi.fn(); + mountView(); + await flushPromises(); + + expect(injectedUrls()).toEqual([]); + }); + it("points the emulator payloads at whichever base served the runtime", async () => { stubRuntimeProbe("text/html"); const wrapper = await mountPlayer(makeHandle()); @@ -273,7 +291,7 @@ describe("JsDos player exit", () => { wrapper.unmount(); }); - it("hard-navigates after saving without awaiting stop", async () => { + it("leaves within the app after saving without awaiting stop", async () => { const handle = makeHandle(); const wrapper = await mountPlayer(handle); @@ -282,13 +300,49 @@ describe("JsDos player exit", () => { expect(handle.save).toHaveBeenCalledOnce(); expect(handle.stop).toHaveBeenCalledOnce(); - expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); + expect(mocks.push).toHaveBeenCalledWith("/rom/1"); + expect(mocks.locationReplace).not.toHaveBeenCalled(); expect(mocks.flushPlaySession).toHaveBeenCalledOnce(); expect(mocks.setPlaying).toHaveBeenLastCalledWith(false); wrapper.unmount(); expect(handle.stop).toHaveBeenCalledOnce(); }); + // A player document opened directly is cross-origin isolated, and the rest + // of the app cannot embed third-party images under that policy. + it("replaces an isolated document after saving", async () => { + setIsolated(true); + const handle = makeHandle(); + const wrapper = await mountPlayer(handle); + + await wrapper.get(".r-v2-player__quit").trigger("click"); + await flushPromises(); + + expect(handle.save).toHaveBeenCalledOnce(); + expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); + expect(mocks.push).not.toHaveBeenCalled(); + wrapper.unmount(); + }); + + it("lets a departure from the launch view through", async () => { + const wrapper = mountView(); + await flushPromises(); + + expect(mocks.routeLeaveGuard?.({ fullPath: "/platform/2" })).toBe(true); + expect(mocks.locationReplace).not.toHaveBeenCalled(); + wrapper.unmount(); + }); + + it("replaces an isolated document on departure from the launch view", async () => { + setIsolated(true); + const wrapper = mountView(); + await flushPromises(); + + expect(mocks.routeLeaveGuard?.({ fullPath: "/platform/2" })).toBe(false); + expect(mocks.locationReplace).toHaveBeenCalledWith("/platform/2"); + wrapper.unmount(); + }); + it("keeps the player open when the final save is not confirmed", async () => { const handle = makeHandle(false); const wrapper = await mountPlayer(handle); @@ -300,6 +354,7 @@ describe("JsDos player exit", () => { "play.stream-save-unconfirmed", ); expect(handle.stop).not.toHaveBeenCalled(); + expect(mocks.push).not.toHaveBeenCalled(); expect(mocks.locationReplace).not.toHaveBeenCalled(); expect(mocks.flushPlaySession).not.toHaveBeenCalled(); expect(mocks.setPlaying).not.toHaveBeenCalledWith(false); @@ -320,7 +375,7 @@ describe("JsDos player exit", () => { expect(handle.stop).toHaveBeenCalledOnce(); expect(mocks.flushPlaySession).toHaveBeenCalledOnce(); expect(mocks.setPlaying).toHaveBeenLastCalledWith(false); - expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); + expect(mocks.push).toHaveBeenCalledWith("/rom/1"); wrapper.unmount(); }); @@ -336,7 +391,7 @@ describe("JsDos player exit", () => { "play.stream-save-unconfirmed", ); expect(handle.stop).not.toHaveBeenCalled(); - expect(mocks.locationReplace).not.toHaveBeenCalled(); + expect(mocks.push).not.toHaveBeenCalled(); wrapper.unmount(); }); @@ -356,7 +411,7 @@ describe("JsDos player exit", () => { finishSave?.(true); await flushPromises(); - expect(mocks.locationReplace).toHaveBeenCalledOnce(); + expect(mocks.push).toHaveBeenCalledOnce(); wrapper.unmount(); }); @@ -376,12 +431,12 @@ describe("JsDos player exit", () => { finishSave?.(true); await flushPromises(); - expect(mocks.locationReplace).toHaveBeenCalledOnce(); - expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); + expect(mocks.push).toHaveBeenCalledOnce(); + expect(mocks.push).toHaveBeenCalledWith("/rom/1"); wrapper.unmount(); }); - it("converts route departure into a saved hard navigation", async () => { + it("saves before following a route departure", async () => { const handle = makeHandle(); const wrapper = await mountPlayer(handle); @@ -389,7 +444,7 @@ describe("JsDos player exit", () => { await flushPromises(); expect(handle.save).toHaveBeenCalledOnce(); - expect(mocks.locationReplace).toHaveBeenCalledWith("/platform/2"); + expect(mocks.push).toHaveBeenCalledWith("/platform/2"); wrapper.unmount(); }); diff --git a/frontend/src/v2/views/Player/JsDos.vue b/frontend/src/v2/views/Player/JsDos.vue index a11c64220..9a63076c1 100644 --- a/frontend/src/v2/views/Player/JsDos.vue +++ b/frontend/src/v2/views/Player/JsDos.vue @@ -14,6 +14,7 @@ import { useConfirm } from "@/v2/composables/useConfirm"; import { useFullscreenFallback } from "@/v2/composables/useFullscreenFallback"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; import { usePlaySession } from "@/v2/composables/usePlaySession"; +import { usePlayerExit } from "@/v2/composables/usePlayerExit"; import { usePlayerHero } from "@/v2/composables/usePlayerHero"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useUnloadGuard } from "@/v2/composables/useUnloadGuard"; @@ -21,7 +22,8 @@ import { isJsResource, loadScript } from "@/v2/utils/scriptLoader"; const JSDOS_LOCAL_BASE = "/assets/jsdos"; // Fallback for slim images and the dev server, which ship no local copy. Pinned -// to the image's JSDOS_VERSION; jsDelivr sends the CORP the player's COEP needs. +// to the image's JSDOS_VERSION; jsDelivr sends the CORP a directly opened player +// document needs under its COEP. const JSDOS_CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist"; // Where the runtime actually came from, so the emulator payloads follow it. @@ -35,6 +37,7 @@ useFullscreenFallback(); const playSession = usePlaySession(); const snackbar = useSnackbar(); const confirm = useConfirm(); +const exit = usePlayerExit(); const rom = shallowRef(null); const gameRunning = ref(false); @@ -46,6 +49,8 @@ let dos: JsDosProps | null = null; const { romId, heroRom, title, platformLabel } = usePlayerHero(rom); async function loadRuntime() { + // The runtime outlives the view within the document, so inject it once. + if (window.Dos) return; jsDosAssetBase = (await isJsResource(`${JSDOS_LOCAL_BASE}/js-dos.js`)) ? JSDOS_LOCAL_BASE : JSDOS_CDN_BASE; @@ -147,7 +152,7 @@ async function leavePlayer(destination: string) { } teardown(); - window.location.replace(destination); + exit.leave(destination); } function onlyQuit() { @@ -166,6 +171,8 @@ onMounted(async () => { }); onBeforeRouteLeave((to) => { + // With nothing running there is nothing to save first. + if (!dos) return exit.guard(to); void leavePlayer(to.fullPath); return false; }); diff --git a/frontend/src/v2/views/Player/launchIntent.test.ts b/frontend/src/v2/views/Player/launchIntent.test.ts new file mode 100644 index 000000000..38aa7ee95 --- /dev/null +++ b/frontend/src/v2/views/Player/launchIntent.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; +import { existingSlot } from "@/v2/utils/saveSlots"; +import { isLaunchIntent, type LaunchIntent } from "./launchIntent"; + +const INTENT: LaunchIntent = { + saveId: 3, + stateId: null, + firmwareId: 12, + slot: existingSlot("slot-2"), + customSlot: "", +}; + +describe("isLaunchIntent", () => { + it("accepts what the view stores", () => { + expect(isLaunchIntent(INTENT)).toBe(true); + }); + + it("accepts a cleared selection", () => { + expect( + isLaunchIntent({ + saveId: null, + stateId: null, + firmwareId: null, + slot: { kind: "new" }, + customSlot: "my slot", + }), + ).toBe(true); + }); + + it.each([ + ["nothing", null], + ["another shape", { core: "snes9x" }], + ["a string id", { ...INTENT, saveId: "3" }], + ["a bare slot name", { ...INTENT, slot: "slot-2" }], + ["a missing slot name", { ...INTENT, customSlot: undefined }], + ])("rejects %s", (_label, value) => { + expect(isLaunchIntent(value)).toBe(false); + }); +}); diff --git a/frontend/src/v2/views/Player/launchIntent.ts b/frontend/src/v2/views/Player/launchIntent.ts new file mode 100644 index 000000000..81794d982 --- /dev/null +++ b/frontend/src/v2/views/Player/launchIntent.ts @@ -0,0 +1,33 @@ +// What the EmulatorJS launch view carries across the reload that isolates the +// document (see useIsolatedLaunch). The core and the disc are remembered per +// game already, so only the rest travels. +import { isSlotChoice, type SlotChoice } from "@/v2/utils/saveSlots"; + +export interface LaunchIntent { + saveId: number | null; + stateId: number | null; + firmwareId: number | null; + slot: SlotChoice; + customSlot: string; +} + +function isOptionalId(value: unknown): value is number | null { + return value === null || typeof value === "number"; +} + +export function isLaunchIntent(value: unknown): value is LaunchIntent { + return ( + typeof value === "object" && + value !== null && + "saveId" in value && + isOptionalId(value.saveId) && + "stateId" in value && + isOptionalId(value.stateId) && + "firmwareId" in value && + isOptionalId(value.firmwareId) && + "slot" in value && + isSlotChoice(value.slot) && + "customSlot" in value && + typeof value.customSlot === "string" + ); +} diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 7cb4d9092..f38b42a59 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -8,6 +8,27 @@ import { VitePWA } from "vite-plugin-pwa"; import vuetify, { transformAssetUrls } from "vite-plugin-vuetify"; import { precompress } from "./scripts/precompress"; +// Mirror of the nginx map that isolates the player documents (see +// docker/nginx/templates/default.conf.template), so a threaded EmulatorJS +// core boots on the dev server too, given a secure context (localhost or +// https). Like there, the query string is matched explicitly. +const ISOLATED_PLAYER_URL_RE = /^\/rom\/.*\/(ejs|jsdos)(\?|$)/; + +function playerIsolationHeaders() { + return { + name: "romm:player-isolation-headers", + configureServer(server) { + server.middlewares.use((req, res, next) => { + if (ISOLATED_PLAYER_URL_RE.test(req.url ?? "")) { + res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); + res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); + } + next(); + }); + }, + }; +} + // Vuetify components to preoptimize for faster dev startup const VUETIFY_COMPONENTS = [ "vuetify/components/transitions", @@ -149,6 +170,7 @@ export default defineConfig(({ mode }) => { }, }), precompress(), + playerIsolationHeaders(), httpsMode && mkcert({ savePath: "/app/.vite-plugin-mkcert", From 8d4e8563603f994d182bde9c134751a27b69810e Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 05:33:30 +0200 Subject: [PATCH 2/4] fix(v2): close the gaps the code review found in the player launch path Findings from the review pass over the SPA launch change, plus the two bot reviews on the PR. Correctness: - Presence stops were addressed to the device, not to a rom, so a view that never announced anything could clear what another tab was playing. A stop now needs a started session, and happens once; `useActivityPresence` grows the `stop()` the two call sites were spelling out by hand. - The EmulatorJS exit read `window.EJS_emulator`, which a departure taken while the loader was still injecting would not see yet, so the runtime could be left in a document a later launch then failed to load into. It tracks the injection itself. - js-dos resolved its asset base per view: a second launch in a document whose runtime came from the CDN looked for the payloads locally. Two views mounting at once could also both inject the runtime. Both now go through one document-level loader, which resolves with the base it served from and lets a later mount retry a failed load. - A blocked sessionStorage threw while every EmulatorJS view was initialising. Storage that cannot be read is an absent intent, and one that cannot be written cancels the relaunch rather than losing the selection to it. - Outside a secure context the headers cannot expose SharedArrayBuffer, so the reload only delayed the same error by a round trip. It is refused up front. - The dev server mirrored one of the two nginx isolation entries, leaving the console player unisolated there. Reuse and cover: - `usePlayerExit` owns the whole rule again: `departing` moved in, so both views use `guard` rather than one of them restating it, and the `leaving` flag it never needed is gone. - Resolving an intent back into a selection is a pure pair in `launchIntent.ts` with its own tests, rather than closures the view kept to itself. - The Vite plugin is a script beside `precompress`, so the regexes that have to track nginx are tested. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01R1VFUvsR5wYK3axxR1gebc --- docker/nginx/templates/default.conf.template | 1 + docs/FRONTEND_ARCHITECTURE.md | 8 +- frontend/scripts/playerIsolationHeaders.ts | 38 +++++++ .../composables/useActivityPresence/index.ts | 18 ++- .../useIsolatedLaunch/index.test.ts | 89 ++++++++++++--- .../v2/composables/useIsolatedLaunch/index.ts | 30 +++-- .../composables/usePlayerExit/index.test.ts | 30 +++-- .../src/v2/composables/usePlayerExit/index.ts | 29 +++-- frontend/src/v2/views/Player/EmulatorJS.vue | 66 +++++------ frontend/src/v2/views/Player/JsDos.test.ts | 94 ++++++---------- frontend/src/v2/views/Player/JsDos.vue | 44 +++----- .../src/v2/views/Player/jsDosRuntime.test.ts | 105 ++++++++++++++++++ frontend/src/v2/views/Player/jsDosRuntime.ts | 37 ++++++ .../src/v2/views/Player/launchIntent.test.ts | 105 ++++++++++++++++-- frontend/src/v2/views/Player/launchIntent.ts | 56 +++++++++- frontend/test/playerIsolationHeaders.test.ts | 90 +++++++++++++++ frontend/vite.config.js | 22 +--- 17 files changed, 649 insertions(+), 213 deletions(-) create mode 100644 frontend/scripts/playerIsolationHeaders.ts create mode 100644 frontend/src/v2/views/Player/jsDosRuntime.test.ts create mode 100644 frontend/src/v2/views/Player/jsDosRuntime.ts create mode 100644 frontend/test/playerIsolationHeaders.test.ts diff --git a/docker/nginx/templates/default.conf.template b/docker/nginx/templates/default.conf.template index 168e22fa9..4a8ef969c 100644 --- a/docker/nginx/templates/default.conf.template +++ b/docker/nginx/templates/default.conf.template @@ -18,6 +18,7 @@ map $http_x_forwarded_proto $forwardscheme { # EmulatorJS and js-dos player paths, to enable SharedArrayBuffer support, which # is needed for multi-threaded cores. Not $uri: try_files rewrites it to # /index.html before add_header runs, so the query string is matched explicitly. +# The dev server mirrors these entries in frontend/scripts/playerIsolationHeaders.ts. map $request_uri $coep_header { default ""; ~^/rom/.*/(ejs|jsdos)(\?|$) "require-corp"; diff --git a/docs/FRONTEND_ARCHITECTURE.md b/docs/FRONTEND_ARCHITECTURE.md index c72588ad2..8f9b295d1 100644 --- a/docs/FRONTEND_ARCHITECTURE.md +++ b/docs/FRONTEND_ARCHITECTURE.md @@ -868,10 +868,12 @@ Threaded EmulatorJS cores need `SharedArrayBuffer`, which browsers expose only i A v2 player view is reached by SPA navigation, so it is not isolated on arrival. Two composables cover that: -- `useIsolatedLaunch(player, romId, isIntent)` reloads the view into an isolated document when a launch needs it. The view defines the `Intent` the reload cannot carry in the URL, calls `relaunch(intent)` when `hasSharedArrayBuffer()` is false, and boots from `intent` on mount. `relaunch()` returns false when the view already came from such a reload: the context cannot be isolated (plain HTTP, or a proxy dropping the headers), so the view reports that instead of looping. -- `usePlayerExit(runtimeBound)` leaves the view by a full navigation when the document is isolated, or when the player's runtime cannot be injected twice (EmulatorJS declares globals), so the app resumes in a fresh document. Otherwise leaving is an SPA navigation. +- `useIsolatedLaunch(player, romId, isIntent)` reloads the view into an isolated document when a launch needs it. The view defines the `Intent` the reload cannot carry in the URL, calls `relaunch(intent)` when `hasSharedArrayBuffer()` is false, and boots from `intent` on mount. `relaunch()` returns false, and the view reports the context instead, when the reload would not help: outside a secure context (the headers alone never expose `SharedArrayBuffer`), where storage refused to keep the selection, or from a view that already came from such a reload. +- `usePlayerExit(runtimeBound)` leaves the view by a full navigation when the document is isolated, or when the player's runtime cannot be injected twice (EmulatorJS declares top-level classes), so the app resumes in a fresh document. Otherwise leaving is an SPA navigation. `guard` is the `onBeforeRouteLeave` form, `leave(path)` the programmatic one, and `departing` tells an unload prompt that this exit is the view's own. -To add an EmulatorJS core that needs threads, add it to `areThreadsRequiredForEJSCore` in `utils/index.ts`; nothing else changes. To add a player that needs isolation, use both composables the way `v2/views/Player/EmulatorJS.vue` does. A player whose runtime needs no `SharedArrayBuffer` (js-dos) only needs `usePlayerExit()`. +To add an EmulatorJS core that needs threads, add it to `areThreadsRequiredForEJSCore` in `utils/index.ts`; nothing else changes. To add a player that needs isolation, use both composables the way `v2/views/Player/EmulatorJS.vue` does, and track `runtimeBound` from the moment the runtime is injected rather than from the global it eventually defines. A player whose runtime needs no `SharedArrayBuffer` (js-dos) only needs `usePlayerExit()`. + +The dev server has no nginx in front of it, so `scripts/playerIsolationHeaders.ts` answers the same URLs with the same headers. It is one entry per entry of the nginx map, and the two are meant to be edited together. ### Platform Detection diff --git a/frontend/scripts/playerIsolationHeaders.ts b/frontend/scripts/playerIsolationHeaders.ts new file mode 100644 index 000000000..1d2deab86 --- /dev/null +++ b/frontend/scripts/playerIsolationHeaders.ts @@ -0,0 +1,38 @@ +/** + * playerIsolationHeaders: the dev server's twin of the nginx COOP/COEP map. + * + * Threaded EmulatorJS cores need SharedArrayBuffer, which only a cross-origin + * isolated document exposes. In production nginx attaches the headers to the + * player URLs alone, because the rest of the app embeds third-party images that + * COEP would block. Nothing sits in front of the dev server, so it answers the + * same URLs the same way. + */ +import type { Plugin } from "vite"; + +// One entry per entry of the map in docker/nginx/templates/default.conf.template, +// matched the same way: against the full request URI rather than the path, since +// there try_files rewrites the path to /index.html before the headers run. +const ISOLATED_PLAYER_URLS = [ + /^\/rom\/.*\/(ejs|jsdos)(\?|$)/, + /^\/console\/rom\/[0-9]+\/play/, +]; + +/** Whether a request URI addresses a player document that must be isolated. */ +export function isIsolatedPlayerUrl(url: string): boolean { + return ISOLATED_PLAYER_URLS.some((pattern) => pattern.test(url)); +} + +export function playerIsolationHeaders(): Plugin { + return { + name: "romm:player-isolation-headers", + configureServer(server) { + server.middlewares.use((req, res, next) => { + if (isIsolatedPlayerUrl(req.url ?? "")) { + res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); + res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); + } + next(); + }); + }, + }; +} diff --git a/frontend/src/v2/composables/useActivityPresence/index.ts b/frontend/src/v2/composables/useActivityPresence/index.ts index 89883dd3d..e3d482fb1 100644 --- a/frontend/src/v2/composables/useActivityPresence/index.ts +++ b/frontend/src/v2/composables/useActivityPresence/index.ts @@ -18,6 +18,8 @@ export function useActivityPresence( start: () => void; stopHeartbeat: () => void; emitStop: () => void; + /** End the session: stop beating and announce it, in that order. */ + stop: () => void; } { const auth = storeAuth(); @@ -38,18 +40,30 @@ export function useActivityPresence( immediate: false, }); + // A stop is addressed to the device, not to a rom, so one sent by a view + // that never announced anything would clear whatever else the device is + // playing. Only a started session stops, and only once. + let started = false; + function start(): void { const romId = getRomId(); if (!auth.user || romId == null) return; if (!socket.connected) socket.connect(); socket.emit("activity:start", { rom_id: romId, device_id: deviceId() }); + started = true; resume(); } function emitStop(): void { - if (!auth.user) return; + if (!auth.user || !started) return; + started = false; socket.emit("activity:stop", { device_id: deviceId() }); } - return { start, stopHeartbeat: pause, emitStop }; + function stop(): void { + pause(); + emitStop(); + } + + return { start, stopHeartbeat: pause, emitStop, stop }; } diff --git a/frontend/src/v2/composables/useIsolatedLaunch/index.test.ts b/frontend/src/v2/composables/useIsolatedLaunch/index.test.ts index 7ced43520..ac10aacc4 100644 --- a/frontend/src/v2/composables/useIsolatedLaunch/index.test.ts +++ b/frontend/src/v2/composables/useIsolatedLaunch/index.test.ts @@ -25,6 +25,29 @@ function isIntent(value: unknown): value is Intent { const KEY = "player:7:ejs:launch"; const reload = vi.fn(); let originalLocation: Location; +const realStorage = window.sessionStorage; + +/** Stand in for a browser that denies storage access outright. */ +function blockStorage() { + const denied = () => { + throw new Error("storage is blocked"); + }; + Object.defineProperty(window, "sessionStorage", { + configurable: true, + value: { getItem: denied, setItem: denied, removeItem: denied }, + }); +} + +function launch() { + return useIsolatedLaunch("ejs", 7, isIntent); +} + +function setSecureContext(secure: boolean) { + Object.defineProperty(window, "isSecureContext", { + configurable: true, + value: secure, + }); +} beforeAll(() => { originalLocation = window.location; @@ -43,42 +66,45 @@ afterAll(() => { beforeEach(() => { reload.mockClear(); + Object.defineProperty(window, "sessionStorage", { + configurable: true, + value: realStorage, + }); sessionStorage.clear(); + setSecureContext(true); }); describe("useIsolatedLaunch", () => { it("opens without an intent", () => { - const launch = useIsolatedLaunch("ejs", 7, isIntent); + const first = launch(); - expect(launch.intent).toBeNull(); - expect(launch.relaunching.value).toBe(false); + expect(first.intent).toBeNull(); + expect(first.relaunching.value).toBe(false); }); it("keeps the intent and reloads the document", () => { - const launch = useIsolatedLaunch("ejs", 7, isIntent); + const first = launch(); - expect(launch.relaunch({ saveId: 3 })).toBe(true); + expect(first.relaunch({ saveId: 3 })).toBe(true); - expect(launch.relaunching.value).toBe(true); + expect(first.relaunching.value).toBe(true); expect(reload).toHaveBeenCalledOnce(); expect(sessionStorage.getItem(KEY)).toBe('{"saveId":3}'); }); it("hands the intent to the reloaded view once", () => { - useIsolatedLaunch("ejs", 7, isIntent).relaunch({ saveId: 3 }); + launch().relaunch({ saveId: 3 }); - expect(useIsolatedLaunch("ejs", 7, isIntent).intent).toEqual({ - saveId: 3, - }); - expect(useIsolatedLaunch("ejs", 7, isIntent).intent).toBeNull(); + expect(launch().intent).toEqual({ saveId: 3 }); + expect(launch().intent).toBeNull(); }); // A second reload could not isolate the document either, so the view is // told to report the context instead of looping. it("refuses to reload again from the reloaded view", () => { - useIsolatedLaunch("ejs", 7, isIntent).relaunch({ saveId: 3 }); + launch().relaunch({ saveId: 3 }); reload.mockClear(); - const reloaded = useIsolatedLaunch("ejs", 7, isIntent); + const reloaded = launch(); expect(reloaded.relaunch({ saveId: 4 })).toBe(false); @@ -86,14 +112,41 @@ describe("useIsolatedLaunch", () => { expect(reloaded.relaunching.value).toBe(false); }); + // The headers cannot expose SharedArrayBuffer over plain HTTP, so the round + // trip would only delay the same error. + it("refuses to reload outside a secure context", () => { + setSecureContext(false); + const first = launch(); + + expect(first.relaunch({ saveId: 3 })).toBe(false); + + expect(reload).not.toHaveBeenCalled(); + expect(sessionStorage.getItem(KEY)).toBeNull(); + }); + + it("refuses to reload when the selection cannot be kept", () => { + const first = launch(); + blockStorage(); + + expect(first.relaunch({ saveId: 3 })).toBe(false); + + expect(reload).not.toHaveBeenCalled(); + expect(first.relaunching.value).toBe(false); + }); + + // A player has to open even where storage access is denied outright. + it("opens with no intent when storage cannot be read", () => { + blockStorage(); + + expect(launch().intent).toBeNull(); + }); + it("keeps players and games apart", () => { - useIsolatedLaunch("ejs", 7, isIntent).relaunch({ saveId: 3 }); + launch().relaunch({ saveId: 3 }); expect(useIsolatedLaunch("jsdos", 7, isIntent).intent).toBeNull(); expect(useIsolatedLaunch("ejs", 8, isIntent).intent).toBeNull(); - expect(useIsolatedLaunch("ejs", 7, isIntent).intent).toEqual({ - saveId: 3, - }); + expect(launch().intent).toEqual({ saveId: 3 }); }); it.each([ @@ -102,7 +155,7 @@ describe("useIsolatedLaunch", () => { ])("drops a stored value that is %s", (_label, raw) => { sessionStorage.setItem(KEY, raw); - expect(useIsolatedLaunch("ejs", 7, isIntent).intent).toBeNull(); + expect(launch().intent).toBeNull(); expect(sessionStorage.getItem(KEY)).toBeNull(); }); }); diff --git a/frontend/src/v2/composables/useIsolatedLaunch/index.ts b/frontend/src/v2/composables/useIsolatedLaunch/index.ts index dd993498d..032700f08 100644 --- a/frontend/src/v2/composables/useIsolatedLaunch/index.ts +++ b/frontend/src/v2/composables/useIsolatedLaunch/index.ts @@ -32,9 +32,10 @@ export function useIsolatedLaunch( /** True once a reload is under way, so the Play control stays busy. */ relaunching: Ref; /** - * Keep `intent` and reload into the isolated document. False when this view - * already came from such a reload: the context cannot be isolated (plain - * HTTP, or a proxy dropping the headers), so the caller reports it instead. + * Keep `intent` and reload into the isolated document. False when the reload + * would not help: the context is not secure (the headers alone never expose + * SharedArrayBuffer), the selection could not be kept, or this view already + * came from such a reload. The caller reports the context instead. */ relaunch: (intent: Intent) => boolean; } { @@ -43,9 +44,9 @@ export function useIsolatedLaunch( const relaunching = ref(false); function relaunch(next: Intent): boolean { - if (intent !== null) return false; + if (intent !== null || !window.isSecureContext) return false; + if (!keepIntent(key, next)) return false; relaunching.value = true; - sessionStorage.setItem(key, JSON.stringify(next)); window.location.reload(); return true; } @@ -53,15 +54,28 @@ export function useIsolatedLaunch( return { intent, relaunching, relaunch }; } +// Storage access can be denied outright (a strict privacy mode, a blocked +// third-party context), and a player must open and run regardless, so both +// sides treat that as "no intent" rather than throwing through the view. + +function keepIntent(key: string, intent: unknown): boolean { + try { + sessionStorage.setItem(key, JSON.stringify(intent)); + return true; + } catch { + return false; + } +} + /** The intent under `key`, cleared on read so it boots only once. */ function takeIntent( key: string, isIntent: (value: unknown) => value is Intent, ): Intent | null { - const raw = sessionStorage.getItem(key); - if (raw === null) return null; - sessionStorage.removeItem(key); try { + const raw = sessionStorage.getItem(key); + if (raw === null) return null; + sessionStorage.removeItem(key); const parsed: unknown = JSON.parse(raw); return isIntent(parsed) ? parsed : null; } catch { diff --git a/frontend/src/v2/composables/usePlayerExit/index.test.ts b/frontend/src/v2/composables/usePlayerExit/index.test.ts index d11abf8d8..3b99c100d 100644 --- a/frontend/src/v2/composables/usePlayerExit/index.test.ts +++ b/frontend/src/v2/composables/usePlayerExit/index.test.ts @@ -9,7 +9,7 @@ import { } from "vitest"; import { usePlayerExit } from "./index"; -const push = vi.fn(() => Promise.resolve()); +const push = vi.fn(); const locationReplace = vi.fn(); let originalLocation: Location; @@ -53,6 +53,7 @@ describe("usePlayerExit", () => { expect(push).toHaveBeenCalledWith("/rom/1"); expect(locationReplace).not.toHaveBeenCalled(); + expect(exit.departing.value).toBe(false); }); it("replaces the document when it is cross-origin isolated", () => { @@ -89,17 +90,24 @@ describe("usePlayerExit", () => { expect(locationReplace).toHaveBeenCalledWith("/platform/2"); }); - it("lets its own departure through", async () => { - let bound = false; - const exit = usePlayerExit(() => bound); + // The view arms an unload prompt while a game is up, and the exit it asked + // for must not be what triggers it. + it.each([ + [ + "an exit", + (exit: ReturnType) => exit.leave("/rom/1"), + ], + [ + "a route departure", + (exit: ReturnType) => + exit.guard({ fullPath: "/rom/1" }), + ], + ])("announces %s that replaces the document", (_label, act) => { + setIsolated(true); + const exit = usePlayerExit(); - exit.leave("/rom/1"); - // The runtime cannot bind between leave() and the guard, but a guard that - // re-checked the document would otherwise still be able to block the push. - bound = true; - expect(exit.guard({ fullPath: "/rom/1" })).toBe(true); + act(exit); - await new Promise((resolve) => setTimeout(resolve, 0)); - expect(exit.guard({ fullPath: "/rom/1" })).toBe(false); + expect(exit.departing.value).toBe(true); }); }); diff --git a/frontend/src/v2/composables/usePlayerExit/index.ts b/frontend/src/v2/composables/usePlayerExit/index.ts index f346db57b..3aed038f1 100644 --- a/frontend/src/v2/composables/usePlayerExit/index.ts +++ b/frontend/src/v2/composables/usePlayerExit/index.ts @@ -7,43 +7,42 @@ // And a runtime that declares globals when injected (EmulatorJS) cannot be // injected a second time. Either way the exit is a full navigation, so the // app resumes in a fresh document; otherwise it is an SPA navigation. +import { ref, type Ref } from "vue"; import { useRouter, type RouteLocationNormalized } from "vue-router"; export function usePlayerExit( /** True once the view injected a runtime the document cannot take twice. */ runtimeBound: () => boolean = () => false, ): { - /** Whether leaving has to replace the document. */ - documentBound: () => boolean; + /** True once an exit is replacing the document, so an unload prompt can stand down. */ + departing: Ref; /** Go to `path`, by a full navigation when the document is bound. */ leave: (path: string) => void; /** `onBeforeRouteLeave` guard: lets a departure through unless bound. */ guard: (to: Pick) => boolean; } { const router = useRouter(); - // Set by leave() so the guard lets its own push through. - let leaving = false; + const departing = ref(false); function documentBound(): boolean { return window.crossOriginIsolated || runtimeBound(); } + function replaceDocument(path: string): void { + departing.value = true; + window.location.replace(path); + } + function leave(path: string): void { - if (documentBound()) { - window.location.replace(path); - return; - } - leaving = true; - void router.push(path).finally(() => { - leaving = false; - }); + if (documentBound()) replaceDocument(path); + else void router.push(path); } function guard(to: Pick): boolean { - if (leaving || !documentBound()) return true; - window.location.replace(to.fullPath); + if (!documentBound()) return true; + replaceDocument(to.fullPath); return false; } - return { documentBound, leave, guard }; + return { departing, leave, guard }; } diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index f70857329..f187458b1 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -104,7 +104,12 @@ import { } from "@/v2/utils/saveSlots"; import { isJsResource, loadScript } from "@/v2/utils/scriptLoader"; import { rememberCore, resolveRememberedCore } from "./coreStorage"; -import { isLaunchIntent, type LaunchIntent } from "./launchIntent"; +import { + isLaunchIntent, + launchIntentFor, + resolveLaunchIntent, + type LaunchIntent, +} from "./launchIntent"; import { defaultResumeSelection, newerThanPick, @@ -154,9 +159,6 @@ const selectedCore = ref(null); const selectedFirmware = ref(null); const supportedCores = ref([]); const gameRunning = ref(false); -// A route departure while a game runs is deliberate, so the reload prompt -// stays quiet for the full navigation it turns into. -const departing = ref(false); // Threaded cores need SharedArrayBuffer, so their launch may first have to // reload the view into a cross-origin isolated document. const { @@ -165,18 +167,18 @@ const { relaunch: relaunchIsolated, } = useIsolatedLaunch("ejs", romId, isLaunchIntent); -useUnloadGuard(() => gameRunning.value && !departing.value); -useStageActive(gameRunning); +// The EmulatorJS loader declares top-level classes and instantiates the +// emulator, so a document it was injected into cannot host another launch. +// Tracked from the injection rather than from `window.EJS_emulator`, which a +// departure mid-load would not see yet. +let runtimeInjected = false; +const exit = usePlayerExit(() => runtimeInjected); -// The EmulatorJS loader declares globals and instantiates the emulator when -// injected, so a document that ran a game cannot host another launch. -const exit = usePlayerExit(() => window.EJS_emulator !== undefined); -onBeforeRouteLeave((to) => { - if (!exit.documentBound()) return true; - departing.value = true; - exit.leave(to.fullPath); - return false; -}); +// A departure while a game runs is deliberate, so the unload prompt stays +// quiet for the full navigation it turns into. +useUnloadGuard(() => gameRunning.value && !exit.departing.value); +useStageActive(gameRunning); +onBeforeRouteLeave(exit.guard); // Stage-scoped so the non-passive listener never taxes touches elsewhere. const stageRef = ref(null); @@ -188,8 +190,7 @@ const presence = useActivityPresence(() => rom.value?.id); function endSession() { playSession.flush(); - presence.stopHeartbeat(); - presence.emitStop(); + presence.stop(); } // A full navigation out of the view unmounts nothing, so the session also // closes on pagehide; flush() is idempotent, so no path records it twice. @@ -313,6 +314,7 @@ async function onPlay() { throw new Error(`Loader at ${loaderUrl} did not return JavaScript`); } window.EJS_pathtodata = path; + runtimeInjected = true; await loadScript(loaderUrl); } @@ -332,29 +334,27 @@ async function onPlay() { } } -// What the reload cannot carry in the URL; the core and the disc are already -// remembered per game. function currentIntent(): LaunchIntent { - return { - saveId: resume.value.save?.id ?? null, - stateId: resume.value.state?.id ?? null, - firmwareId: selectedFirmware.value?.id ?? null, + return launchIntentFor({ + resume: resume.value, + firmware: selectedFirmware.value, slot: slotChoice.value, customSlot: customSlot.value, - }; + }); } // What the view had selected before the reload, re-applied over the defaults. function applyLaunchIntent(intent: LaunchIntent, current: DetailedRom) { - const save = current.user_saves.find((s) => s.id === intent.saveId) ?? null; - const state = - compatibleStates.value.find((s) => s.id === intent.stateId) ?? null; - resume.value = { save, state }; - isSavesTabSelected.value = !state; - slotChoice.value = intent.slot; - customSlot.value = intent.customSlot; - selectedFirmware.value = - firmwareOptions.value.find((f) => f.id === intent.firmwareId) ?? null; + const selection = resolveLaunchIntent(intent, { + saves: current.user_saves, + states: compatibleStates.value, + firmware: firmwareOptions.value, + }); + resume.value = selection.resume; + isSavesTabSelected.value = !selection.resume.state; + slotChoice.value = selection.slot; + customSlot.value = selection.customSlot; + selectedFirmware.value = selection.firmware; } // A slotted save fixes the write slot, and it stays put for the session diff --git a/frontend/src/v2/views/Player/JsDos.test.ts b/frontend/src/v2/views/Player/JsDos.test.ts index b1fdde14b..1a300b507 100644 --- a/frontend/src/v2/views/Player/JsDos.test.ts +++ b/frontend/src/v2/views/Player/JsDos.test.ts @@ -15,6 +15,7 @@ import JsDos from "./JsDos.vue"; const mocks = vi.hoisted(() => ({ flushPlaySession: vi.fn(), getRom: vi.fn(), + loadRuntime: vi.fn(), locationReplace: vi.fn(), playSessionStart: vi.fn(), push: vi.fn(() => Promise.resolve()), @@ -102,6 +103,12 @@ vi.mock("@/v2/stores/galleryRoms", () => ({ default: () => ({ getRomById: () => mocks.galleryRom }), })); +// The runtime is a document-level singleton with its own suite; here it only +// has to say which base the emulator payloads follow. +vi.mock("./jsDosRuntime", () => ({ + loadJsDosRuntime: mocks.loadRuntime, +})); + const rom = { id: 1, name: "Windows Game", @@ -111,6 +118,9 @@ const rom = { rom_user: { status: null }, }; +const LOCAL_BASE = "/assets/jsdos"; +const CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist"; + let originalLocation: Location; function setIsolated(isolated: boolean) { @@ -126,8 +136,6 @@ beforeAll(() => { configurable: true, value: { ...originalLocation, replace: mocks.locationReplace }, }); - vi.spyOn(document.body, "appendChild").mockImplementation((node) => node); - vi.spyOn(document.head, "appendChild").mockImplementation((node) => node); vi.spyOn(console, "error").mockImplementation(() => undefined); }); @@ -140,35 +148,10 @@ afterAll(() => { }); }); -function stubRuntimeProbe(contentType: string, ok = true) { - vi.stubGlobal( - "fetch", - vi.fn().mockResolvedValue({ - ok, - headers: { get: () => contentType }, - clone: () => ({ text: async () => "" }), - }), - ); -} - -function injectedUrls(): string[] { - return [document.head.appendChild, document.body.appendChild].flatMap((spy) => - vi - .mocked(spy) - .mock.calls.map( - ([node]) => - (node as Element).getAttribute?.("src") ?? - (node as Element).getAttribute?.("href") ?? - "", - ) - .filter(Boolean), - ); -} - beforeEach(() => { vi.clearAllMocks(); setIsolated(false); - stubRuntimeProbe("text/javascript"); + mocks.loadRuntime.mockResolvedValue(LOCAL_BASE); mocks.galleryRom = null; mocks.routeLeaveGuard = null; mocks.userId = 7; @@ -204,7 +187,7 @@ async function mountPlayer(handle: JsDosProps): Promise { (_element: HTMLDivElement, _options: Partial) => handle, ); await wrapper.get(".r-v2-player__play").trigger("click"); - await nextTick(); + await flushPromises(); return wrapper; } @@ -217,56 +200,45 @@ function makeHandle(saveResult = true) { } describe("JsDos runtime loading", () => { - const CDN = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist"; - - it("serves the runtime from the local assets when they are present", async () => { + it("starts loading the runtime alongside the ROM payload", async () => { mountView(); await flushPromises(); - expect(injectedUrls()).toEqual( - expect.arrayContaining([ - "/assets/jsdos/js-dos.css", - "/assets/jsdos/js-dos.js", - ]), - ); - }); - - // Slim images and the Vite dev server ship no local copy, and both answer a - // missing asset with 200 + index.html rather than a 404. - it("falls back to the pinned CDN when the local path serves index.html", async () => { - stubRuntimeProbe("text/html"); - mountView(); - await flushPromises(); - - expect(injectedUrls()).toEqual( - expect.arrayContaining([`${CDN}/js-dos.css`, `${CDN}/js-dos.js`]), - ); - }); - - it("injects the runtime once per document", async () => { - window.Dos = vi.fn(); - mountView(); - await flushPromises(); - - expect(injectedUrls()).toEqual([]); + expect(mocks.loadRuntime).toHaveBeenCalled(); }); it("points the emulator payloads at whichever base served the runtime", async () => { - stubRuntimeProbe("text/html"); + mocks.loadRuntime.mockResolvedValue(CDN_BASE); const wrapper = await mountPlayer(makeHandle()); const options = vi.mocked(window.Dos!).mock.calls[0]![1]; - expect(options.pathPrefix).toBe(`${CDN}/emulators/`); + expect(options.pathPrefix).toBe(`${CDN_BASE}/emulators/`); + wrapper.unmount(); + }); + + it("reports a runtime that never arrived", async () => { + mocks.loadRuntime.mockRejectedValue(new Error("network")); + const wrapper = mountView(); + await flushPromises(); + + await wrapper.get(".r-v2-player__play").trigger("click"); + await flushPromises(); + + expect(mocks.snackbarError).toHaveBeenCalledWith( + "play.stream-error-generic", + ); + expect(mocks.setPlaying).not.toHaveBeenCalledWith(true); wrapper.unmount(); }); }); describe("JsDos player exit", () => { - it("reports when the runtime has not loaded", async () => { + it("reports when the runtime defined no factory", async () => { const wrapper = mountView(); await flushPromises(); await wrapper.get(".r-v2-player__play").trigger("click"); + await flushPromises(); expect(mocks.snackbarError).toHaveBeenCalledWith( "play.stream-error-generic", diff --git a/frontend/src/v2/views/Player/JsDos.vue b/frontend/src/v2/views/Player/JsDos.vue index 9a63076c1..6b4aab5b0 100644 --- a/frontend/src/v2/views/Player/JsDos.vue +++ b/frontend/src/v2/views/Player/JsDos.vue @@ -18,16 +18,7 @@ import { usePlayerExit } from "@/v2/composables/usePlayerExit"; import { usePlayerHero } from "@/v2/composables/usePlayerHero"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useUnloadGuard } from "@/v2/composables/useUnloadGuard"; -import { isJsResource, loadScript } from "@/v2/utils/scriptLoader"; - -const JSDOS_LOCAL_BASE = "/assets/jsdos"; -// Fallback for slim images and the dev server, which ship no local copy. Pinned -// to the image's JSDOS_VERSION; jsDelivr sends the CORP a directly opened player -// document needs under its COEP. -const JSDOS_CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist"; - -// Where the runtime actually came from, so the emulator payloads follow it. -let jsDosAssetBase = JSDOS_LOCAL_BASE; +import { loadJsDosRuntime } from "./jsDosRuntime"; const { t } = useI18n(); const authStore = storeAuth(); @@ -48,27 +39,22 @@ let dos: JsDosProps | null = null; const { romId, heroRom, title, platformLabel } = usePlayerHero(rom); -async function loadRuntime() { - // The runtime outlives the view within the document, so inject it once. - if (window.Dos) return; - jsDosAssetBase = (await isJsResource(`${JSDOS_LOCAL_BASE}/js-dos.js`)) - ? JSDOS_LOCAL_BASE - : JSDOS_CDN_BASE; - - const css = document.createElement("link"); - css.rel = "stylesheet"; - css.href = `${jsDosAssetBase}/js-dos.css`; - document.head.appendChild(css); - - await loadScript(`${jsDosAssetBase}/js-dos.js`); -} - async function onPlay() { - // Preserve narrowing across nextTick(). - const dosFactory = window.Dos; const currentRom = rom.value; const userId = authStore.user?.id; if (!currentRom || userId == null) return; + + // Resolves at once when the mount-time load already landed, and waits for it + // otherwise, so the emulator payloads always follow the base it served from. + let assetBase: string; + try { + assetBase = await loadJsDosRuntime(); + } catch { + snackbar.error(t("play.stream-error-generic")); + return; + } + // Preserve narrowing across nextTick(). + const dosFactory = window.Dos; if (!dosFactory) { snackbar.error(t("play.stream-error-generic")); return; @@ -89,7 +75,7 @@ async function onPlay() { url: getDownloadPath({ rom: currentRom }), backend: "dosboxX", backendLocked: true, - pathPrefix: `${jsDosAssetBase}/emulators/`, + pathPrefix: `${assetBase}/emulators/`, autoStart: true, autoSave: true, // js-dos calls exitFullscreen() unguarded when this is false, which @@ -164,7 +150,7 @@ useUnloadGuard(() => !!dos && !quitting.value); onMounted(async () => { // The runtime reads nothing from the ROM payload, so let both loads overlap // instead of holding the 300 KB bundle behind the API roundtrip. - void loadRuntime().catch((e) => console.error(e)); + void loadJsDosRuntime().catch((e: unknown) => console.error(e)); const romResponse = await romApi.getRom({ romId }); rom.value = romResponse.data; diff --git a/frontend/src/v2/views/Player/jsDosRuntime.test.ts b/frontend/src/v2/views/Player/jsDosRuntime.test.ts new file mode 100644 index 000000000..2611dd391 --- /dev/null +++ b/frontend/src/v2/views/Player/jsDosRuntime.test.ts @@ -0,0 +1,105 @@ +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; + +const mocks = vi.hoisted(() => ({ + isJsResource: vi.fn(), + loadScript: vi.fn(), +})); + +vi.mock("@/v2/utils/scriptLoader", () => ({ + isJsResource: mocks.isJsResource, + loadScript: mocks.loadScript, +})); + +const LOCAL = "/assets/jsdos"; +const CDN = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist"; + +// The loader is a module-level singleton, so each case starts from a document +// that has never loaded it. +async function loadFresh() { + vi.resetModules(); + return import("./jsDosRuntime"); +} + +// Intercepted rather than inserted: a real would have the test +// environment go out and fetch the stylesheet. +beforeAll(() => { + vi.spyOn(document.head, "appendChild").mockImplementation((node) => node); +}); + +afterAll(() => { + vi.restoreAllMocks(); +}); + +function stylesheets(): string[] { + return vi + .mocked(document.head.appendChild) + .mock.calls.map(([node]) => (node as Element).getAttribute("href") ?? ""); +} + +beforeEach(() => { + vi.clearAllMocks(); + mocks.isJsResource.mockResolvedValue(true); + mocks.loadScript.mockResolvedValue(undefined); +}); + +describe("loadJsDosRuntime", () => { + it("serves the runtime from the local assets when they are present", async () => { + const { loadJsDosRuntime } = await loadFresh(); + + await expect(loadJsDosRuntime()).resolves.toBe(LOCAL); + expect(mocks.loadScript).toHaveBeenCalledWith(`${LOCAL}/js-dos.js`); + expect(stylesheets()).toContain(`${LOCAL}/js-dos.css`); + }); + + // Slim images and the Vite dev server ship no local copy, and both answer a + // missing asset with 200 + index.html rather than a 404. + it("falls back to the pinned CDN when the local path serves no JavaScript", async () => { + mocks.isJsResource.mockResolvedValue(false); + const { loadJsDosRuntime } = await loadFresh(); + + await expect(loadJsDosRuntime()).resolves.toBe(CDN); + expect(mocks.loadScript).toHaveBeenCalledWith(`${CDN}/js-dos.js`); + expect(stylesheets()).toContain(`${CDN}/js-dos.css`); + }); + + it("injects once however many views ask", async () => { + const { loadJsDosRuntime } = await loadFresh(); + + await loadJsDosRuntime(); + await expect(loadJsDosRuntime()).resolves.toBe(LOCAL); + + expect(mocks.loadScript).toHaveBeenCalledOnce(); + }); + + // Two views can mount in the same document before the first load resolves. + it("makes a second view wait on the load already in flight", async () => { + const { loadJsDosRuntime } = await loadFresh(); + + const [first, second] = await Promise.all([ + loadJsDosRuntime(), + loadJsDosRuntime(), + ]); + + expect(first).toBe(LOCAL); + expect(second).toBe(LOCAL); + expect(mocks.loadScript).toHaveBeenCalledOnce(); + }); + + it("lets a later view retry after a failed load", async () => { + mocks.loadScript.mockRejectedValueOnce(new Error("network")); + const { loadJsDosRuntime } = await loadFresh(); + + await expect(loadJsDosRuntime()).rejects.toThrow("network"); + await expect(loadJsDosRuntime()).resolves.toBe(LOCAL); + + expect(mocks.loadScript).toHaveBeenCalledTimes(2); + }); +}); diff --git a/frontend/src/v2/views/Player/jsDosRuntime.ts b/frontend/src/v2/views/Player/jsDosRuntime.ts new file mode 100644 index 000000000..42d65a046 --- /dev/null +++ b/frontend/src/v2/views/Player/jsDosRuntime.ts @@ -0,0 +1,37 @@ +// The js-dos runtime is a document-level singleton: one injection and one asset +// base however many launch views mount. Held as the in-flight promise, so a +// view mounting while another is still loading waits for that load instead of +// injecting a second copy of a runtime that declares its own globals. +import { isJsResource, loadScript } from "@/v2/utils/scriptLoader"; + +const LOCAL_BASE = "/assets/jsdos"; +// Fallback for slim images and the dev server, which ship no local copy. Pinned +// to the image's JSDOS_VERSION; jsDelivr sends the CORP a directly opened player +// document needs under its COEP. +const CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist"; + +let pending: Promise | null = null; + +/** Load the runtime, resolving with the base the emulator payloads follow. */ +export function loadJsDosRuntime(): Promise { + pending ??= inject().catch((error: unknown) => { + // A failed load is not the document's verdict, so let the next mount retry. + pending = null; + throw error; + }); + return pending; +} + +async function inject(): Promise { + const base = (await isJsResource(`${LOCAL_BASE}/js-dos.js`)) + ? LOCAL_BASE + : CDN_BASE; + + const css = document.createElement("link"); + css.rel = "stylesheet"; + css.href = `${base}/js-dos.css`; + document.head.appendChild(css); + + await loadScript(`${base}/js-dos.js`); + return base; +} diff --git a/frontend/src/v2/views/Player/launchIntent.test.ts b/frontend/src/v2/views/Player/launchIntent.test.ts index 38aa7ee95..124b68696 100644 --- a/frontend/src/v2/views/Player/launchIntent.test.ts +++ b/frontend/src/v2/views/Player/launchIntent.test.ts @@ -1,6 +1,31 @@ import { describe, expect, it } from "vitest"; +import type { FirmwareSchema, SaveSchema, StateSchema } from "@/__generated__"; import { existingSlot } from "@/v2/utils/saveSlots"; -import { isLaunchIntent, type LaunchIntent } from "./launchIntent"; +import { + isLaunchIntent, + launchIntentFor, + resolveLaunchIntent, + type LaunchIntent, + type LaunchOptions, + type LaunchSelection, +} from "./launchIntent"; + +const save = { id: 3, slot: "slot-2" } as SaveSchema; +const state = { id: 5, emulator: "snes9x" } as StateSchema; +const firmware = { id: 12, file_name: "bios.bin" } as FirmwareSchema; + +const OPTIONS: LaunchOptions = { + saves: [save], + states: [state], + firmware: [firmware], +}; + +const SELECTION: LaunchSelection = { + resume: { save, state: null }, + firmware, + slot: existingSlot("slot-2"), + customSlot: "", +}; const INTENT: LaunchIntent = { saveId: 3, @@ -10,21 +35,81 @@ const INTENT: LaunchIntent = { customSlot: "", }; +const EMPTY: LaunchSelection = { + resume: { save: null, state: null }, + firmware: null, + slot: { kind: "new" }, + customSlot: "my slot", +}; + +describe("launchIntentFor", () => { + it("names the selection by id", () => { + expect(launchIntentFor(SELECTION)).toEqual(INTENT); + }); + + it("names a state pick over a save", () => { + expect( + launchIntentFor({ ...SELECTION, resume: { save: null, state } }), + ).toEqual({ ...INTENT, saveId: null, stateId: 5 }); + }); + + it("carries a cleared selection", () => { + expect(launchIntentFor(EMPTY)).toEqual({ + saveId: null, + stateId: null, + firmwareId: null, + slot: { kind: "new" }, + customSlot: "my slot", + }); + }); +}); + +describe("resolveLaunchIntent", () => { + it("round-trips a selection through its intent", () => { + expect(resolveLaunchIntent(launchIntentFor(SELECTION), OPTIONS)).toEqual( + SELECTION, + ); + }); + + it("round-trips a cleared selection", () => { + expect(resolveLaunchIntent(launchIntentFor(EMPTY), OPTIONS)).toEqual(EMPTY); + }); + + // A save deleted from another tab, or a state the reloaded core cannot read, + // is simply not offered any more. + it.each([ + ["save", { ...INTENT, saveId: 99 }, "save"], + ["state", { ...INTENT, saveId: null, stateId: 99 }, "state"], + ])("drops a %s that is no longer offered", (_label, intent, key) => { + const resolved = resolveLaunchIntent(intent as LaunchIntent, OPTIONS); + + expect(resolved.resume[key as "save" | "state"]).toBeNull(); + }); + + it("drops firmware that is no longer offered", () => { + expect( + resolveLaunchIntent({ ...INTENT, firmwareId: 99 }, OPTIONS).firmware, + ).toBeNull(); + }); + + it("keeps the slot the session writes to", () => { + const resolved = resolveLaunchIntent( + { ...INTENT, slot: { kind: "new" }, customSlot: "speedrun" }, + OPTIONS, + ); + + expect(resolved.slot).toEqual({ kind: "new" }); + expect(resolved.customSlot).toBe("speedrun"); + }); +}); + describe("isLaunchIntent", () => { it("accepts what the view stores", () => { expect(isLaunchIntent(INTENT)).toBe(true); }); it("accepts a cleared selection", () => { - expect( - isLaunchIntent({ - saveId: null, - stateId: null, - firmwareId: null, - slot: { kind: "new" }, - customSlot: "my slot", - }), - ).toBe(true); + expect(isLaunchIntent(launchIntentFor(EMPTY))).toBe(true); }); it.each([ diff --git a/frontend/src/v2/views/Player/launchIntent.ts b/frontend/src/v2/views/Player/launchIntent.ts index 81794d982..7812bb143 100644 --- a/frontend/src/v2/views/Player/launchIntent.ts +++ b/frontend/src/v2/views/Player/launchIntent.ts @@ -1,8 +1,20 @@ // What the EmulatorJS launch view carries across the reload that isolates the -// document (see useIsolatedLaunch). The core and the disc are remembered per -// game already, so only the rest travels. +// document (see useIsolatedLaunch). Only ids travel, so the view resolves them +// again against what the server offers; the core and the disc are remembered +// per game already and need no part in this. +import type { FirmwareSchema, SaveSchema, StateSchema } from "@/__generated__"; import { isSlotChoice, type SlotChoice } from "@/v2/utils/saveSlots"; +import type { ResumeSelection } from "./resumeSelection"; +/** The pre-play selection a reload has to preserve. */ +export interface LaunchSelection { + resume: ResumeSelection; + firmware: FirmwareSchema | null; + slot: SlotChoice; + customSlot: string; +} + +/** That selection as ids, which is all a stored intent can hold. */ export interface LaunchIntent { saveId: number | null; stateId: number | null; @@ -11,6 +23,46 @@ export interface LaunchIntent { customSlot: string; } +/** What the view offers to pick from, on the other side of the reload. */ +export interface LaunchOptions { + saves: readonly SaveSchema[]; + states: readonly StateSchema[]; + firmware: readonly FirmwareSchema[]; +} + +export function launchIntentFor(selection: LaunchSelection): LaunchIntent { + return { + saveId: selection.resume.save?.id ?? null, + stateId: selection.resume.state?.id ?? null, + firmwareId: selection.firmware?.id ?? null, + slot: selection.slot, + customSlot: selection.customSlot, + }; +} + +/** The selection an intent names, dropping whatever is no longer offered. */ +export function resolveLaunchIntent( + intent: LaunchIntent, + options: LaunchOptions, +): LaunchSelection { + return { + resume: { + save: byId(options.saves, intent.saveId), + state: byId(options.states, intent.stateId), + }, + firmware: byId(options.firmware, intent.firmwareId), + slot: intent.slot, + customSlot: intent.customSlot, + }; +} + +function byId( + items: readonly T[], + id: number | null, +): T | null { + return items.find((item) => item.id === id) ?? null; +} + function isOptionalId(value: unknown): value is number | null { return value === null || typeof value === "number"; } diff --git a/frontend/test/playerIsolationHeaders.test.ts b/frontend/test/playerIsolationHeaders.test.ts new file mode 100644 index 000000000..4f50c4b36 --- /dev/null +++ b/frontend/test/playerIsolationHeaders.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it, vi } from "vitest"; +import { + isIsolatedPlayerUrl, + playerIsolationHeaders, +} from "../scripts/playerIsolationHeaders"; + +type Middleware = ( + req: { url?: string }, + res: { setHeader: (name: string, value: string) => void }, + next: () => void, +) => void; + +/** Drive the plugin's server hook and hand back the middleware it registered. */ +function middleware(): Middleware { + let registered: Middleware | undefined; + const { configureServer } = playerIsolationHeaders() as unknown as { + configureServer: (server: { + middlewares: { use: (fn: Middleware) => void }; + }) => void; + }; + configureServer({ + middlewares: { + use: (fn) => { + registered = fn; + }, + }, + }); + if (!registered) throw new Error("no middleware registered"); + return registered; +} + +function headersFor(url: string | undefined): Record { + const headers: Record = {}; + const next = vi.fn(); + middleware()( + { url }, + { + setHeader: (name, value) => { + headers[name] = value; + }, + }, + next, + ); + expect(next).toHaveBeenCalledOnce(); + return headers; +} + +const ISOLATED = { + "Cross-Origin-Embedder-Policy": "require-corp", + "Cross-Origin-Opener-Policy": "same-origin", +}; + +describe("isIsolatedPlayerUrl", () => { + it.each([ + "/rom/1/ejs", + "/rom/1/jsdos", + // The v2 players carry their state in the query, and nginx matches the + // request URI, so the query string has to be allowed for explicitly. + "/rom/1/ejs?core=snes9x", + "/console/rom/1/play", + ])("isolates %s", (url) => { + expect(isIsolatedPlayerUrl(url)).toBe(true); + }); + + it.each([ + "/rom/1", + "/rom/1/pico8", + "/rom/1/ruffle", + "/rom/1/stream", + "/platform/2", + "/api/roms/1/content/game.zip", + "/assets/emulatorjs/data/loader.js", + ])("leaves %s alone", (url) => { + expect(isIsolatedPlayerUrl(url)).toBe(false); + }); +}); + +describe("playerIsolationHeaders", () => { + it("isolates a player document", () => { + expect(headersFor("/rom/1/ejs")).toEqual(ISOLATED); + }); + + it("leaves every other document embeddable", () => { + expect(headersFor("/rom/1")).toEqual({}); + }); + + it("passes a request with no URL through", () => { + expect(headersFor(undefined)).toEqual({}); + }); +}); diff --git a/frontend/vite.config.js b/frontend/vite.config.js index f38b42a59..a72aed72d 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -6,29 +6,9 @@ import { defineConfig, loadEnv } from "vite"; import mkcert from "vite-plugin-mkcert"; import { VitePWA } from "vite-plugin-pwa"; import vuetify, { transformAssetUrls } from "vite-plugin-vuetify"; +import { playerIsolationHeaders } from "./scripts/playerIsolationHeaders"; import { precompress } from "./scripts/precompress"; -// Mirror of the nginx map that isolates the player documents (see -// docker/nginx/templates/default.conf.template), so a threaded EmulatorJS -// core boots on the dev server too, given a secure context (localhost or -// https). Like there, the query string is matched explicitly. -const ISOLATED_PLAYER_URL_RE = /^\/rom\/.*\/(ejs|jsdos)(\?|$)/; - -function playerIsolationHeaders() { - return { - name: "romm:player-isolation-headers", - configureServer(server) { - server.middlewares.use((req, res, next) => { - if (ISOLATED_PLAYER_URL_RE.test(req.url ?? "")) { - res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); - res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); - } - next(); - }); - }, - }; -} - // Vuetify components to preoptimize for faster dev startup const VUETIFY_COMPONENTS = [ "vuetify/components/transitions", From 6bf6ed25d231320d3ab0a1c9960b2b8f25c006b0 Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 05:44:52 +0200 Subject: [PATCH 3/4] refactor(v2): fold the cleanup pass findings into the launch path - The stream player restated the stop pair `useActivityPresence.stop()` now owns, so it calls it. - The dev server's isolation list and the nginx map it mirrors are checked against each other by a test, rather than by a comment asking whoever edits one to remember the other. - One case covers the js-dos runtime being injected once, whichever side of the first load a second view mounts on. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01R1VFUvsR5wYK3axxR1gebc --- frontend/scripts/playerIsolationHeaders.ts | 2 +- frontend/src/v2/views/Player/Stream.test.ts | 1 + frontend/src/v2/views/Player/Stream.vue | 3 +-- .../src/v2/views/Player/jsDosRuntime.test.ts | 18 ++++--------- frontend/test/playerIsolationHeaders.test.ts | 26 +++++++++++++++++++ 5 files changed, 34 insertions(+), 16 deletions(-) diff --git a/frontend/scripts/playerIsolationHeaders.ts b/frontend/scripts/playerIsolationHeaders.ts index 1d2deab86..d656a15e0 100644 --- a/frontend/scripts/playerIsolationHeaders.ts +++ b/frontend/scripts/playerIsolationHeaders.ts @@ -12,7 +12,7 @@ import type { Plugin } from "vite"; // One entry per entry of the map in docker/nginx/templates/default.conf.template, // matched the same way: against the full request URI rather than the path, since // there try_files rewrites the path to /index.html before the headers run. -const ISOLATED_PLAYER_URLS = [ +export const ISOLATED_PLAYER_URLS = [ /^\/rom\/.*\/(ejs|jsdos)(\?|$)/, /^\/console\/rom\/[0-9]+\/play/, ]; diff --git a/frontend/src/v2/views/Player/Stream.test.ts b/frontend/src/v2/views/Player/Stream.test.ts index 37a4554d5..3aab9dcd0 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -76,6 +76,7 @@ vi.mock("@/v2/composables/useActivityPresence", () => ({ start: vi.fn(), stopHeartbeat: vi.fn(), emitStop: vi.fn(), + stop: vi.fn(), }), })); diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index fd51b2971..3174ebb49 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -653,8 +653,7 @@ watch(gameRunning, (running, prev) => { nextTick(focusStream); } if (prev && !running) { - presence.stopHeartbeat(); - presence.emitStop(); + presence.stop(); nextTick(focusPlayButton); } }); diff --git a/frontend/src/v2/views/Player/jsDosRuntime.test.ts b/frontend/src/v2/views/Player/jsDosRuntime.test.ts index 2611dd391..8f5a29890 100644 --- a/frontend/src/v2/views/Player/jsDosRuntime.test.ts +++ b/frontend/src/v2/views/Player/jsDosRuntime.test.ts @@ -70,26 +70,18 @@ describe("loadJsDosRuntime", () => { expect(stylesheets()).toContain(`${CDN}/js-dos.css`); }); + // Views can mount in the same document either side of the first load + // resolving, and neither order may inject a second runtime. it("injects once however many views ask", async () => { const { loadJsDosRuntime } = await loadFresh(); - await loadJsDosRuntime(); - await expect(loadJsDosRuntime()).resolves.toBe(LOCAL); - - expect(mocks.loadScript).toHaveBeenCalledOnce(); - }); - - // Two views can mount in the same document before the first load resolves. - it("makes a second view wait on the load already in flight", async () => { - const { loadJsDosRuntime } = await loadFresh(); - - const [first, second] = await Promise.all([ + const concurrent = await Promise.all([ loadJsDosRuntime(), loadJsDosRuntime(), ]); + await expect(loadJsDosRuntime()).resolves.toBe(LOCAL); - expect(first).toBe(LOCAL); - expect(second).toBe(LOCAL); + expect(concurrent).toEqual([LOCAL, LOCAL]); expect(mocks.loadScript).toHaveBeenCalledOnce(); }); diff --git a/frontend/test/playerIsolationHeaders.test.ts b/frontend/test/playerIsolationHeaders.test.ts index 4f50c4b36..1e3efc5af 100644 --- a/frontend/test/playerIsolationHeaders.test.ts +++ b/frontend/test/playerIsolationHeaders.test.ts @@ -1,5 +1,8 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; import { describe, expect, it, vi } from "vitest"; import { + ISOLATED_PLAYER_URLS, isIsolatedPlayerUrl, playerIsolationHeaders, } from "../scripts/playerIsolationHeaders"; @@ -88,3 +91,26 @@ describe("playerIsolationHeaders", () => { expect(headersFor(undefined)).toEqual({}); }); }); + +// The dev server and nginx have to isolate the same documents, and nothing +// generates one list from the other, so the drift is what is tested. +describe("the nginx map it mirrors", () => { + // Vitest roots at frontend/, so the template sits one level above it. + const template = readFileSync( + resolve(process.cwd(), "../docker/nginx/templates/default.conf.template"), + "utf8", + ); + + it("isolates exactly the same URLs", () => { + const nginx = [ + ...template.matchAll(/^\s*~(\S+)\s+"(?:require-corp|same-origin)";/gm), + ].map((entry) => entry[1]); + // nginx patterns are unescaped, since the delimiter is whitespace there. + const mirrored = ISOLATED_PLAYER_URLS.map((pattern) => + pattern.source.replaceAll("\\/", "/"), + ); + + expect(nginx.length).toBeGreaterThan(0); + expect(new Set(nginx)).toEqual(new Set(mirrored)); + }); +}); From 5497ee9edb6625de8f7350582bca95485d64bebd Mon Sep 17 00:00:00 2001 From: zurdi Date: Thu, 17 Sep 2026 05:53:30 +0200 Subject: [PATCH 4/4] chore(v2): trim the launch-path comments and factor the test fixtures Comments down to the fact a reader cannot recover from the code, and the save, state and firmware fixtures behind one factory each rather than a cast per literal. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01R1VFUvsR5wYK3axxR1gebc --- frontend/scripts/playerIsolationHeaders.ts | 10 ++++------ .../composables/useActivityPresence/index.ts | 5 ++--- .../v2/composables/useIsolatedLaunch/index.ts | 18 +++++++----------- .../src/v2/composables/usePlayerExit/index.ts | 12 +++++------- frontend/src/v2/views/Player/EmulatorJS.vue | 10 ++++------ .../src/v2/views/Player/launchIntent.test.ts | 18 +++++++++++++++--- frontend/src/v2/views/Player/launchIntent.ts | 5 ++--- 7 files changed, 39 insertions(+), 39 deletions(-) diff --git a/frontend/scripts/playerIsolationHeaders.ts b/frontend/scripts/playerIsolationHeaders.ts index d656a15e0..f9a17ebdb 100644 --- a/frontend/scripts/playerIsolationHeaders.ts +++ b/frontend/scripts/playerIsolationHeaders.ts @@ -2,16 +2,14 @@ * playerIsolationHeaders: the dev server's twin of the nginx COOP/COEP map. * * Threaded EmulatorJS cores need SharedArrayBuffer, which only a cross-origin - * isolated document exposes. In production nginx attaches the headers to the - * player URLs alone, because the rest of the app embeds third-party images that - * COEP would block. Nothing sits in front of the dev server, so it answers the - * same URLs the same way. + * isolated document exposes, and only the player URLs may be isolated, since + * the rest of the app embeds third-party images that COEP would block. */ import type { Plugin } from "vite"; // One entry per entry of the map in docker/nginx/templates/default.conf.template, -// matched the same way: against the full request URI rather than the path, since -// there try_files rewrites the path to /index.html before the headers run. +// matched against the request URI as it is there, since try_files rewrites the +// path to /index.html before nginx reaches the headers. export const ISOLATED_PLAYER_URLS = [ /^\/rom\/.*\/(ejs|jsdos)(\?|$)/, /^\/console\/rom\/[0-9]+\/play/, diff --git a/frontend/src/v2/composables/useActivityPresence/index.ts b/frontend/src/v2/composables/useActivityPresence/index.ts index e3d482fb1..38dc816f9 100644 --- a/frontend/src/v2/composables/useActivityPresence/index.ts +++ b/frontend/src/v2/composables/useActivityPresence/index.ts @@ -40,9 +40,8 @@ export function useActivityPresence( immediate: false, }); - // A stop is addressed to the device, not to a rom, so one sent by a view - // that never announced anything would clear whatever else the device is - // playing. Only a started session stops, and only once. + // A stop is addressed to the device, not to a rom, so one sent without a + // session would clear whatever else that device is playing. let started = false; function start(): void { diff --git a/frontend/src/v2/composables/useIsolatedLaunch/index.ts b/frontend/src/v2/composables/useIsolatedLaunch/index.ts index 032700f08..112f244d1 100644 --- a/frontend/src/v2/composables/useIsolatedLaunch/index.ts +++ b/frontend/src/v2/composables/useIsolatedLaunch/index.ts @@ -1,13 +1,10 @@ // useIsolatedLaunch: reloading a player view into a cross-origin isolated -// document. -// -// A runtime that needs SharedArrayBuffer only gets it in a cross-origin -// isolated document, and a view reached by SPA navigation is not one. Nginx +// document, which is the only kind that exposes SharedArrayBuffer. Nginx // attaches the COOP/COEP headers to the player URLs, so reloading the view is -// what isolates it. What the user had set up crosses the reload as an intent -// kept per tab, and the view boots from it on arrival. +// what isolates it, and the pre-play selection crosses as an intent kept per +// tab. // -// Usage, in a player whose runtime (or one of its cores) needs it: +// In a player whose runtime, or one of its cores, needs it: // const { intent, relaunching, relaunch } = // useIsolatedLaunch("myplayer", romId, isMyIntent); // on Play: if (!hasSharedArrayBuffer()) { @@ -15,7 +12,7 @@ // return; // } // on mount: if (intent) { apply(intent); boot(); } -// Pair it with usePlayerExit, which drops the isolation again on the way out. +// Pair it with usePlayerExit, which drops the isolation on the way out. import { ref, type Ref } from "vue"; export function hasSharedArrayBuffer(): boolean { @@ -54,9 +51,8 @@ export function useIsolatedLaunch( return { intent, relaunching, relaunch }; } -// Storage access can be denied outright (a strict privacy mode, a blocked -// third-party context), and a player must open and run regardless, so both -// sides treat that as "no intent" rather than throwing through the view. +// Storage access can be denied outright, and a player has to open and run +// regardless, so both sides treat that as "no intent". function keepIntent(key: string, intent: unknown): boolean { try { diff --git a/frontend/src/v2/composables/usePlayerExit/index.ts b/frontend/src/v2/composables/usePlayerExit/index.ts index 3aed038f1..a8a78cb83 100644 --- a/frontend/src/v2/composables/usePlayerExit/index.ts +++ b/frontend/src/v2/composables/usePlayerExit/index.ts @@ -1,12 +1,10 @@ // usePlayerExit: how a player view hands the tab back to the app. // -// Two things can bind a player to its document. A player URL opened directly -// carries the COOP/COEP headers nginx attaches to it, and the resulting -// cross-origin isolation outlives every SPA navigation after it, blocking the -// third-party images the app embeds elsewhere (provider covers in Match ROM). -// And a runtime that declares globals when injected (EmulatorJS) cannot be -// injected a second time. Either way the exit is a full navigation, so the -// app resumes in a fresh document; otherwise it is an SPA navigation. +// Two things bind a player to its document: cross-origin isolation, which +// outlives every SPA navigation after it and blocks the third-party images the +// app embeds elsewhere, and a runtime that cannot be injected twice. Either +// leaves the app a fresh document to resume in; otherwise leaving is an SPA +// navigation. import { ref, type Ref } from "vue"; import { useRouter, type RouteLocationNormalized } from "vue-router"; diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index f187458b1..9c659e384 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -167,10 +167,9 @@ const { relaunch: relaunchIsolated, } = useIsolatedLaunch("ejs", romId, isLaunchIntent); -// The EmulatorJS loader declares top-level classes and instantiates the -// emulator, so a document it was injected into cannot host another launch. -// Tracked from the injection rather than from `window.EJS_emulator`, which a -// departure mid-load would not see yet. +// The EmulatorJS loader declares top-level classes, so a document it reached +// cannot host another launch. Tracked from the injection, which a departure +// taken mid-load would otherwise outrun. let runtimeInjected = false; const exit = usePlayerExit(() => runtimeInjected); @@ -278,8 +277,7 @@ async function onPlay() { } // Threaded cores need SharedArrayBuffer, which only a cross-origin isolated - // secure context exposes. A relaunch that still lacks it means the context - // itself is not secure. + // secure context exposes, so the launch may have to reload into one first. if ( selectedCore.value && areThreadsRequiredForEJSCore(selectedCore.value) && diff --git a/frontend/src/v2/views/Player/launchIntent.test.ts b/frontend/src/v2/views/Player/launchIntent.test.ts index 124b68696..a0256c0c4 100644 --- a/frontend/src/v2/views/Player/launchIntent.test.ts +++ b/frontend/src/v2/views/Player/launchIntent.test.ts @@ -10,9 +10,21 @@ import { type LaunchSelection, } from "./launchIntent"; -const save = { id: 3, slot: "slot-2" } as SaveSchema; -const state = { id: 5, emulator: "snes9x" } as StateSchema; -const firmware = { id: 12, file_name: "bios.bin" } as FirmwareSchema; +function makeSave(overrides: Partial = {}): SaveSchema { + return { id: 3, slot: "slot-2", ...overrides } as SaveSchema; +} + +function makeState(overrides: Partial = {}): StateSchema { + return { id: 5, emulator: "snes9x", ...overrides } as StateSchema; +} + +function makeFirmware(overrides: Partial = {}): FirmwareSchema { + return { id: 12, file_name: "bios.bin", ...overrides } as FirmwareSchema; +} + +const save = makeSave(); +const state = makeState(); +const firmware = makeFirmware(); const OPTIONS: LaunchOptions = { saves: [save], diff --git a/frontend/src/v2/views/Player/launchIntent.ts b/frontend/src/v2/views/Player/launchIntent.ts index 7812bb143..8bb4bca91 100644 --- a/frontend/src/v2/views/Player/launchIntent.ts +++ b/frontend/src/v2/views/Player/launchIntent.ts @@ -1,7 +1,6 @@ // What the EmulatorJS launch view carries across the reload that isolates the -// document (see useIsolatedLaunch). Only ids travel, so the view resolves them -// again against what the server offers; the core and the disc are remembered -// per game already and need no part in this. +// document (see useIsolatedLaunch). Only ids travel, so they are resolved again +// against what the server offers; the core and the disc persist per game. import type { FirmwareSchema, SaveSchema, StateSchema } from "@/__generated__"; import { isSlotChoice, type SlotChoice } from "@/v2/utils/saveSlots"; import type { ResumeSelection } from "./resumeSelection";