音频改走无扩展名的 /media 路由:IDM / 迅雷 这类下载管理器不再弹「下载文件信息」
玩家那边遇到的是:游戏放着 BGM,突然弹出下载管理器的「下载文件信息」框,有时还会把整条 音轨抢去下载。原因是这些工具会嗅探以媒体扩展名结尾的 XHR/fetch。改成客户端统一请求不带 扩展名的 `/media/<原路径去掉 .mp3>`,服务端再解析回 `public/assets/audio/…`。 - `public/js/media.js`:`mediaUrl()` 把 `/assets/audio/**.mp3` 换算成 `/media/**`,只处理同源、 且扩展名在名单内的地址;跨域、目录、`..`、点开头、不认识的扩展名一律原样返回。 - `server/index.js`:新增 `/media/` 路由。按 `AUDIO_EXTS` 顺序找 `.mp3/.m4a/.aac/.ogg/.oga/.opus/.wav`, 显式写了扩展名的以它为准;Range/ETag/Content-Type/缓存策略都复用 `serveFile`,所以和直接请求 `/assets/audio/…` 行为一致(一天缓存、支持 Range)。 - 直接请求 `/assets/audio/…` 仍然可用 —— 这是给不支持 `/media/` 的纯静态托管留的退路,客户端 在 `/media/` 404 时才回退到原地址。 安全:`/media/` 的路径只接受正常片段,`..`/`.` 直接 403,点开头或点结尾的片段 404,解析出的 绝对路径必须落在 `public/assets/audio` 之内,且只允许上面那几个音频扩展名 —— 不会变成任意文件读取。 测试: - `test/media-url.test.js`:`mediaUrl()` 的换算与各种「别动它」的边界。 - `test/lobby.test.js`:真实服务器上的 `/media` 路由(正常解析、显式扩展名优先、Range、HEAD、 目录与穿越请求被拒、客户端回退用到的 `/media/bgm.mp3` 仍 200)。 - `test/ui/audio.test.js`:音频管理器现在先请求无扩展名地址,404 才回退原地址;断言跟着 `mediaUrl()` 换算后再比对(原先拿 manifest 原地址比对,等于断言一个客户端永不请求的 URL)。
This commit is contained in:
1 parent
8cd6491e43
commit
a069be4538
6 files changed
+281
-14
No files matched your search
+5
-1
@@ -31,6 +31,7 @@
|
||||
// which follows the store).
|
||||
|
||||
import { PHASE } from '../../shared/constants.js';
|
||||
import { mediaUrl } from './media.js';
|
||||
|
||||
const MAX_VOICES = 8;
|
||||
const UNIT_COOLDOWN_MS = 160;
|
||||
@@ -383,7 +384,10 @@ export class AudioManager {
|
||||
}
|
||||
const p = (async () => {
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
// Extension-less URL first so download managers leave the BGM alone; a host without /media/ still works.
|
||||
const media = mediaUrl(url);
|
||||
let res = await fetch(media);
|
||||
if (!res.ok && media !== url) res = await fetch(url);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const ab = await res.arrayBuffer();
|
||||
return await new Promise((resolve) => {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// Audio URLs for download managers (IDM / 迅雷 / FDM …) — and why they have no extension.
|
||||
//
|
||||
// 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
|
||||
// media extension and (usually above ~1 MB) pops up "下载文件信息" for every BGM track. That dialog has nothing
|
||||
// to do with the game, but players see it and blame the game.
|
||||
//
|
||||
// So audio is fetched through a same-origin, extension-less path instead:
|
||||
//
|
||||
// /assets/audio/bgm/act1.mp3 → /media/bgm/act1
|
||||
//
|
||||
// `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.
|
||||
// A host that does not implement /media/ keeps working: `audio.js` falls back to the original URL on 404.
|
||||
|
||||
/** Prefix of the extension-less audio route served by `server/index.js`. */
|
||||
export const MEDIA_PREFIX = '/media/';
|
||||
|
||||
/** 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;
|
||||
|
||||
/**
|
||||
* Rewrite an audio URL to its extension-less `/media/…` form.
|
||||
*
|
||||
* Returns the input unchanged when the URL is not one of our audio assets, points at another origin (a CDN
|
||||
* serves media itself, so the download-manager problem is not ours to solve there), or would produce a path the
|
||||
* server refuses (empty / dot segments).
|
||||
* @param {string} url
|
||||
* @param {string} [origin] origin of the page; defaults to `location.origin`
|
||||
* @returns {string} a URL safe to pass to fetch()
|
||||
*/
|
||||
export function mediaUrl(url, origin = globalThis.location?.origin) {
|
||||
if (typeof url !== 'string' || !url) return url;
|
||||
let u;
|
||||
// No origin known (Node / tests): parse relative URLs against a placeholder, absolute ones are rejected below.
|
||||
try { u = new URL(url, origin || 'http://localhost'); } catch { return url; }
|
||||
// Cross-origin (or absolute while the page origin is unknown) stays untouched: that host serves its own media.
|
||||
const absolute = /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//');
|
||||
if (origin ? u.origin !== origin : absolute) return url;
|
||||
const m = AUDIO_PATH.exec(u.pathname);
|
||||
if (!m) return url;
|
||||
let rest = m[1];
|
||||
const ext = AUDIO_EXTS.find((e) => rest.toLowerCase().endsWith(e));
|
||||
if (!ext) return url; // not a file we serve as audio (e.g. "x.mp3.bak") — leave it alone
|
||||
rest = rest.slice(0, -ext.length);
|
||||
const segments = rest.split('/');
|
||||
if (!rest || segments.some((s) => !s || s === '.' || s === '..' || s.startsWith('.'))) return url;
|
||||
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;
|
||||
}
|
||||
@@ -311,6 +311,11 @@ export function createStaticHandler({ publicDir, dataDir, sharedDir, simDir = pa
|
||||
res.end(req.method === 'HEAD' ? undefined : shimBody);
|
||||
return;
|
||||
}
|
||||
// Extension-less audio (download-manager avoidance): /media/bgm/act1 → /assets/audio/bgm/act1.mp3
|
||||
if (decoded.startsWith(MEDIA_PREFIX)) {
|
||||
await serveMedia(req, res, decoded.slice(MEDIA_PREFIX.length), query, publicDir, gzipCache, log);
|
||||
return;
|
||||
}
|
||||
// Bare mount paths (e.g. "/data") → treat as the mount directory.
|
||||
const mount = mounts.find((m) => decoded.startsWith(m.prefix) || decoded === m.prefix.slice(0, -1)) || mounts[mounts.length - 1];
|
||||
const rest = decoded.length > mount.prefix.length ? decoded.slice(mount.prefix.length) : '';
|
||||
@@ -372,6 +377,53 @@ export function createStaticHandler({ publicDir, dataDir, sharedDir, simDir = pa
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extension-less audio route: `/media/bgm/act1` → `public/assets/audio/bgm/act1.mp3`.
|
||||
*
|
||||
* 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`.
|
||||
* Requests for the direct `/assets/audio/…` URLs keep working (they are the fallback for plain static hosts).
|
||||
*/
|
||||
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) {
|
||||
const root = path.join(path.resolve(publicDir), 'assets', 'audio');
|
||||
const segments = String(rest || '').split('/').filter((s) => s.length > 0);
|
||||
if (!segments.length || rest.endsWith('/')) { sendError(req, res, 404, '页面不存在 · Not found'); return; }
|
||||
if (segments.some((s) => s === '..' || s === '.')) { sendError(req, res, 403, '禁止访问 · Forbidden'); return; }
|
||||
// A leading or trailing dot would address something else (dotfiles, "x..mp3") — and the client never asks for it.
|
||||
if (segments.some((s) => s.startsWith('.') || s.endsWith('.'))) { sendError(req, res, 404, '页面不存在 · Not found'); return; }
|
||||
|
||||
const last = segments[segments.length - 1];
|
||||
const given = path.extname(last).toLowerCase();
|
||||
const wanted = AUDIO_EXTS.includes(given) ? given : '';
|
||||
const stem = wanted ? last.slice(0, -wanted.length) : last;
|
||||
if (!stem || stem.startsWith('.')) { sendError(req, res, 404, '页面不存在 · Not found'); return; }
|
||||
const dir = path.join(root, ...segments.slice(0, -1));
|
||||
if (dir !== root && !dir.startsWith(root + path.sep)) { sendError(req, res, 403, '禁止访问 · Forbidden'); return; }
|
||||
|
||||
// An explicit extension wins (`/media/bgm.ogg` → bgm.ogg), otherwise the usual order decides.
|
||||
const order = wanted ? [wanted, ...AUDIO_EXTS.filter((e) => e !== wanted)] : AUDIO_EXTS;
|
||||
for (const ext of order) {
|
||||
const absPath = path.join(dir, stem + ext);
|
||||
if (!absPath.startsWith(root + path.sep)) continue;
|
||||
let stat;
|
||||
try {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
stat = await fsp.stat(absPath);
|
||||
} catch { continue; }
|
||||
if (!stat.isFile()) continue;
|
||||
// serveFile decides Content-Type from the resolved name (`.mp3` → audio/mpeg) — Range/ETag handling is shared.
|
||||
// Cache policy is that of the public path the client would otherwise have asked for (`/assets/audio/…`, 1 day).
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await serveFile(req, res, absPath, stat, 'public', ['assets', 'audio', ...segments], query, gzipCache, log);
|
||||
return;
|
||||
}
|
||||
sendError(req, res, 404, '页面不存在 · Not found');
|
||||
}
|
||||
|
||||
async function serveFile(req, res, absPath, stat, mountName, segments, query, gzipCache, log) {
|
||||
const ext = path.extname(absPath).toLowerCase();
|
||||
const type = MIME[ext] || 'application/octet-stream';
|
||||
|
||||
@@ -281,6 +281,44 @@ describe('static http server', () => {
|
||||
assert.equal(textRange.body.toString(), js.slice(0, 2));
|
||||
});
|
||||
|
||||
test('extension-less /media audio route (download managers sniff .mp3 URLs)', async () => {
|
||||
const direct = await httpReq(srv.port, '/assets/audio/bgm.mp3');
|
||||
const media = await httpReq(srv.port, '/media/bgm');
|
||||
assert.equal(media.status, 200);
|
||||
assert.equal(media.headers['content-type'], 'audio/mpeg', 'resolved from the real .mp3 on disk');
|
||||
assert.equal(media.headers['accept-ranges'], 'bytes');
|
||||
assert.deepEqual(media.body, mp3, 'same bytes as the direct URL');
|
||||
assert.equal(media.headers['cache-control'], direct.headers['cache-control'], 'same 1-day policy as /assets/…');
|
||||
assert.equal(media.headers.etag, direct.headers.etag, 'ETag is the file validator, not the URL');
|
||||
|
||||
const range = await httpReq(srv.port, '/media/bgm', { headers: { range: 'bytes=0-9' } });
|
||||
assert.equal(range.status, 206);
|
||||
assert.equal(range.headers['content-range'], `bytes 0-9/${mp3.length}`);
|
||||
assert.deepEqual(range.body, mp3.subarray(0, 10));
|
||||
const head = await httpReq(srv.port, '/media/bgm', { method: 'HEAD' });
|
||||
assert.equal(head.status, 200);
|
||||
assert.equal(head.body.length, 0);
|
||||
|
||||
// The extension may still be given, and the other audio extension resolves too.
|
||||
assert.equal((await httpReq(srv.port, '/media/bgm.mp3')).status, 200);
|
||||
const ogg = await httpReq(srv.port, '/media/bgm.ogg');
|
||||
assert.equal(ogg.status, 200);
|
||||
assert.equal(ogg.headers['content-type'], 'audio/ogg');
|
||||
assert.equal(ogg.body.length, 64);
|
||||
|
||||
// …and it only ever reaches public/assets/audio.
|
||||
for (const p of ['/media/nope', '/media/bgm/', '/media/', '/media/.hidden', '/media/bgm.mp3/nope', '/media/js/app']) {
|
||||
const r = await httpReq(srv.port, p);
|
||||
assert.equal(r.status, 404, `${p} → 404`);
|
||||
assert.doesNotMatch(r.body.toString(), /TOP-SECRET-CONTENT/, `${p} must not leak files outside public/assets/audio`);
|
||||
}
|
||||
for (const p of ['/media/..%2f..%2fsecret.txt', '/media/bgm/../..%2f..%2fsecret.txt']) {
|
||||
const r = await httpReq(srv.port, p);
|
||||
assert.equal(r.status, 403, `${p} → 403 (same as the rest of the server)`);
|
||||
assert.doesNotMatch(r.body.toString(), /TOP-SECRET-CONTENT/);
|
||||
}
|
||||
});
|
||||
|
||||
test('path traversal and dotfiles are blocked', async () => {
|
||||
const attempts = [
|
||||
'/../secret.txt', '/%2e%2e/secret.txt', '/..%2fsecret.txt', '/%2e%2e%2fsecret.txt', '/data/../../secret.txt',
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// mediaUrl(): audio is fetched through an extension-less /media/… path so download managers (IDM / 迅雷 / FDM)
|
||||
// stop hijacking BGM playback with a "下载文件信息" dialog. See public/js/media.js for the full rationale.
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mediaUrl, isMediaUrl, MEDIA_PREFIX, AUDIO_EXTS } from '../public/js/media.js';
|
||||
|
||||
const ORIGIN = 'http://127.0.0.1:3000';
|
||||
|
||||
describe('mediaUrl: 音频地址去掉扩展名(躲开下载器嗅探)', () => {
|
||||
test('把 /assets/audio/**.mp3 改写成 /media/**', () => {
|
||||
assert.equal(mediaUrl('/assets/audio/bgm/m_sys_act1autochess_loop.mp3', ORIGIN), '/media/bgm/m_sys_act1autochess_loop');
|
||||
assert.equal(mediaUrl('/assets/audio/sfx/player/p_imp/hit.mp3', ORIGIN), '/media/sfx/player/p_imp/hit');
|
||||
// 绝对同源地址同样改写
|
||||
assert.equal(mediaUrl(`${ORIGIN}/assets/audio/bgm/a.mp3`, ORIGIN), '/media/bgm/a');
|
||||
// 查询串保留(?v=… 会拿到 immutable 缓存)
|
||||
assert.equal(mediaUrl('/assets/audio/bgm/a.mp3?v=2', ORIGIN), '/media/bgm/a?v=2');
|
||||
// 各音频扩展名
|
||||
for (const ext of AUDIO_EXTS) {
|
||||
assert.equal(mediaUrl(`/assets/audio/x/a${ext}`, ORIGIN), '/media/x/a', ext);
|
||||
}
|
||||
assert.equal(mediaUrl('/assets/audio/x/A.MP3', ORIGIN), '/media/x/A', '大小写不敏感');
|
||||
});
|
||||
|
||||
test('改写后的地址里不再有任何媒体扩展名(下载器就是按这个嗅探的)', () => {
|
||||
const out = mediaUrl('/assets/audio/bgm/m_bat_vtlionk_loop.mp3', ORIGIN);
|
||||
assert.equal(out.startsWith(MEDIA_PREFIX), true);
|
||||
assert.doesNotMatch(out, /\.(mp3|m4a|aac|ogg|oga|opus|wav)(\?|$)/i);
|
||||
});
|
||||
|
||||
test('不是我们的音频、或不是同源时不改写', () => {
|
||||
assert.equal(mediaUrl('/assets/img/a.png', ORIGIN), '/assets/img/a.png');
|
||||
assert.equal(mediaUrl('/assets/audio/bgm.m4a.bak', ORIGIN), '/assets/audio/bgm.m4a.bak', '扩展名不认识就原样返回');
|
||||
assert.equal(mediaUrl('https://cdn.example.com/assets/audio/a.mp3', ORIGIN), 'https://cdn.example.com/assets/audio/a.mp3', '别的源自己负责');
|
||||
assert.equal(mediaUrl('/data/assets.json', ORIGIN), '/data/assets.json');
|
||||
assert.equal(mediaUrl('', ORIGIN), '');
|
||||
assert.equal(mediaUrl(null, ORIGIN), null);
|
||||
assert.equal(mediaUrl(undefined, ORIGIN), undefined);
|
||||
assert.equal(mediaUrl('/assets/audio/', ORIGIN), '/assets/audio/', '空路径不改写(服务端只会 404)');
|
||||
});
|
||||
|
||||
test('会产生非法路径的输入不碰(点目录 / 空段)', () => {
|
||||
assert.equal(mediaUrl('/assets/audio/.hidden.mp3', ORIGIN), '/assets/audio/.hidden.mp3');
|
||||
// URL 解析本来就会把 .. 归一化,改写跟着归一化后的路径走(服务端仍是同一道校验)
|
||||
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 判断同源', () => {
|
||||
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');
|
||||
});
|
||||
});
|
||||
+70
-13
@@ -7,11 +7,20 @@ import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { bgmKeyFor, resolveBgm, SfxLimiter, AudioManager, normalAttackSfx } from '../../public/js/audio.js';
|
||||
import { mediaUrl } from '../../public/js/media.js';
|
||||
import { PHASE } from '../../shared/constants.js';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
const manifest = JSON.parse(readFileSync(path.join(ROOT, 'data', 'assets.json'), 'utf8'));
|
||||
|
||||
// audio.js 取音频时**先请求无扩展名的 /media/…**(正是为了躲开下载管理器对 .mp3 后缀的嗅探),
|
||||
// 只有那样 404 了才回退到 manifest 里的原始地址。所以「某个音效响了没有」不能拿原始地址去比对——
|
||||
// 那样断言的是一个客户端永远不会请求的 URL。下面两个助手把比对放到同一条换算上。
|
||||
/** 这个 manifest 地址被请求过吗(/media/ 形式或 404 后的原始形式)。 */
|
||||
const asked = (urls, raw) => urls.includes(mediaUrl(raw)) || urls.includes(raw);
|
||||
/** 这个 manifest 地址被请求了几次。 */
|
||||
const askedCount = (urls, raw) => urls.filter((u) => u === mediaUrl(raw) || u === raw).length;
|
||||
|
||||
describe('bgm selection', () => {
|
||||
test('route and phase → key', () => {
|
||||
assert.equal(bgmKeyFor('title', null), 'lobby');
|
||||
@@ -129,11 +138,11 @@ describe('AudioManager', () => {
|
||||
fw.fire('pointerdown');
|
||||
assert.equal(a.unlocked, true);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.ok(urls.includes(manifest.audio.bgm.prep.loop), 'BGM fetched after unlock');
|
||||
assert.ok(asked(urls, manifest.audio.bgm.prep.loop), 'BGM fetched after unlock');
|
||||
a.sfx('buy');
|
||||
a.sfx('nonexistent');
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.ok(urls.includes(manifest.audio.sfx.ui.buy));
|
||||
assert.ok(asked(urls, manifest.audio.sfx.ui.buy));
|
||||
// same loop URL ⇒ no restart
|
||||
const before = fw.made.started;
|
||||
a.playBgm('combat');
|
||||
@@ -144,8 +153,8 @@ describe('AudioManager', () => {
|
||||
a.setFieldUnits([{ id: 1, side: 'ally', spine: charId }, { id: 2, side: 'enemy', spine: 'enemy_nope' }]);
|
||||
a.handleBattleEvents([['atk', 1, 2, 'arrow'], ['dmg', 2, 100, 'phys'], ['die', 2], ['spawn', { id: 3, side: 'enemy', spine: 'x' }], ['bounty', 'p', 1]]);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.ok(urls.includes(manifest.audio.sfx.units[charId].attack));
|
||||
assert.ok(urls.includes(manifest.audio.sfx.battle.enemyDie), 'fallback death sound');
|
||||
assert.ok(asked(urls, manifest.audio.sfx.units[charId].attack));
|
||||
assert.ok(asked(urls, manifest.audio.sfx.battle.enemyDie), 'fallback death sound');
|
||||
assert.ok(a.limiter.active <= a.limiter.maxVoices);
|
||||
a.setVolumes({ muted: true });
|
||||
const n = urls.length;
|
||||
@@ -176,6 +185,51 @@ describe('AudioManager', () => {
|
||||
console.warn = origWarn;
|
||||
}
|
||||
});
|
||||
test('音频先走无扩展名的 /media/ 路由;只有它 404 才回退到带扩展名的原地址', async () => {
|
||||
const raw = manifest.audio.bgm.prep.loop;
|
||||
const media = mediaUrl(raw);
|
||||
assert.notEqual(media, raw, '前提:manifest 地址确实会被换算成 /media/ 路径');
|
||||
|
||||
// 第一发 404:必须看到 /media/ 在前、原地址在后,两者都请求过
|
||||
{
|
||||
const fw = fakeWindow();
|
||||
const urls = [];
|
||||
const origFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (u) => {
|
||||
urls.push(u);
|
||||
return u === media ? { ok: false, status: 404 } : { ok: true, 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));
|
||||
const first = urls.indexOf(media);
|
||||
const fallback = urls.indexOf(raw);
|
||||
assert.ok(first !== -1, '先试无扩展名路径');
|
||||
assert.ok(fallback !== -1, '404 后回退到原地址');
|
||||
assert.ok(first < fallback, '顺序必须是先 /media/ 再原地址');
|
||||
} finally { globalThis.fetch = origFetch; }
|
||||
}
|
||||
|
||||
// 第一发 200:不该再去碰带扩展名的地址(否则白白多一次请求,也正是 IDM 会拦的那个 URL)
|
||||
{
|
||||
const fw = fakeWindow();
|
||||
const urls = [];
|
||||
const origFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (u) => { urls.push(u); return { ok: true, 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), '走了 /media/');
|
||||
assert.ok(!urls.includes(raw), '/media/ 成功就不该再请求 .mp3 地址');
|
||||
} finally { globalThis.fetch = origFetch; }
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// user playtest #4 item 6: 纯烬艾雅法拉's skill sound rang outside her skill — her manifest `hit` is her S3 impact
|
||||
@@ -218,23 +272,26 @@ describe('impact sounds (user playtest #4 item 6)', () => {
|
||||
{ id: 3, side: 'enemy', kind: 'enemy', spine: enemyId },
|
||||
]);
|
||||
try {
|
||||
const own = new Set(Object.values(manifest.audio.sfx.units[AGOAT2]).filter((x) => typeof x === 'string'));
|
||||
// 她的技能形态(_s)文件:这条断言要盯住它们一个都没响,所以先确认音效表里真的有 _s ——
|
||||
// 否则集合为空,断言会永远成立、形同虚设。
|
||||
const ownSkill = Object.values(manifest.audio.sfx.units[AGOAT2]).filter((x) => typeof x === 'string' && /_s\.mp3$/.test(x));
|
||||
assert.ok(ownSkill.length > 0, '前提:她的音效表里确实有 _s(技能形态)文件');
|
||||
a.handleBattleEvents([['atk', 1, 2, 'orb'], ['heal', 2, 300], ['dmg', 2, 120, 'phys'], ['dmg', 2, 80, 'arts']]);
|
||||
await settle();
|
||||
assert.ok(urls.includes(manifest.audio.sfx.units[AGOAT2].attack), 'her cast sound');
|
||||
assert.ok(!urls.some((x) => x === manifest.audio.sfx.units[AGOAT2].hit), 'no impact sound of hers on the ally');
|
||||
assert.ok(!urls.some((x) => own.has(x) && /_s\.mp3$/.test(x)), 'nothing of her S3');
|
||||
assert.ok(asked(urls, manifest.audio.sfx.units[AGOAT2].attack), 'her cast sound');
|
||||
assert.ok(!asked(urls, manifest.audio.sfx.units[AGOAT2].hit), 'no impact sound of hers on the ally');
|
||||
assert.ok(!ownSkill.some((p) => asked(urls, p)), 'nothing of her S3');
|
||||
// a hostile attack still authors its impact — once, and only for a real hit (not an element gauge fill)
|
||||
a.handleBattleEvents([['atk', 3, 2, 'none'], ['dmg', 2, 900, 'burn']]);
|
||||
await settle();
|
||||
assert.ok(!urls.includes(manifest.audio.sfx.units[enemyId].hit), 'a gauge fill is no impact');
|
||||
assert.ok(!asked(urls, manifest.audio.sfx.units[enemyId].hit), 'a gauge fill is no impact');
|
||||
a.handleBattleEvents([['dmg', 2, 200, 'phys']]);
|
||||
await settle();
|
||||
assert.equal(urls.filter((x) => x === manifest.audio.sfx.units[enemyId].hit).length, 1, 'the impact');
|
||||
assert.equal(askedCount(urls, manifest.audio.sfx.units[enemyId].hit), 1, 'the impact');
|
||||
a.limiter.lastByUnit.clear(); a.limiter.lastByUrl.clear();
|
||||
a.handleBattleEvents([['dmg', 2, 50, 'phys']]);
|
||||
await settle();
|
||||
assert.equal(urls.filter((x) => x === manifest.audio.sfx.units[enemyId].hit).length, 1, 'a later tick is not the same attack\'s impact');
|
||||
assert.equal(askedCount(urls, manifest.audio.sfx.units[enemyId].hit), 1, 'a later tick is not the same attack\'s impact');
|
||||
} finally { restore(); }
|
||||
});
|
||||
|
||||
@@ -251,12 +308,12 @@ describe('impact sounds (user playtest #4 item 6)', () => {
|
||||
try {
|
||||
a.handleBattleEvents([['atk', 5, 6, 'chain']]);
|
||||
await settle();
|
||||
assert.ok(!urls.includes(manifest.audio.sfx.units[enemyId].attack), 'the bounce is not an enemy attack');
|
||||
assert.ok(!asked(urls, manifest.audio.sfx.units[enemyId].attack), 'the bounce is not an enemy attack');
|
||||
a.handleBattleEvents([['atk', 1, 5, 'arrow']]);
|
||||
fakeNow += 4000;
|
||||
a.handleBattleEvents([['dmg', 5, 100, 'phys']]);
|
||||
await settle();
|
||||
assert.ok(!urls.includes(manifest.audio.sfx.units[charId].hit), '4 s later: not that attack\'s impact');
|
||||
assert.ok(!asked(urls, manifest.audio.sfx.units[charId].hit), '4 s later: not that attack\'s impact');
|
||||
} finally { globalThis.performance = perf; restore(); }
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user