fix(frontend): restate the player isolation URLs instead of reading nginx

The vite plugin parsed the COOP/COEP patterns out of the nginx template at
config load, but the Dockerfile's frontend-build stage copies frontend/
alone, so the config threw ENOENT and the image build failed.

Restate the two patterns in the plugin and let its test assert they still
match the template's map, which also drops the dev container mount that
existed only to feed that read.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-17 09:13:32 -04:00
parent cd32850da7
commit b5cd86e3f7
6 changed files with 39 additions and 80 deletions

View File

@@ -28,7 +28,6 @@ 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

View File

@@ -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 reads these entries from frontend/scripts/playerIsolationHeaders.ts.
# frontend/scripts/playerIsolationHeaders.ts restates these entries for the dev server.
map $request_uri $coep_header {
default "";
~^/rom/.*/(ejs|jsdos)(\?|$) "require-corp";

View File

@@ -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 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.
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 restates the template's patterns, since the production build runs from `frontend/` alone and cannot read that file, and its test fails when the two drift.
### Platform Detection

View File

@@ -1,38 +1,28 @@
// 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";
// The dev server's stand-in for nginx's COOP/COEP map. Only the player URLs
// are isolated: COEP would block the third-party images the rest of the app
// embeds.
import type { Connect, Plugin } from "vite";
// The `~<pattern> "<header>";` 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;
/** 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));
}
// A copy of the `$coep_header`/`$coop_header` map entries in
// docker/nginx/templates/default.conf.template, restated here because the
// production build runs from frontend/ alone and cannot read that file.
// playerIsolationHeaders.test.ts fails when the two drift.
export const ISOLATED_PLAYER_URLS: readonly RegExp[] = [
/^\/rom\/.*\/(ejs|jsdos)(\?|$)/,
/^\/console\/rom\/[0-9]+\/play/,
];
// 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));
function isIsolated(url: string): boolean {
return ISOLATED_PLAYER_URLS.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);
export function playerIsolationHeaders(): Plugin {
const isolate: Connect.NextHandleFunction = (req, res, next) => {
if (isIsolated(patterns, req.url ?? "")) {
if (isIsolated(req.url ?? "")) {
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
}

View File

@@ -1,9 +1,8 @@
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it, vi } from "vitest";
import {
isolatedPlayerUrls,
ISOLATED_PLAYER_URLS,
playerIsolationHeaders,
} from "../scripts/playerIsolationHeaders";
@@ -13,6 +12,10 @@ const TEMPLATE = resolve(
"../docker/nginx/templates/default.conf.template",
);
// The `~<pattern> "<header>";` 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;
type Middleware = (
req: { url?: string },
res: { setHeader: (name: string, value: string) => void },
@@ -24,7 +27,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(TEMPLATE) as unknown as Record<
const plugin = playerIsolationHeaders() as unknown as Record<
ServerHook,
(server: { middlewares: { use: (fn: Middleware) => void } }) => void
>;
@@ -63,39 +66,6 @@ const ISOLATED = {
"Cross-Origin-Opener-Policy": "same-origin",
};
/** 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",
@@ -132,12 +102,19 @@ describe("playerIsolationHeaders", () => {
});
});
// 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",
// The plugin restates the nginx map instead of reading it, so a URL isolated
// in production but not in dev would otherwise only surface as SharedArrayBuffer
// being unavailable behind the dev server.
describe("the nginx COOP/COEP map", () => {
it("holds the patterns the plugin restates", () => {
const template = readFileSync(TEMPLATE, "utf8");
const sources = [
...new Set([...template.matchAll(MAP_ENTRY)].map((entry) => entry[1]!)),
].map((source) => new RegExp(source).source);
expect(sources.length).toBeGreaterThan(0);
expect(sources.sort()).toEqual(
ISOLATED_PLAYER_URLS.map((pattern) => pattern.source).sort(),
);
});
});

View File

@@ -150,14 +150,7 @@ export default defineConfig(({ mode }) => {
},
}),
precompress(),
playerIsolationHeaders(
fileURLToPath(
new URL(
"../docker/nginx/templates/default.conf.template",
import.meta.url,
),
),
),
playerIsolationHeaders(),
httpsMode &&
mkcert({
savePath: "/app/.vite-plugin-mkcert",