按 review 意见:/media/ 的路径与扩展名列表提到 shared/ 共用

- server/index.js 开头的路由说明补上 /media/
- AUDIO_EXTS 原先客户端(public/js/media.js)与服务端各一份,只改一边就会悄悄漂移:
  现在两边都从 shared/media.js 取;服务端那份不再 export
- isMediaUrl 只有测试在用,删掉(新增 shared/media.js,测试改从那里取前缀/扩展名)
- 顺手做了 review 里「可选」的那点:有些静态托管对不存在的路径回 200 + index.html,
  这种响应解码会静默失败,所以除了 404,声明了非 audio/* 类型的响应也回退到原地址
  (完全没声明 content-type 的不算错——没有证据表明它不是音频)
This commit is contained in:
kanomahoro1224 committed 2026-10-03 22:33:20 +08:00
1 parent a069be4538
commit cfa51e5f1b
6 files changed
+109 -28

No files matched your search

+19 -1
View File
@@ -216,6 +216,20 @@ export class SfxLimiter {
// ---- manager ----------------------------------------------------------------------------------------------- // ---- manager -----------------------------------------------------------------------------------------------
/**
* Could Web Audio decode this response? A host without the `/media/` route answers 404; some static hosts answer a
* missing path with 200 + the SPA's index.html instead, and fetching *that* would fail to decode as silently as a
* 404 would — so the fallback looks at the declared type too.
*
* A response that declares no type at all is not treated as wrong: absence of a header is not evidence of an HTML
* page, and fetch stubs / minimal hosts legitimately omit it.
* @param {{ ok?: boolean, headers?: { get?: (n: string) => string | null } }} res
*/
function isAudioResponse(res) {
if (!res || !res.ok) return false;
const type = res.headers?.get?.('content-type');
return !type || /^\s*audio\//i.test(type);
}
export class AudioManager { export class AudioManager {
/** /**
* @param {{ getManifest?: () => any, win?: any }} [opts] * @param {{ getManifest?: () => any, win?: any }} [opts]
@@ -387,7 +401,11 @@ export class AudioManager {
// Extension-less URL first so download managers leave the BGM alone; a host without /media/ still works. // Extension-less URL first so download managers leave the BGM alone; a host without /media/ still works.
const media = mediaUrl(url); const media = mediaUrl(url);
let res = await fetch(media); let res = await fetch(media);
if (!res.ok && media !== url) res = await fetch(url); if (media !== url && !isAudioResponse(res)) {
// Drop the unusable response (404, or a 200 that is really index.html) before trying the original URL.
try { await res.body?.cancel?.(); } catch { /* the fallback request matters more than draining this one */ }
res = await fetch(url);
}
if (!res.ok) throw new Error(`HTTP ${res.status}`); if (!res.ok) throw new Error(`HTTP ${res.status}`);
const ab = await res.arrayBuffer(); const ab = await res.arrayBuffer();
return await new Promise((resolve) => { return await new Promise((resolve) => {
+5 -17
View File
@@ -1,4 +1,4 @@
// Audio URLs for download managers (IDM / 迅雷 / FDM …) — and why they have no extension. // audio URL rewriting for download managers (IDM / 迅雷 / FDM …) — see shared/media.js for the why.
// //
// The game plays audio with fetch() + Web Audio (`audio.js`): it never uses <audio src>, <a download> or a // The game plays audio with fetch() + Web Audio (`audio.js`): it never uses <audio src>, <a download> or a
// navigation. Download managers do not care — their browser integration hooks XHR/fetch whose URL ends in a // navigation. Download managers do not care — their browser integration hooks XHR/fetch whose URL ends in a
@@ -11,13 +11,10 @@
// //
// `server/index.js` resolves /media/… back to the real file under public/assets/audio and still answers with // `server/index.js` resolves /media/… back to the real file under public/assets/audio and still answers with
// `Content-Type: audio/mpeg` + range support; Web Audio sniffs the container, so the URL is all the same to it. // `Content-Type: audio/mpeg` + range support; Web Audio sniffs the container, so the URL is all the same to it.
// A host that does not implement /media/ keeps working: `audio.js` falls back to the original URL on 404. // A host that does not implement /media/ keeps working: `audio.js` falls back to the original URL whenever the
// /media/ response is unusable (a 404, or a 200 that is not audio at all — some static hosts answer a missing
/** Prefix of the extension-less audio route served by `server/index.js`. */ // path with the SPA's index.html).
export const MEDIA_PREFIX = '/media/'; import { MEDIA_PREFIX, AUDIO_EXTS } from '../../shared/media.js';
/** Extensions `/media/…` may resolve to, in the order the server tries them. */
export const AUDIO_EXTS = Object.freeze(['.mp3', '.m4a', '.aac', '.ogg', '.oga', '.opus', '.wav']);
const AUDIO_PATH = /^\/assets\/audio\/(.+)$/i; const AUDIO_PATH = /^\/assets\/audio\/(.+)$/i;
@@ -49,12 +46,3 @@ export function mediaUrl(url, origin = globalThis.location?.origin) {
if (!rest || segments.some((s) => !s || s === '.' || s === '..' || s.startsWith('.'))) return url; if (!rest || segments.some((s) => !s || s === '.' || s === '..' || s.startsWith('.'))) return url;
return `${MEDIA_PREFIX}${rest}${u.search}`; return `${MEDIA_PREFIX}${rest}${u.search}`;
} }
/**
* Is this URL already one of the extension-less media paths?
* @param {string} url
* @param {string} [origin]
*/
export function isMediaUrl(url, origin = globalThis.location?.origin) {
return mediaUrl(url, origin) !== url;
}
+6 -4
View File
@@ -8,6 +8,9 @@
// /data.js → a generated browser stand-in of server/data.js (the sim's content modules // /data.js → a generated browser stand-in of server/data.js (the sim's content modules
// import `../../../data.js`; in the browser it serves the data injected with // import `../../../data.js`; in the browser it serves the data injected with
// /sim/simdata.js setSimData). No other server file is ever served. // /sim/simdata.js setSimData). No other server file is ever served.
// /media/bgm/act1 → public/assets/audio/bgm/act1.mp3 — the same audio files, addressed
// **without** an extension so download managers (IDM / 迅雷 …) stop popping a
// "下载文件信息" dialog for every BGM track (shared/media.js, public/js/media.js)
// MIME types incl. .mjs/.js text/javascript, .skel application/octet-stream, .atlas text/plain; // MIME types incl. .mjs/.js text/javascript, .skel application/octet-stream, .atlas text/plain;
// gzip for text-like types, .skel and uncompressed fonts when the client accepts it (small files are // gzip for text-like types, .skel and uncompressed fonts when the client accepts it (small files are
// compressed once and cached in memory); strong ETag + Last-Modified with 304s; Cache-Control // compressed once and cached in memory); strong ETag + Last-Modified with 304s; Cache-Control
@@ -39,6 +42,7 @@ import { Network, SessionRegistry, NET_DEFAULTS } from './net.js';
import { Lobby } from './lobby.js'; import { Lobby } from './lobby.js';
import { getData, loadData } from './data.js'; import { getData, loadData } from './data.js';
import { PROTOCOL_VERSION, APP_VERSION } from '../shared/constants.js'; import { PROTOCOL_VERSION, APP_VERSION } from '../shared/constants.js';
import { MEDIA_PREFIX, AUDIO_EXTS } from '../shared/media.js';
/** Repository root. */ /** Repository root. */
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -383,11 +387,9 @@ export function createStaticHandler({ publicDir, dataDir, sharedDir, simDir = pa
* Clients ask for audio through this path because download managers (IDM, 迅雷, FDM …) hijack XHR/fetch whose * Clients ask for audio through this path because download managers (IDM, 迅雷, FDM …) hijack XHR/fetch whose
* URL ends in a media extension and pop a "下载文件信息" dialog for every BGM track — see `public/js/media.js`. * URL ends in a media extension and pop a "下载文件信息" dialog for every BGM track — see `public/js/media.js`.
* Requests for the direct `/assets/audio/…` URLs keep working (they are the fallback for plain static hosts). * Requests for the direct `/assets/audio/…` URLs keep working (they are the fallback for plain static hosts).
* `MEDIA_PREFIX` / `AUDIO_EXTS` live in `shared/media.js`: the browser decides which URLs to rewrite with the
* same two values, and they must not drift apart.
*/ */
const MEDIA_PREFIX = '/media/';
/** Extensions a `/media/…` request may resolve to, in order. */
export const AUDIO_EXTS = Object.freeze(['.mp3', '.m4a', '.aac', '.ogg', '.oga', '.opus', '.wav']);
async function serveMedia(req, res, rest, query, publicDir, gzipCache, log) { async function serveMedia(req, res, rest, query, publicDir, gzipCache, log) {
const root = path.join(path.resolve(publicDir), 'assets', 'audio'); const root = path.join(path.resolve(publicDir), 'assets', 'audio');
const segments = String(rest || '').split('/').filter((s) => s.length > 0); const segments = String(rest || '').split('/').filter((s) => s.length > 0);
+20
View File
@@ -0,0 +1,20 @@
// Extension-less audio route (/media/…) — the one place that defines it.
//
// The game plays audio with fetch() + Web Audio, never <audio src> / <a download>. Download managers (IDM / 迅雷 /
// FDM …) do not care: their browser integration hooks XHR/fetch whose URL ends in a media extension and pops up
// "下载文件信息" for every BGM track. So the browser asks for audio through a same-origin, extension-less path —
//
// /assets/audio/bgm/act1.mp3 → /media/bgm/act1
//
// — and `server/index.js` resolves it back to the real file under public/assets/audio, still answering with
// `Content-Type: audio/mpeg`, Range support and the ETag of the file it resolved.
//
// Both sides import this module: the browser to decide which URLs to rewrite (`public/js/media.js`), the server to
// decide which extensions a `/media/…` request may resolve to. A second copy of the list on one side would let them
// drift apart silently — the client would rewrite to a path the server no longer accepts.
/** Prefix of the extension-less audio route served by `server/index.js`. */
export const MEDIA_PREFIX = '/media/';
/** Extensions a `/media/…` request may resolve to, in the order the server tries them. */
export const AUDIO_EXTS = Object.freeze(['.mp3', '.m4a', '.aac', '.ogg', '.oga', '.opus', '.wav']);
+3 -6
View File
@@ -2,7 +2,9 @@
// stop hijacking BGM playback with a "下载文件信息" dialog. See public/js/media.js for the full rationale. // stop hijacking BGM playback with a "下载文件信息" dialog. See public/js/media.js for the full rationale.
import { test, describe } from 'node:test'; import { test, describe } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { mediaUrl, isMediaUrl, MEDIA_PREFIX, AUDIO_EXTS } from '../public/js/media.js'; import { mediaUrl } from '../public/js/media.js';
// 前缀与扩展名列表只有一份(客户端和服务端都从这里取),所以断言也直接盯住这一份。
import { MEDIA_PREFIX, AUDIO_EXTS } from '../shared/media.js';
const ORIGIN = 'http://127.0.0.1:3000'; const ORIGIN = 'http://127.0.0.1:3000';
@@ -44,11 +46,6 @@ describe('mediaUrl: 音频地址去掉扩展名(躲开下载器嗅探)', ()
assert.equal(mediaUrl('/assets/audio/bgm/../x.mp3', ORIGIN), '/media/x'); assert.equal(mediaUrl('/assets/audio/bgm/../x.mp3', ORIGIN), '/media/x');
}); });
test('isMediaUrl 只对真正会改写的地址为真', () => {
assert.equal(isMediaUrl('/assets/audio/bgm/a.mp3', ORIGIN), true);
assert.equal(isMediaUrl('/assets/img/a.png', ORIGIN), false);
});
test('没有 location 时(测试环境)用传入的 origin 判断同源', () => { test('没有 location 时(测试环境)用传入的 origin 判断同源', () => {
assert.equal(mediaUrl('/assets/audio/bgm/a.mp3'), '/media/bgm/a', '相对地址本来就同源'); assert.equal(mediaUrl('/assets/audio/bgm/a.mp3'), '/media/bgm/a', '相对地址本来就同源');
assert.equal(mediaUrl('https://other.example/assets/audio/a.mp3'), 'https://other.example/assets/audio/a.mp3'); assert.equal(mediaUrl('https://other.example/assets/audio/a.mp3'), 'https://other.example/assets/audio/a.mp3');
+56
View File
@@ -229,6 +229,62 @@ describe('AudioManager', () => {
assert.ok(!urls.includes(raw), '/media/ 成功就不该再请求 .mp3 地址'); assert.ok(!urls.includes(raw), '/media/ 成功就不该再请求 .mp3 地址');
} finally { globalThis.fetch = origFetch; } } finally { globalThis.fetch = origFetch; }
} }
// 第一发 200 但内容不是音频:有些静态托管对不存在的路径回 200 + index.html,解码会静默失败,也要回退。
{
const fw = fakeWindow();
const urls = [];
let cancelled = 0;
const origFetch = globalThis.fetch;
globalThis.fetch = async (u) => {
urls.push(u);
if (u !== media) return { ok: true, arrayBuffer: async () => new ArrayBuffer(8) };
return {
ok: true,
status: 200,
headers: { get: (n) => (n.toLowerCase() === 'content-type' ? 'text/html; charset=utf-8' : null) },
body: { cancel: async () => { cancelled += 1; } },
arrayBuffer: async () => new ArrayBuffer(8),
};
};
try {
const a = new AudioManager({ win: fw.win, getManifest: () => manifest });
a.install();
fw.fire('pointerdown');
a.playBgm('prep');
await new Promise((r) => setTimeout(r, 25));
assert.ok(urls.includes(raw), '内容不是音频时回退到原地址');
assert.equal(cancelled, 1, '丢掉那个用不上的响应,别把连接挂着');
} finally { globalThis.fetch = origFetch; }
}
// /media/ 直接给出 audio/*(服务端真实行为):不回退,也不去 cancel 一个能用的响应
{
const fw = fakeWindow();
const urls = [];
let cancelled = 0;
const origFetch = globalThis.fetch;
globalThis.fetch = async (u) => {
urls.push(u);
return {
ok: true,
status: 200,
headers: { get: (n) => (n.toLowerCase() === 'content-type' ? 'audio/mpeg' : null) },
body: { cancel: async () => { cancelled += 1; } },
arrayBuffer: async () => new ArrayBuffer(8),
};
};
try {
const a = new AudioManager({ win: fw.win, getManifest: () => manifest });
a.install();
fw.fire('pointerdown');
a.playBgm('prep');
await new Promise((r) => setTimeout(r, 25));
assert.ok(urls.includes(media));
assert.ok(!urls.includes(raw), 'audio/* 就是成功,不该再回退');
assert.equal(cancelled, 0);
} finally { globalThis.fetch = origFetch; }
}
}); });
}); });