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",