From 8c7a940de5a5ca66bf9b8f76234a84219f9917aa Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Tue, 1 Sep 2026 16:52:26 +0800 Subject: [PATCH] M002: harden session lifecycle and directory sync --- README.md | 4 +- src/server/directory-sync.ts | 77 +++++ src/server/server.ts | 2 +- src/server/session-manager.ts | 144 +++++++++ src/server/voice-bridge.ts | 354 +++++++++++++---------- src/server/voice-protocol.ts | 43 +++ test/directory-sync.test.ts | 33 +++ test/session-manager.test.ts | 47 +++ test/voice-protocol.test.ts | 29 ++ web/src/composables/useVoiceWebSocket.ts | 26 +- web/src/views/WebClient.vue | 9 + 11 files changed, 615 insertions(+), 153 deletions(-) create mode 100644 src/server/directory-sync.ts create mode 100644 src/server/session-manager.ts create mode 100644 src/server/voice-protocol.ts create mode 100644 test/directory-sync.test.ts create mode 100644 test/session-manager.test.ts create mode 100644 test/voice-protocol.test.ts diff --git a/README.md b/README.md index b08faa5..75d98e7 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ WebSpeak 是一个自托管的 TeamSpeak 浏览器客户端与访客接入网关 - TeamSpeak 3 / TeamSpeak 6 自动探测,无需选择协议。 - 每个浏览器 Session 独立连接,硬上限固定为 100。 +- Session 生命周期统一管理:连接状态机、WebSocket 心跳、幂等清理和优雅关闭。 - 完整频道/成员树、频道切换、频道文字聊天和成员实时移动。 - PCM/Opus 语音桥接、自由麦、按键说话、麦克风选择与音量控制。 - 发言成员头像显示绿色动态边框。 @@ -155,7 +156,7 @@ npm run dev # 前端开发服务;/api 和 /ws 代理到 3040 npm run web:dev -# M000/M001 自动测试 +# 自动测试(覆盖 M000、M001、M002) npm test # 后端类型检查与构建 @@ -193,6 +194,7 @@ WebSpeak is a self-hosted TeamSpeak web client and guest gateway. Every browser - Automatic TeamSpeak 3 / TeamSpeak 6 detection. - Independent browser sessions with a fixed hard limit of 100. +- Managed session lifecycle with a connection state machine, WebSocket heartbeat, idempotent teardown, and graceful shutdown. - Channel/member directory, channel switching, channel text chat, and live member movement. - PCM/Opus voice bridge, VOX, push-to-talk, microphone selection, and volume controls. - Bilingual guest UI and bilingual admin console. diff --git a/src/server/directory-sync.ts b/src/server/directory-sync.ts new file mode 100644 index 0000000..754309a --- /dev/null +++ b/src/server/directory-sync.ts @@ -0,0 +1,77 @@ +import type { ClientInfo } from "@honeybbq/teamspeak-client"; +import type { TSDirectorySnapshot } from "./ts-client.js"; + +type DirectoryDelta = + | { type: "clientEnter"; info: ClientInfo } + | { type: "clientLeave"; id: number } + | { type: "clientMoved"; id: number; channelID: bigint }; + +/** + * Merges the welcome snapshot with events received while that snapshot is in + * flight. Each TeamSpeak connection owns its own instance, so no directory + * event can leak into another browser session. + */ +export class DirectorySynchronizer { + private snapshot: TSDirectorySnapshot | null = null; + private clients = new Map(); + private pending: DirectoryDelta[] = []; + + get ready(): boolean { + return this.snapshot !== null; + } + + applySnapshot(snapshot: TSDirectorySnapshot): void { + this.snapshot = { channels: snapshot.channels.slice(), clients: [] }; + this.clients.clear(); + for (const client of snapshot.clients) this.clients.set(client.id, client); + const pending = this.pending.splice(0); + for (const delta of pending) this.applyDelta(delta); + } + + applyClientEnter(info: ClientInfo): void { + this.applyOrQueue({ type: "clientEnter", info }); + } + + applyClientLeave(id: number): void { + this.applyOrQueue({ type: "clientLeave", id }); + } + + applyClientMoved(id: number, channelID: bigint): void { + this.applyOrQueue({ type: "clientMoved", id, channelID }); + } + + getSnapshot(): TSDirectorySnapshot | null { + if (!this.snapshot) return null; + return { + channels: this.snapshot.channels.slice(), + clients: [...this.clients.values()], + }; + } + + clear(): void { + this.snapshot = null; + this.clients.clear(); + this.pending = []; + } + + private applyOrQueue(delta: DirectoryDelta): void { + if (!this.snapshot) { + if (this.pending.length < 4096) this.pending.push(delta); + return; + } + this.applyDelta(delta); + } + + private applyDelta(delta: DirectoryDelta): void { + if (delta.type === "clientEnter") { + this.clients.set(delta.info.id, delta.info); + return; + } + if (delta.type === "clientLeave") { + this.clients.delete(delta.id); + return; + } + const current = this.clients.get(delta.id); + if (current) this.clients.set(delta.id, { ...current, channelID: delta.channelID }); + } +} diff --git a/src/server/server.ts b/src/server/server.ts index bce773b..e09080e 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -130,7 +130,7 @@ export function createWebServer(options: WebServerOptions): WebServer { }); }, async stop(): Promise { - voiceBridge.shutdown(); + await voiceBridge.shutdown(); adminSessions.clear(); return new Promise((resolve) => { server.close(() => resolve()); diff --git a/src/server/session-manager.ts b/src/server/session-manager.ts new file mode 100644 index 0000000..32f41ab --- /dev/null +++ b/src/server/session-manager.ts @@ -0,0 +1,144 @@ +import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../constants.js"; + +export type ConnectionState = + | "idle" + | "connecting" + | "authenticating" + | "syncing" + | "connected" + | "interrupted" + | "reconnecting" + | "disconnecting" + | "failed"; + +export type SessionTeardownReason = + | "client-disconnect" + | "websocket-close" + | "websocket-error" + | "protocol-error" + | "teamSpeak-disconnect" + | "teamSpeak-connect-failed" + | "heartbeat-timeout" + | "gateway-shutdown"; + +const ALLOWED_TRANSITIONS: Record = { + idle: ["connecting", "disconnecting"], + connecting: ["authenticating", "failed", "disconnecting"], + authenticating: ["syncing", "failed", "disconnecting"], + syncing: ["connected", "failed", "disconnecting"], + connected: ["interrupted", "failed", "disconnecting"], + interrupted: ["reconnecting", "failed", "disconnecting"], + reconnecting: ["connecting", "failed", "disconnecting"], + disconnecting: ["idle"], + failed: ["disconnecting", "idle"], +}; + +export class ConnectionStateMachine { + private current: ConnectionState = "idle"; + + get state(): ConnectionState { + return this.current; + } + + transition(next: ConnectionState): void { + if (next === this.current) return; + if (!ALLOWED_TRANSITIONS[this.current].includes(next)) { + throw new Error(`Illegal connection state transition: ${this.current} -> ${next}`); + } + this.current = next; + } +} + +export type SessionCleanup = (reason: SessionTeardownReason) => Promise; + +export class ManagedSession { + readonly createdAt = Date.now(); + private readonly stateMachine = new ConnectionStateMachine(); + private teardownPromise: Promise | null = null; + + constructor( + readonly id: string, + private readonly cleanup: SessionCleanup, + ) {} + + get state(): ConnectionState { + return this.stateMachine.state; + } + + transition(next: ConnectionState): void { + this.stateMachine.transition(next); + } + + async teardown(reason: SessionTeardownReason): Promise { + if (this.teardownPromise) return this.teardownPromise; + this.teardownPromise = (async () => { + if (this.state !== "idle" && this.state !== "disconnecting") { + this.stateMachine.transition("disconnecting"); + } else if (this.state === "idle") { + this.stateMachine.transition("disconnecting"); + } + try { + await this.cleanup(reason); + } catch { + // Teardown is best effort and must not be interrupted by an already + // closed socket, TeamSpeak client, or codec resource. + } finally { + if (this.state === "disconnecting") this.stateMachine.transition("idle"); + } + })(); + return this.teardownPromise; + } +} + +export class SessionManager { + private readonly sessions = new Map(); + private accepting = true; + private peak = 0; + private created = 0; + + admit(id: string, cleanup: SessionCleanup): ManagedSession | null { + if (!this.accepting || !canAcceptSession(this.sessions.size)) return null; + if (this.sessions.has(id)) throw new Error(`Session already exists: ${id}`); + const session = new ManagedSession(id, cleanup); + this.sessions.set(id, session); + this.created++; + this.peak = Math.max(this.peak, this.sessions.size); + return session; + } + + get(id: string): ManagedSession | undefined { + return this.sessions.get(id); + } + + get activeCount(): number { + return this.sessions.size; + } + + get peakCount(): number { + return this.peak; + } + + get createdCount(): number { + return this.created; + } + + get isAccepting(): boolean { + return this.accepting; + } + + async teardown(id: string, reason: SessionTeardownReason): Promise { + const session = this.sessions.get(id); + if (!session) return; + await session.teardown(reason); + this.sessions.delete(id); + } + + async shutdown(reason: SessionTeardownReason = "gateway-shutdown"): Promise { + this.accepting = false; + await Promise.all([...this.sessions.keys()].map((id) => this.teardown(id, reason))); + } + + get maxSessions(): number { + return MAX_ACTIVE_SESSIONS; + } +} diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index cc3c842..2c4e532 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -1,22 +1,23 @@ import { WebSocketServer, WebSocket } from "ws"; -import type { IncomingMessage } from "node:http"; -import type { Server } from "node:http"; +import type { IncomingMessage, Server } from "node:http"; import { createRequire } from "node:module"; +import { DirectorySynchronizer } from "./directory-sync.js"; import { TSClient, type TSDirectorySnapshot, type TSVoiceData } from "./ts-client.js"; import type { Logger as LoggerType } from "../logger.js"; -import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../constants.js"; import { normalizeTeamSpeakError } from "../errors.js"; -import { - formatTeamSpeakTarget, - type TeamSpeakTarget, -} from "../domain/teamspeak-target.js"; +import { formatTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js"; import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js"; +import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js"; +import { parseClientCommand, type ClientCommand } from "./voice-protocol.js"; const require = createRequire(import.meta.url); const { OpusEncoder } = require("@discordjs/opus") as { OpusEncoder: new (sampleRate: number, channels: number) => { encode(pcm: Buffer): Buffer }; }; +const HEARTBEAT_INTERVAL_MS = 30_000; +const AUDIO_FRAME_BYTES = 1_920; + export interface VoiceBridgeOptions { joinTickets: JoinTicketStore; } @@ -28,22 +29,23 @@ interface ChannelMember { interface WebClientEntry { id: string; + session: ManagedSession; tsClient: TSClient; ws: WebSocket; nickname: string; target: TeamSpeakTarget; channelTree: unknown[]; members: Map; - opusEncoder: { encode(pcm: Buffer): Buffer }; + opusEncoder: { encode(pcm: Buffer): Buffer } | null; + isAlive: boolean; } export class VoiceBridge { - // Connecting sessions are tracked immediately so a dropped browser socket - // cannot leave a half-open TeamSpeak client behind. - private clients = new Map(); + private readonly sessionManager = new SessionManager(); + private readonly entries = new Map(); private wss: WebSocketServer | null = null; + private heartbeatTimer: ReturnType | null = null; private logger: LoggerType; - private peakClients = 0; constructor( private options: VoiceBridgeOptions, @@ -54,6 +56,7 @@ export class VoiceBridge { attach(server: Server): void { this.wss = new WebSocketServer({ server, path: "/ws/voice", maxPayload: 256 * 1024 }); + this.startHeartbeat(); this.wss.on("connection", (ws: WebSocket, req: IncomingMessage) => { const url = new URL(req.url ?? "/", `https://${req.headers.host ?? "localhost"}`); @@ -62,104 +65,125 @@ export class VoiceBridge { ws.close(4001, "Join ticket required"); return; } + const { target, serverPassword, nickname } = connection; const channelName = connection.channel; - - if (!canAcceptSession(this.clients.size)) { - this.logger.warn({ max: MAX_ACTIVE_SESSIONS }, "Max clients reached"); - ws.close(4004, "Server full"); + const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`; + let entry: WebClientEntry | null = null; + const session = this.sessionManager.admit(entryId, async (reason) => { + if (entry) await this.cleanupEntry(entry, reason); + }); + if (!session) { + this.logger.warn({ max: this.sessionManager.maxSessions }, "Max clients reached"); + ws.close(4004, "GATEWAY_FULL"); return; } - const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`; this.logger.info({ entryId, nickname, channel: channelName, target: formatTeamSpeakTarget(target) }, "WebClient connecting"); - - const tsClient = new TSClient({ - target, - nickname, - serverPassword, - defaultChannel: channelName, - }, this.logger); - - const entry: WebClientEntry = { + let tsClient: TSClient; + try { + tsClient = new TSClient({ target, nickname, serverPassword, defaultChannel: channelName }, this.logger); + } catch (error: unknown) { + this.logger.error({ err: error, entryId }, "Could not create TeamSpeak client"); + void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed"); + ws.close(4003, "TeamSpeak client unavailable"); + return; + } + entry = { id: entryId, + session, tsClient, ws, nickname, target, channelTree: [], members: new Map(), - opusEncoder: new OpusEncoder(48000, 1), + opusEncoder: null, + isAlive: true, }; - this.clients.set(entryId, entry); - this.peakClients = Math.max(this.peakClients, this.clients.size); + this.entries.set(entryId, entry); + try { + entry.opusEncoder = new OpusEncoder(48000, 1); + } catch (error: unknown) { + this.logger.error({ err: error, entryId }, "Could not create Opus encoder"); + void this.teardown(entryId, "teamSpeak-connect-failed"); + return; + } let tsReady = false; let selfId = 0; let selfChannelId = 0n; - let directoryReady = false; let initialStateSent = false; - let latestDirectorySnapshot: TSDirectorySnapshot | null = null; + let audioReady = true; + let realtimeReady = false; + const directory = new DirectorySynchronizer(); + const sendJson = (message: Record) => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message)); }; const refreshDirectory = () => { - if (!latestDirectorySnapshot) return; + const snapshot = directory.getSnapshot(); + if (!snapshot) return; const effectiveSelfId = selfId || tsClient.getClientId(); const sdkChannelId = tsClient.getChannelId(); if (selfChannelId === 0n && sdkChannelId !== 0n) selfChannelId = sdkChannelId; - const normalizedSnapshot = normalizeDirectorySnapshot(latestDirectorySnapshot, effectiveSelfId, selfChannelId, nickname, channelName); - entry.channelTree = mapChannelTree(normalizedSnapshot); - entry.members.clear(); + const normalizedSnapshot = normalizeDirectorySnapshot(snapshot, effectiveSelfId, selfChannelId, nickname, channelName); + entry!.channelTree = mapChannelTree(normalizedSnapshot); + entry!.members.clear(); for (const client of normalizedSnapshot.clients) { - entry.members.set(client.id, { id: client.id, nickname: client.nickname }); + entry!.members.set(client.id, { id: client.id, nickname: client.nickname }); } }; const sendInitialState = () => { - if (!tsReady || !directoryReady || initialStateSent) return; + if (initialStateSent || !tsReady || !directory.ready || !realtimeReady || !audioReady || session.state !== "syncing") return; initialStateSent = true; - sendJson({ - type: "connected", - tsClientId: selfId, - members: Array.from(entry.members.values()), - }); - sendJson({ type: "channelList", channels: entry.channelTree }); + session.transition("connected"); + sendJson({ type: "connected", tsClientId: selfId, members: Array.from(entry!.members.values()) }); + sendJson({ type: "channelList", channels: entry!.channelTree }); }; + // Register every directory listener before connect(). Events emitted by + // the welcome flow are queued by DirectorySynchronizer until its + // snapshot establishes the baseline. + realtimeReady = true; tsClient.on("directorySnapshot", (snapshot: TSDirectorySnapshot) => { - latestDirectorySnapshot = snapshot; - directoryReady = true; + directory.applySnapshot(snapshot); refreshDirectory(); - if (tsReady && !initialStateSent) sendInitialState(); - else if (tsReady) sendJson({ type: "channelList", channels: entry.channelTree }); + sendInitialState(); + if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree }); }); - // These listeners must be attached before connect(): TeamSpeak emits the - // initial clientEnter events during the handshake. tsClient.on("clientEnter", (info) => { const candidateSelfId = tsClient.getClientId(); if (candidateSelfId > 0 && info.id === candidateSelfId) { selfId = candidateSelfId; if (info.channelID !== undefined && info.channelID !== 0n) selfChannelId = info.channelID; - refreshDirectory(); - if (tsReady && directoryReady && initialStateSent) { - sendJson({ type: "channelList", channels: entry.channelTree }); - } } - entry.members.set(info.id, { id: info.id, nickname: info.nickname }); - if (tsReady) sendJson({ type: "memberEnter", id: info.id, nickname: info.nickname, isSelf: info.id === selfId }); + const wasKnown = entry!.members.has(info.id); + directory.applyClientEnter(info); + refreshDirectory(); + if (tsReady && initialStateSent) { + sendJson({ type: "channelList", channels: entry!.channelTree }); + if (!wasKnown) sendJson({ type: "memberEnter", id: info.id, nickname: info.nickname, isSelf: info.id === selfId }); + } }); tsClient.on("clientLeave", (info) => { - entry.members.delete(info.id); - if (tsReady) sendJson({ type: "memberLeave", id: info.id }); + const wasKnown = entry!.members.has(info.id); + directory.applyClientLeave(info.id); + refreshDirectory(); + if (tsReady && initialStateSent && wasKnown) { + sendJson({ type: "memberLeave", id: info.id }); + sendJson({ type: "channelList", channels: entry!.channelTree }); + } }); tsClient.on("clientMoved", (info) => { - if (info.id === selfId && info.targetChannelID !== undefined && info.targetChannelID !== 0n) { - selfChannelId = info.targetChannelID; - refreshDirectory(); - } + if (info.targetChannelID === undefined || info.targetChannelID === 0n) return; + if (info.id === selfId) selfChannelId = info.targetChannelID; + directory.applyClientMoved(info.id, info.targetChannelID); + refreshDirectory(); + if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree }); }); tsClient.on("voiceData", (data: TSVoiceData) => { @@ -181,94 +205,150 @@ export class VoiceBridge { }); tsClient.on("disconnected", () => { - if (ws.readyState === WebSocket.OPEN) sendJson({ type: "disconnected" }); - this.cleanup(entryId); + if (session.state !== "disconnecting" && session.state !== "idle") { + try { session.transition("interrupted"); } catch { /* teardown below is authoritative */ } + sendJson({ type: "disconnected" }); + void this.teardown(entryId, "teamSpeak-disconnect"); + } }); - ws.on("message", (data: Buffer | string) => { - if (typeof data === "string" || (data.length > 0 && data[0] === 0x7b)) { - try { - const command = JSON.parse(typeof data === "string" ? data : data.toString("utf-8")); - if (command && typeof command.type === "string") { - if (tsReady && ["switchChannel", "sendTextMessage"].includes(command.type)) { - handleCommand(entry, command).catch((error: unknown) => { - this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Command failed"); - }); - } - return; - } - } catch { - // Not JSON; let the binary audio path handle it below. + ws.on("pong", () => { if (entry) entry.isAlive = true; }); + ws.on("message", (data: Buffer | string, isBinary: boolean) => { + if (isBinary) { + const frame = typeof data === "string" ? Buffer.from(data) : data; + if (!tsReady || frame.length !== AUDIO_FRAME_BYTES) { + sendProtocolError(sendJson, "INVALID_AUDIO_FRAME", "音频帧格式无效"); + return; } - } - - // Browser sends exactly 1920 bytes: 960 samples at 48 kHz, one 20 ms frame. - if (Buffer.isBuffer(data) && tsReady && data.length >= 1920) { - const pcm = data.length === 1920 ? data : data.subarray(0, 1920); try { - tsClient.sendVoice(entry.opusEncoder.encode(pcm), 4); + if (entry!.opusEncoder) tsClient.sendVoice(entry!.opusEncoder.encode(frame), 4); } catch { // A frame arriving during shutdown is safe to discard. } + return; } + + const command = parseClientCommand(typeof data === "string" ? data : data.toString("utf-8")); + if ("error" in command) { + sendProtocolError(sendJson, command.error.code, command.error.message); + return; + } + if (!tsReady || session.state !== "connected") { + sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪"); + return; + } + void handleCommand(entry!, command, sendJson); }); ws.on("close", () => { this.logger.info({ entryId }, "WebSocket closed"); - this.cleanup(entryId); + void this.teardown(entryId, "websocket-close"); }); ws.on("error", (error) => { this.logger.error({ err: error, entryId }, "WebSocket error"); - this.cleanup(entryId); + void this.teardown(entryId, "websocket-error"); }); + try { + session.transition("connecting"); + session.transition("authenticating"); + } catch (error: unknown) { + this.logger.error({ err: error instanceof Error ? error.message : String(error), entryId }, "Session state initialization failed"); + void this.teardown(entryId, "protocol-error"); + return; + } + tsClient.connect() .then(() => { + if (session.state !== "authenticating") return; + session.transition("syncing"); tsReady = true; selfId = tsClient.getClientId(); const sdkChannelId = tsClient.getChannelId(); if (sdkChannelId !== 0n) selfChannelId = sdkChannelId; refreshDirectory(); - if (selfId > 0 && !entry.members.has(selfId)) { - entry.members.set(selfId, { id: selfId, nickname }); + if (selfId > 0 && !entry!.members.has(selfId)) { + directory.applyClientEnter({ id: selfId, nickname, channelID: selfChannelId, uid: "", type: 1, serverGroups: [] }); + refreshDirectory(); } sendInitialState(); }) .catch((error: Error) => { const normalized = normalizeTeamSpeakError(error); this.logger.error({ code: normalized.code, entryId }, "TS connect failed"); + try { if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed"); } catch { /* cleanup below */ } if (ws.readyState === WebSocket.OPEN) ws.close(4003, normalized.code); - else this.cleanup(entryId); + void this.teardown(entryId, "teamSpeak-connect-failed"); }); }); + this.wss.on("error", (error) => { + this.logger.error({ err: error }, "Voice WebSocket server error"); + }); this.logger.info("Voice WebSocket endpoint ready at /ws/voice"); } - private cleanup(entryId: string): void { - const entry = this.clients.get(entryId); - if (!entry) return; - this.clients.delete(entryId); - entry.tsClient.disconnect().catch(() => {}); - this.logger.info({ entryId }, "Client cleaned up"); + async shutdown(): Promise { + if (this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = null; + } + await this.sessionManager.shutdown("gateway-shutdown"); + const wss = this.wss; + this.wss = null; + if (!wss) return; + await new Promise((resolve) => { + try { wss.close(() => resolve()); } catch { resolve(); } + }); } getActiveCount(): number { - return this.clients.size; + return this.sessionManager.activeCount; } getPeakCount(): number { - return this.peakClients; + return this.sessionManager.peakCount; } - shutdown(): void { - for (const [id, entry] of this.clients) { - this.clients.delete(id); - entry.ws.terminate(); - entry.tsClient.disconnect().catch(() => {}); + getCreatedCount(): number { + return this.sessionManager.createdCount; + } + + private async teardown(entryId: string, reason: SessionTeardownReason): Promise { + await this.sessionManager.teardown(entryId, reason); + } + + private async cleanupEntry(entry: WebClientEntry, reason: SessionTeardownReason): Promise { + if (this.entries.get(entry.id) === entry) this.entries.delete(entry.id); + entry.opusEncoder = null; + entry.channelTree = []; + entry.members.clear(); + entry.tsClient.removeAllListeners(); + try { await entry.tsClient.disconnect(); } catch { /* disconnect is intentionally idempotent */ } + entry.ws.removeAllListeners(); + if (entry.ws.readyState === WebSocket.OPEN || entry.ws.readyState === WebSocket.CONNECTING) { + if (reason === "heartbeat-timeout" || reason === "gateway-shutdown") entry.ws.terminate(); + else entry.ws.close(reason === "protocol-error" ? 1008 : 1000, reason); } - this.wss?.close(); + this.logger.info({ entryId: entry.id, reason }, "Client session torn down"); + } + + private startHeartbeat(): void { + if (this.heartbeatTimer) clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => { + for (const entry of this.entries.values()) { + if (entry.ws.readyState !== WebSocket.OPEN) continue; + if (!entry.isAlive) { + entry.ws.terminate(); + void this.teardown(entry.id, "heartbeat-timeout"); + continue; + } + entry.isAlive = false; + entry.ws.ping(); + } + }, HEARTBEAT_INTERVAL_MS); + this.heartbeatTimer.unref?.(); } private resolveConnection(url: URL): JoinTicketPayload | null { @@ -277,37 +357,33 @@ export class VoiceBridge { } } -async function handleCommand(entry: WebClientEntry, command: { type: string; [key: string]: unknown }) { - switch (command.type) { - case "switchChannel": { - const rawId = command.channelId; - if (typeof rawId !== "string" || !/^\d+$/.test(rawId)) { - if (entry.ws.readyState === WebSocket.OPEN) entry.ws.send(JSON.stringify({ type: "error", message: "无效的频道" })); - break; +async function handleCommand( + entry: WebClientEntry, + command: ClientCommand, + sendJson: (message: Record) => void, +): Promise { + if (command.type === "switchChannel") { + const rawId = command.payload.channelId as string; + try { + await entry.tsClient.switchChannel(BigInt(rawId)); + } catch (error: unknown) { + const message = error instanceof Error ? error.message : String(error); + if (!message.includes("already member")) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "CHANNEL_SWITCH_FAILED", message: "频道切换失败", recoverable: false } }); + return; } - try { - await entry.tsClient.switchChannel(BigInt(rawId)); - } catch (error: unknown) { - const message = error instanceof Error ? error.message : String(error); - // Double-clicking the current channel is harmless. - if (!message.includes("already member")) { - if (entry.ws.readyState === WebSocket.OPEN) entry.ws.send(JSON.stringify({ type: "error", message: `切换失败:${message}` })); - break; - } - } - if (entry.ws.readyState === WebSocket.OPEN) { - entry.ws.send(JSON.stringify({ type: "channelSwitched", channelId: rawId })); - entry.ws.send(JSON.stringify({ type: "channelList", channels: entry.channelTree })); - } - break; - } - case "sendTextMessage": { - if (typeof command.message !== "string") break; - const message = command.message.trim().slice(0, 500); - if (message) entry.tsClient.sendTextMessage(message); - break; } + sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId }); + sendJson({ type: "channelList", channels: entry.channelTree }); + return; } + + const message = (command.payload.message as string).trim(); + if (message) entry.tsClient.sendTextMessage(message); +} + +function sendProtocolError(sendJson: (message: Record) => void, code: string, message: string): void { + sendJson({ type: "error", error: { code, message, recoverable: false } }); } function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] { @@ -318,10 +394,7 @@ function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] { description: channel.description || "", members: snapshot.clients .filter((client) => client.channelID === channel.id) - .map((client) => ({ - id: client.id, - nickname: client.nickname || "未知用户", - })), + .map((client) => ({ id: client.id, nickname: client.nickname || "未知用户" })), })); } @@ -341,10 +414,6 @@ function normalizeDirectorySnapshot( const requestedChannel = requestedName ? snapshot.channels.find((channel) => channel.name.trim().toLocaleLowerCase() === requestedName) : undefined; - // TS6 may report channelID=0 for the newly connected normal client even - // though the server has already placed it. The requested channel is the - // authoritative fallback; an empty request means the first welcome channel, - // which is the server's default channel in the normal client snapshot. const resolvedChannelId = selfChannelId !== 0n ? selfChannelId : snapshotChannelId !== 0n @@ -354,14 +423,7 @@ function normalizeDirectorySnapshot( const current = clients[selfIndex]!; if (resolvedChannelId !== 0n) clients[selfIndex] = { ...current, channelID: resolvedChannelId }; } else if (resolvedChannelId !== 0n) { - clients.push({ - id: selfId, - nickname, - uid: "", - channelID: resolvedChannelId, - type: 1, - serverGroups: [], - }); + clients.push({ id: selfId, nickname, uid: "", channelID: resolvedChannelId, type: 1, serverGroups: [] }); } return { ...snapshot, clients }; diff --git a/src/server/voice-protocol.ts b/src/server/voice-protocol.ts new file mode 100644 index 0000000..155f584 --- /dev/null +++ b/src/server/voice-protocol.ts @@ -0,0 +1,43 @@ +export interface ClientCommand { + type: "switchChannel" | "sendTextMessage"; + requestId?: string; + payload: Record; +} + +export type ClientCommandResult = ClientCommand | { error: { code: string; message: string } }; + +export function parseClientCommand(raw: string): ClientCommandResult { + let value: unknown; + try { + value = JSON.parse(raw); + } catch { + return { error: { code: "INVALID_JSON", message: "消息不是有效的 JSON" } }; + } + if (!isRecord(value) || typeof value.type !== "string") { + return { error: { code: "INVALID_MESSAGE", message: "消息类型不能为空" } }; + } + if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) { + return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } }; + } + if (value.type !== "switchChannel" && value.type !== "sendTextMessage") { + return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } }; + } + if (!isRecord(value.payload)) { + return { error: { code: "INVALID_PAYLOAD", message: "消息参数无效" } }; + } + if (value.type === "switchChannel" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) { + return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } }; + } + if (value.type === "sendTextMessage" && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) { + return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } }; + } + return { + type: value.type, + ...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}), + payload: value.payload, + }; +} + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} diff --git a/test/directory-sync.test.ts b/test/directory-sync.test.ts new file mode 100644 index 0000000..baafc53 --- /dev/null +++ b/test/directory-sync.test.ts @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { ChannelInfo, ClientInfo } from "@honeybbq/teamspeak-client"; +import { DirectorySynchronizer } from "../src/server/directory-sync.js"; + +const root: ChannelInfo = { id: 1n, parentID: 0n, name: "Lobby", description: "", }; +const games: ChannelInfo = { id: 2n, parentID: 1n, name: "Games", description: "", }; + +function client(id: number, nickname: string, channelID: bigint): ClientInfo { + return { id, nickname, uid: `uid-${id}`, channelID, type: 1, serverGroups: [] }; +} + +test("directory synchronizer merges welcome events that arrive before the snapshot", () => { + const sync = new DirectorySynchronizer(); + sync.applyClientEnter(client(7, "Alice", 1n)); + sync.applyClientMoved(7, 2n); + sync.applySnapshot({ channels: [root, games], clients: [client(3, "Bob", 1n)] }); + assert.equal(sync.ready, true); + assert.deepEqual(sync.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n], [7, 2n]]); +}); + +test("directory state and movement events remain isolated per session", () => { + const first = new DirectorySynchronizer(); + const second = new DirectorySynchronizer(); + const snapshot = { channels: [root, games], clients: [client(3, "Bob", 1n)] }; + first.applySnapshot(snapshot); + second.applySnapshot(snapshot); + first.applyClientEnter(client(7, "Alice", 2n)); + first.applyClientMoved(3, 2n); + first.applyClientLeave(7); + assert.deepEqual(first.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 2n]]); + assert.deepEqual(second.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n]]); +}); diff --git a/test/session-manager.test.ts b/test/session-manager.test.ts new file mode 100644 index 0000000..74ec5d1 --- /dev/null +++ b/test/session-manager.test.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { ConnectionStateMachine, SessionManager } from "../src/server/session-manager.js"; + +test("connection state machine accepts the normal lifecycle and rejects illegal jumps", () => { + const machine = new ConnectionStateMachine(); + machine.transition("connecting"); + machine.transition("authenticating"); + machine.transition("syncing"); + machine.transition("connected"); + machine.transition("interrupted"); + machine.transition("reconnecting"); + machine.transition("connecting"); + assert.throws(() => machine.transition("connected"), /Illegal connection state transition/); +}); + +test("managed session teardown is idempotent and reaches idle even when cleanup fails", async () => { + const manager = new SessionManager(); + let cleanupCalls = 0; + const session = manager.admit("session-a", async () => { + cleanupCalls++; + throw new Error("already closed"); + }); + assert.ok(session); + session.transition("connecting"); + await Promise.all([session.teardown("websocket-close"), session.teardown("websocket-error")]); + assert.equal(cleanupCalls, 1); + assert.equal(session.state, "idle"); + assert.equal(manager.activeCount, 1); + await manager.teardown("session-a", "websocket-close"); + assert.equal(manager.activeCount, 0); +}); + +test("session manager admits 100 active sessions and rejects the 101st", async () => { + const manager = new SessionManager(); + for (let index = 0; index < 100; index++) { + assert.ok(manager.admit(`session-${index}`, async () => undefined)); + } + assert.equal(manager.activeCount, 100); + assert.equal(manager.admit("session-100", async () => undefined), null); + assert.equal(manager.peakCount, 100); + assert.equal(manager.createdCount, 100); + await manager.shutdown(); + assert.equal(manager.activeCount, 0); + assert.equal(manager.isAccepting, false); + assert.equal(manager.admit("after-shutdown", async () => undefined), null); +}); diff --git a/test/voice-protocol.test.ts b/test/voice-protocol.test.ts new file mode 100644 index 0000000..fefd56b --- /dev/null +++ b/test/voice-protocol.test.ts @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { parseClientCommand } from "../src/server/voice-protocol.js"; + +test("voice protocol accepts the versioned command payload", () => { + const command = parseClientCommand(JSON.stringify({ + type: "switchChannel", + requestId: "switch-1", + payload: { channelId: "42" }, + })); + assert.deepEqual(command, { + type: "switchChannel", + requestId: "switch-1", + payload: { channelId: "42" }, + }); +}); + +test("voice protocol rejects malformed and unsupported commands", () => { + assert.deepEqual(parseClientCommand("not-json"), { + error: { code: "INVALID_JSON", message: "消息不是有效的 JSON" }, + }); + assert.equal("error" in parseClientCommand(JSON.stringify({ type: "unknown", payload: {} })), true); + assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage" })), { + error: { code: "INVALID_PAYLOAD", message: "消息参数无效" }, + }); + assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage", payload: { message: "x".repeat(501) } })), { + error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" }, + }); +}); diff --git a/web/src/composables/useVoiceWebSocket.ts b/web/src/composables/useVoiceWebSocket.ts index 857a344..c0e6e81 100644 --- a/web/src/composables/useVoiceWebSocket.ts +++ b/web/src/composables/useVoiceWebSocket.ts @@ -461,7 +461,7 @@ export function useVoiceWebSocket() { state.error = "TeamSpeak 连接已断开"; break; case "error": - state.error = String(msg.message || "操作失败"); + state.error = protocolErrorMessage(String(msg.error?.code || ""), String(msg.error?.message || msg.message || "操作失败")); break; } } @@ -474,18 +474,18 @@ export function useVoiceWebSocket() { playAudioFrame(clientId, data.slice(3)); } - function sendCmd(command: Record): void { - if (ws.value?.readyState === WebSocket.OPEN) ws.value.send(JSON.stringify(command)); + function sendCmd(type: string, payload: Record = {}): void { + if (ws.value?.readyState === WebSocket.OPEN) ws.value.send(JSON.stringify({ type, payload })); } function switchChannel(channelId: string): void { - sendCmd({ type: "switchChannel", channelId }); + sendCmd("switchChannel", { channelId }); } function sendTextMessage(message: string): void { const trimmed = message.trim(); if (!trimmed || trimmed.length > 500) return; - sendCmd({ type: "sendTextMessage", message: trimmed }); + sendCmd("sendTextMessage", { message: trimmed }); chatMessages.push({ id: `self-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, invokerName: "你", @@ -508,6 +508,22 @@ export function useVoiceWebSocket() { state.error = ""; } + function protocolErrorMessage(code: string, fallback: string): string { + const messages: Record = { + INVALID_JSON: "消息格式无效", + INVALID_MESSAGE: "消息格式无效", + INVALID_REQUEST_ID: "请求标识无效", + UNKNOWN_MESSAGE_TYPE: "不支持的操作", + INVALID_PAYLOAD: "操作参数无效", + INVALID_CHANNEL_ID: "频道标识无效", + INVALID_TEXT_MESSAGE: "文字消息无效", + INVALID_AUDIO_FRAME: "音频帧格式无效", + SESSION_NOT_READY: "TeamSpeak 会话尚未就绪", + CHANNEL_SWITCH_FAILED: "频道切换失败", + }; + return messages[code] || fallback; + } + function setVolume(clientId: number, volume: number): void { const normalized = Math.max(0, Math.min(4, volume)); volumes[clientId] = normalized; diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 157b7a7..652ebc0 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -555,6 +555,15 @@ function localizedMessage(message: string) { "WebSpeak 尚未配置 TeamSpeak 目标。": "The WebSpeak TeamSpeak target has not been configured", "此 TeamSpeak 服务器地址不允许连接": "This TeamSpeak server address is not allowed", "请输入有效的昵称": "Enter a valid nickname", + "消息格式无效": "The message format is invalid", + "请求标识无效": "The request id is invalid", + "不支持的操作": "This operation is not supported", + "操作参数无效": "The operation payload is invalid", + "频道标识无效": "The channel id is invalid", + "文字消息无效": "The text message is invalid", + "音频帧格式无效": "The audio frame is invalid", + "TeamSpeak 会话尚未就绪": "The TeamSpeak session is not ready", + "频道切换失败": "Channel switch failed", }; if (exact[message]) return exact[message]; if (message.startsWith("麦克风访问失败:")) return `Microphone access failed: ${message.slice(8)}`;