feat: 浏览器端报错翻译与提示改造

- errors: 新增 TeamSpeak 服务器错误 ID 映射表与不可重连错误码集合,归一化
  normalizeTeamSpeakError 按 错误ID/关键词/异常类/传输层特征 分级收敛错误
- voice-bridge: 身份无效/客户端不可用时先发结构化 connectionFailed 帧再关闭,
  新增 pendingKickReason 机制在 kicked 事件后优先回放踢出原因;Opus 编码器
  不可用时限流上报 AUDIO_ENCODER_UNAVAILABLE
- ts-client: 记录本端退出 reasonID,转发 kicked 事件并归一化踢出/封禁原因
- network-probe/teamspeak-probe: 收窄关键字匹配、拒绝原因收敛到既有探测码
- session-manager: 新增 teamSpeak-kicked 拆除原因
- WebClient: 麦克风失败不再假成功,音频状态避免自相矛盾,新增降级横幅与
  中/英/德三语提示词表
- useVoiceWebSocket: 导出 ensureMicrophone 供开麦前预检,新增音频诊断状态、
  CONNECTION_FAILURE_MESSAGES 总表与网关关闭码映射
- 关键新增逻辑补充中文注释说明改动意图
This commit is contained in:
LainHE committed 2026-09-16 22:24:25 +08:00
1 parent 1ba8cd5ee1
commit 4ead174c04
8 files changed
+677 -74

No files matched your search

+253 -18
View File
@@ -1,19 +1,31 @@
export type WebSpeakErrorCode =
| "invalid_target"
| "invalid_nickname"
| "nickname_in_use"
| "host_not_found"
| "unreachable"
| "connection_refused"
| "connection_reset"
| "timeout"
| "authentication_failed"
| "protocol_negotiation_failed"
| "channel_password_required"
| "identity_security_level_too_low"
| "identity_limit_reached"
| "client_version_outdated"
| "flooding"
| "banned"
| "kicked"
| "server_shutting_down"
| "server_full"
| "invalid_parameter_size"
| "connection_initialisation_failed"
| "protocol_negotiation_failed"
| "unknown";
export type ClientConnectionFailureCode =
| "INVALID_TARGET"
| "INVALID_NICKNAME"
| "NICKNAME_IN_USE"
| "HOST_NOT_FOUND"
| "UNREACHABLE"
| "CONNECTION_REFUSED"
@@ -21,8 +33,18 @@ export type ClientConnectionFailureCode =
| "TIMEOUT"
| "SERVER_PASSWORD_REQUIRED"
| "INVALID_SERVER_PASSWORD"
| "CHANNEL_PASSWORD_REQUIRED"
| "IDENTITY_SECURITY_LEVEL_TOO_LOW"
| "IDENTITY_LIMIT_REACHED"
| "CLIENT_VERSION_OUTDATED"
| "FLOOD_PROTECTION"
| "BANNED"
| "KICKED"
| "SERVER_SHUTTING_DOWN"
| "SERVER_FULL"
| "INVALID_PARAMETER"
| "PROTOCOL_NEGOTIATION_FAILED"
| "SERVER_REJECTED"
| "CONNECTION_INITIALISATION_FAILED"
| "CONNECTION_FAILED";
export interface TeamSpeakErrorDiagnostics {
@@ -53,37 +75,220 @@ export class WebSpeakError extends Error {
}
}
/**
* TeamSpeak server error ids (SDK `public_errors.h`, shared by TS3 and TS6) that
* the gateway can name precisely. Ids that are absent on purpose fall through to
* the text heuristics below and finally to `unknown`, which still carries the raw
* server detail to the browser.
*/
export const TEAMSPEAK_SERVER_ERROR_IDS: Readonly<Record<string, WebSpeakErrorCode>> = {
// Client (0x02xx): nickname, capacity, identity, password, version, flooding.
"513": "nickname_in_use",
"515": "server_full",
"519": "identity_security_level_too_low",
"520": "authentication_failed",
"521": "identity_limit_reached",
"522": "client_version_outdated",
"524": "flooding",
// Parameter (0x06xx). During the connect handshake the only size-checked value
// the gateway sends is the nickname, so 1541 is reported as a nickname problem
// instead of a generic parameter error.
"1536": "invalid_parameter_size",
"1537": "invalid_parameter_size",
"1538": "invalid_parameter_size",
"1539": "invalid_parameter_size",
"1540": "invalid_parameter_size",
"1541": "invalid_nickname",
"1542": "invalid_parameter_size",
"1543": "protocol_negotiation_failed",
// Connection (0x07xx).
"1792": "connection_reset",
"1794": "channel_password_required",
"1796": "connection_initialisation_failed",
"1797": "host_not_found",
"1804": "unreachable",
"1805": "protocol_negotiation_failed",
"1806": "protocol_negotiation_failed",
// Server (0x04xx).
"1041": "server_shutting_down",
// Accounting (0x0bxx): the slot and virtual-server limits both surface as a
// full server from the user's point of view.
"2816": "server_full",
"2817": "server_full",
"2825": "protocol_negotiation_failed",
// Ban (0x0dxx).
"3329": "banned",
"3330": "banned",
"3331": "flooding",
};
/**
* Default (English) message per normalized code. The browser translates these
* strings for zh/en/de, so keep them stable and never embed a raw server id here:
* the raw detail travels separately in `diagnostics`.
*/
export const WEBSPEAK_ERROR_MESSAGES: Readonly<Record<WebSpeakErrorCode, string>> = {
invalid_target: "The TeamSpeak server address is invalid",
invalid_nickname: "TeamSpeak refused the nickname: it must be 3-30 characters long",
nickname_in_use: "This nickname is already used by another user on the TeamSpeak server",
host_not_found: "TeamSpeak server hostname could not be resolved",
unreachable: "TeamSpeak server is unreachable",
connection_refused: "TeamSpeak server refused the connection",
connection_reset: "TeamSpeak connection was reset",
timeout: "TeamSpeak connection timed out",
authentication_failed: "TeamSpeak authentication failed",
channel_password_required: "The TeamSpeak channel requires a password",
identity_security_level_too_low: "This TeamSpeak identity's security level is below the server requirement",
identity_limit_reached: "This TeamSpeak identity already holds the maximum number of connections",
client_version_outdated: "The TeamSpeak server requires a newer client version",
flooding: "The TeamSpeak server's flood protection refused the connection",
banned: "You are banned from this TeamSpeak server",
kicked: "You were kicked from the TeamSpeak server",
server_shutting_down: "The TeamSpeak server is shutting down",
connection_initialisation_failed: "The TeamSpeak server refused the connection during initialisation",
server_full: "The TeamSpeak server is full",
invalid_parameter_size: "TeamSpeak refused a parameter because its length or value is out of range",
protocol_negotiation_failed: "TeamSpeak protocol negotiation failed",
unknown: "TeamSpeak connection failed",
};
// 不可重连的错误码集合:这些错误原样重连必然失败(如被封禁、昵称被占用等),
// 集合与消息表相邻存放便于审计重连决策;unknown 保持不可重连,防止未映射的
// 服务器拒绝演变成无限重连循环。
/**
* Codes for which reconnecting unchanged cannot succeed. Keeping the list next to
* the messages makes the retry decision auditable; `unknown` stays non-retryable
* so an unmapped server refusal can never turn into a reconnect loop.
*/
const NON_RETRYABLE_CODES: ReadonlySet<WebSpeakErrorCode> = new Set<WebSpeakErrorCode>([
"invalid_target",
"invalid_nickname",
"nickname_in_use",
"authentication_failed",
"channel_password_required",
"identity_security_level_too_low",
"identity_limit_reached",
"client_version_outdated",
"banned",
"kicked",
"invalid_parameter_size",
"connection_initialisation_failed",
"unknown",
]);
function createTeamSpeakError(code: WebSpeakErrorCode, cause: unknown, diagnostics: TeamSpeakErrorDiagnostics): WebSpeakError {
return new WebSpeakError(code, WEBSPEAK_ERROR_MESSAGES[code], !NON_RETRYABLE_CODES.has(code), cause, diagnostics);
}
/**
* Resolve a raw TeamSpeak server error id to a normalized code. Accepts the
* decimal form the SDK forwards (`err.id`, `id=515`) and the hex form used by the
* official headers (`0x0203`), because both shapes show up in logs.
*/
export function teamSpeakServerErrorCode(id: unknown): WebSpeakErrorCode | null {
if (id === undefined || id === null) return null;
const text = String(id).trim().toLocaleLowerCase();
if (/^\d{1,6}$/.test(text)) return TEAMSPEAK_SERVER_ERROR_IDS[String(Number(text))] ?? null;
const hexMatch = /^(?:0x)?([0-9a-f]{4,6})$/.exec(text);
if (hexMatch) return TEAMSPEAK_SERVER_ERROR_IDS[String(parseInt(hexMatch[1], 16))] ?? null;
return null;
}
// 归一化入口:按「服务器错误ID → 关键词启发式 → 异常类名 → 传输层特征」的
// 优先级,把 SDK/Node 抛出的原始错误收敛为带稳定错误码的 WebSpeakError。
export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
if (error instanceof WebSpeakError) return error;
const diagnostics = collectDiagnostics(error);
const text = diagnosticText(error).toLocaleLowerCase();
if (/password|authenticate|authentication|not authorized|invalid.*(credential|password)/.test(text)) {
return new WebSpeakError("authentication_failed", "TeamSpeak authentication failed", false, error, diagnostics);
// 1) A TeamSpeak server error id names the exact reason, so it outranks every
// keyword heuristic below. Only 1541 used to be recognised, which pushed
// "banned", "server is full" and every other refusal into the generic
// fallback. The inline scan keeps the `id=515` shape working even when the
// SDK does not attach the id as a structured field.
const inlineId = /\bid[\s=:]*(\d{3,5})\b/.exec(text)?.[1];
const serverErrorCode =
teamSpeakServerErrorCode(diagnostics.id) ?? teamSpeakServerErrorCode(diagnostics.code) ?? teamSpeakServerErrorCode(inlineId);
if (serverErrorCode) return createTeamSpeakError(serverErrorCode, error, diagnostics);
// 2) Explicit refusals that arrive without a stable id. Every pattern stays
// narrow on purpose: bare words such as "password", "network", "socket",
// "crypto" or "denied" also appear in unrelated Teamspeak messages and used
// to steal the classification from the real cause.
if (/invalid[\s_-]*parameter[\s_-]*size|parameter.{0,20}(size|out of range)|nickname.{0,20}(length|size)/.test(text)) {
return createTeamSpeakError("invalid_nickname", error, diagnostics);
}
if (/invalid parameter size|nickname.{0,20}(length|size)|(?:length|size).{0,20}nickname|id[=: ]1541/.test(text)) {
return new WebSpeakError("invalid_nickname", "TeamSpeak nickname length is invalid", false, error, diagnostics);
if (/nickname.{0,30}(in use|already (in )?use|taken|exists)|nickname_in_use/.test(text)) {
return createTeamSpeakError("nickname_in_use", error, diagnostics);
}
if (/enotfound|eai_again|host not found|name or service not known|dns/.test(text)) {
return new WebSpeakError("host_not_found", "TeamSpeak server hostname could not be resolved", true, error, diagnostics);
if (/channel.{0,30}password|password.{0,30}channel|i_channel_password/.test(text)) {
return createTeamSpeakError("channel_password_required", error, diagnostics);
}
if (/security ?level|insufficient security|could not validate identity/.test(text)) {
return createTeamSpeakError("identity_security_level_too_low", error, diagnostics);
}
if (/too many clones|clone.{0,20}(limit|connected)|identity.{0,20}(limit|maximum|max).{0,20}connection/.test(text)) {
return createTeamSpeakError("identity_limit_reached", error, diagnostics);
}
if (/version.{0,25}(outdated|out of date|too old|not allowed|unsupported)|outdated.{0,25}version/.test(text)) {
return createTeamSpeakError("client_version_outdated", error, diagnostics);
}
if (/flood/.test(text)) {
return createTeamSpeakError("flooding", error, diagnostics);
}
if (/\bban(ned)?\b|blacklist|you may retry in/.test(text)) {
return createTeamSpeakError("banned", error, diagnostics);
}
if (/kicked/.test(text)) {
return createTeamSpeakError("kicked", error, diagnostics);
}
if (/server.{0,20}shut ?down|server_shutdown|server is shutting down/.test(text)) {
return createTeamSpeakError("server_shutting_down", error, diagnostics);
}
if (/failed[\s_-]*connection[\s_-]*initiali[sz]ation|connection initiali[sz]ation failed|failed to (initialise|initialize) the connection/.test(text)) {
return createTeamSpeakError("connection_initialisation_failed", error, diagnostics);
}
if (/server.{0,25}full|server is full|maximum (number of )?(clients|slots)|slot limit|client protocol limit/.test(text)) {
return createTeamSpeakError("server_full", error, diagnostics);
}
if (/invalid (server )?password|wrong (server )?password|password (is )?(invalid|incorrect|wrong)|password required|i_server_password|authentication failed|not authorized|invalid credential|login (failed|refused)/.test(text)) {
return createTeamSpeakError("authentication_failed", error, diagnostics);
}
// 3) SDK handshake/crypto error classes carry no numeric id at all, so match
// the class name before falling back to the message text.
const errorName = (diagnostics.name ?? "").toLocaleLowerCase();
if (/eaxtagmismatch|fakesignaturemismatch|cryptoinit|invalididentity|license/.test(errorName)) {
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
}
if (/alreadyconnected/.test(errorName)) {
return createTeamSpeakError("identity_limit_reached", error, diagnostics);
}
if (/timeout/.test(errorName)) {
return createTeamSpeakError("timeout", error, diagnostics);
}
// 4) Transport level failures reported by Node or the TLS layer.
if (/enotfound|eai_again|host not found|name or service not known|getaddrinfo/.test(text)) {
return createTeamSpeakError("host_not_found", error, diagnostics);
}
if (/econnrefused|connection refused/.test(text)) {
return new WebSpeakError("connection_refused", "TeamSpeak server refused the connection", true, error, diagnostics);
return createTeamSpeakError("connection_refused", error, diagnostics);
}
if (/econnreset|econnaborted|connection reset|connection aborted/.test(text)) {
return new WebSpeakError("connection_reset", "TeamSpeak connection was reset", true, error, diagnostics);
if (/econnreset|econnaborted|connection reset|connection aborted|socket hang up/.test(text)) {
return createTeamSpeakError("connection_reset", error, diagnostics);
}
if (/timeout|timed out|ack timeout|idle timeout|etimedout/.test(text)) {
return new WebSpeakError("timeout", "TeamSpeak connection timed out", true, error, diagnostics);
return createTeamSpeakError("timeout", error, diagnostics);
}
if (/ehostunreach|enetunreach|network is unreachable|no route to host|network|socket/.test(text)) {
return new WebSpeakError("unreachable", "TeamSpeak server is unreachable", true, error, diagnostics);
if (/ehostunreach|enetunreach|network is unreachable|no route to host|unable to connect|transport error|unexpected eof/.test(text)) {
return createTeamSpeakError("unreachable", error, diagnostics);
}
if (/protocol|handshake|crypto|init1/.test(text)) {
return new WebSpeakError("protocol_negotiation_failed", "TeamSpeak protocol negotiation failed", true, error, diagnostics);
if (/handshake|protocol|eax|crypto ?(init|handshake|setup)|init1|signature|license/.test(text)) {
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
}
return new WebSpeakError("unknown", "TeamSpeak connection failed", false, error, diagnostics);
return createTeamSpeakError("unknown", error, diagnostics);
}
export function clientConnectionFailureCode(error: WebSpeakError, serverPassword = ""): ClientConnectionFailureCode {
@@ -93,19 +298,49 @@ export function clientConnectionFailureCode(error: WebSpeakError, serverPassword
const mapping: Record<WebSpeakErrorCode, ClientConnectionFailureCode> = {
invalid_target: "INVALID_TARGET",
invalid_nickname: "INVALID_NICKNAME",
nickname_in_use: "NICKNAME_IN_USE",
host_not_found: "HOST_NOT_FOUND",
unreachable: "UNREACHABLE",
connection_refused: "CONNECTION_REFUSED",
connection_reset: "CONNECTION_RESET",
timeout: "TIMEOUT",
authentication_failed: "SERVER_PASSWORD_REQUIRED",
channel_password_required: "CHANNEL_PASSWORD_REQUIRED",
identity_security_level_too_low: "IDENTITY_SECURITY_LEVEL_TOO_LOW",
identity_limit_reached: "IDENTITY_LIMIT_REACHED",
client_version_outdated: "CLIENT_VERSION_OUTDATED",
flooding: "FLOOD_PROTECTION",
banned: "BANNED",
kicked: "KICKED",
server_shutting_down: "SERVER_SHUTTING_DOWN",
connection_initialisation_failed: "CONNECTION_INITIALISATION_FAILED",
server_full: "SERVER_FULL",
invalid_parameter_size: "INVALID_PARAMETER",
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
server_full: "SERVER_REJECTED",
unknown: "CONNECTION_FAILED",
};
return mapping[error.code];
}
/**
* Normalize the SDK `kicked` event. TeamSpeak reports a kick/ban as a
* `clientleftview` whose reason id is 4 (kicked) or 5 (kicked with ban) and whose
* `reasonMsg` is written by the admin, e.g. "Slow down!" or "you may retry in
* 300 seconds". Before this helper existed the reason text was dropped and the
* browser only showed a generic connection failure, which is exactly the
* experience this translation layer removes. The ban/kick split prefers the
* server text and falls back to reason id 5.
*/
export function normalizeTeamSpeakKickedReason(reasonMsg: unknown, reasonId?: unknown): WebSpeakError {
const text = typeof reasonMsg === "string" ? reasonMsg.trim() : "";
const numericReasonId = typeof reasonId === "number" ? reasonId : Number(reasonId);
const isBan = /\bban(ned)?\b|blacklist|you may retry in/i.test(text) || numericReasonId === 5;
const diagnostics: TeamSpeakErrorDiagnostics = { name: isBan ? "TeamSpeakBan" : "TeamSpeakKick" };
if (text) diagnostics.serverMessage = text;
if (Number.isFinite(numericReasonId)) diagnostics.id = String(numericReasonId);
return createTeamSpeakError(isBan ? "banned" : "kicked", reasonMsg, diagnostics);
}
/** Format useful SDK/Node details for a safe operational log field. */
export function describeTeamSpeakError(error: WebSpeakError): string {
const details = error.diagnostics;
+8 -3
View File
@@ -114,9 +114,14 @@ function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
if (/password|authentication|invalid.*credential/.test(lower)) return "INVALID_PASSWORD";
if (/protocol|version|handshake|negotiat/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED";
if (/reject|full|denied/.test(lower)) return "SERVER_REJECTED";
// 关键词刻意收窄:裸的 password/version/denied 会出现在大量无关的 ping/传输
// 输出中,误判会把用户引向错误的排查方向,只把明确的短语视为证据。
// Keep the keywords narrow: a bare "password", "version" or "denied" appears in
// plenty of unrelated ping/transport output, and guessing here used to send the
// user to the wrong remedy. Only explicit phrases are treated as evidence.
if (/invalid password|password (?:required|incorrect|wrong|rejected)|authentication failed|invalid credential/.test(lower)) return "INVALID_PASSWORD";
if (/protocol (?:version )?(?:mismatch|not supported|error)|version (?:is )?(?:outdated|too old|not supported)|handshake (?:failed|error|timeout)|negotiation failed/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED";
if (/server (?:is )?full|slot limit|client protocol limit|banned?|flooding|server rejected|connection (?:denied|refused) by (?:the )?server/.test(lower)) return "SERVER_REJECTED";
return "UNREACHABLE";
}
+1
View File
@@ -17,6 +17,7 @@ export type SessionTeardownReason =
| "websocket-error"
| "protocol-error"
| "teamSpeak-disconnect"
| "teamSpeak-kicked" // 会话被 TeamSpeak 服务器踢出/封禁时拆除
| "teamSpeak-connect-failed"
| "heartbeat-timeout"
| "admin-terminated"
+16
View File
@@ -103,15 +103,31 @@ export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
}
// 探测只回答「该地址是否可用」,因此把网关能细分的拒绝原因收敛到既有探测码,
// 具体原因由连接/重连路径向浏览器上报。
// The probe only answers "can this address be used at all", so the richer
// rejection reasons the gateway can now name are bucketed into the existing
// probe codes; the exact reason is reported by the connect/reconnect path.
const mapping: Record<WebSpeakErrorCode, ProbeErrorCode> = {
invalid_target: "INTERNAL_ERROR",
invalid_nickname: "INVALID_NICKNAME",
nickname_in_use: "INVALID_NICKNAME",
invalid_parameter_size: "INVALID_NICKNAME",
unreachable: "UNREACHABLE",
host_not_found: "HOST_NOT_FOUND",
connection_refused: "CONNECTION_REFUSED",
connection_reset: "CONNECTION_RESET",
timeout: "TIMEOUT",
authentication_failed: password.trim() ? "INVALID_PASSWORD" : "PASSWORD_REQUIRED",
channel_password_required: "PASSWORD_REQUIRED",
identity_security_level_too_low: "SERVER_REJECTED",
identity_limit_reached: "SERVER_REJECTED",
client_version_outdated: "SERVER_REJECTED",
flooding: "SERVER_REJECTED",
banned: "SERVER_REJECTED",
kicked: "SERVER_REJECTED",
server_shutting_down: "SERVER_REJECTED",
connection_initialisation_failed: "SERVER_REJECTED",
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
server_full: "SERVER_REJECTED",
unknown: "SERVER_REJECTED",
+19 -1
View File
@@ -14,7 +14,7 @@ import {
type TextMessage,
} from "@echosixhiya/teamspeak-client";
import type { Logger } from "../logger.js";
import { describeTeamSpeakError, normalizeTeamSpeakError } from "../errors.js";
import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKickedReason } from "../errors.js";
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { createAccelerationRelayClient, type AccelerationRelayClient, type AccelerationRelayOptions } from "./acceleration-relay.js";
@@ -74,6 +74,10 @@ export class TSClient extends EventEmitter {
private connected = false;
private preferredChannelId = 0n;
private accelerationClient: AccelerationRelayClient | null = null;
// Reason id of the most recent self leave, kept so the SDK `kicked` event can
// tell a plain kick (4) from a kick with ban (5). The SDK only forwards the
// reason message to its `kicked` handler, not the reason id.
private selfLeaveReasonId: number | null = null;
constructor(private options: TSClientOptions, logger: Logger) {
super();
@@ -214,9 +218,23 @@ export class TSClient extends EventEmitter {
});
client.on("clientLeave", (info) => {
// 仅记录本客户端的踢出(4)/踢出并封禁(5)退出原因,供 kicked 事件区分普通踢出与封禁
if (info.id === this.clientId && (info.reasonID === 4 || info.reasonID === 5)) this.selfLeaveReasonId = info.reasonID;
this.emit("clientLeave", info);
});
// 转发 SDK 的 kicked 事件:不转发的话管理员填写的踢出原因会被丢弃,浏览器
// 只能看到笼统的「连接失败」。这里把原因连同 reason id 一起归一化后向上抛。
// The SDK emits `kicked` only for a self leave with reason 4 (kick) or 5
// (kick with ban) and hands over the admin written reason message. Without
// this listener the reason was dropped, so the browser degraded to a generic
// "connection failed" right after the transport went away.
client.on("kicked", (reasonMsg) => {
const reasonId = this.selfLeaveReasonId;
this.selfLeaveReasonId = null;
this.emit("kicked", normalizeTeamSpeakKickedReason(reasonMsg, reasonId));
});
client.on("clientMoved", (info) => {
if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID;
this.emit("clientMoved", info);
+65 -5
View File
@@ -6,7 +6,7 @@ import { identityFromString } from "@echosixhiya/teamspeak-client";
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 { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError } from "../errors.js";
import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError, teamSpeakServerErrorCode, type WebSpeakError } from "../errors.js";
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js";
import { IdentityLeaseStore } from "./identity-lease.js";
@@ -141,6 +141,7 @@ interface WebClientEntry {
members: Map<number, ChannelMember>;
eventLog: ServerEvent[];
opusEncoder: { encode(pcm: Buffer): Buffer } | null;
opusEncoderWarnedAt: number; // Opus 编码器不可用告警的时间戳,用于限流避免反复刷屏
whisperTargetIds: Set<number>;
whisperActive: boolean;
isAlive: boolean;
@@ -191,7 +192,10 @@ export class VoiceBridge {
try {
identity = connection.identity ? identityFromString(connection.identity) : undefined;
} catch {
ws.close(4003, "Invalid identity");
// Send a structured failure before the close so the browser can tell
// an invalid remembered identity apart from a real connection failure.
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "connectionFailed", code: "IDENTITY_INVALID", detail: "Invalid identity" }));
ws.close(4003, "IDENTITY_INVALID");
return;
}
const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
@@ -229,8 +233,11 @@ export class VoiceBridge {
} catch (error: unknown) {
if (identityLeaseKey) this.identityLeases.release(identityLeaseKey, entryId);
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");
// A 4003 with a bare close used to be reported as "identity rejected".
// Send a structured failure so the browser says the TeamSpeak client
// could not be created (server down / unreachable) instead.
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "connectionFailed", code: "TEAM_SPEAK_CLIENT_UNAVAILABLE", detail: "TeamSpeak client unavailable" }));
ws.close(4003, "TEAM_SPEAK_CLIENT_UNAVAILABLE");
return;
}
entry = {
@@ -250,6 +257,7 @@ export class VoiceBridge {
members: new Map(),
eventLog: [],
opusEncoder: null,
opusEncoderWarnedAt: 0,
whisperTargetIds: new Set(),
whisperActive: false,
isAlive: true,
@@ -274,6 +282,10 @@ export class VoiceBridge {
let audioReady = true;
let realtimeReady = false;
let hasConnectedOnce = false;
// Set when the server kicks or bans this client. The kick and the transport
// drop can arrive in either order, so the reason is parked here and consumed
// by whichever handler runs second.
let pendingKickReason: WebSpeakError | null = null;
let reconnectStartedAt = 0;
let reconnectAttempt = 0;
const directory = new DirectorySynchronizer();
@@ -338,6 +350,8 @@ export class VoiceBridge {
initialStateSent = true;
const wasReconnecting = hasConnectedOnce;
hasConnectedOnce = true;
// A previous kick reason never applies to a fresh, successful session.
pendingKickReason = null;
reconnectAttempt = 0;
reconnectStartedAt = 0;
if (!wasReconnecting) {
@@ -602,10 +616,30 @@ export class VoiceBridge {
addServerEvent("poke", `${event.invokerName || "用户"} 戳了你一下`);
});
// 被踢/封禁对本会话是终态:把服务器给出的原因回放给浏览器并拆除会话,
// 而不是像以前那样因原因被丢弃而反复重连、再次撞上同一踢出。
// A kick or ban is terminal for this session: replay the reason the server
// sent instead of reconnecting, which is what used to happen once the reason
// message was dropped (the browser kept retrying straight into the kick).
tsClient.on("kicked", (kick: WebSpeakError) => {
if (!hasConnectedOnce || session.state !== "connected") return;
pendingKickReason = kick;
resetDirectoryForReconnect();
const failureCode = clientConnectionFailureCode(kick, serverPassword);
const failureDetail = publicFailureDetail(kick);
entry!.connectionFailureCode = failureCode;
this.logger.warn({ entryId, code: failureCode, normalizedCode: kick.code, failureDetail: describeTeamSpeakError(kick) }, "TeamSpeak session ended by kick/ban");
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
void this.teardown(entryId, "teamSpeak-kicked");
});
tsClient.on("disconnected", (error?: Error) => {
if (!hasConnectedOnce || session.state !== "connected") return;
resetDirectoryForReconnect();
const normalized = error ? normalizeTeamSpeakError(error) : null;
// Prefer a kick reason over the generic transport error that follows it,
// regardless of which of the two events arrives first.
const normalized = pendingKickReason ?? (error ? normalizeTeamSpeakError(error) : null);
pendingKickReason = null;
sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) });
scheduleReconnect(normalized);
});
@@ -637,6 +671,16 @@ export class VoiceBridge {
entry!.audio.tsSendFirstAt ??= sentAt;
entry!.audio.tsSendLastAt = sentAt;
entry!.audio.tsSendFrames++;
} else {
// Opus 编码器不可用(初始化失败或销毁后仍有帧在途):显式告知浏览器
// 而不是静默丢帧,5 秒限流避免高频告警刷屏。
// The Opus encoder is unavailable (init failed or torn down while
// frames are still in flight): say it instead of dropping silently.
const warnedAt = entry!.opusEncoderWarnedAt;
if (Date.now() - warnedAt > 5_000) {
entry!.opusEncoderWarnedAt = Date.now();
sendJson({ type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" });
}
}
} catch {
// A frame arriving during shutdown is safe to discard.
@@ -1059,6 +1103,22 @@ async function handleCommand(
function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } {
const text = error instanceof Error ? error.message : String(error);
const normalized = text.toLocaleLowerCase();
// A TeamSpeak server error id is authoritative when the SDK preserved it, so it
// is consulted before the keyword rules: 1794 (channel password), 2568
// (permissions), 515/2817 (server or slot limit) and friends keep their exact
// meaning instead of being guessed from prose.
const serverCode =
teamSpeakServerErrorCode(isRecord(error) ? (error.id ?? error.code) : undefined) ??
teamSpeakServerErrorCode(/\bid[\s=:]*(\d{3,5})\b/.exec(normalized)?.[1]);
if (serverCode) {
if (serverCode === "identity_security_level_too_low") return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" };
if (serverCode === "channel_password_required") return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" };
if (serverCode === "server_full") return { code: "CHANNEL_FULL", message: "该频道已满" };
if (serverCode === "client_version_outdated") return { code: "CLIENT_VERSION_OUTDATED", message: "客户端版本过旧,服务器拒绝了该操作" };
if (serverCode === "flooding") return { code: "FLOOD_PROTECTION", message: "操作过于频繁,请稍后重试" };
if (serverCode === "banned") return { code: "BANNED", message: "你已被该服务器封禁" };
if (serverCode === "connection_initialisation_failed") return { code: "CONNECTION_INITIALISATION_FAILED", message: "TeamSpeak 服务器未能完成连接初始化,请稍后重试" };
}
if (/permission|not permitted|insufficient|i_permission|2568/.test(normalized)) return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" };
if (/channel.*(password|password.*required)|invalid.*(channel|password)|i_channel_password|1794/.test(normalized)) return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" };
if (/already member/.test(normalized)) return { code: "ALREADY_IN_CHANNEL", message: "你已经在该频道中" };