diff --git a/docker-compose.yml b/docker-compose.yml index b64be6106..dd98867e6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -28,6 +28,7 @@ services: - /app/frontend/node_modules # Empty directory - /app/frontend/dist # Empty directory - ./romm_mock:/app/romm + - ./docker/nginx/templates:/app/docker/nginx/templates:ro - ~/.vite-plugin-mkcert:/app/.vite-plugin-mkcert depends_on: - romm-db-dev diff --git a/docker/nginx/templates/default.conf.template b/docker/nginx/templates/default.conf.template index 4a8ef969c..344db0bb2 100644 --- a/docker/nginx/templates/default.conf.template +++ b/docker/nginx/templates/default.conf.template @@ -18,7 +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. +# The dev server reads these entries from 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 8f9b295d1..cb882e17b 100644 --- a/docs/FRONTEND_ARCHITECTURE.md +++ b/docs/FRONTEND_ARCHITECTURE.md @@ -869,11 +869,11 @@ 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, 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. +- `usePlayerExit(runtimeBound, settle)` 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. A full navigation aborts the route change, so the leave guards of the components below never run: `settle` is where their work goes (EmulatorJS awaits the v1 `Player`'s save flush there). -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()`. +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. js-dos needs isolation unconditionally (the DOSBox-X backend is a threaded build), so `JsDos.vue` relaunches on every launch that did not arrive isolated and carries no intent beyond a marker. -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. +The dev server and `vite preview` have no nginx in front of them, so `scripts/playerIsolationHeaders.ts` answers the same URLs with the same headers. It parses the patterns out of the nginx template rather than restating them, and throws when that file yields none, so the template stays the only list. ### Platform Detection diff --git a/frontend/scripts/playerIsolationHeaders.ts b/frontend/scripts/playerIsolationHeaders.ts index f9a17ebdb..a6960e4e3 100644 --- a/frontend/scripts/playerIsolationHeaders.ts +++ b/frontend/scripts/playerIsolationHeaders.ts @@ -1,36 +1,52 @@ -/** - * 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, 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"; +// The dev server's stand-in for nginx's COOP/COEP map, reading its URLs from +// the template so the two cannot drift. Only the player URLs are isolated: +// COEP would block the third-party images the rest of the app embeds. +import { readFileSync } from "node:fs"; +import type { Connect, Plugin } from "vite"; -// One entry per entry of the map in docker/nginx/templates/default.conf.template, -// 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/, -]; +// The `~ "
";` entries of the COOP/COEP maps. nginx delimits +// those patterns by whitespace, so they carry no escaping to undo. +const MAP_ENTRY = /^\s*~(\S+)\s+"(?:require-corp|same-origin)";/gm; -/** 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)); +/** The URL patterns the nginx template isolates, as JS regexes. */ +export function isolatedPlayerUrls(templatePath: string): RegExp[] { + const template = readFileSync(templatePath, "utf8"); + const sources = new Set( + [...template.matchAll(MAP_ENTRY)].map((entry) => entry[1]!), + ); + if (sources.size === 0) { + throw new Error(`No COOP/COEP map entries in ${templatePath}`); + } + return [...sources].map((source) => new RegExp(source)); } -export function playerIsolationHeaders(): Plugin { +// nginx matches the request URI rather than the path, since try_files rewrites +// the path to /index.html before it reaches the headers. +function isIsolated(patterns: readonly RegExp[], url: string): boolean { + return patterns.some((pattern) => pattern.test(url)); +} + +// `vite preview` serves the built app with no nginx in front of it either, so +// it answers the player URLs the same way the dev server does. +export function playerIsolationHeaders(templatePath: string): Plugin { + const patterns = isolatedPlayerUrls(templatePath); + + const isolate: Connect.NextHandleFunction = (req, res, next) => { + if (isIsolated(patterns, req.url ?? "")) { + res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); + res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); + } + next(); + }; + return { name: "romm:player-isolation-headers", + apply: "serve", 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(); - }); + server.middlewares.use(isolate); + }, + configurePreviewServer(server) { + server.middlewares.use(isolate); }, }; } diff --git a/frontend/src/v2/composables/useIsolatedLaunch/index.ts b/frontend/src/v2/composables/useIsolatedLaunch/index.ts index 112f244d1..c4e93044e 100644 --- a/frontend/src/v2/composables/useIsolatedLaunch/index.ts +++ b/frontend/src/v2/composables/useIsolatedLaunch/index.ts @@ -1,24 +1,17 @@ // useIsolatedLaunch: reloading a player view into a cross-origin isolated -// 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, and the pre-play selection crosses as an intent kept per -// tab. -// -// 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 on the way out. +// document, the only kind that exposes SharedArrayBuffer. Nginx isolates the +// player URLs, so the reload is what earns it, and the pre-play selection +// crosses as an intent kept per tab. See also usePlayerExit. import { ref, type Ref } from "vue"; export function hasSharedArrayBuffer(): boolean { return typeof window.SharedArrayBuffer === "function"; } +/** Intent for a player with no pre-play selection: the relaunch is the message. */ +export const isRelaunchMarker = (value: unknown): value is true => + value === true; + export function useIsolatedLaunch( player: string, romId: number, diff --git a/frontend/src/v2/composables/usePlayerExit/index.test.ts b/frontend/src/v2/composables/usePlayerExit/index.test.ts index 3b99c100d..45d28fc9f 100644 --- a/frontend/src/v2/composables/usePlayerExit/index.test.ts +++ b/frontend/src/v2/composables/usePlayerExit/index.test.ts @@ -1,3 +1,4 @@ +import { flushPromises } from "@vue/test-utils"; import { afterAll, afterEach, @@ -9,12 +10,12 @@ import { } from "vitest"; import { usePlayerExit } from "./index"; -const push = vi.fn(); +const replace = vi.fn(); const locationReplace = vi.fn(); let originalLocation: Location; vi.mock("vue-router", () => ({ - useRouter: () => ({ push }), + useRouter: () => ({ replace }), })); function setIsolated(isolated: boolean) { @@ -40,8 +41,8 @@ afterAll(() => { }); afterEach(() => { - push.mockClear(); - locationReplace.mockClear(); + replace.mockClear(); + locationReplace.mockReset(); setIsolated(false); }); @@ -51,45 +52,82 @@ describe("usePlayerExit", () => { exit.leave("/rom/1"); - expect(push).toHaveBeenCalledWith("/rom/1"); + expect(replace).toHaveBeenCalledWith("/rom/1"); expect(locationReplace).not.toHaveBeenCalled(); expect(exit.departing.value).toBe(false); }); - it("replaces the document when it is cross-origin isolated", () => { + it("replaces the document when it is cross-origin isolated", async () => { setIsolated(true); const exit = usePlayerExit(); exit.leave("/rom/1"); + await flushPromises(); expect(locationReplace).toHaveBeenCalledWith("/rom/1"); - expect(push).not.toHaveBeenCalled(); + expect(replace).not.toHaveBeenCalled(); }); - it("replaces the document once a runtime is bound to it", () => { + it("replaces the document once a runtime is bound to it", async () => { const exit = usePlayerExit(() => true); exit.leave("/rom/1"); + await flushPromises(); expect(locationReplace).toHaveBeenCalledWith("/rom/1"); - expect(push).not.toHaveBeenCalled(); + expect(replace).not.toHaveBeenCalled(); }); - it("lets a route departure through when nothing binds the document", () => { + it("lets a route departure through when nothing binds the document", async () => { const exit = usePlayerExit(); - expect(exit.guard({ fullPath: "/platform/2" })).toBe(true); + await expect(exit.guard({ fullPath: "/platform/2" })).resolves.toBe(true); expect(locationReplace).not.toHaveBeenCalled(); }); - it("turns a route departure into a full navigation when bound", () => { + it("turns a route departure into a full navigation when bound", async () => { setIsolated(true); const exit = usePlayerExit(); - expect(exit.guard({ fullPath: "/platform/2" })).toBe(false); + await expect(exit.guard({ fullPath: "/platform/2" })).resolves.toBe(false); expect(locationReplace).toHaveBeenCalledWith("/platform/2"); }); + // What the departing document still owes runs while it is still there, since + // the aborted navigation leaves the guards below it unrun. + it("settles the document before replacing it", async () => { + setIsolated(true); + const settled: string[] = []; + locationReplace.mockImplementation(() => settled.push("replace")); + const exit = usePlayerExit( + () => false, + async () => { + await Promise.resolve(); + settled.push("settle"); + }, + ); + + await exit.guard({ fullPath: "/platform/2" }); + + expect(settled).toEqual(["settle", "replace"]); + }); + + it("replaces the document even when settling fails", async () => { + setIsolated(true); + const error = vi + .spyOn(console, "error") + .mockImplementation(() => undefined); + const exit = usePlayerExit( + () => false, + () => Promise.reject(new Error("nope")), + ); + + await exit.guard({ fullPath: "/platform/2" }); + + expect(locationReplace).toHaveBeenCalledWith("/platform/2"); + error.mockRestore(); + }); + // 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([ @@ -102,11 +140,12 @@ describe("usePlayerExit", () => { (exit: ReturnType) => exit.guard({ fullPath: "/rom/1" }), ], - ])("announces %s that replaces the document", (_label, act) => { + ])("announces %s that replaces the document", async (_label, act) => { setIsolated(true); const exit = usePlayerExit(); act(exit); + await flushPromises(); 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 a8a78cb83..76d789ded 100644 --- a/frontend/src/v2/composables/usePlayerExit/index.ts +++ b/frontend/src/v2/composables/usePlayerExit/index.ts @@ -1,23 +1,25 @@ -// usePlayerExit: how a player view hands the tab back to the app. -// -// 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. +// usePlayerExit: how a player view hands the tab back to the app. Cross-origin +// isolation outlives every SPA navigation after it and blocks the third-party +// images the app embeds elsewhere, and a runtime cannot always be injected +// twice, so a bound document is replaced rather than navigated away from. 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, + /** + * Work the departing document still owes, awaited before it is replaced. + * A replace aborts the navigation, so the guards below never run. + */ + settle: () => Promise | void = () => undefined, ): { /** 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. */ + /** Go to `path` in place of the player, so Back never re-enters it. */ leave: (path: string) => void; /** `onBeforeRouteLeave` guard: lets a departure through unless bound. */ - guard: (to: Pick) => boolean; + guard: (to: Pick) => Promise; } { const router = useRouter(); const departing = ref(false); @@ -26,19 +28,27 @@ export function usePlayerExit( return window.crossOriginIsolated || runtimeBound(); } - function replaceDocument(path: string): void { + async function replaceDocument(path: string): Promise { departing.value = true; + try { + await settle(); + } catch (error) { + // The document goes either way; stranding the user in the player is worse. + console.error("Player exit settle failed", error); + } window.location.replace(path); } function leave(path: string): void { - if (documentBound()) replaceDocument(path); - else void router.push(path); + if (documentBound()) void replaceDocument(path); + else void router.replace(path); } - function guard(to: Pick): boolean { + async function guard( + to: Pick, + ): Promise { if (!documentBound()) return true; - replaceDocument(to.fullPath); + await replaceDocument(to.fullPath); return false; } diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index 6e2e3d7ca..6f9535181 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -171,7 +171,16 @@ const { // cannot host another launch. Tracked from the injection, which a departure // taken mid-load would otherwise outrun. let runtimeInjected = false; -const exit = usePlayerExit(() => runtimeInjected); +const playerRef = ref<{ flushPendingSave: () => Promise } | null>(null); +const exit = usePlayerExit( + () => runtimeInjected, + async () => { + // The flush also uninstalls v1's auto-save sync, which is what keeps its + // own `beforeunload` handler from prompting on the way out. + await playerRef.value?.flushPendingSave(); + endSession(); + }, +); // A departure while a game runs is deliberate, so the unload prompt stays // quiet for the full navigation it turns into. @@ -192,7 +201,8 @@ function endSession() { 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. +// closes on the way out and, for a tab close, on pagehide. Both are +// idempotent, so no path records the session twice. useEventListener(window, "pagehide", endSession); declare global { @@ -342,17 +352,17 @@ function currentIntent(): LaunchIntent { } // What the view had selected before the reload, re-applied over the defaults. -function applyLaunchIntent(intent: LaunchIntent, current: DetailedRom) { +function applyLaunchIntent(intent: LaunchIntent) { const selection = resolveLaunchIntent(intent, { - saves: current.user_saves, + saves: rom.value?.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; + isSavesTabSelected.value = !resume.value.state; } // A slotted save fixes the write slot, and it stays put for the session @@ -448,7 +458,7 @@ onMounted(async () => { }); if (storedIntent) { - applyLaunchIntent(storedIntent, romResponse.data); + applyLaunchIntent(storedIntent); await nextTick(); void onPlay(); return; @@ -871,6 +881,7 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
({ flushPlaySession: vi.fn(), getRom: vi.fn(), loadRuntime: vi.fn(), + locationReload: vi.fn(), locationReplace: vi.fn(), playSessionStart: vi.fn(), - push: vi.fn(() => Promise.resolve()), + routerReplace: vi.fn(() => Promise.resolve()), confirm: vi.fn(), galleryRom: null as Record | null, routeLeaveGuard: null as ((to: { fullPath: string }) => unknown) | null, @@ -37,7 +38,7 @@ vi.mock("vue-router", () => ({ mocks.routeLeaveGuard = guard; }, useRoute: () => ({ params: { rom: "1" } }), - useRouter: () => ({ push: mocks.push }), + useRouter: () => ({ replace: mocks.routerReplace }), })); vi.mock("@/plugins/router", () => ({ @@ -118,23 +119,34 @@ const rom = { rom_user: { status: null }, }; +// The runtime is mocked, so any base will do as long as the payloads follow it. const LOCAL_BASE = "/assets/jsdos"; -const CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist"; +const CDN_BASE = "https://cdn.example/js-dos/dist"; let originalLocation: Location; +// The launch needs SharedArrayBuffer for the threaded DOSBox-X build, and a +// document that has it is one the reload no longer has to produce. function setIsolated(isolated: boolean) { Object.defineProperty(window, "crossOriginIsolated", { configurable: true, value: isolated, }); + Object.defineProperty(window, "SharedArrayBuffer", { + configurable: true, + value: isolated ? ArrayBuffer : undefined, + }); } beforeAll(() => { originalLocation = window.location; Object.defineProperty(window, "location", { configurable: true, - value: { ...originalLocation, replace: mocks.locationReplace }, + value: { + ...originalLocation, + reload: mocks.locationReload, + replace: mocks.locationReplace, + }, }); vi.spyOn(console, "error").mockImplementation(() => undefined); }); @@ -150,7 +162,8 @@ afterAll(() => { beforeEach(() => { vi.clearAllMocks(); - setIsolated(false); + sessionStorage.clear(); + setIsolated(true); mocks.loadRuntime.mockResolvedValue(LOCAL_BASE); mocks.galleryRom = null; mocks.routeLeaveGuard = null; @@ -232,6 +245,62 @@ describe("JsDos runtime loading", () => { }); }); +// Threaded DOSBox-X needs SharedArrayBuffer, which only a cross-origin +// isolated document exposes, and an SPA navigation reaches the view without +// one. See useIsolatedLaunch. +describe("JsDos isolated launch", () => { + function setSecureContext(secure: boolean) { + Object.defineProperty(window, "isSecureContext", { + configurable: true, + value: secure, + }); + } + + it("reloads into an isolated document instead of booting without one", async () => { + setIsolated(false); + setSecureContext(true); + const wrapper = mountView(); + await flushPromises(); + window.Dos = vi.fn(); + + await wrapper.get(".r-v2-player__play").trigger("click"); + await flushPromises(); + + expect(window.Dos).not.toHaveBeenCalled(); + expect(mocks.locationReload).toHaveBeenCalledOnce(); + expect(sessionStorage.getItem("player:1:jsdos:launch")).toBe("true"); + wrapper.unmount(); + }); + + it("boots straight away on the other side of the reload", async () => { + sessionStorage.setItem("player:1:jsdos:launch", "true"); + const handle = makeHandle(); + const factory = vi.fn(() => handle); + window.Dos = factory; + const wrapper = mountView(); + await flushPromises(); + + expect(factory).toHaveBeenCalledOnce(); + expect(mocks.playSessionStart).toHaveBeenCalledOnce(); + wrapper.unmount(); + }); + + it("reports the context when no reload can produce one", async () => { + setIsolated(false); + setSecureContext(false); + const wrapper = mountView(); + await flushPromises(); + window.Dos = vi.fn(); + + await wrapper.get(".r-v2-player__play").trigger("click"); + await flushPromises(); + + expect(mocks.locationReload).not.toHaveBeenCalled(); + expect(mocks.snackbarError).toHaveBeenCalledWith("play.https-required"); + wrapper.unmount(); + }); +}); + describe("JsDos player exit", () => { it("reports when the runtime defined no factory", async () => { const wrapper = mountView(); @@ -263,7 +332,7 @@ describe("JsDos player exit", () => { wrapper.unmount(); }); - it("leaves within the app after saving without awaiting stop", async () => { + it("replaces the document after saving without awaiting stop", async () => { const handle = makeHandle(); const wrapper = await mountPlayer(handle); @@ -272,8 +341,8 @@ describe("JsDos player exit", () => { expect(handle.save).toHaveBeenCalledOnce(); expect(handle.stop).toHaveBeenCalledOnce(); - expect(mocks.push).toHaveBeenCalledWith("/rom/1"); - expect(mocks.locationReplace).not.toHaveBeenCalled(); + expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); + expect(mocks.routerReplace).not.toHaveBeenCalled(); expect(mocks.flushPlaySession).toHaveBeenCalledOnce(); expect(mocks.setPlaying).toHaveBeenLastCalledWith(false); wrapper.unmount(); @@ -292,25 +361,29 @@ describe("JsDos player exit", () => { expect(handle.save).toHaveBeenCalledOnce(); expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); - expect(mocks.push).not.toHaveBeenCalled(); + expect(mocks.routerReplace).not.toHaveBeenCalled(); wrapper.unmount(); }); it("lets a departure from the launch view through", async () => { + setIsolated(false); const wrapper = mountView(); await flushPromises(); - expect(mocks.routeLeaveGuard?.({ fullPath: "/platform/2" })).toBe(true); + await expect( + mocks.routeLeaveGuard?.({ fullPath: "/platform/2" }), + ).resolves.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); + await expect( + mocks.routeLeaveGuard?.({ fullPath: "/platform/2" }), + ).resolves.toBe(false); expect(mocks.locationReplace).toHaveBeenCalledWith("/platform/2"); wrapper.unmount(); }); @@ -326,7 +399,7 @@ describe("JsDos player exit", () => { "play.stream-save-unconfirmed", ); expect(handle.stop).not.toHaveBeenCalled(); - expect(mocks.push).not.toHaveBeenCalled(); + expect(mocks.routerReplace).not.toHaveBeenCalled(); expect(mocks.locationReplace).not.toHaveBeenCalled(); expect(mocks.flushPlaySession).not.toHaveBeenCalled(); expect(mocks.setPlaying).not.toHaveBeenCalledWith(false); @@ -347,7 +420,7 @@ describe("JsDos player exit", () => { expect(handle.stop).toHaveBeenCalledOnce(); expect(mocks.flushPlaySession).toHaveBeenCalledOnce(); expect(mocks.setPlaying).toHaveBeenLastCalledWith(false); - expect(mocks.push).toHaveBeenCalledWith("/rom/1"); + expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); wrapper.unmount(); }); @@ -363,7 +436,7 @@ describe("JsDos player exit", () => { "play.stream-save-unconfirmed", ); expect(handle.stop).not.toHaveBeenCalled(); - expect(mocks.push).not.toHaveBeenCalled(); + expect(mocks.locationReplace).not.toHaveBeenCalled(); wrapper.unmount(); }); @@ -383,7 +456,7 @@ describe("JsDos player exit", () => { finishSave?.(true); await flushPromises(); - expect(mocks.push).toHaveBeenCalledOnce(); + expect(mocks.locationReplace).toHaveBeenCalledOnce(); wrapper.unmount(); }); @@ -403,8 +476,8 @@ describe("JsDos player exit", () => { finishSave?.(true); await flushPromises(); - expect(mocks.push).toHaveBeenCalledOnce(); - expect(mocks.push).toHaveBeenCalledWith("/rom/1"); + expect(mocks.locationReplace).toHaveBeenCalledOnce(); + expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); wrapper.unmount(); }); @@ -416,7 +489,7 @@ describe("JsDos player exit", () => { await flushPromises(); expect(handle.save).toHaveBeenCalledOnce(); - expect(mocks.push).toHaveBeenCalledWith("/platform/2"); + expect(mocks.locationReplace).toHaveBeenCalledWith("/platform/2"); wrapper.unmount(); }); diff --git a/frontend/src/v2/views/Player/JsDos.vue b/frontend/src/v2/views/Player/JsDos.vue index 6b4aab5b0..d6104e79e 100644 --- a/frontend/src/v2/views/Player/JsDos.vue +++ b/frontend/src/v2/views/Player/JsDos.vue @@ -1,5 +1,6 @@ @@ -172,7 +200,7 @@ onBeforeUnmount(teardown); :title="title" :platform-label="platformLabel" :rom-id="romId" - :ready="!!rom" + :ready="!!rom && !relaunching" :running="gameRunning" :quitting="quitting" @play="onPlay" diff --git a/frontend/src/v2/views/Player/jsDosRuntime.test.ts b/frontend/src/v2/views/Player/jsDosRuntime.test.ts index 8f5a29890..92feae1fa 100644 --- a/frontend/src/v2/views/Player/jsDosRuntime.test.ts +++ b/frontend/src/v2/views/Player/jsDosRuntime.test.ts @@ -7,6 +7,8 @@ import { it, vi, } from "vitest"; +// Re-imported per case below, but the bases are the same strings either way. +import { CDN_BASE as CDN, LOCAL_BASE as LOCAL } from "./jsDosRuntime"; const mocks = vi.hoisted(() => ({ isJsResource: vi.fn(), @@ -18,9 +20,6 @@ vi.mock("@/v2/utils/scriptLoader", () => ({ 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() { diff --git a/frontend/src/v2/views/Player/jsDosRuntime.ts b/frontend/src/v2/views/Player/jsDosRuntime.ts index 42d65a046..4e1d2bee2 100644 --- a/frontend/src/v2/views/Player/jsDosRuntime.ts +++ b/frontend/src/v2/views/Player/jsDosRuntime.ts @@ -1,16 +1,16 @@ -// 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. +// The js-dos runtime is a document-level singleton, held as the in-flight +// promise so a second mount waits for that load rather than injecting another +// 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"; +export const LOCAL_BASE = "/assets/jsdos"; +// Fallback for slim images and the dev server, pinned to the image's +// JSDOS_VERSION. jsDelivr sends the CORP the player's COEP needs. +export const CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist"; let pending: Promise | null = null; +// A retry after a failed script load would otherwise stack a second stylesheet. +let styledBase: string | null = null; /** Load the runtime, resolving with the base the emulator payloads follow. */ export function loadJsDosRuntime(): Promise { @@ -27,10 +27,13 @@ async function inject(): Promise { ? LOCAL_BASE : CDN_BASE; - const css = document.createElement("link"); - css.rel = "stylesheet"; - css.href = `${base}/js-dos.css`; - document.head.appendChild(css); + if (styledBase !== base) { + const css = document.createElement("link"); + css.rel = "stylesheet"; + css.href = `${base}/js-dos.css`; + document.head.appendChild(css); + styledBase = base; + } 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 a0256c0c4..e28b2a8a8 100644 --- a/frontend/src/v2/views/Player/launchIntent.test.ts +++ b/frontend/src/v2/views/Player/launchIntent.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import type { FirmwareSchema, SaveSchema, StateSchema } from "@/__generated__"; -import { existingSlot } from "@/v2/utils/saveSlots"; +import { existingSlot, NEW_SLOT_CHOICE } from "@/v2/utils/saveSlots"; import { isLaunchIntent, launchIntentFor, @@ -9,13 +9,24 @@ import { type LaunchOptions, type LaunchSelection, } from "./launchIntent"; +import type { ResumeSelection } from "./resumeSelection"; function makeSave(overrides: Partial = {}): SaveSchema { - return { id: 3, slot: "slot-2", ...overrides } as SaveSchema; + return { + id: 3, + file_name: "3.srm", + slot: "slot-2", + ...overrides, + } as SaveSchema; } function makeState(overrides: Partial = {}): StateSchema { - return { id: 5, emulator: "snes9x", ...overrides } as StateSchema; + return { + id: 5, + file_name: "5.state", + emulator: "snes9x", + ...overrides, + } as StateSchema; } function makeFirmware(overrides: Partial = {}): FirmwareSchema { @@ -89,13 +100,12 @@ describe("resolveLaunchIntent", () => { // 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(); + const dropped: [keyof ResumeSelection, LaunchIntent][] = [ + ["save", { ...INTENT, saveId: 99 }], + ["state", { ...INTENT, saveId: null, stateId: 99 }], + ]; + it.each(dropped)("drops a %s that is no longer offered", (key, intent) => { + expect(resolveLaunchIntent(intent, OPTIONS).resume[key]).toBeNull(); }); it("drops firmware that is no longer offered", () => { @@ -106,11 +116,11 @@ describe("resolveLaunchIntent", () => { it("keeps the slot the session writes to", () => { const resolved = resolveLaunchIntent( - { ...INTENT, slot: { kind: "new" }, customSlot: "speedrun" }, + { ...INTENT, slot: NEW_SLOT_CHOICE, customSlot: "speedrun" }, OPTIONS, ); - expect(resolved.slot).toEqual({ kind: "new" }); + expect(resolved.slot).toEqual(NEW_SLOT_CHOICE); expect(resolved.customSlot).toBe("speedrun"); }); }); diff --git a/frontend/src/v2/views/Player/launchIntent.ts b/frontend/src/v2/views/Player/launchIntent.ts index 8bb4bca91..c548a32dd 100644 --- a/frontend/src/v2/views/Player/launchIntent.ts +++ b/frontend/src/v2/views/Player/launchIntent.ts @@ -62,20 +62,19 @@ function byId( return items.find((item) => item.id === id) ?? null; } -function isOptionalId(value: unknown): value is number | null { - return value === null || typeof value === "number"; +const ID_KEYS = ["saveId", "stateId", "firmwareId"] as const; + +function hasOptionalId(value: object, key: string): boolean { + if (!(key in value)) return false; + const id = (value as Record)[key]; + return id === null || typeof id === "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) && + ID_KEYS.every((key) => hasOptionalId(value, key)) && "slot" in value && isSlotChoice(value.slot) && "customSlot" in value && diff --git a/frontend/src/views/Player/EmulatorJS/Player.vue b/frontend/src/views/Player/EmulatorJS/Player.vue index 9f2e4f478..6ab1a605a 100644 --- a/frontend/src/views/Player/EmulatorJS/Player.vue +++ b/frontend/src/views/Player/EmulatorJS/Player.vue @@ -422,6 +422,9 @@ async function flushPendingSave() { } } onBeforeRouteLeave(flushPendingSave); +// A v2 shell that leaves by replacing the document aborts the navigation, so +// the guard above never runs and the flush has to be asked for. Idempotent. +defineExpose({ flushPendingSave }); // Closing the tab cancels requests in flight, so a save the tick has not // uploaded goes out on `pagehide` with fetch keepalive, which the browser caps // at 64 KB. `beforeunload` asks first while one is pending: for a bigger save diff --git a/frontend/test/playerIsolationHeaders.test.ts b/frontend/test/playerIsolationHeaders.test.ts index 1e3efc5af..af6065291 100644 --- a/frontend/test/playerIsolationHeaders.test.ts +++ b/frontend/test/playerIsolationHeaders.test.ts @@ -1,27 +1,34 @@ -import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; import { describe, expect, it, vi } from "vitest"; import { - ISOLATED_PLAYER_URLS, - isIsolatedPlayerUrl, + isolatedPlayerUrls, playerIsolationHeaders, } from "../scripts/playerIsolationHeaders"; +// Vitest roots at frontend/, so the template sits one level above it. +const TEMPLATE = resolve( + process.cwd(), + "../docker/nginx/templates/default.conf.template", +); + 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 { +type ServerHook = "configureServer" | "configurePreviewServer"; + +/** Drive one of the plugin's server hooks and hand back its middleware. */ +function middleware(hook: ServerHook = "configureServer"): Middleware { let registered: Middleware | undefined; - const { configureServer } = playerIsolationHeaders() as unknown as { - configureServer: (server: { - middlewares: { use: (fn: Middleware) => void }; - }) => void; - }; - configureServer({ + const plugin = playerIsolationHeaders(TEMPLATE) as unknown as Record< + ServerHook, + (server: { middlewares: { use: (fn: Middleware) => void } }) => void + >; + plugin[hook]({ middlewares: { use: (fn) => { registered = fn; @@ -32,10 +39,13 @@ function middleware(): Middleware { return registered; } -function headersFor(url: string | undefined): Record { +function headersFor( + url: string | undefined, + hook?: ServerHook, +): Record { const headers: Record = {}; const next = vi.fn(); - middleware()( + middleware(hook)( { url }, { setHeader: (name, value) => { @@ -53,7 +63,40 @@ const ISOLATED = { "Cross-Origin-Opener-Policy": "same-origin", }; -describe("isIsolatedPlayerUrl", () => { +/** A template holding `body` where the real one holds its maps. */ +function templateWith(body: string): string { + const dir = mkdtempSync(join(tmpdir(), "romm-nginx-")); + const path = join(dir, "default.conf.template"); + writeFileSync(path, body, "utf8"); + return path; +} + +describe("isolatedPlayerUrls", () => { + it("reads the patterns the shipped template isolates", () => { + const patterns = isolatedPlayerUrls(TEMPLATE); + + expect(patterns.some((p) => p.test("/rom/1/ejs"))).toBe(true); + expect(patterns.some((p) => p.test("/console/rom/1/play"))).toBe(true); + }); + + // The template is the only list, so a rename that silently isolates nothing + // would leave the dev server serving no headers at all. + it("refuses a template with no map entries", () => { + const path = templateWith( + 'map $request_uri $coep_header {\n default "";\n}\n', + ); + + expect(() => isolatedPlayerUrls(path)).toThrow(/No COOP\/COEP map entries/); + }); + + it("refuses a template that is not there", () => { + expect(() => + isolatedPlayerUrls("/nowhere/default.conf.template"), + ).toThrow(); + }); +}); + +describe("playerIsolationHeaders", () => { it.each([ "/rom/1/ejs", "/rom/1/jsdos", @@ -62,7 +105,7 @@ describe("isIsolatedPlayerUrl", () => { "/rom/1/ejs?core=snes9x", "/console/rom/1/play", ])("isolates %s", (url) => { - expect(isIsolatedPlayerUrl(url)).toBe(true); + expect(headersFor(url)).toEqual(ISOLATED); }); it.each([ @@ -73,44 +116,28 @@ describe("isIsolatedPlayerUrl", () => { "/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({}); + ])("leaves %s embeddable", (url) => { + expect(headersFor(url)).toEqual({}); }); it("passes a request with no URL through", () => { 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("\\/", "/"), + // `vite preview` has no nginx in front of it either. + it("isolates a player document on the preview server too", () => { + expect(headersFor("/rom/1/ejs", "configurePreviewServer")).toEqual( + ISOLATED, + ); + }); +}); + +// The plugin config is what vite.config.js passes it, and a moved template +// would otherwise only surface as a dev server serving no headers. +describe("the template vite.config.js points at", () => { + it("is the one the tests read", () => { + expect(readFileSync("vite.config.js", "utf8")).toContain( + "../docker/nginx/templates/default.conf.template", ); - - expect(nginx.length).toBeGreaterThan(0); - expect(new Set(nginx)).toEqual(new Set(mirrored)); }); }); diff --git a/frontend/vite.config.js b/frontend/vite.config.js index a72aed72d..661c167c5 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -150,7 +150,14 @@ export default defineConfig(({ mode }) => { }, }), precompress(), - playerIsolationHeaders(), + playerIsolationHeaders( + fileURLToPath( + new URL( + "../docker/nginx/templates/default.conf.template", + import.meta.url, + ), + ), + ), httpsMode && mkcert({ savePath: "/app/.vite-plugin-mkcert",