From 275e27c4ac47bb3f8aa4881fc60c2cd9a8c10ae4 Mon Sep 17 00:00:00 2001
From: illusia <64828020+EchoSixHIYA@users.noreply.github.com>
Date: Mon, 26 Oct 2026 10:28:45 +0800
Subject: [PATCH] fix(security): address PR 48 findings with bounded concurrent
authentication
Classify IPv6 subnets numerically, reserve login capacity before hashing, bind authentication to credential revisions, revoke other sessions on password rotation, reuse trusted proxy client keys and bound PCM encoding by monotonic time. Credit ph1gros for the findings and proposed regression cases.
---
README.md | 1 +
docs/README.de.md | 3 +
docs/README.en.md | 3 +
docs/README.ja.md | 3 +
docs/README.ru.md | 3 +
docs/README.zh-CN.md | 3 +
package.json | 2 +-
scripts/acceleration-poc/relay-server.mjs | 23 ++-
.../target-guard-parity.test.mjs | 22 ++
src/admin/admin-router.ts | 28 ++-
src/admin/admin-service.ts | 8 +-
src/admin/admin-session.ts | 7 +
src/admin/login-rate-limit.ts | 61 +++---
src/admin/security-boundaries.test.ts | 189 ++++++++++++++++++
src/domain/teamspeak-target.test.ts | 28 +++
src/domain/teamspeak-target.ts | 4 +-
src/errors.ts | 6 +-
src/security/open-target-policy.test.ts | 19 ++
src/security/open-target-policy.ts | 25 ++-
src/server/network-probe.ts | 2 +-
src/server/server.ts | 7 +-
src/server/session-audio.test.ts | 36 +++-
src/server/session-audio.ts | 21 +-
src/server/teamspeak-probe.ts | 2 +-
src/server/ts-client.ts | 4 +-
src/server/voice-bridge.test.ts | 8 +
src/server/voice-bridge.ts | 5 +-
src/server/voice-commands.ts | 2 +-
.../composables/useWebClientServerHistory.ts | 2 +-
web/src/services/quick-servers.ts | 4 +-
web/src/views/WebClient.vue | 2 +-
31 files changed, 449 insertions(+), 84 deletions(-)
create mode 100644 src/admin/security-boundaries.test.ts
create mode 100644 src/domain/teamspeak-target.test.ts
diff --git a/README.md b/README.md
index d846c58..26ebd7b 100644
--- a/README.md
+++ b/README.md
@@ -120,6 +120,7 @@ Skins own appearance, layout and attached widgets. Functional plugins provide co
查看贡献说明 · View contribution credits
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
+- [ph1gros](https://github.com/ph1gros) — 在 [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 中报告并提供公开目标 IPv6 校验、管理员认证与会话、代理限流和 PCM 上行边界的安全审查、补丁及回归测试;相关问题由项目在 `dev` 分支重新实现并修复。Security findings, proposed fixes and regression tests; reimplemented on `dev`.
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
diff --git a/docs/README.de.md b/docs/README.de.md
index 2207fa2..e059074 100644
--- a/docs/README.de.md
+++ b/docs/README.de.md
@@ -15,6 +15,8 @@ WebSpeak ist ein selbst gehosteter Browserclient und ein Sprach-Gateway für Tea
Stabile Version: [Hinweise zu v0.2.9](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Der Store für funktionale Plugins ist derzeit auf `dev` verfügbar und nicht in v0.2.9 enthalten.
+Sicherheitskorrekturen im Entwicklungszweig: `dev` enthält neu implementierte IPv6-Zielprüfungen, Limits für gleichzeitige Anmeldungen, Sitzungswiderruf nach Passwortwechsel, Proxy-Ratenlimits und PCM-Uplink-Schutz aus PR #48. Die historischen Hinweise zu v0.2.9 beziehen sich auf die ursprüngliche Veröffentlichung, ohne diese noch unveröffentlichten Korrekturen.
+
[Live-Demo](#demo) · [Funktionen](#features) · [Screenshots](#screenshots) · [Bereitstellung](#deployment) · [Verwaltung](#administration) · [Erweiterte Einstellungen](#advanced) · [Skins & Plugins](#extensions) · [Problemlösung](#troubleshooting) · [Änderungsprotokoll](#changelog)
@@ -465,6 +467,7 @@ Integriertes WebRTC, aktualisiertes TeamSpeak-SDK und bessere Mitgliedersynchron
Diese Liste würdigt den Autor des zugrunde liegenden SDKs, Beiträge aus zusammengeführten GitHub-PRs sowie ursprüngliche Arbeiten, die in eigenständig verteilte Skin-Pakete übernommen wurden.
- [HoneyBBQ](https://github.com/HoneyBBQ) — Autor des [teamspeak-js-SDKs (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js), das den von WebSpeak verwendeten TeamSpeak-Protokollclient bereitstellt.
+- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) meldete Sicherheitsprobleme und lieferte Korrekturvorschläge sowie Regressionstests für IPv6-Zielprüfung, Admin-Anmeldung und Sitzungen, Proxy-Ratenlimits und PCM-Uplink. Der ursprüngliche Patch wurde nicht direkt übernommen; die Korrekturen wurden auf `dev` neu implementiert.
- [LainHE](https://github.com/LainHE) — [zusammengeführte PRs #2, #8, #28, #31–#35, #37, #38 und #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): Browser-Fehlerübersetzungen, Skalierung und Startseitenlayout, Bildschirmfreigabe-Bitrate und Zuschaueravatare, Relay-Zielprüfung und Wiederverbindung, vertrauenswürdige Proxys, Weitergabe von Verbindungsfehlern, Audio-Fehlermeldungen und Ressourcenfreigabe bei WebRTC-Fehlern.
- [TimmySheep](https://github.com/TimmySheep) — [zusammengeführte PRs #13 und #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep) zu vorhandenen TS6-Freigaben, Seitenverhältnis, mobiler Sprache/Bildschirm-Wachhalten/Skin-Menü, Kanaloptionen der Identität, PWA/Design, Chatverlauf, Mitglieder-Audiozuständen und Mikrofonberechtigungen.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) ermöglichte Verbindungen über registrierte TeamSpeak-Nicknames und bewahrte Nickname-Ziele; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) verbesserte das Beibehalten des KAAK-Arbeitsbereichs und die Wiederverbindung nach der ersten Verbindung. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) und [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) lieferten das ursprüngliche Design und die Implementierung des Discord-Skins (Commit-Autor **yumi**), die das WebSpeak-Projekt in einen [eigenständig verteilten `.wskin`-Skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) überführte.
diff --git a/docs/README.en.md b/docs/README.en.md
index 38dd4fe..6e393c1 100644
--- a/docs/README.en.md
+++ b/docs/README.en.md
@@ -15,6 +15,8 @@ WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and T
Stable release: [v0.2.9 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). The functional plugin store is currently available on `dev` and is not part of v0.2.9.
+Development security fixes: `dev` now reimplements the IPv6 target checks, concurrent login limits, password-rotation session revocation, trusted-proxy rate limits and PCM uplink safeguards reported in PR #48. The historical v0.2.9 notes below describe the original release and do not include these unreleased fixes.
+
[Live demo](#demo) · [Features](#features) · [Screenshots](#screenshots) · [Deployment](#deployment) · [Administration](#administration) · [Advanced settings](#advanced) · [Skins & plugins](#extensions) · [Troubleshooting](#troubleshooting) · [Changelog](#changelog)
@@ -465,6 +467,7 @@ Added bundled WebRTC, migrated the TeamSpeak SDK, and improved member synchroniz
This list acknowledges the upstream SDK author, contributions through merged GitHub PRs, and original work adapted into independently distributed skin packages.
- [HoneyBBQ](https://github.com/HoneyBBQ) — Author of the upstream [teamspeak-js (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK, which provides the TeamSpeak protocol client used by WebSpeak.
+- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) reported security issues and supplied proposed fixes and regression tests for open-target IPv6 validation, admin authentication/sessions, proxy-aware limits and PCM uplink boundaries. The original patch was not merged directly; the fixes were reimplemented on `dev`.
- [LainHE](https://github.com/LainHE) — [merged PRs #2, #8, #28, #31–#35, #37, #38 and #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE), covering browser error translations, scaling and home layout, screen-share bitrate and viewer avatars, relay target validation and recovery, trusted proxy handling, connection-failure propagation, audio fault reporting, and WebRTC failure cleanup.
- [TimmySheep](https://github.com/TimmySheep) — [merged PRs #13 and #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep), covering existing TS6 share discovery, share aspect ratio, mobile voice/wake/skin-menu behavior, identity channel options, PWA/theme work, chat history, member audio states, and microphone permission.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) added registered TeamSpeak nickname connections and preserved nickname targets; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) improved KAAK workspace retention and reconnection after the first connection. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) and [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) supplied the original Discord skin design and implementation (commit author **yumi**), later adapted by the WebSpeak project into an [independently distributed `.wskin` skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
diff --git a/docs/README.ja.md b/docs/README.ja.md
index 16fb1a3..50642d5 100644
--- a/docs/README.ja.md
+++ b/docs/README.ja.md
@@ -15,6 +15,8 @@ WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザー
安定版:[v0.2.9 の更新履歴](#latest-release-notes) · [パッケージを取得](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。機能プラグインストアは現在 `dev` ブランチで提供しており、v0.2.9 には含まれません。
+開発ブランチのセキュリティ修正:`dev` では PR #48 の IPv6 検証、同時ログイン制限、パスワード変更後のセッション失効、信頼済みプロキシごとの制限、PCM 送信保護を再実装しました。以下の v0.2.9 履歴は元のリリースの内容であり、今回の未リリース修正は含みません。
+
[オンラインデモ](#demo) · [機能](#features) · [画面プレビュー](#screenshots) · [デプロイ](#deployment) · [管理](#administration) · [詳細設定](#advanced) · [スキンとプラグイン](#extensions) · [トラブル対処](#troubleshooting) · [更新履歴](#changelog)
@@ -400,6 +402,7 @@ WebRTC とチャンネルチャットを修正し、管理画面、ログ、モ
上流 SDK の作者、マージ済みの GitHub PR、および独立配布のスキンパッケージへ移植された原作の貢献を記載しています。
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上流 SDK [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) の作者。WebSpeak の TeamSpeak プロトコル通信を支えるクライアントライブラリを提供。
+- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) で IPv6 接続先検証、管理者認証とセッション、プロキシ配下の制限、PCM 送信境界の問題を報告し、修正案と回帰テストを提供。元のパッチは直接マージせず、`dev` で改めて修正を実装しました。
- [LainHE](https://github.com/LainHE) — [マージ済み PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE)。ブラウザのエラー翻訳、拡大縮小とホームのレイアウト、画面共有のビットレートと視聴者アバター、中継先の検証と再接続、信頼済みプロキシの扱い、接続失敗の通知、音声エラー報告、WebRTC 失敗時のリソース解放を改善。
- [TimmySheep](https://github.com/TimmySheep) — [マージ済み PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep)。既存 TS6 共有の検出、画面比率、モバイル音声・画面点灯・スキンメニュー、ID のチャンネル設定、PWA/テーマ、チャット履歴、メンバー音声状態、マイク権限などに貢献。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) で TeamSpeak の登録済みニックネーム接続と接続先の保持に対応し、[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) で初回接続後の KAAK ワークスペース保持と再接続を改善。[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) と [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) では Discord スキンの原作デザインと実装を提供(コミット名義 **yumi**)。その後、WebSpeak プロジェクトが[独立配布の `.wskin` スキン](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)へ移植。
diff --git a/docs/README.ru.md b/docs/README.ru.md
index 88b692e..264cea7 100644
--- a/docs/README.ru.md
+++ b/docs/README.ru.md
@@ -15,6 +15,8 @@ WebSpeak — самостоятельно размещаемый браузер
Стабильный выпуск: [изменения v0.2.9](#latest-release-notes) · [скачать пакеты](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Магазин функциональных плагинов пока доступен в `dev` и не входит в v0.2.9.
+Исправления безопасности в ветке разработки: в `dev` заново реализованы проверки IPv6, ограничения параллельных входов, отзыв сессий после смены пароля, лимиты за доверенным прокси и защита PCM из PR #48. Исторические заметки v0.2.9 ниже относятся к исходному выпуску без этих ещё не опубликованных исправлений.
+
[Онлайн-демо](#demo) · [Возможности](#features) · [Скриншоты](#screenshots) · [Развёртывание](#deployment) · [Управление](#administration) · [Расширенные настройки](#advanced) · [Скины и плагины](#extensions) · [Решение проблем](#troubleshooting) · [История изменений](#changelog)
@@ -400,6 +402,7 @@ relay.example.com {
Список отмечает автора SDK, используемого в основе проекта, вклад через объединённые PR на GitHub и исходные работы, перенесённые в отдельно распространяемые пакеты скинов.
- [HoneyBBQ](https://github.com/HoneyBBQ) — Автор SDK [teamspeak-js (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js), который предоставляет используемый WebSpeak клиент протокола TeamSpeak.
+- [ph1gros](https://github.com/ph1gros) — В [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) сообщил о проблемах безопасности и предложил исправления с регрессионными тестами для проверки IPv6, входа и сессий администратора, лимитов за прокси и PCM-аудио. Исходный патч не объединён напрямую; исправления реализованы заново в `dev`.
- [LainHE](https://github.com/LainHE) — [объединённые PR #2, #8, #28, #31–#35, #37, #38 и #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): переводы ошибок браузера, масштабирование и компоновка главной страницы, битрейт трансляции и аватары зрителей, проверка целей и восстановление ретранслятора, доверенные прокси, передача ошибок подключения, сообщения об ошибках аудио и освобождение ресурсов при сбоях WebRTC.
- [TimmySheep](https://github.com/TimmySheep) — [объединённые PR #13 и #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep): обнаружение активных трансляций TS6, пропорции экрана, мобильное аудио/подсветка экрана/меню скинов, канал в настройках идентичности, PWA/темы, история чата, состояние аудио участников и разрешение микрофона.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) добавил подключение по зарегистрированным именам TeamSpeak с сохранением имени цели; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) улучшил сохранение рабочего пространства KAAK и повторное подключение после первого соединения. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) и [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) содержали исходный дизайн и реализацию скина Discord (автор коммитов **yumi**), которые проект WebSpeak перенёс в [отдельно распространяемый скин `.wskin`](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md
index 5afab9f..b5ebc88 100644
--- a/docs/README.zh-CN.md
+++ b/docs/README.zh-CN.md
@@ -15,6 +15,8 @@ WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语
稳定版:[v0.2.9 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。功能插件商店目前仅在 `dev` 分支提供,尚未包含在 v0.2.9 中。
+开发分支安全修复:`dev` 已重新实现 PR #48 报告的 IPv6 目标校验、并发登录、改密会话撤销、可信代理限流与 PCM 上行保护。以下 v0.2.9 历史记录描述的是原发布包,不包含这次尚未发布的修复。
+
[在线演示](#demo) · [功能](#features) · [界面预览](#screenshots) · [部署](#deployment) · [管理](#administration) · [高级配置](#advanced) · [皮肤与插件](#extensions) · [常见问题](#troubleshooting) · [更新日志](#changelog)
@@ -469,6 +471,7 @@ relay.example.com {
以下列出上游 SDK 作者、已合并的 GitHub PR,以及已移植为独立皮肤包的原始贡献。
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
+- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 提供公开目标 IPv6 校验、管理员认证与会话、代理限流及 PCM 上行边界的安全审查、补丁和回归测试;原补丁未直接合并,相关修复已在 `dev` 中重新实现。
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
diff --git a/package.json b/package.json
index 6bb2939..70eab6e 100644
--- a/package.json
+++ b/package.json
@@ -11,7 +11,7 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
- "test": "node --import tsx --test web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-transport.test.ts",
+ "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-transport.test.ts",
"verify": "npm test && npm run build && npm run web:build",
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
diff --git a/scripts/acceleration-poc/relay-server.mjs b/scripts/acceleration-poc/relay-server.mjs
index 12d62f3..0271173 100644
--- a/scripts/acceleration-poc/relay-server.mjs
+++ b/scripts/acceleration-poc/relay-server.mjs
@@ -1,6 +1,6 @@
import { createSocket } from "node:dgram";
import { lookup } from "node:dns/promises";
-import { isIP } from "node:net";
+import { BlockList, isIP, SocketAddress } from "node:net";
import { decodeFrame, encodeFrame, FrameType, jsonPayload, parseJsonPayload, verifyFrame } from "./protocol.mjs";
function endpointKey(address, port) {
@@ -19,27 +19,28 @@ function endpointKey(address, port) {
* Keep this an exact mirror: fail closed on anything that is not a literal
* public address.
*/
+const restrictedIpv6 = new BlockList();
+for (const [network, prefix] of [
+ ["::", 16], ["64:ff9b::", 96], ["64:ff9b:1::", 48],
+ ["100::", 64], ["100:0:0:1::", 64], ["2001::", 32], ["2002::", 16],
+ ["2001:db8::", 32], ["3fff::", 20], ["fc00::", 7], ["fe80::", 10],
+ ["fec0::", 10], ["ff00::", 8],
+]) restrictedIpv6.addSubnet(network, prefix, "ipv6");
+
export function isRestrictedAddress(host) {
+ if (host.includes("%")) return true;
const version = isIP(host);
if (version === 4) return isRestrictedIpv4(host);
if (version !== 6) return true;
- const normalized = host.toLowerCase();
- if (normalized === "::" || normalized === "::1") return true;
+ const normalized = new SocketAddress({ address: host, family: "ipv6" }).address;
if (normalized.startsWith("::ffff:")) {
// IPv4-mapped addresses must be unwrapped before the IPv4 rules apply:
// ::ffff:10.0.0.1 is private traffic in IPv6 clothing.
const mapped = normalized.slice("::ffff:".length);
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
}
- if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms
- const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
- if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
- if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
- if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10
- if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8
- if (normalized.startsWith("2001:db8:")) return true; // documentation range
- return false;
+ return restrictedIpv6.check(normalized, "ipv6");
}
function isRestrictedIpv4(host) {
diff --git a/scripts/acceleration-poc/target-guard-parity.test.mjs b/scripts/acceleration-poc/target-guard-parity.test.mjs
index 91ecfdc..72d47c7 100644
--- a/scripts/acceleration-poc/target-guard-parity.test.mjs
+++ b/scripts/acceleration-poc/target-guard-parity.test.mjs
@@ -60,6 +60,28 @@ const CASES = [
["::ffff:127.0.0.1", true],
["::ffff:10.0.0.1", true],
["::ffff:8.8.8.8", false],
+ ["0:0:0:0:0:ffff:808:808", false],
+ ["2001:4860:0:0:0:0:0:8888", false],
+ ["0:0:0:0:0:0:0:1", true],
+ ["0::1", true],
+ ["0:1234::1", true],
+ ["0:0:0:0:0:0:0:0", true],
+ ["::ffff:7f00:1", true],
+ ["0::ffff:a00:1", true],
+ ["::127.0.0.1", true],
+ ["fe80::1%eth0", true],
+ ["64:ff9b::808:808", true],
+ ["64:ff9b:1:1234::1", true],
+ ["64:ff9b:2::1", false],
+ ["100::1", true],
+ ["100:0:0:1::1", true],
+ ["100:0:1::1", false],
+ ["2001:0::1", true],
+ ["2002:808:808::1", true],
+ ["2001:0db8::1", true],
+ ["2001:db9::1", false],
+ ["3fff:fff::1", true],
+ ["3fff:1000::1", false],
// Anything that is not a literal address fails closed.
["localhost", true],
["public.example.invalid", true],
diff --git a/src/admin/admin-router.ts b/src/admin/admin-router.ts
index 74faf65..bebbb6a 100644
--- a/src/admin/admin-router.ts
+++ b/src/admin/admin-router.ts
@@ -44,6 +44,7 @@ export interface AdminRouterOptions {
pluginRegistry?: PluginRegistry;
pluginStore?: PluginStore;
startedAt: number;
+ clientIp?: (request: Request) => string;
}
export function createAdminRouter(options: AdminRouterOptions): Router {
@@ -90,25 +91,29 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
response.status(409).json({ ok: false, code: "NOT_INITIALIZED" });
return;
}
- const peer = request.socket.remoteAddress ?? "unknown";
- const retryAfterMs = limiter.retryAfterMs(peer);
- if (retryAfterMs > 0) {
- response.setHeader("Retry-After", String(Math.ceil(retryAfterMs / 1000)));
- response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs });
- return;
- }
+ const peer = options.clientIp?.(request) ?? request.socket.remoteAddress ?? "unknown";
const body = asRecord(request.body);
const username = readString(body, "username", 64).trim();
const password = readOptionalString(body, "password", 1024);
- if (!await options.service.verifyPassword(username, password)) {
- const delayMs = limiter.recordFailure(peer);
+ const reservation = limiter.reserve(peer);
+ if (!reservation.allowed) {
+ response.setHeader("Retry-After", String(Math.ceil(reservation.retryAfterMs / 1000)));
+ response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs: reservation.retryAfterMs });
+ return;
+ }
+ const revision = options.service.credentialRevision;
+ let verified: boolean;
+ try { verified = await options.service.verifyPassword(username, password); }
+ catch (error) { reservation.finish("cancelled"); sendAdminError(response, error); return; }
+ if (!verified || revision !== options.service.credentialRevision) {
+ const delayMs = reservation.finish("failure");
await waitFor(delayMs);
options.service.database.addAudit("ADMIN_LOGIN_FAILED");
logger.warn("Administrator login failed");
response.status(401).json({ ok: false, code: "INVALID_PASSWORD" });
return;
}
- limiter.recordSuccess(peer);
+ reservation.finish("success");
options.service.database.addAudit("ADMIN_LOGIN_SUCCEEDED");
const session = options.sessions.create(response, isSecureRequest(request));
response.json({ ok: true, csrfToken: session.csrfToken, expiresAt: session.expiresAt, mustChangePassword: options.service.isPasswordChangeRequired() });
@@ -118,6 +123,7 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
try {
const body = asRecord(request.body);
await options.service.changePassword(readString(body, "newPassword", 1024));
+ options.sessions.revokeOthers(request);
response.json({ ok: true, mustChangePassword: false });
} catch (error: unknown) {
sendAdminError(response, error);
@@ -801,7 +807,7 @@ function logLevelName(level: unknown): string {
function sendAdminError(response: Response, error: unknown): void {
if (error instanceof AdminInputError) {
- response.status(400).json({ ok: false, code: error.code });
+ response.status(error.code === "AUTH_REQUIRED" ? 401 : 400).json({ ok: false, code: error.code });
return;
}
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
diff --git a/src/admin/admin-service.ts b/src/admin/admin-service.ts
index 59c462b..deaaa89 100644
--- a/src/admin/admin-service.ts
+++ b/src/admin/admin-service.ts
@@ -45,6 +45,8 @@ type ProbeFunction = typeof probeTeamSpeak;
export class AdminService {
private readonly tsAdmin: TsAdminService;
+ private revision = 0;
+ get credentialRevision(): number { return this.revision; }
constructor(
readonly database: WebSpeakDatabase,
private readonly masterSecret: Buffer,
@@ -74,8 +76,9 @@ export class AdminService {
}
async verifyPassword(username: string, password: string): Promise {
+ const revision = this.revision;
const credential = this.database.getAdminCredential();
- return credential?.username === username && await verifyAdminPassword(password, credential);
+ return credential?.username === username && await verifyAdminPassword(password, credential) && revision === this.revision;
}
isPasswordChangeRequired(): boolean {
@@ -83,12 +86,15 @@ export class AdminService {
}
async changePassword(password: string): Promise {
+ const revision = this.revision;
const credential = this.database.getAdminCredential();
if (!credential) throw new AdminInputError("NOT_INITIALIZED", "The administrator account is not initialized");
const passwordError = validateAdminPassword(password);
if (passwordError) throw new AdminInputError("INVALID_ADMIN_PASSWORD", passwordError);
const replacement = await hashAdminPassword(password, { username: credential.username, mustChangePassword: false });
+ if (revision !== this.revision) throw new AdminInputError("AUTH_REQUIRED", "Administrator credentials changed during the request");
this.database.updateAdminCredential(replacement);
+ this.revision++;
this.database.addAudit("ADMIN_PASSWORD_CHANGED");
}
diff --git a/src/admin/admin-session.ts b/src/admin/admin-session.ts
index f179aa6..84e50e9 100644
--- a/src/admin/admin-session.ts
+++ b/src/admin/admin-session.ts
@@ -50,6 +50,13 @@ export class AdminSessionStore {
clear(): void {
this.sessions.clear();
}
+
+ /** A credential change retains only the authenticated session that performed it. */
+ revokeOthers(request: Request): void {
+ const token = readCookie(request.headers.cookie, COOKIE_NAME);
+ const keep = token ? hashToken(token) : null;
+ for (const key of this.sessions.keys()) if (key !== keep) this.sessions.delete(key);
+ }
}
export function isSecureRequest(request: Request): boolean {
diff --git a/src/admin/login-rate-limit.ts b/src/admin/login-rate-limit.ts
index 1828b47..a538e03 100644
--- a/src/admin/login-rate-limit.ts
+++ b/src/admin/login-rate-limit.ts
@@ -1,51 +1,54 @@
+import { performance } from "node:perf_hooks";
+
const WINDOW_MS = 5 * 60 * 1000;
const MAX_FAILURES = 5;
interface LoginAttempt {
failures: number;
+ pending: number;
firstFailureAt: number;
}
+type Reservation = { allowed: false; retryAfterMs: number }
+ | { allowed: true; finish(result: "success" | "failure" | "cancelled"): number };
+
export class AdminLoginRateLimiter {
private readonly attempts = new Map();
+ private pending = 0;
- constructor(private readonly maxTrackedPeers = 1024) {}
+ constructor(private readonly maxTrackedPeers = 1024, private readonly maxConcurrentChecks = 8) {}
- retryAfterMs(peer: string, now = Date.now()): number {
- const attempt = this.attempts.get(peer);
- if (!attempt) return 0;
- if (now - attempt.firstFailureAt >= WINDOW_MS) {
- this.attempts.delete(peer);
- return 0;
- }
- if (attempt.failures < MAX_FAILURES) return 0;
- return WINDOW_MS - (now - attempt.firstFailureAt);
- }
-
- recordFailure(peer: string, now = Date.now()): number {
+ /** Reserve before hashing; pending checks count against capacity, successes are not failures. */
+ reserve(peer: string, now = performance.now()): Reservation {
+ this.pruneExpired(now);
const current = this.attempts.get(peer);
- if (!current) {
- this.pruneExpired(now);
- while (this.attempts.size >= this.maxTrackedPeers) {
- const oldestPeer = this.attempts.keys().next().value;
- if (!oldestPeer) break;
- this.attempts.delete(oldestPeer);
- }
+ if (current && current.failures + current.pending >= MAX_FAILURES) {
+ return { allowed: false, retryAfterMs: Math.max(1000, WINDOW_MS - (now - current.firstFailureAt)) };
}
- const attempt = !current || now - current.firstFailureAt >= WINDOW_MS
- ? { failures: 1, firstFailureAt: now }
- : { ...current, failures: current.failures + 1 };
+ if (this.pending >= this.maxConcurrentChecks || (!current && this.attempts.size >= this.maxTrackedPeers)) {
+ // Never evict another visitor's lockout or pending check to admit a new address.
+ return { allowed: false, retryAfterMs: 1000 };
+ }
+ const attempt = current ?? { failures: 0, pending: 0, firstFailureAt: now };
this.attempts.set(peer, attempt);
- return Math.min(2000, 250 * (2 ** Math.min(3, attempt.failures - 1)));
- }
-
- recordSuccess(peer: string): void {
- this.attempts.delete(peer);
+ attempt.pending++;
+ this.pending++;
+ let finished = false;
+ return { allowed: true, finish: result => {
+ if (finished) return 0;
+ finished = true;
+ this.pending--;
+ attempt.pending--;
+ if (result === "success") attempt.failures = 0;
+ else if (result === "failure") attempt.failures++;
+ if (!attempt.failures && !attempt.pending) this.attempts.delete(peer);
+ return result === "failure" ? Math.min(2000, 250 * 2 ** Math.min(3, attempt.failures - 1)) : 0;
+ } };
}
private pruneExpired(now: number): void {
for (const [peer, attempt] of this.attempts) {
- if (now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
+ if (!attempt.pending && now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
}
}
}
diff --git a/src/admin/security-boundaries.test.ts b/src/admin/security-boundaries.test.ts
new file mode 100644
index 0000000..70f97a3
--- /dev/null
+++ b/src/admin/security-boundaries.test.ts
@@ -0,0 +1,189 @@
+import assert from "node:assert/strict";
+import test, { type TestContext } from "node:test";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { createServer } from "node:net";
+import express from "express";
+import { AdminLoginRateLimiter } from "./login-rate-limit.js";
+import { AdminService } from "./admin-service.js";
+import { AdminSessionStore } from "./admin-session.js";
+import { createAdminRouter } from "./admin-router.js";
+import { WebSpeakDatabase } from "../persistence/database.js";
+import { createWebServer } from "../server/server.js";
+import { JoinTicketStore } from "../server/join-ticket.js";
+import type { Logger } from "../logger.js";
+
+const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
+const deferred = () => { let resolve!: () => void; const promise = new Promise(yes => { resolve = yes; }); return { promise, resolve }; };
+
+test("login reservations bound pending work, count only failures and preserve other lockouts", () => {
+ const limiter = new AdminLoginRateLimiter(2, 8);
+ const reserved = Array.from({ length: 5 }, () => limiter.reserve("a", 0));
+ assert.ok(reserved.every(value => value.allowed));
+ assert.equal(limiter.reserve("a", 0).allowed, false);
+ for (const item of reserved) if (item.allowed) item.finish("failure");
+ const b = limiter.reserve("b", 0); assert.ok(b.allowed); b.finish("failure");
+ assert.equal(limiter.reserve("c", 0).allowed, false, "new IPs cannot evict an existing lockout");
+ assert.equal(limiter.reserve("a", 0).allowed, false);
+ assert.equal(limiter.reserve("a", 300_001).allowed, true);
+ const successes = new AdminLoginRateLimiter(1);
+ for (let i = 0; i < 20; i++) { const item = successes.reserve("a", 0); assert.ok(item.allowed); item.finish("success"); }
+ const cap = new AdminLoginRateLimiter(10, 2);
+ const first = cap.reserve("a", 0), second = cap.reserve("b", 0);
+ assert.ok(first.allowed && second.allowed);
+ assert.equal(cap.reserve("c", 0).allowed, false, "different IPs share the hash concurrency ceiling");
+ first.finish("cancelled"); first.finish("cancelled");
+ const third = cap.reserve("c", 0); assert.ok(third.allowed);
+ assert.equal(cap.reserve("d", 0).allowed, false, "finishing twice cannot release another request's slot");
+ second.finish("success"); third.finish("success");
+});
+
+test("a pending check cannot expire out of the reservation count", () => {
+ const limiter = new AdminLoginRateLimiter(1);
+ const checks = Array.from({ length: 5 }, () => limiter.reserve("a", 0));
+ assert.ok(checks.every(item => item.allowed));
+ assert.equal(limiter.reserve("a", 400_000).allowed, false);
+ for (const item of checks) if (item.allowed) item.finish("cancelled");
+ assert.equal(limiter.reserve("b", 400_000).allowed, true);
+});
+
+test("a successful concurrent login cannot erase another request's reservation", () => {
+ const limiter = new AdminLoginRateLimiter(1);
+ const slow = limiter.reserve("a", 0), success = limiter.reserve("a", 0);
+ assert.ok(slow.allowed && success.allowed);
+ success.finish("success");
+ const additional = Array.from({ length: 4 }, () => limiter.reserve("a", 0));
+ assert.ok(additional.every(item => item.allowed));
+ assert.equal(limiter.reserve("a", 0).allowed, false);
+ slow.finish("failure");
+ assert.equal(limiter.reserve("a", 0).allowed, false);
+});
+
+async function availablePort() {
+ const server = createServer();
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address(); assert.ok(address && typeof address !== "string");
+ await new Promise(resolve => server.close(() => resolve()));
+ return address.port;
+}
+
+for (const trusted of [true, false]) test(`HTTP login and join limits ${trusted ? "separate trusted proxy clients" : "ignore spoofed headers from an untrusted peer"}`, async t => {
+ let checks = 0;
+ const gate = deferred();
+ const service = { credentialRevision: 0, isInitialized: () => true,
+ verifyPassword: async () => { checks++; await gate.promise; return false; },
+ database: { addAudit() {} },
+ getConnectionPolicy: () => ({ accessMode: "fixed", defaultTarget: "8.8.8.8#9987", serverPassword: "" }),
+ isPasswordChangeRequired: () => false,
+ } as unknown as AdminService;
+ const port = await availablePort(), origin = `http://127.0.0.1:${port}`;
+ const gateway = createWebServer({ port, logger, adminService: service, voiceBridgeOptions: {
+ joinTickets: new JoinTicketStore(), trustedProxies: trusted ? ["127.0.0.1", "::1"] : ["192.0.2.1"],
+ } });
+ await gateway.start();
+ t.after(async () => { gate.resolve(); await gateway.stop(); });
+ const post = (route: string, client: string, body: unknown) => fetch(origin + route, {
+ method: "POST", headers: { origin, "content-type": "application/json", "x-forwarded-for": client }, body: JSON.stringify(body),
+ });
+ const a = "203.0.113.9", b = "198.51.100.4";
+ const logins = Array.from({ length: 12 }, () => post("/api/admin/login", a, { username: "admin", password: "bad" }));
+ const results = Promise.all(logins);
+ gate.resolve();
+ const responses = await results;
+ const statuses = responses.map(r => r.status);
+ assert.equal(checks, 5);
+ assert.equal(statuses.filter(s => s === 401).length, 5);
+ assert.equal(statuses.filter(s => s === 429).length, 7);
+ assert.ok(Number(responses.find(r => r.status === 429)!.headers.get("retry-after")) > 0);
+ assert.equal((await post("/api/admin/login", b, { username: "admin", password: "bad" })).status, trusted ? 401 : 429);
+ for (let i = 0; i < 30; i++) assert.equal((await post("/api/join-ticket", a, { nickname: "Test" })).status, 201);
+ assert.equal((await post("/api/join-ticket", a, { nickname: "Test" })).status, 429);
+ assert.equal((await post("/api/join-ticket", b, { nickname: "Test" })).status, trusted ? 201 : 429);
+});
+
+test("password-verifier exceptions release reservations without leaking their details", async t => {
+ const app = express(); app.use(express.json());
+ const service = { credentialRevision: 0, isInitialized: () => true,
+ verifyPassword: async () => { throw new Error("secret verifier failure detail"); },
+ } as unknown as AdminService;
+ app.use("/api/admin", createAdminRouter({ service, sessions: new AdminSessionStore(), logger,
+ getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now() }));
+ const server = app.listen(0, "127.0.0.1");
+ await new Promise(resolve => server.once("listening", resolve));
+ const address = server.address(); assert.ok(address && typeof address !== "string");
+ const origin = `http://127.0.0.1:${address.port}`;
+ t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())); });
+ for (let i = 0; i < 10; i++) {
+ const response = await fetch(origin + "/api/admin/login", { method: "POST", headers: { origin, "content-type": "application/json" },
+ body: JSON.stringify({ username: "admin", password: "irrelevant" }) });
+ assert.equal(response.status, 500);
+ assert.deepEqual(await response.json(), { ok: false, code: "INTERNAL_ERROR" });
+ }
+});
+
+async function adminFixture(t: TestContext) {
+ const directory = await mkdtemp(path.join(tmpdir(), "webspeak-auth-race-"));
+ const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
+ const service = new AdminService(database, Buffer.alloc(32, 3), logger, path.join(directory, "absent.json"));
+ await service.initialize(); // Intentionally keep the default password for the bootstrap race.
+ const app = express(); app.use(express.json());
+ app.use("/api/admin", createAdminRouter({ service, sessions: new AdminSessionStore(), logger,
+ getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now() }));
+ const server = app.listen(0, "127.0.0.1");
+ await new Promise(resolve => server.once("listening", resolve));
+ const address = server.address(); assert.ok(address && typeof address !== "string");
+ const origin = `http://127.0.0.1:${address.port}`;
+ t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())); database.close(); await rm(directory, { recursive: true }); });
+ const post = (route: string, body: unknown, cookie = "", csrf = "") => fetch(origin + "/api/admin" + route, {
+ method: "POST", headers: { origin, cookie, "content-type": "application/json", "x-csrf-token": csrf }, body: JSON.stringify(body),
+ });
+ const login = async (password: string) => {
+ const response = await post("/login", { username: "admin", password });
+ assert.equal(response.status, 200);
+ const body = await response.json() as { csrfToken: string };
+ return { cookie: response.headers.get("set-cookie")!.split(";", 1)[0]!, csrf: body.csrfToken };
+ };
+ const authenticated = async (cookie: string) => (await (await fetch(origin + "/api/admin/session", { headers: { cookie } })).json() as { authenticated: boolean }).authenticated;
+ return { service, database, post, login, authenticated };
+}
+
+test("password rotation revokes other default-password sessions and a login finishing after rotation", { timeout: 15_000 }, async t => {
+ const f = await adminFixture(t);
+ const current = await f.login("admin"), other = await f.login("admin");
+ const verified = deferred(), release = deferred();
+ const verify = f.service.verifyPassword.bind(f.service);
+ t.mock.method(f.service, "verifyPassword", async (username: string, password: string) => {
+ const result = await verify(username, password);
+ if (password === "admin") { verified.resolve(); await release.promise; }
+ return result;
+ });
+ const pending = f.post("/login", { username: "admin", password: "admin" });
+ await verified.promise;
+ try {
+ const changed = await f.post("/change-password", { newPassword: "new-password-for-test" }, current.cookie, current.csrf);
+ assert.equal(changed.status, 200);
+ assert.equal(await f.authenticated(current.cookie), true);
+ assert.equal(await f.authenticated(other.cookie), false);
+ } finally { release.resolve(); }
+ const stale = await pending;
+ assert.equal(stale.status, 401);
+ assert.equal(stale.headers.get("set-cookie"), null, "an old verification cannot mint a new session");
+ await f.login("new-password-for-test");
+});
+
+test("failed password updates keep other sessions and concurrent rotations cannot overwrite a winner", { timeout: 15_000 }, async t => {
+ const f = await adminFixture(t);
+ const current = await f.login("admin"), other = await f.login("admin");
+ assert.equal((await f.post("/change-password", { newPassword: "short" }, current.cookie, current.csrf)).status, 400);
+ assert.equal(await f.authenticated(other.cookie), true);
+ const results = await Promise.all([
+ f.post("/change-password", { newPassword: "first-possible-password" }, current.cookie, current.csrf),
+ f.post("/change-password", { newPassword: "second-possible-password" }, other.cookie, other.csrf),
+ ]);
+ assert.deepEqual(results.map(r => r.status).sort(), [200, 401]);
+ const winner = results[0]!.status === 200 ? current : other;
+ const loser = winner === current ? other : current;
+ assert.equal(await f.authenticated(winner.cookie), true);
+ assert.equal(await f.authenticated(loser.cookie), false);
+});
diff --git a/src/domain/teamspeak-target.test.ts b/src/domain/teamspeak-target.test.ts
new file mode 100644
index 0000000..cee41d1
--- /dev/null
+++ b/src/domain/teamspeak-target.test.ts
@@ -0,0 +1,28 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { spawnSync } from "node:child_process";
+
+test("protocol identifiers and favorite addresses keep ASCII casing under a Turkish locale", () => {
+ const child = spawnSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", `
+ import assert from 'node:assert/strict';
+ import { parseTeamSpeakTarget, teamSpeakTargetKey } from './src/domain/teamspeak-target.ts';
+ import { quickServerTargetsEqual, mergeQuickServers } from './web/src/services/quick-servers.ts';
+ import { normalizeTeamSpeakError } from './src/errors.ts';
+ // Windows ignores LANG for ICU's default locale; isolate the Turkish default in this child.
+ const localeLower = String.prototype.toLocaleLowerCase;
+ String.prototype.toLocaleLowerCase = function(...locales) {
+ return localeLower.call(this, ...(locales.length ? locales : ['tr']));
+ };
+ assert.equal('I'.toLocaleLowerCase(), 'ı', 'the child must actually run under Turkish casing');
+ const target = parseTeamSpeakTarget('VOICE.EXAMPLE.IO#9987');
+ assert.equal(target.host, 'voice.example.io');
+ assert.equal(teamSpeakTargetKey({host:'VOICE.EXAMPLE.IO',port:9987}), 'voice.example.io:9987');
+ assert.equal(quickServerTargetsEqual('VOICE.EXAMPLE.IO:9987', 'voice.example.io#9987'), true);
+ assert.equal(mergeQuickServers([{id:'a',label:'a',address:'VOICE.EXAMPLE.IO:9987'}],
+ [{id:'b',address:'voice.example.io:9987',lastConnectedAt:1}]).length, 1);
+ const upper=normalizeTeamSpeakError(new Error('INVALID IDENTITY'));
+ const lower=normalizeTeamSpeakError(new Error('invalid identity'));
+ assert.equal(upper.code, lower.code);
+ `], { env: { ...process.env, LANG: "tr_TR.UTF-8", LC_ALL: "tr_TR.UTF-8" }, encoding: "utf8" });
+ assert.equal(child.status, 0, child.stderr || child.stdout);
+});
diff --git a/src/domain/teamspeak-target.ts b/src/domain/teamspeak-target.ts
index 32ff9c6..55ab997 100644
--- a/src/domain/teamspeak-target.ts
+++ b/src/domain/teamspeak-target.ts
@@ -72,11 +72,11 @@ export function formatTeamSpeakTarget(target: TeamSpeakTarget): string {
}
export function teamSpeakTargetKey(target: TeamSpeakTarget): string {
- return formatTeamSpeakTarget(target).toLocaleLowerCase();
+ return formatTeamSpeakTarget(target).toLowerCase();
}
function createTarget(hostValue: string, portValue: string | number): TeamSpeakTarget {
- const host = hostValue.trim().toLocaleLowerCase();
+ const host = hostValue.trim().toLowerCase();
if (!host || host.length > 255 || /[\s/\\?#@\[\]]/.test(host)) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
}
diff --git a/src/errors.ts b/src/errors.ts
index 58abdaa..72408c4 100644
--- a/src/errors.ts
+++ b/src/errors.ts
@@ -186,7 +186,7 @@ function createTeamSpeakError(code: WebSpeakErrorCode, cause: unknown, diagnosti
*/
export function teamSpeakServerErrorCode(id: unknown): WebSpeakErrorCode | null {
if (id === undefined || id === null) return null;
- const text = String(id).trim().toLocaleLowerCase();
+ const text = String(id).trim().toLowerCase();
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;
@@ -199,7 +199,7 @@ export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
if (error instanceof WebSpeakError) return error;
const diagnostics = collectDiagnostics(error);
- const text = diagnosticText(error).toLocaleLowerCase();
+ const text = diagnosticText(error).toLowerCase();
// 1) A TeamSpeak server error id names the exact reason, so it outranks every
// keyword heuristic below. The inline scan keeps the `id=515` shape
@@ -258,7 +258,7 @@ export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
// 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();
+ const errorName = (diagnostics.name ?? "").toLowerCase();
if (/eaxtagmismatch|fakesignaturemismatch|cryptoinit|invalididentity|license/.test(errorName)) {
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
}
diff --git a/src/security/open-target-policy.test.ts b/src/security/open-target-policy.test.ts
index f3819d7..7de6c21 100644
--- a/src/security/open-target-policy.test.ts
+++ b/src/security/open-target-policy.test.ts
@@ -12,6 +12,25 @@ const resolved = (...addresses: string[]) => async () => addresses.map((address)
family: address.includes(":") ? 6 : 4,
}));
+test("open targets classify equivalent IPv6 spellings and embedded IPv4 before DNS pinning", async () => {
+ const blocked = ["0:0:0:0:0:0:0:1", "0::1", "0:1234::1", "0:0:0:0:0:0:0:0", "0:0:0:0:0:ffff:a00:1",
+ "::ffff:7f00:1", "0::ffff:192.168.1.1", "0:0:0:0:0:0:7f00:1", "fe80::1%1",
+ "64:ff9b::808:808", "64:ff9b:1:abcd::1", "2002:0808:0808::1", "2001:0:4136:e378::1",
+ "0100:0000:0:0:ffff::1", "100:0:0:1::1", "2001:0db8::1", "3fff::1"];
+ for (const host of blocked) {
+ assert.equal(isRestrictedAddress(host), true, host);
+ await assert.rejects(resolveSafeOpenTarget({ host, port: 9987 }), { name: "UnsafeTeamSpeakTargetError" });
+ await assert.rejects(resolveSafeOpenTarget({ host: "voice.example.com", port: 9987 }, {
+ resolveSrv: async () => [], lookup: resolved("8.8.8.8", host),
+ }), { name: "UnsafeTeamSpeakTargetError" });
+ }
+ for (const host of ["0:0:0:0:0:ffff:808:808", "::ffff:1.1.1.1", "2001:4860:0000:0:0:0:0:8888",
+ "64:ff9b:2::1", "100:0:1::1", "2001:db9::1", "2003::1"]) {
+ assert.equal(isRestrictedAddress(host), false, host);
+ assert.deepEqual(await resolveSafeOpenTarget({ host, port: 9987 }), { host, port: 9987 });
+ }
+});
+
test("Mihomo fake-IP DNS answers remain connectable without allowing literal or mixed fake-IP targets", async () => {
const target = { host: "ts.twilightly.top", port: 9987 };
diff --git a/src/security/open-target-policy.ts b/src/security/open-target-policy.ts
index 8599db6..72fddd2 100644
--- a/src/security/open-target-policy.ts
+++ b/src/security/open-target-policy.ts
@@ -1,4 +1,4 @@
-import { isIP } from "node:net";
+import { BlockList, isIP, SocketAddress } from "node:net";
import { lookup, resolveSrv } from "node:dns/promises";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
@@ -108,25 +108,28 @@ export async function isSafeOpenTargetForPrefill(
}
}
+const restrictedIpv6 = new BlockList();
+// Match address bits, not textual compression or the case/width of hex groups.
+for (const [network, prefix] of [
+ ["::", 16], ["64:ff9b::", 96], ["64:ff9b:1::", 48],
+ ["100::", 64], ["100:0:0:1::", 64], ["2001::", 32], ["2002::", 16],
+ ["2001:db8::", 32], ["3fff::", 20], ["fc00::", 7], ["fe80::", 10],
+ ["fec0::", 10], ["ff00::", 8],
+] as const) restrictedIpv6.addSubnet(network, prefix, "ipv6");
+
export function isRestrictedAddress(address: string): boolean {
+ // Scoped destinations refer to a gateway-local interface and are never public targets.
+ if (address.includes("%")) return true;
const version = isIP(address);
if (version === 4) return isRestrictedIpv4(address);
if (version !== 6) return true;
- const normalized = address.toLocaleLowerCase();
- if (normalized === "::" || normalized === "::1") return true;
+ const normalized = new SocketAddress({ address, family: "ipv6" }).address;
if (normalized.startsWith("::ffff:")) {
const mapped = normalized.slice("::ffff:".length);
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
}
- if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms
- const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
- if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
- if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
- if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10
- if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8
- if (normalized.startsWith("2001:db8:")) return true; // documentation range
- return false;
+ return restrictedIpv6.check(normalized, "ipv6");
}
function isMihomoFakeIpv4(address: string): boolean {
diff --git a/src/server/network-probe.ts b/src/server/network-probe.ts
index 5cae769..380b1c2 100644
--- a/src/server/network-probe.ts
+++ b/src/server/network-probe.ts
@@ -110,7 +110,7 @@ export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempt
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
const text = error instanceof Error ? error.message : String(error);
- const lower = text.toLocaleLowerCase();
+ const lower = text.toLowerCase();
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";
diff --git a/src/server/server.ts b/src/server/server.ts
index c005470..cc9258d 100644
--- a/src/server/server.ts
+++ b/src/server/server.ts
@@ -3,7 +3,7 @@ import { createServer as createHttpsServer } from "node:https";
import { createServer as createHttpServer } from "node:http";
import { readFileSync } from "node:fs";
import path from "node:path";
-import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
+import { VoiceBridge, createTrustedProxies, resolveClientIp, type VoiceBridgeOptions } from "./voice-bridge.js";
import type { Logger } from "../logger.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
@@ -63,6 +63,8 @@ export function createWebServer(options: WebServerOptions): WebServer {
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, pluginRegistry: options.pluginRegistry }, logger);
const adminSessions = new AdminSessionStore();
const joinRateLimiter = new JoinRateLimiter();
+ const trustedProxies = createTrustedProxies(options.voiceBridgeOptions.trustedProxies);
+ const clientIp = (request: express.Request) => resolveClientIp(request, trustedProxies);
const startedAt = Date.now();
const healthHandler: express.RequestHandler = (_request, response) => {
@@ -163,7 +165,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
response.status(503).json({ ok: false, code: "NOT_INITIALIZED" });
return;
}
- if (!joinRateLimiter.allow(request.socket.remoteAddress ?? "unknown")) {
+ if (!joinRateLimiter.allow(clientIp(request))) {
response.status(429).json({ ok: false, code: "RATE_LIMITED" });
return;
}
@@ -280,6 +282,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
version: options.version,
logFile: options.logFile,
startedAt,
+ clientIp,
}));
// Serve static frontend
diff --git a/src/server/session-audio.test.ts b/src/server/session-audio.test.ts
index 5a5989e..44139a5 100644
--- a/src/server/session-audio.test.ts
+++ b/src/server/session-audio.test.ts
@@ -35,11 +35,45 @@ function fixture() {
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
sendJson: message => { notices.push(message); },
- }, encoder, () => state.now);
+ }, encoder, () => state.now, () => state.now);
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote };
}
+test("PCM flooding is bounded before encoding while real-time, jitter and recovery remain usable", t => {
+ const realtime = fixture();
+ for (let i = 0; i < 1_000; i++) { realtime.state.now = i * 20; realtime.transport.receivePcm(Buffer.alloc(1_920)); }
+ assert.equal(realtime.encoded.length, 1_000);
+ const flood = fixture();
+ t.mock.method(flood.encoder, "encode", () => { flood.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
+ for (let i = 0; i < 1_000; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
+ assert.ok(flood.encoded.length <= 50);
+ assert.equal(flood.audio.ingressDroppedFrames, 1_000 - flood.encoded.length);
+ assert.equal(flood.warnings.filter(w => w.code === "AUDIO_RATE_EXCEEDED").length, 1);
+ assert.equal(flood.notices.length, 0);
+ flood.state.now = 10_000;
+ const before = flood.forwarded.length;
+ for (let i = 0; i < 50; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
+ assert.equal(flood.forwarded.length - before, 50, "one-second backlog after a stall is allowed");
+ const recovered = flood.forwarded.length;
+ for (let i = 1; i <= 100; i++) { flood.state.now = 10_000 + i * 20; flood.transport.receivePcm(Buffer.alloc(1_920)); }
+ assert.equal(flood.forwarded.length - recovered, 100, "flood drops do not lock out subsequent real-time audio");
+});
+
+test("PCM budget uses a separate monotonic clock and cannot refill twice after a clock rollback", t => {
+ const f = fixture();
+ t.mock.method(f.encoder, "encode", () => { f.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
+ for (let i = 0; i < 50; i++) f.transport.receivePcm(Buffer.alloc(1_920));
+ f.state.now = -1_000;
+ f.transport.receivePcm(Buffer.alloc(1_920));
+ f.state.now = 0;
+ f.transport.receivePcm(Buffer.alloc(1_920));
+ assert.equal(f.encoded.length, 50);
+ f.state.now = 100;
+ for (let i = 0; i < 20; i++) f.transport.receivePcm(Buffer.alloc(1_920));
+ assert.equal(f.encoded.length, 56);
+});
+
test("PCM framing preserves codec, whisper routing and timing counters", () => {
const f = fixture();
f.transport.receivePcm(Buffer.alloc(1_920));
diff --git a/src/server/session-audio.ts b/src/server/session-audio.ts
index ae534c2..38d810e 100644
--- a/src/server/session-audio.ts
+++ b/src/server/session-audio.ts
@@ -1,4 +1,5 @@
import { WebSocket } from "ws";
+import { performance } from "node:perf_hooks";
import type { Logger as LoggerType } from "../logger.js";
import type { ServerMessage } from "../shared/server-messages.js";
import type { AudioFlowStats } from "./audio-stats.js";
@@ -12,6 +13,8 @@ const MAX_BUFFERED_BYTES = 4_096;
// frame: the reply is roughly 100x the offending payload, and the browser only
// ever shows the first one because it writes the same error string.
const AUDIO_ISSUE_REPORT_MS = 5_000;
+const PCM_BURST_FRAMES = 50; // One second of buffered 20 ms capture after a stall.
+const PCM_FRAMES_PER_MS = 60 / 1_000; // 50 fps capture plus 20% scheduling headroom.
export interface VoiceEncoder {
encode(frame: Buffer): Buffer;
@@ -39,8 +42,11 @@ export class SessionAudioTransport {
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
private readonly reportedAt = new Map();
private readonly logger: LoggerType | null;
+ private pcmTokens = PCM_BURST_FRAMES;
+ private pcmRefilledAt: number | null = null;
- constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) {
+ constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now,
+ private readonly rateClock: () => number = performance.now.bind(performance)) {
this.encoder = encoder;
this.logger = options.logger ?? null;
}
@@ -127,6 +133,19 @@ export class SessionAudioTransport {
this.reportInvalidFrame(frame.length);
return;
}
+ const now = this.rateClock();
+ if (this.pcmRefilledAt !== null) {
+ this.pcmTokens = Math.min(PCM_BURST_FRAMES, this.pcmTokens + Math.max(0, now - this.pcmRefilledAt) * PCM_FRAMES_PER_MS);
+ }
+ this.pcmRefilledAt = Math.max(this.pcmRefilledAt ?? now, now);
+ if (this.pcmTokens < 1) {
+ stats.ingressDroppedFrames++;
+ if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
+ this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser PCM above the real-time budget");
+ }
+ return;
+ }
+ this.pcmTokens--;
this.recordIngress();
const startedAt = this.clock();
let encoded: Buffer;
diff --git a/src/server/teamspeak-probe.ts b/src/server/teamspeak-probe.ts
index 20810a6..1c63fd5 100644
--- a/src/server/teamspeak-probe.ts
+++ b/src/server/teamspeak-probe.ts
@@ -99,7 +99,7 @@ export async function probeTeamSpeak(
export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError {
if (error instanceof TeamSpeakProbeError) return error;
const normalized = normalizeTeamSpeakError(error);
- const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLocaleLowerCase();
+ const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLowerCase();
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
}
diff --git a/src/server/ts-client.ts b/src/server/ts-client.ts
index c13d1ca..5e974a6 100644
--- a/src/server/ts-client.ts
+++ b/src/server/ts-client.ts
@@ -595,9 +595,7 @@ export class TSClient extends EventEmitter {
}
getChannelId(): bigint {
- if (!this.client) return 0n;
- const sdkClient = this.client as unknown as { channelID?: () => bigint };
- return sdkClient.channelID?.() ?? 0n;
+ return this.client?.channelID() ?? 0n;
}
isConnected(): boolean {
diff --git a/src/server/voice-bridge.test.ts b/src/server/voice-bridge.test.ts
index 4aff2f6..2df0055 100644
--- a/src/server/voice-bridge.test.ts
+++ b/src/server/voice-bridge.test.ts
@@ -238,6 +238,14 @@ function ipRequest(remoteAddress: string | undefined, headers: Record {
+ const trusted = createTrustedProxies(["127.0.0.1"]);
+ const resolve = (value: string) => resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": value }), trusted);
+ assert.equal(resolve("2001:0DB9:0000:0000:0000:0000:0000:0001"), resolve("2001:db9::1"));
+ assert.equal(resolve("0:0:0:0:0:ffff:cb00:7109"), "203.0.113.9");
+ assert.equal(resolve("::ffff:203.0.113.9"), "203.0.113.9");
+});
+
test("a direct client cannot choose the address recorded for it", () => {
const trusted = createTrustedProxies(["127.0.0.1"]);
assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), "192.0.2.7");
diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts
index 500b39b..071d832 100644
--- a/src/server/voice-bridge.ts
+++ b/src/server/voice-bridge.ts
@@ -11,7 +11,7 @@ import type { ServerEvent as SharedServerEvent } from "../shared/voice-models.js
import { WebSocketServer, WebSocket } from "ws";
import type { IncomingMessage, Server } from "node:http";
import { randomUUID } from "node:crypto";
-import { BlockList, isIP } from "node:net";
+import { BlockList, isIP, SocketAddress } from "node:net";
import { parseIdentity } from "@honeybbq/teamspeak/client";
import { TSClient, type TSClientOptions } from "./ts-client.js";
import type { Logger as LoggerType } from "../logger.js";
@@ -1007,6 +1007,9 @@ function normalizeClientIp(value: string | undefined): string | undefined {
if (!value) return undefined;
let trimmed = value.trim();
if (trimmed.startsWith("[") && trimmed.endsWith("]")) trimmed = trimmed.slice(1, -1);
+ const family = isIP(trimmed);
+ if (!family) return undefined;
+ if (family === 6) trimmed = new SocketAddress({ address: trimmed, family: "ipv6" }).address;
if (trimmed.toLowerCase().startsWith("::ffff:")) {
const mapped = trimmed.slice("::ffff:".length);
if (isIP(mapped) === 4) trimmed = mapped;
diff --git a/src/server/voice-commands.ts b/src/server/voice-commands.ts
index 8cffa31..789d669 100644
--- a/src/server/voice-commands.ts
+++ b/src/server/voice-commands.ts
@@ -172,7 +172,7 @@ export 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();
+ const normalized = text.toLowerCase();
// A TeamSpeak server error id is authoritative when the SDK preserved it, so it
// is consulted before the keyword rules: 781 (channel password), 2568
// (permissions), 515/2817 (server or slot limit) and friends keep their exact
diff --git a/web/src/composables/useWebClientServerHistory.ts b/web/src/composables/useWebClientServerHistory.ts
index 1d2ac2e..3337dd9 100644
--- a/web/src/composables/useWebClientServerHistory.ts
+++ b/web/src/composables/useWebClientServerHistory.ts
@@ -184,5 +184,5 @@ export function useWebClientServerHistory({
}
function serverKey(address: string): string {
- return address.trim().toLocaleLowerCase();
+ return address.trim().toLowerCase();
}
diff --git a/web/src/services/quick-servers.ts b/web/src/services/quick-servers.ts
index 20e194f..bae4055 100644
--- a/web/src/services/quick-servers.ts
+++ b/web/src/services/quick-servers.ts
@@ -90,12 +90,12 @@ export function mergeQuickServers(
}
function serverKey(address: string): string {
- return address.trim().toLocaleLowerCase();
+ return address.trim().toLowerCase();
}
function comparableServerKey(address: string): string {
const target = splitTeamSpeakTarget(address);
- const host = target.address.trim().toLocaleLowerCase();
+ const host = target.address.trim().toLowerCase();
const port = target.port.trim() || "9987";
return host ? `${host}:${port}` : "";
}
diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue
index 01f7d55..8e3f5ac 100644
--- a/web/src/views/WebClient.vue
+++ b/web/src/views/WebClient.vue
@@ -1464,7 +1464,7 @@ const favoriteSwitchLabel = computed(() => quickServers.value.find((server) =>
)?.label ?? currentServerTarget());
function isQuickServerTarget(server: QuickServer): boolean {
- return server.id === currentServerTarget().toLocaleLowerCase()
+ return server.id === currentServerTarget().toLowerCase()
|| quickServerTargetsEqual(server.address, currentServerTarget());
}