From 3eadc4c33c5d2ca52b2f97756dcd881f46a031a2 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Sep 2026 07:39:31 -0400 Subject: [PATCH 1/6] fix(v2): apply the code review fixes to the launch path Replace the player entry when leaving by SPA navigation, keep a failed js-dos runtime load from stacking a second stylesheet, and answer the player URLs from `vite preview` as well as the dev server. Co-Authored-By: Claude Opus 5 (1M context) --- frontend/scripts/playerIsolationHeaders.ts | 24 +++++++++----- .../composables/usePlayerExit/index.test.ts | 12 +++---- .../src/v2/composables/usePlayerExit/index.ts | 8 +++-- frontend/src/v2/views/Player/JsDos.test.ts | 22 ++++++------- frontend/src/v2/views/Player/jsDosRuntime.ts | 13 +++++--- frontend/test/playerIsolationHeaders.test.ts | 31 +++++++++++++------ 6 files changed, 69 insertions(+), 41 deletions(-) diff --git a/frontend/scripts/playerIsolationHeaders.ts b/frontend/scripts/playerIsolationHeaders.ts index f9a17ebdb..d0573c88b 100644 --- a/frontend/scripts/playerIsolationHeaders.ts +++ b/frontend/scripts/playerIsolationHeaders.ts @@ -5,7 +5,7 @@ * 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"; +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 @@ -20,17 +20,25 @@ export function isIsolatedPlayerUrl(url: string): boolean { return ISOLATED_PLAYER_URLS.some((pattern) => pattern.test(url)); } +const isolate: Connect.NextHandleFunction = (req, res, next) => { + if (isIsolatedPlayerUrl(req.url ?? "")) { + res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); + res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); + } + next(); +}; + +// `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(): Plugin { 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/usePlayerExit/index.test.ts b/frontend/src/v2/composables/usePlayerExit/index.test.ts index 3b99c100d..1ade04136 100644 --- a/frontend/src/v2/composables/usePlayerExit/index.test.ts +++ b/frontend/src/v2/composables/usePlayerExit/index.test.ts @@ -9,12 +9,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,7 +40,7 @@ afterAll(() => { }); afterEach(() => { - push.mockClear(); + replace.mockClear(); locationReplace.mockClear(); setIsolated(false); }); @@ -51,7 +51,7 @@ 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); }); @@ -63,7 +63,7 @@ describe("usePlayerExit", () => { exit.leave("/rom/1"); expect(locationReplace).toHaveBeenCalledWith("/rom/1"); - expect(push).not.toHaveBeenCalled(); + expect(replace).not.toHaveBeenCalled(); }); it("replaces the document once a runtime is bound to it", () => { @@ -72,7 +72,7 @@ describe("usePlayerExit", () => { exit.leave("/rom/1"); expect(locationReplace).toHaveBeenCalledWith("/rom/1"); - expect(push).not.toHaveBeenCalled(); + expect(replace).not.toHaveBeenCalled(); }); it("lets a route departure through when nothing binds the document", () => { diff --git a/frontend/src/v2/composables/usePlayerExit/index.ts b/frontend/src/v2/composables/usePlayerExit/index.ts index a8a78cb83..f26c09ce1 100644 --- a/frontend/src/v2/composables/usePlayerExit/index.ts +++ b/frontend/src/v2/composables/usePlayerExit/index.ts @@ -14,7 +14,11 @@ export function usePlayerExit( ): { /** 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, by a full navigation when the document + * is bound. The player is replaced either way, so Back never re-enters the + * view it just left and relaunches the game. + */ leave: (path: string) => void; /** `onBeforeRouteLeave` guard: lets a departure through unless bound. */ guard: (to: Pick) => boolean; @@ -33,7 +37,7 @@ export function usePlayerExit( function leave(path: string): void { if (documentBound()) replaceDocument(path); - else void router.push(path); + else void router.replace(path); } function guard(to: Pick): boolean { diff --git a/frontend/src/v2/views/Player/JsDos.test.ts b/frontend/src/v2/views/Player/JsDos.test.ts index 1a300b507..6b2f0314b 100644 --- a/frontend/src/v2/views/Player/JsDos.test.ts +++ b/frontend/src/v2/views/Player/JsDos.test.ts @@ -18,7 +18,7 @@ const mocks = vi.hoisted(() => ({ loadRuntime: 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 +37,7 @@ vi.mock("vue-router", () => ({ mocks.routeLeaveGuard = guard; }, useRoute: () => ({ params: { rom: "1" } }), - useRouter: () => ({ push: mocks.push }), + useRouter: () => ({ replace: mocks.routerReplace }), })); vi.mock("@/plugins/router", () => ({ @@ -272,7 +272,7 @@ describe("JsDos player exit", () => { expect(handle.save).toHaveBeenCalledOnce(); expect(handle.stop).toHaveBeenCalledOnce(); - expect(mocks.push).toHaveBeenCalledWith("/rom/1"); + expect(mocks.routerReplace).toHaveBeenCalledWith("/rom/1"); expect(mocks.locationReplace).not.toHaveBeenCalled(); expect(mocks.flushPlaySession).toHaveBeenCalledOnce(); expect(mocks.setPlaying).toHaveBeenLastCalledWith(false); @@ -292,7 +292,7 @@ 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(); }); @@ -326,7 +326,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 +347,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.routerReplace).toHaveBeenCalledWith("/rom/1"); wrapper.unmount(); }); @@ -363,7 +363,7 @@ describe("JsDos player exit", () => { "play.stream-save-unconfirmed", ); expect(handle.stop).not.toHaveBeenCalled(); - expect(mocks.push).not.toHaveBeenCalled(); + expect(mocks.routerReplace).not.toHaveBeenCalled(); wrapper.unmount(); }); @@ -383,7 +383,7 @@ describe("JsDos player exit", () => { finishSave?.(true); await flushPromises(); - expect(mocks.push).toHaveBeenCalledOnce(); + expect(mocks.routerReplace).toHaveBeenCalledOnce(); wrapper.unmount(); }); @@ -403,8 +403,8 @@ describe("JsDos player exit", () => { finishSave?.(true); await flushPromises(); - expect(mocks.push).toHaveBeenCalledOnce(); - expect(mocks.push).toHaveBeenCalledWith("/rom/1"); + expect(mocks.routerReplace).toHaveBeenCalledOnce(); + expect(mocks.routerReplace).toHaveBeenCalledWith("/rom/1"); wrapper.unmount(); }); @@ -416,7 +416,7 @@ describe("JsDos player exit", () => { await flushPromises(); expect(handle.save).toHaveBeenCalledOnce(); - expect(mocks.push).toHaveBeenCalledWith("/platform/2"); + expect(mocks.routerReplace).toHaveBeenCalledWith("/platform/2"); wrapper.unmount(); }); diff --git a/frontend/src/v2/views/Player/jsDosRuntime.ts b/frontend/src/v2/views/Player/jsDosRuntime.ts index 42d65a046..adb29ae3e 100644 --- a/frontend/src/v2/views/Player/jsDosRuntime.ts +++ b/frontend/src/v2/views/Player/jsDosRuntime.ts @@ -11,6 +11,8 @@ const LOCAL_BASE = "/assets/jsdos"; 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 +29,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/test/playerIsolationHeaders.test.ts b/frontend/test/playerIsolationHeaders.test.ts index 1e3efc5af..aa2801c73 100644 --- a/frontend/test/playerIsolationHeaders.test.ts +++ b/frontend/test/playerIsolationHeaders.test.ts @@ -13,15 +13,16 @@ type Middleware = ( 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() as unknown as Record< + ServerHook, + (server: { middlewares: { use: (fn: Middleware) => void } }) => void + >; + plugin[hook]({ middlewares: { use: (fn) => { registered = fn; @@ -32,10 +33,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) => { @@ -90,6 +94,13 @@ describe("playerIsolationHeaders", () => { it("passes a request with no URL through", () => { expect(headersFor(undefined)).toEqual({}); }); + + // `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 dev server and nginx have to isolate the same documents, and nothing From 0ccda23164061db0eba2a774aa13f9a4893f3e54 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Sep 2026 07:47:39 -0400 Subject: [PATCH 2/6] fix(v2): keep the save flush and the js-dos isolation on the launch path A full navigation out of the player aborts the route change, so the leave guards below the view never run and the v1 player's pending save was lost. `usePlayerExit` now settles the departing document first, and EmulatorJS asks the v1 `Player` for its flush there. js-dos reached its view by SPA navigation without cross-origin isolation, although the DOSBox-X backend is a threaded build and nginx has always isolated its URL. It now relaunches into an isolated document the way EmulatorJS does, so the view still opens without a page load. Co-Authored-By: Claude Opus 5 (1M context) --- docs/FRONTEND_ARCHITECTURE.md | 4 +- .../composables/usePlayerExit/index.test.ts | 55 ++++++++-- .../src/v2/composables/usePlayerExit/index.ts | 24 ++++- frontend/src/v2/views/Player/EmulatorJS.vue | 13 ++- frontend/src/v2/views/Player/JsDos.test.ts | 100 +++++++++++++++--- frontend/src/v2/views/Player/JsDos.vue | 30 +++++- .../src/views/Player/EmulatorJS/Player.vue | 3 + 7 files changed, 196 insertions(+), 33 deletions(-) diff --git a/docs/FRONTEND_ARCHITECTURE.md b/docs/FRONTEND_ARCHITECTURE.md index 8f9b295d1..b3f0b5aa9 100644 --- a/docs/FRONTEND_ARCHITECTURE.md +++ b/docs/FRONTEND_ARCHITECTURE.md @@ -869,9 +869,9 @@ 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. diff --git a/frontend/src/v2/composables/usePlayerExit/index.test.ts b/frontend/src/v2/composables/usePlayerExit/index.test.ts index 1ade04136..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, @@ -41,7 +42,7 @@ afterAll(() => { afterEach(() => { replace.mockClear(); - locationReplace.mockClear(); + locationReplace.mockReset(); setIsolated(false); }); @@ -56,40 +57,77 @@ describe("usePlayerExit", () => { 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(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(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 f26c09ce1..d823ce7cb 100644 --- a/frontend/src/v2/composables/usePlayerExit/index.ts +++ b/frontend/src/v2/composables/usePlayerExit/index.ts @@ -11,6 +11,12 @@ 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 leave guards of the components + * below never run and whatever they would have flushed belongs here. + */ + settle: () => Promise | void = () => undefined, ): { /** True once an exit is replacing the document, so an unload prompt can stand down. */ departing: Ref; @@ -21,7 +27,7 @@ export function usePlayerExit( */ 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); @@ -30,19 +36,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); + 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..a022b7b2b 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -171,7 +171,14 @@ 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 () => { + 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 +199,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 { @@ -871,6 +879,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(), routerReplace: vi.fn(() => Promise.resolve()), @@ -123,18 +124,28 @@ const CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/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 +161,8 @@ afterAll(() => { beforeEach(() => { vi.clearAllMocks(); - setIsolated(false); + sessionStorage.clear(); + setIsolated(true); mocks.loadRuntime.mockResolvedValue(LOCAL_BASE); mocks.galleryRom = null; mocks.routeLeaveGuard = null; @@ -232,6 +244,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 +331,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 +340,8 @@ describe("JsDos player exit", () => { expect(handle.save).toHaveBeenCalledOnce(); expect(handle.stop).toHaveBeenCalledOnce(); - expect(mocks.routerReplace).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(); @@ -297,20 +365,24 @@ describe("JsDos player exit", () => { }); 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(); }); @@ -347,7 +419,7 @@ describe("JsDos player exit", () => { expect(handle.stop).toHaveBeenCalledOnce(); expect(mocks.flushPlaySession).toHaveBeenCalledOnce(); expect(mocks.setPlaying).toHaveBeenLastCalledWith(false); - expect(mocks.routerReplace).toHaveBeenCalledWith("/rom/1"); + expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); wrapper.unmount(); }); @@ -363,7 +435,7 @@ describe("JsDos player exit", () => { "play.stream-save-unconfirmed", ); expect(handle.stop).not.toHaveBeenCalled(); - expect(mocks.routerReplace).not.toHaveBeenCalled(); + expect(mocks.locationReplace).not.toHaveBeenCalled(); wrapper.unmount(); }); @@ -383,7 +455,7 @@ describe("JsDos player exit", () => { finishSave?.(true); await flushPromises(); - expect(mocks.routerReplace).toHaveBeenCalledOnce(); + expect(mocks.locationReplace).toHaveBeenCalledOnce(); wrapper.unmount(); }); @@ -403,8 +475,8 @@ describe("JsDos player exit", () => { finishSave?.(true); await flushPromises(); - expect(mocks.routerReplace).toHaveBeenCalledOnce(); - expect(mocks.routerReplace).toHaveBeenCalledWith("/rom/1"); + expect(mocks.locationReplace).toHaveBeenCalledOnce(); + expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1"); wrapper.unmount(); }); @@ -416,7 +488,7 @@ describe("JsDos player exit", () => { await flushPromises(); expect(handle.save).toHaveBeenCalledOnce(); - expect(mocks.routerReplace).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..6dc6b15a8 100644 --- a/frontend/src/v2/views/Player/JsDos.vue +++ b/frontend/src/v2/views/Player/JsDos.vue @@ -13,6 +13,10 @@ import PlayerShell from "@/v2/components/Player/PlayerShell.vue"; import { useConfirm } from "@/v2/composables/useConfirm"; import { useFullscreenFallback } from "@/v2/composables/useFullscreenFallback"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; +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"; @@ -28,7 +32,11 @@ useFullscreenFallback(); const playSession = usePlaySession(); const snackbar = useSnackbar(); const confirm = useConfirm(); -const exit = usePlayerExit(); +// A launch isolates the document and boots an emulator into it, and the rest +// of the app cannot live there, so a player that ran hands the tab back a +// fresh document. +let runtimeBound = false; +const exit = usePlayerExit(() => runtimeBound); const rom = shallowRef(null); const gameRunning = ref(false); @@ -39,11 +47,26 @@ let dos: JsDosProps | null = null; const { romId, heroRom, title, platformLabel } = usePlayerHero(rom); +// The DOSBox-X backend is a threaded build, so it needs SharedArrayBuffer. No +// pre-play selection has to survive the reload that isolates the document, so +// the intent is a bare marker saying the launch is already on its second leg. +const isRelaunch = (value: unknown): value is true => value === true; +const { + intent: relaunched, + relaunching, + relaunch: relaunchIsolated, +} = useIsolatedLaunch("jsdos", romId, isRelaunch); + async function onPlay() { const currentRom = rom.value; const userId = authStore.user?.id; if (!currentRom || userId == null) return; + if (!hasSharedArrayBuffer()) { + if (!relaunchIsolated(true)) snackbar.error(t("play.https-required")); + 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; @@ -71,6 +94,7 @@ async function onPlay() { } // DOSBox-X provides Windows support. + runtimeBound = true; dos = dosFactory(stage.value, { url: getDownloadPath({ rom: currentRom }), backend: "dosboxX", @@ -154,6 +178,8 @@ onMounted(async () => { const romResponse = await romApi.getRom({ romId }); rom.value = romResponse.data; + + if (relaunched) void onPlay(); }); onBeforeRouteLeave((to) => { @@ -172,7 +198,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/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 From 8ecb4dd0c5005568c74eac86582be0785d88fddd Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Sep 2026 08:01:44 -0400 Subject: [PATCH 3/6] refactor(v2): fold the cleanup pass findings into the launch path The dev server now parses the isolated URLs out of the nginx template instead of restating them, and refuses a template that yields none. js-dos skips the runtime preload on the leg it is about to reload away, records its play session on pagehide, and takes the relaunch marker from the composable that defines it. Also drops a redundant parameter and a duplicated derivation from applyLaunchIntent, collapses the repeated id checks in isLaunchIntent, gives the js-dos asset bases one home, and trims the comments. Co-Authored-By: Claude Opus 5 (1M context) --- docker/nginx/templates/default.conf.template | 2 +- docs/FRONTEND_ARCHITECTURE.md | 2 +- frontend/scripts/playerIsolationHeaders.ts | 57 +++++++----- .../v2/composables/useIsolatedLaunch/index.ts | 17 ++-- frontend/src/v2/views/Player/EmulatorJS.vue | 10 +- frontend/src/v2/views/Player/JsDos.test.ts | 3 +- frontend/src/v2/views/Player/JsDos.vue | 18 ++-- .../src/v2/views/Player/jsDosRuntime.test.ts | 5 +- frontend/src/v2/views/Player/jsDosRuntime.ts | 4 +- .../src/v2/views/Player/launchIntent.test.ts | 43 ++++----- frontend/src/v2/views/Player/launchIntent.ts | 15 ++- frontend/test/playerIsolationHeaders.test.ts | 92 +++++++++++-------- frontend/vite.config.js | 9 +- 13 files changed, 153 insertions(+), 124 deletions(-) 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 b3f0b5aa9..cb882e17b 100644 --- a/docs/FRONTEND_ARCHITECTURE.md +++ b/docs/FRONTEND_ARCHITECTURE.md @@ -873,7 +873,7 @@ A v2 player view is reached by SPA navigation, so it is not isolated on arrival. 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 d0573c88b..ddc395d6d 100644 --- a/frontend/scripts/playerIsolationHeaders.ts +++ b/frontend/scripts/playerIsolationHeaders.ts @@ -1,36 +1,49 @@ /** - * playerIsolationHeaders: the dev server's twin of the nginx COOP/COEP map. + * playerIsolationHeaders: the dev server's stand-in for nginx's 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. + * Threaded EmulatorJS cores and js-dos 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. The URLs come from the nginx template so there is one list. */ +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)); } -const isolate: Connect.NextHandleFunction = (req, res, next) => { - if (isIsolatedPlayerUrl(req.url ?? "")) { - res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); - res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); - } - next(); -}; +// 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(): Plugin { +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", diff --git a/frontend/src/v2/composables/useIsolatedLaunch/index.ts b/frontend/src/v2/composables/useIsolatedLaunch/index.ts index 112f244d1..febd5b84e 100644 --- a/frontend/src/v2/composables/useIsolatedLaunch/index.ts +++ b/frontend/src/v2/composables/useIsolatedLaunch/index.ts @@ -2,23 +2,18 @@ // 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. +// tab. Pair it with usePlayerExit, which drops the isolation on the way out. +// EmulatorJS.vue and JsDos.vue are the two callers. 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/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index a022b7b2b..6f9535181 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -175,6 +175,8 @@ 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(); }, @@ -350,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 @@ -456,7 +458,7 @@ onMounted(async () => { }); if (storedIntent) { - applyLaunchIntent(storedIntent, romResponse.data); + applyLaunchIntent(storedIntent); await nextTick(); void onPlay(); return; diff --git a/frontend/src/v2/views/Player/JsDos.test.ts b/frontend/src/v2/views/Player/JsDos.test.ts index 78f3d0a98..37dee8698 100644 --- a/frontend/src/v2/views/Player/JsDos.test.ts +++ b/frontend/src/v2/views/Player/JsDos.test.ts @@ -119,8 +119,9 @@ 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; diff --git a/frontend/src/v2/views/Player/JsDos.vue b/frontend/src/v2/views/Player/JsDos.vue index 6dc6b15a8..72f7a9c9e 100644 --- a/frontend/src/v2/views/Player/JsDos.vue +++ b/frontend/src/v2/views/Player/JsDos.vue @@ -1,5 +1,6 @@ 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 adb29ae3e..7ede9b449 100644 --- a/frontend/src/v2/views/Player/jsDosRuntime.ts +++ b/frontend/src/v2/views/Player/jsDosRuntime.ts @@ -4,11 +4,11 @@ // injecting a second copy of a runtime that declares its own globals. import { isJsResource, loadScript } from "@/v2/utils/scriptLoader"; -const LOCAL_BASE = "/assets/jsdos"; +export 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 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. diff --git a/frontend/src/v2/views/Player/launchIntent.test.ts b/frontend/src/v2/views/Player/launchIntent.test.ts index a0256c0c4..59d83fe73 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,22 +9,16 @@ 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; -} - -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(); +// Same shape as the sibling resumeSelection.test.ts factories. +const save = { id: 3, file_name: "3.srm", slot: "slot-2" } as SaveSchema; +const state = { + id: 5, + file_name: "5.state", + emulator: "snes9x", +} as StateSchema; +const firmware = { id: 12, file_name: "bios.bin" } as FirmwareSchema; const OPTIONS: LaunchOptions = { saves: [save], @@ -89,13 +83,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 +99,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/test/playerIsolationHeaders.test.ts b/frontend/test/playerIsolationHeaders.test.ts index aa2801c73..af6065291 100644 --- a/frontend/test/playerIsolationHeaders.test.ts +++ b/frontend/test/playerIsolationHeaders.test.ts @@ -1,12 +1,18 @@ -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 }, @@ -18,7 +24,7 @@ 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 plugin = playerIsolationHeaders() as unknown as Record< + const plugin = playerIsolationHeaders(TEMPLATE) as unknown as Record< ServerHook, (server: { middlewares: { use: (fn: Middleware) => void } }) => void >; @@ -57,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", @@ -66,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([ @@ -77,18 +116,8 @@ 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", () => { @@ -103,25 +132,12 @@ describe("playerIsolationHeaders", () => { }); }); -// 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("\\/", "/"), +// 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", From fdb4cb5e828a6a3c4d33d06cc4e443068e2d481d Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Sep 2026 08:16:37 -0400 Subject: [PATCH 4/6] chore(v2): trim the launch-path comments and mount the nginx map in dev The dev container mounts frontend/ alone, so the vite plugin that now reads the nginx template could not find it and the dev server refused to start. Mount the template directory read-only. Co-Authored-By: Claude Opus 5 (1M context) --- docker-compose.yml | 2 ++ frontend/scripts/playerIsolationHeaders.ts | 9 +++------ .../v2/composables/useIsolatedLaunch/index.ts | 8 +++----- .../src/v2/composables/usePlayerExit/index.ts | 20 ++++++------------- frontend/src/v2/views/Player/jsDosRuntime.ts | 12 +++++------ 5 files changed, 19 insertions(+), 32 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index b64be6106..f4fb5c89b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -28,6 +28,8 @@ services: - /app/frontend/node_modules # Empty directory - /app/frontend/dist # Empty directory - ./romm_mock:/app/romm + # The dev server reads the player isolation URLs out of the nginx map. + - ./docker/nginx/templates:/app/docker/nginx/templates:ro - ~/.vite-plugin-mkcert:/app/.vite-plugin-mkcert depends_on: - romm-db-dev diff --git a/frontend/scripts/playerIsolationHeaders.ts b/frontend/scripts/playerIsolationHeaders.ts index ddc395d6d..7ed641061 100644 --- a/frontend/scripts/playerIsolationHeaders.ts +++ b/frontend/scripts/playerIsolationHeaders.ts @@ -1,10 +1,7 @@ /** - * playerIsolationHeaders: the dev server's stand-in for nginx's COOP/COEP map. - * - * Threaded EmulatorJS cores and js-dos 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. The URLs come from the nginx template so there is one list. + * The dev server's stand-in for nginx's COOP/COEP map, reading its URLs from + * the nginx 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"; diff --git a/frontend/src/v2/composables/useIsolatedLaunch/index.ts b/frontend/src/v2/composables/useIsolatedLaunch/index.ts index febd5b84e..c4e93044e 100644 --- a/frontend/src/v2/composables/useIsolatedLaunch/index.ts +++ b/frontend/src/v2/composables/useIsolatedLaunch/index.ts @@ -1,9 +1,7 @@ // 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. Pair it with usePlayerExit, which drops the isolation on the way out. -// EmulatorJS.vue and JsDos.vue are the two callers. +// 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 { diff --git a/frontend/src/v2/composables/usePlayerExit/index.ts b/frontend/src/v2/composables/usePlayerExit/index.ts index d823ce7cb..76d789ded 100644 --- a/frontend/src/v2/composables/usePlayerExit/index.ts +++ b/frontend/src/v2/composables/usePlayerExit/index.ts @@ -1,10 +1,7 @@ -// 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"; @@ -13,18 +10,13 @@ export function usePlayerExit( runtimeBound: () => boolean = () => false, /** * Work the departing document still owes, awaited before it is replaced. - * A replace aborts the navigation, so the leave guards of the components - * below never run and whatever they would have flushed belongs here. + * 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` in place of the player, by a full navigation when the document - * is bound. The player is replaced either way, so Back never re-enters the - * view it just left and relaunches the game. - */ + /** 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) => Promise; diff --git a/frontend/src/v2/views/Player/jsDosRuntime.ts b/frontend/src/v2/views/Player/jsDosRuntime.ts index 7ede9b449..4e1d2bee2 100644 --- a/frontend/src/v2/views/Player/jsDosRuntime.ts +++ b/frontend/src/v2/views/Player/jsDosRuntime.ts @@ -1,13 +1,11 @@ -// 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"; export 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. +// 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; From 9431063a544bb908379df624a9e71ddaf4547999 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Sep 2026 08:33:37 -0400 Subject: [PATCH 5/6] remove unused comment --- docker-compose.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index f4fb5c89b..dd98867e6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -28,7 +28,6 @@ services: - /app/frontend/node_modules # Empty directory - /app/frontend/dist # Empty directory - ./romm_mock:/app/romm - # The dev server reads the player isolation URLs out of the nginx map. - ./docker/nginx/templates:/app/docker/nginx/templates:ro - ~/.vite-plugin-mkcert:/app/.vite-plugin-mkcert depends_on: From a3b534a1c3b9bff57c7948e39e632fa1c0605b6c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Sep 2026 08:36:53 -0400 Subject: [PATCH 6/6] chore(v2): address the review comments on the launch path Condense the comments that ran past two lines, and build the launch intent fixtures from typed factories again rather than bare literals. Co-Authored-By: Claude Opus 5 (1M context) --- frontend/scripts/playerIsolationHeaders.ts | 8 ++--- frontend/src/v2/views/Player/JsDos.vue | 10 +++--- .../src/v2/views/Player/launchIntent.test.ts | 33 ++++++++++++++----- 3 files changed, 32 insertions(+), 19 deletions(-) diff --git a/frontend/scripts/playerIsolationHeaders.ts b/frontend/scripts/playerIsolationHeaders.ts index 7ed641061..a6960e4e3 100644 --- a/frontend/scripts/playerIsolationHeaders.ts +++ b/frontend/scripts/playerIsolationHeaders.ts @@ -1,8 +1,6 @@ -/** - * The dev server's stand-in for nginx's COOP/COEP map, reading its URLs from - * the nginx 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. - */ +// 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"; diff --git a/frontend/src/v2/views/Player/JsDos.vue b/frontend/src/v2/views/Player/JsDos.vue index 72f7a9c9e..d6104e79e 100644 --- a/frontend/src/v2/views/Player/JsDos.vue +++ b/frontend/src/v2/views/Player/JsDos.vue @@ -34,9 +34,8 @@ useFullscreenFallback(); const playSession = usePlaySession(); const snackbar = useSnackbar(); const confirm = useConfirm(); -// A launch isolates the document and boots an emulator into it, and the rest -// of the app cannot live there, so a player that ran hands the tab back a -// fresh document. +// An isolated document cannot host the rest of the app, so a player that ran +// hands the tab back a fresh one. let runtimeBound = false; const exit = usePlayerExit(() => runtimeBound); @@ -171,9 +170,8 @@ function onlyQuit() { 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. Not on a - // leg that is about to relaunch, which would throw the bundle away. + // The runtime reads nothing from the ROM payload, so overlap the two loads. + // Not on a leg about to relaunch, which would throw the bundle away. if (hasSharedArrayBuffer()) { void loadJsDosRuntime().catch((e: unknown) => console.error(e)); } diff --git a/frontend/src/v2/views/Player/launchIntent.test.ts b/frontend/src/v2/views/Player/launchIntent.test.ts index 59d83fe73..e28b2a8a8 100644 --- a/frontend/src/v2/views/Player/launchIntent.test.ts +++ b/frontend/src/v2/views/Player/launchIntent.test.ts @@ -11,14 +11,31 @@ import { } from "./launchIntent"; import type { ResumeSelection } from "./resumeSelection"; -// Same shape as the sibling resumeSelection.test.ts factories. -const save = { id: 3, file_name: "3.srm", slot: "slot-2" } as SaveSchema; -const state = { - id: 5, - file_name: "5.state", - emulator: "snes9x", -} as StateSchema; -const firmware = { id: 12, file_name: "bios.bin" } as FirmwareSchema; +function makeSave(overrides: Partial = {}): SaveSchema { + return { + id: 3, + file_name: "3.srm", + slot: "slot-2", + ...overrides, + } as SaveSchema; +} + +function makeState(overrides: Partial = {}): StateSchema { + return { + id: 5, + file_name: "5.state", + 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],