fix: surface all connection error codes on join page

This commit is contained in:
illusia committed 2026-09-13 08:20:27 +08:00
1 parent ef3e65ea0b
commit 7f97d54206
3 files changed
+125 -30

No files matched your search

+12 -2
View File
@@ -32,6 +32,14 @@ const AUDIO_FRAME_BYTES = 1_920;
// before scheduling decoded audio.
const MAX_SERVER_AUDIO_BUFFERED_BYTES = 4_096;
function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>): string | undefined {
const serverMessage = error.diagnostics.serverMessage?.trim();
const serverId = error.diagnostics.id?.trim();
const detail = [serverMessage, serverId ? `server error id=${serverId}` : ""].filter(Boolean).join("; ");
const safe = detail.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 160);
return safe || undefined;
}
export interface VoiceBridgeOptions {
joinTickets: JoinTicketStore;
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
@@ -379,8 +387,9 @@ export class VoiceBridge {
if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed");
} catch { /* teardown below remains authoritative */ }
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
const failureDetail = publicFailureDetail(normalized);
entry!.connectionFailureCode = failureCode;
sendJson({ type: "reconnectFailed", code: failureCode });
sendJson({ type: "reconnectFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
void this.teardown(entryId, "teamSpeak-connect-failed");
};
@@ -435,6 +444,7 @@ 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,
@@ -452,7 +462,7 @@ export class VoiceBridge {
// 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 });
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode);
void this.teardown(entryId, "teamSpeak-connect-failed");
return;
+77 -26
View File
@@ -84,6 +84,40 @@ export interface LatencyProbeResult {
teamSpeakErrorCode?: string;
}
const MAX_VISIBLE_ERROR_CODE_LENGTH = 64;
const CLIENT_ERROR_CODE_ALIASES: Record<string, string> = {
PASSWORD_REQUIRED: "SERVER_PASSWORD_REQUIRED",
INVALID_PASSWORD: "INVALID_SERVER_PASSWORD",
AUTHENTICATION_FAILED: "INVALID_SERVER_PASSWORD",
SERVER_FULL: "SERVER_REJECTED",
GATEWAY_FULL: "SERVER_REJECTED",
TS_CONNECT_FAILED: "CONNECTION_FAILED",
TEAM_SPEAK_CONNECT_FAILED: "CONNECTION_FAILED",
};
/** Keep codes useful to the user without allowing an unbounded server value into the UI. */
function safeClientErrorCode(value: unknown): string {
const normalized = String(value ?? "")
.trim()
.toUpperCase()
.replace(/[^A-Z0-9_-]+/g, "_")
.replace(/^_+|_+$/g, "");
return normalized.slice(0, MAX_VISIBLE_ERROR_CODE_LENGTH);
}
function normalizedClientErrorCode(value: unknown, fallback = "CONNECTION_FAILED"): string {
const safe = safeClientErrorCode(value);
return CLIENT_ERROR_CODE_ALIASES[safe] ?? (safe || fallback);
}
function safeClientErrorDetail(value: unknown): string {
return String(value ?? "")
.replace(/[\u0000-\u001f\u007f]/g, " ")
.replace(/\s+/g, " ")
.trim()
.slice(0, 160);
}
export function useVoiceWebSocket() {
const ws = ref<WebSocket | null>(null);
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", channelSwitchedChannelId: "" });
@@ -1109,16 +1143,21 @@ export function useVoiceWebSocket() {
headers: { "content-type": "application/json", accept: "application/json" },
body: JSON.stringify({ target, nickname, channel, serverPassword, ...(inviteToken ? { invite: inviteToken } : {}), ...(accelerated ? { accelerated: true, ...(lastConnection?.accelerationRelayId ? { accelerationRelayId: lastConnection.accelerationRelayId } : {}) } : {}), ...(lastConnection?.rememberIdentity && lastConnection.identity ? { identity: lastConnection.identity } : {}), ...(lastConnection?.rememberIdentity ? { rememberIdentity: true } : {}) }),
});
const result = await response.json().catch(() => ({})) as { ticket?: unknown; code?: unknown };
const result = await response.json().catch(() => ({})) as { ticket?: unknown; code?: unknown; detail?: unknown };
if (!response.ok || typeof result.ticket !== "string") {
throw new Error(joinTicketReason(typeof result.code === "string" ? result.code : ""));
const failureCode = normalizedClientErrorCode(result.code);
const failure = new Error(joinTicketReason(failureCode, result.detail));
Object.assign(failure, { code: failureCode });
throw failure;
}
if (sequence !== connectionSequence) return;
openVoiceSocket(sequence, result.ticket);
} catch (error: unknown) {
if (sequence !== connectionSequence) return;
state.connecting = false;
state.error = error instanceof Error ? error.message : "连接服务器失败,请检查邀请链接或服务器状态";
const errorRecord = error && typeof error === "object" ? error as { code?: unknown } : {};
state.errorCode = normalizedClientErrorCode(errorRecord.code, "REQUEST_FAILED");
state.error = error instanceof Error ? error.message : connectionFailureMessage(state.errorCode);
}
}
@@ -1168,26 +1207,34 @@ export function useVoiceWebSocket() {
};
}
function joinTicketReason(code: string): string {
if (code === "NOT_INITIALIZED") return "WebSpeak 尚未完成首次配置";
if (code === "TARGET_NOT_ALLOWED") return "此 TeamSpeak 服务器地址不允许连接";
if (code === "ACCELERATION_UNAVAILABLE") return "大陆节点智能加速尚未在当前网关配置";
if (code === "INVALID_NICKNAME") return "请输入有效的昵称";
if (code === "INVITE_INVALID") return "邀请链接已失效或已被撤销";
return "连接服务器失败,请检查邀请链接或服务器状态";
function joinTicketReason(code: string, detail?: unknown): string {
const messages: Record<string, string> = {
ORIGIN_REJECTED: "请求来源不受信任,请从正确的网站入口重新打开",
NOT_INITIALIZED: "WebSpeak 尚未完成配置,请联系管理员",
RATE_LIMITED: "请求过于频繁,请稍后重试",
TARGET_NOT_ALLOWED: "此 TeamSpeak 服务器地址不允许连接",
ACCELERATION_UNAVAILABLE: "当前中继加速不可用,请关闭加速或联系管理员",
INVALID_NICKNAME: "请输入有效的昵称",
INVITE_INVALID: "邀请链接已失效或已被撤销",
};
const normalized = normalizedClientErrorCode(code);
return messages[normalized] ?? connectionFailureMessage(normalized, detail);
}
function closeErrorCode(code: number, reason = ""): string {
const known = new Set(["INVALID_TARGET", "INVALID_NICKNAME", "HOST_NOT_FOUND", "UNREACHABLE", "CONNECTION_REFUSED", "CONNECTION_RESET", "TIMEOUT", "SERVER_PASSWORD_REQUIRED", "INVALID_SERVER_PASSWORD", "PROTOCOL_NEGOTIATION_FAILED", "SERVER_REJECTED", "CONNECTION_FAILED"]);
if (known.has(reason)) return reason;
const closeCode = normalizedClientErrorCode(reason, "");
if (closeCode) return closeCode;
if (code === 4002) return "INVALID_TARGET";
if (code === 4004) return "SERVER_REJECTED";
if (code === 4005) return "IDENTITY_IN_USE";
return "CONNECTION_FAILED";
}
function connectionFailureMessage(code: string): string {
function connectionFailureMessage(code: string, detail?: unknown): string {
const messages: Record<string, string> = {
ORIGIN_REJECTED: "请求来源不受信任,请从正确的网站入口重新打开",
NOT_INITIALIZED: "WebSpeak 尚未完成配置,请联系管理员",
RATE_LIMITED: "请求过于频繁,请稍后重试",
INVALID_TARGET: "TeamSpeak 服务器地址无效",
INVALID_NICKNAME: "昵称长度不符合 TeamSpeak 服务器要求,请修改后重试",
HOST_NOT_FOUND: "找不到 TeamSpeak 服务器主机名,请检查地址",
@@ -1202,17 +1249,17 @@ export function useVoiceWebSocket() {
IDENTITY_IN_USE: "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试",
CONNECTION_FAILED: "TeamSpeak 连接失败,请检查地址、网络或服务器状态",
};
return messages[code] ?? "连接已断开";
const normalized = normalizedClientErrorCode(code);
if (messages[normalized]) return messages[normalized];
const safeCode = safeClientErrorCode(normalized);
const safeDetail = safeClientErrorDetail(detail);
return `TeamSpeak 连接失败(错误代码:${safeCode})${safeDetail ? `:${safeDetail}` : ""},请检查输入、网络或服务器状态`;
}
function closeReason(code: number, reason = ""): string {
const failureCode = closeErrorCode(code, reason);
if (failureCode !== "CONNECTION_FAILED") return connectionFailureMessage(failureCode);
if (code === 4002) return "TeamSpeak 服务器地址无效";
if (code === 4003) return "TeamSpeak 服务器连接失败";
if (code === 4004) return "服务器当前已满,请稍后重试";
if (code === 4005) return "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试";
return "连接已断开";
if (code === 4004 && failureCode === "SERVER_REJECTED") return "服务器当前已满或拒绝了连接,请稍后重试";
return connectionFailureMessage(failureCode);
}
function disconnect(preserveConnection = false): void {
@@ -1404,8 +1451,8 @@ export function useVoiceWebSocket() {
state.connecting = false;
state.reconnecting = false;
state.reconnectFailed = true;
state.errorCode = typeof msg.code === "string" ? msg.code : "CONNECTION_FAILED";
state.error = connectionFailureMessage(state.errorCode);
state.errorCode = normalizedClientErrorCode(msg.code);
state.error = connectionFailureMessage(state.errorCode, msg.detail);
whisperTargetIds.clear();
whisperActive.value = false;
break;
@@ -1416,8 +1463,8 @@ export function useVoiceWebSocket() {
// This is the first connection attempt, not a failed reconnect. Keep
// the user on the welcome form instead of showing an empty voice room.
state.reconnectFailed = false;
state.errorCode = typeof msg.code === "string" ? msg.code : "CONNECTION_FAILED";
state.error = connectionFailureMessage(state.errorCode);
state.errorCode = normalizedClientErrorCode(msg.code);
state.error = connectionFailureMessage(state.errorCode, msg.detail);
whisperTargetIds.clear();
whisperActive.value = false;
break;
@@ -1438,7 +1485,7 @@ export function useVoiceWebSocket() {
}
break;
case "error":
state.errorCode = String(msg.error?.code || "");
state.errorCode = normalizedClientErrorCode(msg.error?.code, "OPERATION_FAILED");
state.error = protocolErrorMessage(state.errorCode, String(msg.error?.message || msg.message || "操作失败"));
break;
}
@@ -1591,7 +1638,11 @@ export function useVoiceWebSocket() {
CLIENT_NOT_FOUND: "成员已离线",
OPERATION_FAILED: "操作失败",
};
return messages[code] || fallback;
const normalized = normalizedClientErrorCode(code, "OPERATION_FAILED");
if (messages[normalized]) return messages[normalized];
const safeCode = safeClientErrorCode(normalized);
const safeFallback = safeClientErrorDetail(fallback);
return `操作失败(错误代码:${safeCode})${safeFallback ? `:${safeFallback}` : ""}`;
}
function setVolume(clientId: number, volume: number): void {
+36 -2
View File
@@ -30,7 +30,7 @@
<h2>{{ t('welcomeBack') }}</h2>
<p class="card-lead">{{ t('joinLead') }}</p>
<div v-if="voiceState.error" class="notice error-notice"><span class="notice-symbol">!</span><span>{{ localizedMessage(voiceState.error) }}</span></div>
<div v-if="voiceState.error" class="notice error-notice"><span class="notice-symbol">!</span><span class="notice-content"><span>{{ localizedMessage(voiceState.error) }}</span><code v-if="voiceState.errorCode">{{ t('errorCode') }}: {{ visibleErrorCode(voiceState.errorCode) }}</code></span></div>
<div v-if="browserError" class="notice warning-notice"><span class="notice-symbol">i</span><span>{{ localizedMessage(browserError) }}</span></div>
<div v-if="!serverConfigLoading && !initialized" class="notice warning-notice"><span class="notice-symbol">i</span><span>{{ t('notConfigured') }} <a href="/admin">{{ t('configureNow') }}</a></span></div>
<div v-if="!localPersistenceAvailable" class="notice warning-notice"><span class="notice-symbol">i</span><span>{{ t('localPersistenceUnavailable') }}</span></div>
@@ -451,6 +451,7 @@ const translations: Record<string, Record<string, string>> = {
secureGateway: "安全语音网关",
adminConsole: "管理控制台",
currentVersion: "当前版本",
errorCode: "错误代码",
viewChangelog: "查看更新日志",
notConfigured: "WebSpeak 尚未配置 TeamSpeak 目标。",
configureNow: "打开管理控制台",
@@ -717,6 +718,7 @@ const translations: Record<string, Record<string, string>> = {
secureGateway: "Secure voice gateway",
adminConsole: "Admin console",
currentVersion: "Current version",
errorCode: "Error code",
viewChangelog: "View changelog",
notConfigured: "The WebSpeak TeamSpeak target has not been configured.",
configureNow: "Open admin console",
@@ -986,6 +988,7 @@ translations.de = {
secureGateway: "Sicheres Sprach-Gateway",
adminConsole: "Administrationskonsole",
currentVersion: "Aktuelle Version",
errorCode: "Fehlercode",
viewChangelog: "Änderungsprotokoll ansehen",
notConfigured: "Das TeamSpeak-Ziel von WebSpeak wurde noch nicht konfiguriert.",
configureNow: "Administrationskonsole öffnen",
@@ -1267,6 +1270,14 @@ function t(key: string, variables: Record<string, string | number> = {}) {
function localizedMessage(message: string) {
if (language.value === "zh") return message;
const errorCodeMatch = message.match(/错误代码:([A-Z0-9_-]{1,64}))(?::([^,。]+))?/);
if (errorCodeMatch) {
const code = errorCodeMatch[1];
const detail = errorCodeMatch[2] ? `: ${errorCodeMatch[2]}` : "";
const operation = message.startsWith("操作失败");
if (language.value === "de") return `${operation ? "Vorgang" : "TeamSpeak-Verbindung"} fehlgeschlagen (Fehlercode: ${code})${detail}. Prüfe Eingaben, Netzwerk und Serverstatus`;
return `${operation ? "Operation" : "TeamSpeak connection"} failed (error code: ${code})${detail}. Check your input, network, and server status`;
}
const exact: Record<string, string> = {
"语音功能需要 HTTPS 安全连接": "Voice requires a secure HTTPS connection",
"当前浏览器不支持麦克风访问": "This browser does not support microphone access",
@@ -1275,6 +1286,11 @@ function localizedMessage(message: string) {
"当前浏览器不支持扬声器设备选择,将使用默认输出设备": "Output device selection is not supported by this browser. Using the default output device",
"所选扬声器当前不可用": "The selected speaker is not available",
"连接服务器失败,请检查邀请链接或服务器状态": "Could not connect. Check the invite link or server status",
"请求来源不受信任,请从正确的网站入口重新打开": "The request origin is not trusted. Reopen the official WebSpeak page",
"WebSpeak 尚未完成配置,请联系管理员": "WebSpeak has not been configured yet. Contact the administrator",
"请求过于频繁,请稍后重试": "Too many requests. Try again shortly",
"当前中继加速不可用,请关闭加速或联系管理员": "The selected relay is unavailable. Turn off relay mode or contact the administrator",
"邀请链接已失效或已被撤销": "The invite link is invalid, expired, or revoked",
"TeamSpeak 连接已断开": "The TeamSpeak connection was closed",
"连接已断开": "The connection was closed",
"此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "This TeamSpeak identity is already used by another browser page. Close that connection or clear ‘Remember identity’ and try again",
@@ -1292,6 +1308,7 @@ function localizedMessage(message: string) {
"TeamSpeak 服务器拒绝了连接": "The TeamSpeak server rejected the connection",
"TeamSpeak 连接失败,请检查地址、网络或服务器状态": "TeamSpeak connection failed. Check the address, network, or server status",
"服务器当前已满,请稍后重试": "The server is full. Try again shortly",
"服务器当前已满或拒绝了连接,请稍后重试": "The server is full or rejected the connection. Try again shortly",
"WebSpeak 尚未配置 TeamSpeak 目标。": "The WebSpeak TeamSpeak target has not been configured",
"此 TeamSpeak 服务器地址不允许连接": "This TeamSpeak server address is not allowed",
"请输入有效的昵称": "Enter a valid nickname",
@@ -1327,6 +1344,11 @@ function localizedMessage(message: string) {
"当前浏览器不支持麦克风访问": "Dieser Browser unterstützt keinen Mikrofonzugriff",
"当前浏览器不支持 Web Audio 音频处理": "Dieser Browser unterstützt keine Web-Audio-Verarbeitung",
"连接服务器失败,请检查邀请链接或服务器状态": "Verbindung fehlgeschlagen. Prüfe den Einladungslink oder den Serverstatus",
"请求来源不受信任,请从正确的网站入口重新打开": "Die Anfragequelle ist nicht vertrauenswürdig. Öffne die offizielle WebSpeak-Seite erneut",
"WebSpeak 尚未完成配置,请联系管理员": "WebSpeak wurde noch nicht konfiguriert. Wende dich an den Administrator",
"请求过于频繁,请稍后重试": "Zu viele Anfragen. Versuche es gleich erneut",
"当前中继加速不可用,请关闭加速或联系管理员": "Das ausgewählte Relay ist nicht verfügbar. Deaktiviere den Relay-Modus oder wende dich an den Administrator",
"邀请链接已失效或已被撤销": "Der Einladungslink ist ungültig, abgelaufen oder widerrufen",
"TeamSpeak 连接已断开": "Die TeamSpeak-Verbindung wurde getrennt",
"连接已断开": "Die Verbindung wurde getrennt",
"TeamSpeak 服务器地址无效": "Die TeamSpeak-Serveradresse ist ungültig",
@@ -1341,12 +1363,22 @@ function localizedMessage(message: string) {
"TeamSpeak 协议协商失败": "Die Aushandlung des TeamSpeak-Protokolls ist fehlgeschlagen",
"TeamSpeak 服务器拒绝了连接": "Der TeamSpeak-Server hat die Verbindung abgelehnt",
"TeamSpeak 连接失败,请检查地址、网络或服务器状态": "Die TeamSpeak-Verbindung ist fehlgeschlagen. Prüfe Adresse, Netzwerk und Serverstatus",
"服务器当前已满或拒绝了连接,请稍后重试": "Der Server ist voll oder hat die Verbindung abgelehnt. Versuche es später erneut",
};
if (german[message]) return german[message];
}
return message;
}
function visibleErrorCode(code: string): string {
const normalized = String(code || "CONNECTION_FAILED")
.trim()
.toUpperCase()
.replace(/[^A-Z0-9_-]+/g, "_")
.replace(/^_+|_+$/g, "");
return (normalized || "CONNECTION_FAILED").slice(0, 64);
}
function persistLanguage() {
localStorage.setItem("webspeak:language", language.value);
void saveLocalPreferences({ schemaVersion: 1, language: language.value });
@@ -2078,7 +2110,9 @@ function stopWhisperTalk(): void {
.card-kicker, .section-kicker { color: #79918c; font-size: 10px; font-weight: 700; letter-spacing: .16em; }
.join-card h2 { margin: 10px 0 7px; color: #1b2825; font-size: 27px; letter-spacing: -.045em; }
.card-lead { margin: 0 0 18px; color: #7b8885; font-size: 13px; }
.notice { display: flex; align-items: flex-start; gap: 10px; margin: 0 0 10px; padding: 9px 10px; border-radius: 10px; font-size: 12px; line-height: 1.45; }
.notice { display: flex; align-items: flex-start; gap: 10px; min-width: 0; margin: 0 0 10px; padding: 9px 10px; border-radius: 10px; font-size: 12px; line-height: 1.45; }
.notice-content { min-width: 0; overflow-wrap: anywhere; }
.notice-content code { display: block; max-width: 100%; margin-top: 3px; overflow: hidden; color: currentColor; font-family: ui-monospace,SFMono-Regular,Consolas,monospace; font-size: 10px; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; opacity: .78; }
.error-notice { color: #a53c38; background: #fff0ef; border: 1px solid #f7d4d1; }
.warning-notice { color: #8a6537; background: #fff8e9; border: 1px solid #f2dfb3; }
.notice-symbol { display: grid; place-items: center; width: 16px; height: 16px; flex: 0 0 auto; border-radius: 50%; color: #fff; background: currentColor; color: #fff; font-size: 10px; font-weight: 800; }