feedback2: merge GitHub master (PR #28 extension-less /media audio route, PR #29 explorer.exe browser opener)

This commit is contained in:
sganggs committed 2026-10-03 23:06:10 +08:00
commit ff8db862c9
10 files changed
+569 -30

No files matched your search

+23 -1
View File
@@ -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;
@@ -215,6 +216,20 @@ export class SfxLimiter {
// ---- 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 {
/**
* @param {{ getManifest?: () => any, win?: any }} [opts]
@@ -383,7 +398,14 @@ 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 (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}`);
const ab = await res.arrayBuffer();
return await new Promise((resolve) => {
+48
View File
@@ -0,0 +1,48 @@
// 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
// 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 whenever the
// /media/ response is unusable (a 404, or a 200 that is not audio at all — some static hosts answer a missing
// path with the SPA's index.html).
import { MEDIA_PREFIX, AUDIO_EXTS } from '../../shared/media.js';
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}`;
}
+12 -16
View File
@@ -16,6 +16,8 @@ import { spawn, spawnSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import fs from 'node:fs';
// 打开浏览器只有一份实现(走 shell 关联 = 默认浏览器,且不会把浏览器拉成提权)
import { openBrowser as openInBrowser } from './open-browser.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const IS_WIN = process.platform === 'win32';
@@ -46,21 +48,7 @@ function parseArgs(argv) {
}
function openBrowser(url) {
try {
let cmd; let args;
if (IS_WIN) { cmd = 'rundll32'; args = ['url.dll,FileProtocolHandler', url]; }
else if (process.platform === 'darwin') { cmd = 'open'; args = [url]; }
else {
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return false;
cmd = 'xdg-open'; args = [url];
}
const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true });
child.on('error', () => {});
child.unref();
return true;
} catch {
return false;
}
return openInBrowser(url) !== null;
}
function printShare(port) {
@@ -132,4 +120,12 @@ async function main() {
return exited;
}
main().then((code) => { process.exitCode = code; }, (e) => { console.error(e?.stack || e); process.exitCode = 1; });
// Same convention as tools/setup.mjs: the helpers above are importable, but only running this file starts anything.
// Without the guard, importing launch.mjs would fall through to main() in the background and bind a port.
function isMain() {
try { return !!process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); } catch { return false; }
}
if (isMain()) {
main().then((code) => { process.exitCode = code; }, (e) => { console.error(e?.stack || e); process.exitCode = 1; });
}
+101
View File
@@ -0,0 +1,101 @@
// Opening the game page in the player's browser.
//
// Why not `rundll32 url.dll,FileProtocolHandler` (the usual one-liner): it runs *inside* the caller's token, so a
// launcher started from an elevated console starts Edge/Chrome **elevated** too — and from then on Edge greets the
// player with 「Microsoft Edge 未响应,因为现有实例正在以提升的权限运行。是否要用普通权限重启现有实例? 是/否」
// instead of just opening the page.
//
// `explorer.exe <url>` avoids that because Explorer is not the process that opens the browser: a second Explorer
// invocation hands the request to the shell instance that is already running, and *that* one (started at logon, not
// elevated) resolves the URL through the default-browser association. Caveat: this hand-off is how the shell behaves
// in practice, not an interface Microsoft documents or promises — treat it as the best available trick rather than a
// supported API, and keep the rundll32 rung around for hosts where explorer.exe cannot be found.
//
// Windows therefore has a single rung, chosen synchronously from what is actually on disk: explorer.exe when it is
// there, rundll32 otherwise. There is deliberately no "try one, fall back on spawn failure" ladder: spawn() reports
// ENOENT / EACCES through the child's asynchronous `error` event, not by throwing, so a fallback wired to a thrown
// exception would never fire in practice.
//
// There is deliberately no `cmd /c start "" <url>` rung either: cmd re-parses everything after `/c`, so a URL holding
// an `&` (e.g. the room link `?room=ABCD&name=…`) is split at the `&` — cmd runs `start "" <url-up-to-&>` and then
// tries to run the remainder as a second command. The browser then opens a truncated address, or a stray console
// window flashes. Passing an argument array to CreateProcess avoids the shell entirely, which is why the remaining
// rungs are safe.
import fs from 'node:fs';
import path from 'node:path';
import { spawn } from 'node:child_process';
/** Does this path exist? Injectable as `exists` so the Windows rung can be tested without the host's filesystem. */
function realExists(p) {
try { return fs.existsSync(p); } catch { return false; }
}
/**
* Absolute path of a system executable, or null when it is not where we expect it.
*
* Built with **win32** semantics whatever the host is: the value is handed to a Windows process, and the rung is
* also inspected from tests (CI runs them on Linux, where `path.join` is posix and would emit `C:\Windows/explorer.exe`
* — a mixed-separator string that never matches a real Windows path).
* @param {NodeJS.ProcessEnv} env
* @param {string} sub subdirectory under the Windows root ('' / '.' for the root itself)
* @param {string} name
* @param {(p: string) => boolean} exists
* @returns {string | null}
*/
function systemExe(env, sub, name, exists) {
const root = env.SystemRoot || env.windir || 'C:\\Windows';
const abs = path.win32.join(root, sub || '.', name);
return exists(abs) ? abs : null;
}
/**
* Candidate launch commands for `url`, best first.
*
* At most one entry per platform: which rung Windows gets is decided here, synchronously, from the filesystem.
* @param {string} url
* @param {{ platform?: string, env?: NodeJS.ProcessEnv, exists?: (p: string) => boolean }} [o]
* `exists` defaults to the real filesystem; pass one in to test the Windows rung from any host.
* @returns {{ cmd: string, args: string[], label: string }[]}
*/
export function browserCommands(url, { platform = process.platform, env = process.env, exists = realExists } = {}) {
if (platform === 'win32') {
// shell association: the default browser, opened by the non-elevated shell instance (see the header)
const explorer = systemExe(env, '.', 'explorer.exe', exists);
if (explorer) return [{ cmd: explorer, args: [url], label: 'explorer' }];
// legacy fallback for the theoretical case of a Windows host without explorer.exe; it *does* inherit our token,
// so it is only ever reached when the de-elevating rung is unavailable
const rundll32 = systemExe(env, 'System32', 'rundll32.exe', exists);
if (rundll32) return [{ cmd: rundll32, args: ['url.dll,FileProtocolHandler', url], label: 'rundll32' }];
return [];
}
if (platform === 'darwin') return [{ cmd: 'open', args: [url], label: 'open' }];
if (env.DISPLAY || env.WAYLAND_DISPLAY) return [{ cmd: 'xdg-open', args: [url], label: 'xdg-open' }];
return [];
}
/**
* Open `url` with the player's default browser. Returns the label of the launcher that was spawned, or null when
* there is nothing to start (headless Linux, no known system binary) — callers then just print the URL.
*
* The label is returned as soon as spawn() accepted the command. A missing binary surfaces later as the child's
* `error` event (ENOENT / EACCES), which is why one is attached: an unhandled `error` event would crash the
* launcher, and retrying a different rung at that point would mean opening a second browser after a race.
* @param {string} url
* @param {{ spawnImpl?: typeof spawn, platform?: string, env?: NodeJS.ProcessEnv,
* exists?: (p: string) => boolean, log?: (m: string) => void }} [o]
* @returns {string | null}
*/
export function openBrowser(url, { spawnImpl = spawn, platform = process.platform, env = process.env, exists = realExists, log } = {}) {
for (const { cmd, args, label } of browserCommands(url, { platform, env, exists })) {
try {
const child = spawnImpl(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true });
if (!child || typeof child.unref !== 'function') continue;
child.on?.('error', () => {});
child.unref();
return label;
} catch (err) {
log?.(`${label}: ${err?.code || err?.message || err}`);
}
}
return null;
}
+54
View File
@@ -8,6 +8,9 @@
// /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
// /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;
// 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
@@ -39,6 +42,7 @@ import { Network, SessionRegistry, NET_DEFAULTS } from './net.js';
import { Lobby } from './lobby.js';
import { getData, loadData } from './data.js';
import { PROTOCOL_VERSION, APP_VERSION } from '../shared/constants.js';
import { MEDIA_PREFIX, AUDIO_EXTS } from '../shared/media.js';
/** Repository root. */
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -311,6 +315,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 +381,51 @@ 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).
* `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.
*/
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';
+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']);
+38
View File
@@ -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',
+53
View File
@@ -0,0 +1,53 @@
// 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 } from '../public/js/media.js';
// 前缀与扩展名列表只有一份(客户端和服务端都从这里取),所以断言也直接盯住这一份。
import { MEDIA_PREFIX, AUDIO_EXTS } from '../shared/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('没有 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');
});
});
+94
View File
@@ -0,0 +1,94 @@
// openBrowser(): 用玩家的默认浏览器打开页面,且不会把浏览器拉成提权进程。
// 背景:`rundll32 url.dll,FileProtocolHandler` 继承调用方令牌,从提权终端启动会把 Edge 也拉成提权,之后 Edge 每次
// 都弹「现有实例正在以提升的权限运行」;交给 shell(explorer.exe <url>)则由**已经在运行**的、非提权的 shell 实例
// 转发给默认浏览器。
// 另外这里**故意没有** `cmd /c start "" <url>` 这一档:cmd 会重新解析 /c 之后的整串,URL 里的 `&` 被当成分隔符,
// 浏览器只收到被截断的地址(见最后一条测试)。
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { browserCommands, openBrowser } from '../scripts/open-browser.mjs';
// 这一档是给 Windows 用的,CI 却在 Linux 上跑:探测「C:\Windows\explorer.exe 在不在」必须能被注入,
// 否则测试就在断言**运行这台机器**的文件系统——Linux 上该路径不存在,测试自然红。
const hasWin = () => true; // 假装 SystemRoot 下该有的可执行文件都在
const noExplorer = (p) => !/explorer\.exe$/i.test(p); // 只缺 explorer.exe,rundll32 还在
const emptyWin = () => false; // 假装一个都没找到
const WIN = { platform: 'win32', env: { SystemRoot: 'C:\\Windows' }, exists: hasWin };
describe('openBrowser: 默认浏览器 + 不提权', () => {
test('explorer.exe 在就用它:URL 原样交给 shell,由默认浏览器打开', () => {
const cmds = browserCommands('http://127.0.0.1:3000/', WIN);
assert.deepEqual(cmds.map((c) => c.label), ['explorer']);
assert.equal(cmds[0].cmd, 'C:\\Windows\\explorer.exe', '走 Windows 绝对路径,且分隔符是反斜杠');
assert.deepEqual(cmds[0].args, ['http://127.0.0.1:3000/'], 'URL 原样交给 shell,由默认浏览器打开');
// 不能是 rundll32:从提权终端启动时它会把浏览器也提权
assert.notEqual(cmds[0].label, 'rundll32');
// 路径必须用 win32 语义拼:Linux 上跑测试时 path.join 是 posix,会拼出 C:\Windows/explorer.exe 这种混合分隔符
for (const c of cmds) assert.ok(!c.cmd.includes('/'), `${c.cmd} 不该出现正斜杠`);
});
test('explorer.exe 不在才退到 rundll32,且只有这一档', () => {
const cmds = browserCommands('http://x/', { platform: 'win32', env: { SystemRoot: 'C:\\Windows' }, exists: noExplorer });
assert.deepEqual(cmds.map((c) => c.label), ['rundll32']);
assert.equal(cmds[0].cmd, 'C:\\Windows\\System32\\rundll32.exe');
assert.deepEqual(cmds[0].args, ['url.dll,FileProtocolHandler', 'http://x/']);
});
test('两档都找不到时不猜裸命令名,直接没有候选(调用方只打印地址)', () => {
assert.deepEqual(browserCommands('http://x/', { platform: 'win32', env: { SystemRoot: 'C:\\Windows' }, exists: emptyWin }), []);
// 没给 SystemRoot 时按默认的 C:\Windows 找绝对路径
assert.equal(browserCommands('http://x/', { platform: 'win32', env: {}, exists: hasWin })[0].cmd, 'C:\\Windows\\explorer.exe');
// windir 也认
assert.equal(browserCommands('http://x/', { platform: 'win32', env: { windir: 'D:\\Win' }, exists: hasWin })[0].cmd, 'D:\\Win\\explorer.exe');
});
test('macOS 用 open,无桌面的 Linux 不启动任何东西', () => {
assert.deepEqual(browserCommands('http://x/', { platform: 'darwin', env: {} }).map((c) => c.label), ['open']);
assert.deepEqual(browserCommands('http://x/', { platform: 'linux', env: {} }), []);
assert.deepEqual(browserCommands('http://x/', { platform: 'linux', env: { DISPLAY: ':0' } }).map((c) => c.label), ['xdg-open']);
});
test('openBrowser 启动那一档并返回它的名字;spawn 失败是异步 error 事件,不影响返回值', () => {
const spawned = [];
let errorListener = false;
const ok = openBrowser('http://127.0.0.1:3000/', {
...WIN,
spawnImpl: (cmd, args) => {
spawned.push([cmd, args]);
// 真实 ChildProcess:ENOENT / EACCES 不是抛出来,而是之后 emit('error')
return { unref() {}, on(ev) { if (ev === 'error') errorListener = true; } };
},
});
assert.equal(ok, 'explorer');
assert.deepEqual(spawned, [['C:\\Windows\\explorer.exe', ['http://127.0.0.1:3000/']]]);
assert.ok(errorListener, '必须挂 error 监听,否则未处理的 error 事件会让启动器崩掉');
});
test('没有可用的启动方式时返回 null(调用方只打印地址)', () => {
assert.equal(openBrowser('http://x/', { platform: 'linux', env: {} }), null);
assert.equal(openBrowser('http://x/', { platform: 'win32', env: {}, exists: emptyWin }), null);
// spawn 同步抛错(现实中不该发生)只会被记下来然后继续找下一档,这里没有下一档
const logged = [];
assert.equal(openBrowser('http://x/', { ...WIN, spawnImpl: () => { throw new Error('no'); }, log: (m) => logged.push(m) }), null);
assert.equal(logged.length, 1);
});
test('不带 `cmd /c start` 这一档:URL 里的 & 会被 cmd 当成命令分隔符而截断', () => {
// 房间链接就长这样:`?room=ABCD&name=…`。交给 `cmd /c start "" <url>` 时,cmd 会在 & 处断开,
// 先执行 `start "" <截断到 & 的地址>`,再拿剩下半截当第二条命令 —— 浏览器打开的是错的地址。
const url = 'http://127.0.0.1:3000/?room=ABCD&name=me';
const cmds = browserCommands(url, WIN);
assert.ok(!cmds.some((c) => /^cmd(\.exe)?$/i.test(c.cmd)), '候选里不该再有 cmd.exe');
assert.ok(!cmds.some((c) => c.args.includes('start')), '也不该再用 start');
// 每个候选都把完整 URL 作为**一个 argv 元素**传下去:CreateProcess 直接收参数数组,不经过 cmd 解析
for (const c of cmds) assert.ok(c.args.includes(url), `${c.label} 必须原样收到完整 URL`);
});
test('默认用真实文件系统探测(这台机器上跑得起来就说明探测没被写坏)', () => {
// 不注入 exists:结果取决于当前主机,但**不该抛异常**,且候选数量与平台一致
const cmds = browserCommands('http://x/', { platform: process.platform, env: process.env });
const want = process.platform === 'win32' || process.platform === 'darwin' ? 1
: (process.env.DISPLAY || process.env.WAYLAND_DISPLAY ? 1 : 0);
assert.equal(cmds.length, want);
});
});
+126 -13
View File
@@ -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,107 @@ 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; }
}
// 第一发 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; }
}
});
});
// user playtest #4 item 6: 纯烬艾雅法拉's skill sound rang outside her skill — her manifest `hit` is her S3 impact
@@ -218,23 +328,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 +364,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(); }
});
});