From 9873d27222a2a8a11f81971a49d5d93f0508b4dd Mon Sep 17 00:00:00 2001 From: LainHE <36128030+LainHE@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:23:55 +0800 Subject: [PATCH] fix(voice): never swallow a TeamSpeak drop while the session is settling The gateway only publishes `connected` once the directory snapshot lands in `sendInitialState()`. Between authenticating and that point the session is in `syncing` while `hasConnectedOnce` is still false. `onDisconnect` required both `hasConnectedOnce` and `state === "connected"`, so a transport drop inside that gap returned early and did nothing: * no `disconnected` frame for the browser, * no `scheduleReconnect`, * no peer/WeRTC rollback, no teardown. The session stayed in `syncing` with the browser socket still open, the client kept showing the connecting state forever, and nothing could recover it short of the user closing the tab. `onKick` had the same gap via its own `if (!hasConnectedOnce) return;` guard, so a kick or ban during the same window was silently ignored while the gateway kept the dead session alive. The window is not momentary. `tsClient.connect()` resolves even when the directory reconciliation fails (the failure is logged and the explicit snapshot emit is skipped), and `resetDirectoryForReconnect()` clears the snapshot on every recovery, so each reconnect attempt opens the window again. Treat the settling states (`authenticating`, `syncing`) as an explicit concept and handle transport loss there: * a drop during the first connect is a connect failure, not an interruption: report `connectionFailed`, close with 4003 and tear the session down; * the same reporting is now shared by the rejected-`connect()` path through a single `failConnect` helper, so a transport that reports itself twice (a `disconnected` event plus a rejected connect) still fails exactly once; * a drop during a *reconnect* handshake returns the session to `reconnecting` and schedules another attempt instead of stalling in `syncing`; * a kick that lands before the session settles is reported and terminal. A drop on an established session keeps the previous behaviour: `disconnected` plus a scheduled reconnect. Covered by three regression tests over the real WebSocket wiring with only the external SDK stubbed: a drop before the directory sync, a kick in the same window, and a drop during a reconnect handshake. All three hang on the old code. --- src/server/voice-bridge.integration.test.ts | 91 +++++++++++++++++++++ src/server/voice-bridge.ts | 74 ++++++++++++++--- 2 files changed, 152 insertions(+), 13 deletions(-) diff --git a/src/server/voice-bridge.integration.test.ts b/src/server/voice-bridge.integration.test.ts index 85c06c7..655c6fd 100644 --- a/src/server/voice-bridge.integration.test.ts +++ b/src/server/voice-bridge.integration.test.ts @@ -85,6 +85,26 @@ async function fixture(t: TestContext, overrides: { return { bridge, sdk, socket, messages, entries, wss }; } +function messageTypes(messages: Array<{ data: Buffer; binary: boolean }>): string[] { + return messages + .filter(message => !message.binary) + .map(message => (JSON.parse(message.data.toString()) as { type: string }).type); +} + +function waitForMessage>(socket: WebSocket, type: string): Promise { + return new Promise(resolve => { + socket.on("message", (data, binary) => { + if (binary) return; + const message = JSON.parse(data.toString()) as { type?: string }; + if (message.type === type) resolve(message as unknown as T); + }); + }); +} + +// The native Opus codec is unavailable in some environments. These tests only +// exercise gateway wiring, so the encoder is stubbed out. +const stubEncoder = () => ({ encode: () => Buffer.alloc(0), dispose: () => {} }); + test("a TeamSpeak constructor failure releases the admitted gateway slot", { timeout: 5_000 }, async t => { const f = await fixture(t, { createTeamSpeakClient() { throw new Error("Identity initialization failed"); } }); if (f.socket.readyState !== WebSocket.CLOSED) await once(f.socket, "close"); @@ -127,6 +147,77 @@ test("server identity lookup waits until the directory sync publishes the connec assert.ok(f.bridge.getActiveCount() > 0); }); +test("a TeamSpeak drop before the directory sync fails the connection instead of stalling", { timeout: 5_000 }, async t => { + const f = await fixture(t, { + waitForFirstMessage: false, + createEncoder: stubEncoder, + configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; }, + }); + while (!f.sdk.connectCalls) await nextTurn(); + await nextTurn(); + + // The session is past authentication, but `connected` was never published. + assert.deepEqual(messageTypes(f.messages), []); + + const failure = waitForMessage<{ code: string }>(f.socket, "connectionFailed"); + f.sdk.emit("disconnected"); + assert.ok((await failure).code.length > 0); + await nextTurn(); + assert.equal(f.bridge.getActiveCount(), 0); +}); + +test("a kick before the directory sync is reported instead of leaving the session alive", { timeout: 5_000 }, async t => { + const f = await fixture(t, { + waitForFirstMessage: false, + createEncoder: stubEncoder, + configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; }, + }); + while (!f.sdk.connectCalls) await nextTurn(); + await nextTurn(); + assert.deepEqual(messageTypes(f.messages), []); + + const failure = waitForMessage<{ code: string; detail?: string }>(f.socket, "connectionFailed"); + f.sdk.emit("kicked", normalizeTeamSpeakKickedReason("Removed by operator", 4)); + const message = await failure; + assert.equal(message.code, "KICKED"); + assert.match(message.detail ?? "", /Removed by operator/); + await nextTurn(); + assert.equal(f.bridge.getActiveCount(), 0); +}); + +test("a drop during a reconnect handshake resumes recovery instead of stalling in syncing", { timeout: 15_000 }, async t => { + const f = await fixture(t, { + createEncoder: stubEncoder, + configureSdk(sdk) { + let connects = 0; + sdk.connect = async () => { + sdk.connectCalls += 1; + sdk.disconnected = false; + connects += 1; + // Only the first handshake publishes the directory, so the reconnect + // attempt parks in `syncing` the way a slow server would. + if (connects === 1) sdk.emit("directorySnapshot", sdk.directory); + }; + }, + }); + assert.ok(messageTypes(f.messages).includes("connected")); + + const firstReconnect = waitForMessage<{ attempt: number }>(f.socket, "reconnecting"); + f.sdk.emit("disconnected"); + assert.equal((await firstReconnect).attempt, 1); + + // Wait for the retry handshake to reach `syncing` without republishing `connected`. + while (f.sdk.connectCalls < 2) await nextTurn(); + await nextTurn(); + await nextTurn(); + assert.ok(!messageTypes(f.messages).includes("reconnected")); + + const secondReconnect = waitForMessage<{ attempt: number }>(f.socket, "reconnecting"); + f.sdk.emit("disconnected"); + assert.equal((await secondReconnect).attempt, 2); + assert.ok(f.bridge.getActiveCount() > 0); +}); + test("a codec disposal failure cannot abandon TeamSpeak or the browser socket", { timeout: 5_000 }, async t => { const encoder = new OpusEncoder(48000, 1); t.mock.method(encoder, "dispose", () => { throw new Error("Codec already disposed"); }); diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index 75b5bb2..70a7351 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -245,6 +245,11 @@ export class VoiceBridge { let initialStateSent = false; let serverInfoGeneration = 0; let hasConnectedOnce = false; + // `connected` is only published once the directory sync has landed (see + // `sendInitialState`), so the session can already be past authentication + // while `hasConnectedOnce` is still false. A transport drop inside that + // gap must be handled rather than swallowed. + const isSettling = () => session.state === "authenticating" || session.state === "syncing"; let reconnectStartedAt = 0; let reconnectAttempt = 0; const addServerEvent = (kind: ServerEvent["kind"], message: string) => { @@ -344,6 +349,28 @@ export class VoiceBridge { void this.teardown(entryId, "teamSpeak-connect-failed"); }; + const failConnect = (normalized: ReturnType) => { + // A dead transport can report itself twice -- once as a `disconnected` + // event and once as a rejected `connect()`. Report and tear down once. + if (session.state === "failed" || session.state === "disconnecting" || session.state === "idle") return; + if (entry!.reconnectTimer) { + clearTimeout(entry!.reconnectTimer); + entry!.reconnectTimer = null; + } + try { + session.transition("failed"); + } catch { /* teardown below remains authoritative */ } + const failureCode = clientConnectionFailureCode(normalized, serverPassword); + const failureDetail = publicFailureDetail(normalized); + entry!.connectionFailureCode = failureCode; + // Send the structured failure before closing. Some browsers and reverse + // proxies do not preserve a WebSocket close reason, which would + // otherwise collapse every failure into a generic message. + sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) }); + if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode); + void this.teardown(entryId, "teamSpeak-connect-failed"); + }; + const scheduleReconnect = (normalized: ReturnType | null) => { if (session.state === "disconnecting" || session.state === "idle" || session.state === "failed") return; if (!isRecoverable(normalized)) { @@ -391,7 +418,6 @@ export class VoiceBridge { } catch (error: unknown) { const normalized = normalizeTeamSpeakError(error); const failureCode = clientConnectionFailureCode(normalized, serverPassword); - const failureDetail = publicFailureDetail(normalized); entry!.connectionFailureCode = failureCode; this.logger.warn({ code: failureCode, @@ -403,15 +429,7 @@ export class VoiceBridge { attempt: reconnectAttempt, }, "TS connect failed"); if (!isReconnect) { - try { - if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed"); - } catch { /* teardown below remains authoritative */ } - // Send the structured failure before closing. Some browsers and - // reverse proxies do not preserve a WebSocket close reason, which - // would otherwise collapse every failure into a generic message. - sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) }); - if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode); - void this.teardown(entryId, "teamSpeak-connect-failed"); + failConnect(normalized); return; } if (isReconnect && isRecoverable(normalized)) { @@ -445,7 +463,11 @@ export class VoiceBridge { onKick: kick => { // A transport drop may arrive first and already start recovery. A // subsequent kick is still terminal and must cancel that recovery. - if (!hasConnectedOnce) return; + // A kick that lands before the session ever settled in (during the + // first connect or a reconnect handshake) is terminal too: without + // this the client would sit on the connecting screen while the + // gateway kept the dead session alive. + if (!hasConnectedOnce && !isSettling()) return; resetDirectoryForReconnect(); const failureCode = clientConnectionFailureCode(kick, serverPassword); const failureDetail = publicFailureDetail(kick); @@ -455,10 +477,36 @@ export class VoiceBridge { void this.teardown(entryId, "teamSpeak-kicked"); }, onDisconnect: error => { - if (!hasConnectedOnce || session.state !== "connected") return; + const normalized = error ? normalizeTeamSpeakError(error) : null; + if (isSettling()) { + // `connected` was never published, so there is no live session to + // interrupt -- but staying in `syncing` would leave the client on + // the connecting screen with no recovery scheduled. + if (!hasConnectedOnce) { + this.logger.warn({ + entryId, + normalizedCode: normalized?.code, + ...(normalized ? { failureDetail: describeTeamSpeakError(normalized) } : {}), + }, "TeamSpeak connection lost before the session became usable"); + failConnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection lost during startup"))); + return; + } + // A reconnect attempt dropped mid-handshake. Detach the dead + // transport and fall back into the recovery loop rather than + // stalling in `syncing`. + resetDirectoryForReconnect(); + try { + session.transition("reconnecting"); + } catch { + failReconnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection lost during reconnect"))); + return; + } + scheduleReconnect(normalized); + return; + } + if (session.state !== "connected") return; this.screenShares.removePeer(entryId); resetDirectoryForReconnect(); - const normalized = error ? normalizeTeamSpeakError(error) : null; sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) }); scheduleReconnect(normalized); },