File size: 18,145 Bytes
9f0c00b
 
 
 
 
 
 
 
c04e5ed
9f0c00b
1302ebc
 
9f0c00b
ff3cdfd
82c0837
9f0c00b
b578db4
 
9f0c00b
 
 
 
 
 
 
1302ebc
 
 
 
 
 
 
 
a23faa4
b3d428e
1302ebc
ab413b5
9f0c00b
ab413b5
 
f8c0aee
 
5b36fab
 
9f0c00b
 
 
e412e40
9f0c00b
5995ce3
bebc80d
9f0c00b
f74015b
5b36fab
a736735
9f0c00b
 
b578db4
 
f4c424d
b578db4
f4c424d
 
b578db4
 
 
 
 
 
 
 
f4c424d
 
 
f74015b
 
9f0c00b
1302ebc
f3a8f5c
 
ebdbff1
 
222df40
 
 
 
 
 
 
 
 
 
93ae949
 
9f0c00b
5f82f13
 
 
 
 
 
 
 
 
 
76e92fa
3542667
76e92fa
3542667
 
 
 
 
 
 
76e92fa
5f82f13
 
 
a8e2326
9f0c00b
 
 
5f82f13
9f0c00b
 
 
 
 
 
 
0c167c4
 
 
 
 
9f0c00b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1302ebc
 
 
 
 
 
 
 
a23faa4
b3d428e
1302ebc
 
 
82c0837
 
 
9f0c00b
 
5f82f13
 
222df40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f0c00b
222df40
 
 
5f82f13
222df40
9f0c00b
 
 
9e0e17c
 
9f0c00b
 
 
 
 
 
 
 
 
222df40
 
 
9f0c00b
 
 
 
 
 
5f82f13
 
ba79b8e
 
5f82f13
5995ce3
45ae5ba
 
5995ce3
bebc80d
5995ce3
5f82f13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a736735
5f82f13
 
1f32852
5b36fab
5f82f13
3542667
5f82f13
 
 
9f0c00b
 
5f82f13
222df40
9f0c00b
b578db4
 
222df40
 
 
b578db4
222df40
b578db4
 
 
 
 
 
222df40
 
 
b578db4
 
 
ba79b8e
 
b578db4
 
 
 
 
f4c424d
 
 
c04e5ed
 
f4c424d
b578db4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4c424d
b578db4
 
3542667
b578db4
 
 
 
 
 
222df40
b578db4
9f0c00b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/**
 * 鬼影 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;
}