freeguy2006's picture
Claude Opus 4.8 (1M context)
fix(pvp): 移除對手名的 Google displayName fallback,只用勇者名
9e0e17c
Raw History Blame Contribute Delete
18.1 kB
/**
* 鬼影 REST 伺服器(模式 A,04 §5)。Fastify,路由極簡。
* PvP WebSocket(M5)日後在同進程加掛,鬼影 REST 不動(07 §9)。
*/
import Fastify, { type FastifyInstance } from "fastify";
import fastifyStatic from "@fastify/static";
import websocketPlugin from "@fastify/websocket";
import { randomUUID } from "node:crypto";
import { cleanHeroName, type GhostRecord, type ClassType } from "@wcg/battle-core";
import type { GhostRepository } from "./repository.js";
import type { UserRepository } from "./userRepository.js";
import type { OAuthProvider } from "./oauth.js";
import { validateGhostShape, verifyGhost } from "./ghostService.js";
import { registerAuthRoutes, currentUserId } from "./authRoutes.js";
import { registerDiscordInteractions } from "./discordInteractions.js";
import { PvpHub, type PvpConn } from "./pvpHub.js";
import { CoopHub, type CoopConn } from "./coopHub.js";
import type { Side } from "./coopMatch.js";
export interface ServerOptions {
repo: GhostRepository;
/** true → 重播驗證失敗則拒絕入庫(422);false → 仍入庫但標記 verified=false。 */
requireVerified?: boolean;
/** 提供前端建置目錄路徑時,同進程一併服務靜態檔(單容器部署,如 HF Spaces)。 */
webRoot?: string;
/** 提供使用者儲存庫 → 啟用帳號/統計路由(/api/auth/*、/api/me、/api/me/runs);未提供則完全不註冊。 */
userRepo?: UserRepository;
/** OAuth 與 cookie 設定(沒設 provider secret 則該 provider 不在 providers 內)。 */
oauth?: {
providers?: Record<string, OAuthProvider>;
redirectBase?: string;
cookieSecure?: boolean;
devLogin?: boolean;
adminToken?: string;
adminEmails?: string[];
};
/** PvP PLAN 相時限(ms,預設 100000)。 */
tPlanMs?: number;
/** PvP draft 每抽時限(ms,預設 60000)。 */
tDraftMs?: number;
/** 合作 PvE 每回合/商議窗時限(ms,預設 90000)。 */
tCoopTurnMs?: number;
/** 是否啟用開局 draft(預設 true)。 */
enableDraft?: boolean;
}
interface PvpClientMsg {
type: "CREATE_ROOM" | "QUICK_MATCH" | "CANCEL_QUEUE" | "JOIN" | "RECONNECT" | "SET_CLASS" | "PLAY_CARD" | "CHOOSE_CARDS" | "LOCK" | "SURRENDER" | "DRAFT_PICK" | "REMATCH";
code?: string;
classType?: string; // 房內選職業("WARRIOR" | "BARBARIAN")
token?: string; // 斷線重連 token
handIndex?: number;
indices?: number[]; // 互動選牌:選定的手牌索引(野蠻人 chooseDiscard)
choiceIndex?: number; // draft 三選一:選第幾張(0..2)
pickIndex?: number; // 這是第幾抽(防延遲雙擊套用到下一抽)
}
/** 合作 PvE client → server 訊息。 */
interface CoopClientMsg {
type: "CREATE_ROOM" | "QUICK_MATCH" | "CANCEL_QUEUE" | "JOIN" | "RECONNECT" | "SELECT_BOSS" | "BACK_TO_BOSS" | "SET_CLASS" | "CONFIRM_CLASS" | "PROPOSE_ORDER" | "PLAY_CARD" | "CHOOSE_CARDS" | "END_TURN" | "DRAFT_PICK" | "SURRENDER" | "REMATCH";
code?: string;
token?: string;
bossId?: string;
classType?: string;
first?: Side; // 商議先手
handIndex?: number;
indices?: number[];
choiceIndex?: number;
pickIndex?: number;
}
/** 安全解析職業字串(只接受合法值,預設戰士)。PvP 已開放魔法師。 */
function parseClass(v: unknown): ClassType {
return v === "BARBARIAN" ? "BARBARIAN" : v === "MAGE" ? "MAGE" : "WARRIOR";
}
export function buildServer(opts: ServerOptions): FastifyInstance {
const { repo, requireVerified = false, webRoot, userRepo } = opts;
// trustProxy:部署在反向代理後(HF Spaces 單容器),req.ip 才會讀 X-Forwarded-For 的真實用戶 IP,
// 否則所有人共用代理 IP → 鬼影上傳的 per-IP 速率限制會把正常用戶連坐擋成 429、且防 DoS 形同虛設。
// 設為 1(只信最近一跳)而非 true:true 會信整條 XFF 鏈,讓 client 自帶任意 XFF 偽造 req.ip → 繞過所有 per-IP 限流。
const app = Fastify({ logger: false, bodyLimit: 1_000_000, trustProxy: 1 });
// 安全標頭(縱深防禦):nosniff、referrer-policy、CSP frame-ancestors(允 Discord Activity 內嵌=防點擊劫持)、HSTS(https)。
// 刻意不設限制 script/style 的嚴格 CSP,避免弄壞 Vite SPA;frame-ancestors 為低回歸風險子集。
app.addHook("onSend", async (req, reply, payload) => {
reply.header("X-Content-Type-Options", "nosniff");
reply.header("Referrer-Policy", "no-referrer");
reply.header("Content-Security-Policy", "frame-ancestors 'self' https://discord.com https://*.discord.com");
if (req.protocol === "https") reply.header("Strict-Transport-Security", "max-age=15552000; includeSubDomains");
return payload;
});
const hub = new PvpHub({ tPlanMs: opts.tPlanMs ?? 99000, tDraftMs: opts.tDraftMs ?? 30000, enableDraft: opts.enableDraft }); // 多人手牌 plan 99s、選獎勵牌 30s
const coopHub = new CoopHub({ tTurnMs: opts.tCoopTurnMs, tDraftMs: opts.tDraftMs ?? 30000, enableDraft: opts.enableDraft }); // 選獎勵牌 30s(行動窗/商議窗預設見 coopHub)
// 輕量防 DoS:鬼影上傳 per-IP 速率限制(滑動視窗,無外部相依)。
const postHits = new Map<string, number[]>();
const POST_WINDOW_MS = 60_000;
const POST_MAX = 20; // 每 IP 每分鐘最多 20 次上傳
const rateLimited = (ip: string): boolean => {
const now = Date.now();
const hits = (postHits.get(ip) ?? []).filter((t) => now - t < POST_WINDOW_MS);
if (hits.length >= POST_MAX) { postHits.set(ip, hits); return true; }
hits.push(now);
postHits.set(ip, hits);
if (postHits.size > 10000) {
// 先刪掉已全部過期的死桶(不放寬仍活躍的 IP)。
for (const [k, arr] of postHits) if (now - (arr[arr.length - 1] ?? 0) >= POST_WINDOW_MS) postHits.delete(k);
// 仍過大(分散式攻擊讓死桶清不掉):淘汰「本視窗命中數最少」的 ¼,而非整表 clear()。
// 如此重度命中(逼近上限)的 IP 仍被限流,只有近乎閒置的桶被回收 → 不會瞬間放寬所有 IP。
if (postHits.size > 20000) {
const byFewestHits = [...postHits.entries()].sort((a, b) => a[1].length - b[1].length);
const drop = Math.ceil(byFewestHits.length / 4);
for (let i = 0; i < drop; i++) postHits.delete(byFewestHits[i]![0]);
}
}
return false;
};
app.get("/api/health", async () => ({ ok: true, ghosts: repo.playableCount(), stored: repo.count() }));
// 上傳鬼影存檔(破第 11 關後)
app.post("/api/ghosts", async (req, reply) => {
if (rateLimited(req.ip)) return reply.code(429).send({ error: "rate-limited" });
const err = validateGhostShape(req.body);
if (err) return reply.code(400).send({ error: "invalid-body", reason: err });
const record = req.body as GhostRecord;
const verdict = verifyGhost(record);
if (requireVerified && !verdict.ok) {
return reply.code(422).send({ error: "verification-failed", reason: verdict.reason });
}
// 權威過濾勇者名字(客戶端可繞過 → 後端為準)。meta 不參與 verifyGhost,故在驗證後清洗不影響判定。
if (record.meta && typeof record.meta.heroName === "string") {
const cleaned = cleanHeroName(record.meta.heroName);
record.meta.heroName = cleaned.length > 0 ? cleaned : undefined;
}
const stored = repo.add(record, verdict.ok);
return reply.code(201).send({ id: stored.id, verified: stored.verified, reason: verdict.reason });
});
// 進第 12 關抽一份鬼影;無存檔回 204
app.get("/api/ghosts/random", async (_req, reply) => {
const g = repo.random();
if (!g) return reply.code(204).send();
return reply.send(g);
});
app.get<{ Params: { id: string } }>("/api/ghosts/:id", async (req, reply) => {
const g = repo.getById(req.params.id);
if (!g) return reply.code(404).send({ error: "not-found" });
return reply.send(g);
});
// 帳號 / 個人統計(OAuth 登入、session cookie、權威重播聚合)。僅在有提供 userRepo 時掛載。
if (userRepo) {
registerAuthRoutes(app, {
userRepo,
providers: opts.oauth?.providers ?? {},
redirectBase: opts.oauth?.redirectBase ?? "",
cookieSecure: opts.oauth?.cookieSecure ?? false,
devLogin: opts.oauth?.devLogin ?? false,
adminToken: opts.oauth?.adminToken,
adminEmails: opts.oauth?.adminEmails,
});
}
// Discord 互動端點:讓「頻道打 /play」用 LAUNCH_ACTIVITY 啟動 Activity(自帶 Ed25519 驗簽)。
registerDiscordInteractions(app);
// 即時 PvP WebSocket(M5):房間碼配對 + 四相同步結算(07)。與鬼影 REST 同進程。
app.register(websocketPlugin, { options: { maxPayload: 64 * 1024 } }); // 防超大訊息 OOM
let wsConns = 0;
const WS_MAX_CONNS = 400; // 同時 WS 連線上限(防連線數 DoS;每連線最多 1 房,亦間接限房間數)
// per-IP 連線上限:防單一來源吃光全域 400 槽把所有人擋在外(設稍寬以容共用出口 IP;真實 IP 由 trustProxy:1 提供)。
const WS_MAX_PER_IP = 16;
const wsPerIp = new Map<string, number>();
const ipAcquire = (ip: string): boolean => {
const n = wsPerIp.get(ip) ?? 0;
if (n >= WS_MAX_PER_IP) return false;
wsPerIp.set(ip, n + 1);
return true;
};
const ipRelease = (ip: string): void => {
const n = (wsPerIp.get(ip) ?? 1) - 1;
if (n <= 0) wsPerIp.delete(ip); else wsPerIp.set(ip, n);
};
// per-連線訊息令牌桶:防訊息洪水吃滿單執行緒事件迴圈。每秒回補 WS_MSG_RATE、可累至 WS_MSG_BURST;
// 桶空即丟棄該訊息(在 JSON.parse 前就擋、省 CPU);連續嚴重超量則踢連線。正常對局每回合僅數則,遠低於上限。
const WS_MSG_RATE = 40, WS_MSG_BURST = 80, WS_MSG_KICK = 400;
const makeMsgGate = () => {
let tokens = WS_MSG_BURST, last = Date.now(), overflow = 0;
return (): "ok" | "drop" | "kick" => {
const now = Date.now();
tokens = Math.min(WS_MSG_BURST, tokens + ((now - last) / 1000) * WS_MSG_RATE);
last = now;
if (tokens >= 1) { tokens -= 1; overflow = 0; return "ok"; }
return ++overflow > WS_MSG_KICK ? "kick" : "drop";
};
};
app.register(async (f) => {
f.get("/ws/pvp", { websocket: true }, (socket, req) => {
const ip = req.ip;
if (wsConns >= WS_MAX_CONNS || !ipAcquire(ip)) { try { socket.close(); } catch { /* ignore */ } return; }
wsConns++;
const gate = makeMsgGate();
const playerId = randomUUID();
const conn: PvpConn = {
playerId,
// 對手名只用勇者名(client 連線訊息帶 heroName 覆寫);不洩漏 Google 帳號名。未設勇者名 → 前端退回「對手」。
name: undefined,
send: (m) => {
try {
socket.send(JSON.stringify(m));
} catch {
/* 連線已關 */
}
},
};
socket.on("message", (raw: Buffer) => {
const g = gate();
if (g === "drop") return;
if (g === "kick") { try { socket.close(); } catch { /* ignore */ } return; }
let msg: PvpClientMsg;
try {
msg = JSON.parse(raw.toString());
} catch {
return;
}
// 整段以 try/catch 包覆:任一對局運算(引擎 throw、未知卡 id 等)只結束該連線,絕不讓例外逃出回呼崩潰全服。
try {
// 勇者名(client 連線時帶;覆寫連線當下從 session 取的顯示名)→ 下發給對手當「對手名」
{ const raw2 = (msg as { heroName?: unknown }).heroName; if (typeof raw2 === "string" && raw2.trim()) { const hn = cleanHeroName(raw2); if (hn) conn.name = hn; } }
switch (msg.type) {
case "CREATE_ROOM": hub.createRoom(conn); break;
case "QUICK_MATCH": hub.quickMatch(conn); break;
case "CANCEL_QUEUE": hub.cancelQueue(playerId); break;
case "JOIN": hub.join(String(msg.code ?? "").slice(0, 16), conn); break;
case "RECONNECT": hub.reconnect(String(msg.token ?? "").slice(0, 64), conn); break;
case "SET_CLASS": hub.setClass(playerId, parseClass(msg.classType)); break;
case "PLAY_CARD": {
const idx = Number(msg.handIndex);
if (Number.isInteger(idx) && idx >= 0 && idx < 64) hub.play(playerId, idx);
break;
}
case "CHOOSE_CARDS": {
const idxs = Array.isArray(msg.indices) ? msg.indices.filter((x) => Number.isInteger(x) && x >= 0 && x < 64).slice(0, 16) : [];
hub.choose(playerId, idxs);
break;
}
case "DRAFT_PICK": {
const ci = Number(msg.choiceIndex);
const pi = Number(msg.pickIndex);
if (Number.isInteger(ci) && ci >= 0 && ci < 3) {
hub.draftPick(playerId, ci, Number.isInteger(pi) ? pi : undefined);
}
break;
}
case "LOCK": hub.lock(playerId); break;
case "SURRENDER": hub.surrender(playerId); break;
case "REMATCH": hub.rematch(playerId); break;
}
} catch (e) {
console.error(`[server] pvp message error (player=${playerId}):`, e);
try { conn.send({ type: "ERROR", message: "對局發生錯誤" }); } catch { /* 連線已關 */ }
try { hub.disconnect(playerId); } catch { /* ignore */ }
try { socket.close(); } catch { /* ignore */ }
}
});
socket.on("error", () => { try { hub.disconnect(playerId); } catch { /* ignore */ } });
socket.on("close", () => { wsConns = Math.max(0, wsConns - 1); ipRelease(ip); try { hub.disconnect(playerId); } catch { /* ignore */ } });
});
// 線上雙人合作 PvE WebSocket(順序制;單一 COOP_PHASE 視圖廣播)。
f.get("/ws/coop", { websocket: true }, (socket, req) => {
const ip = req.ip;
if (wsConns >= WS_MAX_CONNS || !ipAcquire(ip)) { try { socket.close(); } catch { /* ignore */ } return; }
wsConns++;
const gate = makeMsgGate();
const playerId = randomUUID();
const conn: CoopConn = {
playerId,
send: (m) => { try { socket.send(JSON.stringify(m)); } catch { /* 連線已關 */ } },
};
socket.on("message", (raw: Buffer) => {
const g = gate();
if (g === "drop") return;
if (g === "kick") { try { socket.close(); } catch { /* ignore */ } return; }
let msg: CoopClientMsg;
try { msg = JSON.parse(raw.toString()); } catch { return; }
try {
// 勇者名(client 連線時帶)→ 下發給隊友當「隊友名」
{ const raw2 = (msg as { heroName?: unknown }).heroName; if (typeof raw2 === "string" && raw2.trim()) { const hn = cleanHeroName(raw2); if (hn) conn.name = hn; } }
switch (msg.type) {
case "CREATE_ROOM": coopHub.createRoom(conn); break;
case "QUICK_MATCH": coopHub.quickMatch(conn); break;
case "CANCEL_QUEUE": coopHub.cancelQueue(playerId); break;
case "JOIN": coopHub.join(String(msg.code ?? "").slice(0, 16), conn); break;
case "RECONNECT": if (typeof msg.token === "string") coopHub.reconnect(msg.token, conn); break;
case "SELECT_BOSS": if (typeof msg.bossId === "string") coopHub.selectBoss(playerId, msg.bossId.slice(0, 32)); break;
case "BACK_TO_BOSS": coopHub.backToBossSelect(playerId); break;
// 不用 parseClass(會把 MAGE 強制成 WARRIOR);傳原字串讓 coopHub 驗證+對魔法師回友善錯誤。
case "SET_CLASS": if (typeof msg.classType === "string") coopHub.setClass(playerId, msg.classType as ClassType); break;
case "CONFIRM_CLASS": coopHub.confirmClass(playerId); break;
case "PROPOSE_ORDER": if (msg.first === "A" || msg.first === "B") coopHub.propose(playerId, msg.first); break;
case "PLAY_CARD": {
const idx = Number(msg.handIndex);
if (Number.isInteger(idx) && idx >= 0 && idx < 64) coopHub.play(playerId, idx);
break;
}
case "CHOOSE_CARDS": {
const idxs = Array.isArray(msg.indices) ? msg.indices.filter((x) => Number.isInteger(x) && x >= 0 && x < 64).slice(0, 16) : [];
coopHub.choose(playerId, idxs);
break;
}
case "END_TURN": coopHub.endTurn(playerId); break;
case "DRAFT_PICK": {
const ci = Number(msg.choiceIndex);
const pi = Number(msg.pickIndex);
if (Number.isInteger(ci) && ci >= 0 && ci < 3) coopHub.draftPick(playerId, ci, Number.isInteger(pi) ? pi : undefined);
break;
}
case "SURRENDER": coopHub.surrender(playerId); break;
case "REMATCH": coopHub.rematch(playerId); break;
}
} catch (e) {
console.error(`[server] coop message error (player=${playerId}):`, e);
try { conn.send({ type: "ERROR", message: "對局發生錯誤" }); } catch { /* 連線已關 */ }
try { coopHub.disconnect(playerId); } catch { /* ignore */ }
try { socket.close(); } catch { /* ignore */ }
}
});
socket.on("error", () => { try { coopHub.disconnect(playerId); } catch { /* ignore */ } });
socket.on("close", () => { wsConns = Math.max(0, wsConns - 1); ipRelease(ip); try { coopHub.disconnect(playerId); } catch { /* ignore */ } });
});
});
// 單容器部署:同進程服務前端靜態檔(index.html / assets / resources),
// /api 路由優先(較精確);其餘 GET 走 SPA fallback 回 index.html。
if (webRoot) {
app.register(fastifyStatic, { root: webRoot, prefix: "/" });
app.setNotFoundHandler((req, reply) => {
if (req.method === "GET" && !req.url.startsWith("/api")) {
return reply.sendFile("index.html");
}
return reply.code(404).send({ error: "not-found" });
});
}
return app;
}