Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
412f560677 | ||
|
|
fdccf86458 | ||
|
|
d43a33aa15 | ||
|
|
056b57bcd1 | ||
|
|
688eb3174e | ||
|
|
c38f67bc3b | ||
|
|
67c7a27af6 | ||
|
|
6d1d2a1f92 | ||
|
|
faff7a2237 | ||
|
|
dc63f4b45b | ||
|
|
380fb67090 | ||
|
|
b71632cc29 | ||
|
|
38f7c94a65 | ||
|
|
d91a145657 | ||
|
|
a2e33ff176 | ||
|
|
010b8ef072 | ||
|
|
883703dd0c | ||
|
|
bcf212738b | ||
|
|
fae21ec086 | ||
|
|
22dcf93925 | ||
|
|
4df59b80d0 | ||
|
|
c49b4ec715 | ||
|
|
1c80791109 | ||
|
|
85f87ecd0b | ||
|
|
3d6752a5e4 | ||
|
|
a0921c35b2 | ||
|
|
ace9e84889 | ||
|
|
4ead174c04 | ||
|
|
f628d19ebf | ||
|
|
75de8f1d2b | ||
|
|
1ba8cd5ee1 | ||
|
|
f639825775 | ||
|
|
0b40a69d74 | ||
|
|
6defbff591 | ||
|
|
b5d167e1e7 | ||
|
|
7f97d54206 | ||
|
|
ef3e65ea0b | ||
|
|
d13b3207a9 | ||
|
|
7e08ee54a5 | ||
|
|
6d8e289b81 | ||
|
|
defbb766e4 | ||
|
|
69043748a1 | ||
|
|
8046985574 | ||
|
|
5ce73d2c84 | ||
|
|
2d1d202981 | ||
|
|
73313f9e2d | ||
|
|
097c72bc5d | ||
|
|
71f219b7ca | ||
|
|
bacc9fe07e | ||
|
|
a9c360fb9c | ||
|
|
04926c8491 | ||
|
|
fa1d1ad01b | ||
|
|
c0fc18c344 | ||
|
|
69d69f0a5a | ||
|
|
6d7976e5d8 | ||
|
|
aef1f68875 | ||
|
|
06e5cc6d8b | ||
|
|
7782e9b327 | ||
|
|
b82c4fe0af | ||
|
|
45584810a2 | ||
|
|
bfefd053a0 | ||
|
|
324213de14 | ||
|
|
a041ba90bb | ||
|
|
0dc623eb69 | ||
|
|
3e6876dbe7 | ||
|
|
a60abffd3b | ||
|
|
2b43952c01 | ||
|
|
12f440ab8b | ||
|
|
7221af78bf | ||
|
|
a88b0616f5 | ||
|
|
ea4d5b2a70 | ||
|
|
a439100ad6 | ||
|
|
620d24f796 | ||
|
|
fc3bbd0c59 | ||
|
|
3b5ce9b446 | ||
|
|
37de6067d0 | ||
|
|
45410fcc7d | ||
|
|
166cb543a1 | ||
|
|
a295ff4b27 | ||
|
|
dcc52c4530 | ||
|
|
dc3ad6a598 | ||
|
|
ef59e51e32 | ||
|
|
9bbc22de25 | ||
|
|
335d93a8b8 | ||
|
|
52ff0560d1 | ||
|
|
a5e5dd6592 | ||
|
|
62e41dbc51 | ||
|
|
d8b2fd9e1b | ||
|
|
8ca3249832 | ||
|
|
92574fddb1 | ||
|
|
596114e6a3 | ||
|
|
2868f7a478 | ||
|
|
63ef6b673d | ||
|
|
5a56e1706f | ||
|
|
986814441d | ||
|
|
0ab6fb6f3f | ||
|
|
a966be4db6 | ||
|
|
556084233d | ||
|
|
c38239ec35 | ||
|
|
21041346e3 | ||
|
|
7320aa3bb5 | ||
|
|
d9b8ea625a | ||
|
|
2323e22fef | ||
|
|
b5f8f01301 | ||
|
|
e964ff460e | ||
|
|
21d8d9c3bc | ||
|
|
169cf88306 | ||
|
|
059435f4cb | ||
|
|
4d4d4cdeb1 | ||
|
|
d42e7a033c | ||
|
|
0986c65551 | ||
|
|
694f864d36 | ||
|
|
512854ab9f | ||
|
|
b298496911 | ||
|
|
b6367e2645 | ||
|
|
b0fa4bf5d0 | ||
|
|
cb3dbe4ca4 | ||
|
|
96ba467d52 | ||
|
|
20fdcc7b1d | ||
|
|
feea39a81c | ||
|
|
69d1653f99 | ||
|
|
a18a5b4920 | ||
|
|
343dd84132 | ||
|
|
a037962cc1 | ||
|
|
680ce246fd | ||
|
|
baa09ad38c | ||
|
|
767bdea018 | ||
|
|
83a8fd0d5a | ||
|
|
e14ddc9465 | ||
|
|
7feb97d77d | ||
|
|
434360cda9 | ||
|
|
d0a2e9edc0 | ||
|
|
61f66ab319 | ||
|
|
e79ad66e1f | ||
|
|
522fa8f409 | ||
|
|
c7def28a8f | ||
|
|
d6c8ccb73f | ||
|
|
ab5851935c | ||
|
|
5c3d1b7e5d | ||
|
|
ecff06e9a1 | ||
|
|
9c3f09b55b | ||
|
|
b42c455e7f | ||
|
|
40ea30b9e2 | ||
|
|
a4cf5b5359 | ||
|
|
1d41d5a3e7 | ||
|
|
46b190a913 | ||
|
|
8abd2d6228 | ||
|
|
7ff6836a7e | ||
|
|
a6187c18af | ||
|
|
8ab2fbe8ea | ||
|
|
3e7674c94f | ||
|
|
30c0d09a33 | ||
|
|
d9904fa154 | ||
|
|
afbbd1e2d4 | ||
|
|
adca8cc1db | ||
|
|
9788e7fa1c | ||
|
|
66da7efe4a | ||
|
|
3fb7000d02 | ||
|
|
03c95abcf7 | ||
|
|
d2ffbee873 | ||
|
|
413dbaf3a8 | ||
|
|
9187d2faed | ||
|
|
af85a73c7d |
No files matched your search
@@ -8,6 +8,7 @@ web/dist
|
||||
data
|
||||
certs
|
||||
release-artifacts
|
||||
scripts/acceleration-poc
|
||||
*.tar.gz
|
||||
*.tar.xz
|
||||
claude.pem
|
||||
|
||||
@@ -9,7 +9,7 @@ on:
|
||||
version:
|
||||
description: Release version without the v prefix
|
||||
required: true
|
||||
default: 0.1.1
|
||||
default: 0.1.3
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
@@ -34,7 +34,11 @@ jobs:
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm run prepare:sdk
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
@@ -130,7 +134,9 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
release_version="${RELEASE_REF#v}"
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
current_version="$(node -p "require('./package.json').version")"
|
||||
if [ "$current_version" != "$release_version" ]; then
|
||||
|
||||
@@ -22,11 +22,12 @@ jobs:
|
||||
web/package-lock.json
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
- name: Test and build
|
||||
- name: Build application
|
||||
run: |
|
||||
npm test
|
||||
npm run build
|
||||
npm --prefix web run build
|
||||
|
||||
|
||||
@@ -1,7 +1,286 @@
|
||||
# Changelog
|
||||
|
||||
## [0.2.3] — 2026-09-19
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增频道成员调度入口:保留拖放移动,并在右键菜单提供“调度到”二级菜单和“我所在的频道”快捷项。
|
||||
- 支持按 TeamSpeak 权限直接移动成员;具备权限时无需重复输入频道密码,无权限时不提供该操作。
|
||||
- 支持成员头像显示、麦克风静音状态同步和保存身份恢复,并增强指针拖动兼容性。
|
||||
- 更新中文、English、Deutsch、Русский、日本語五种语言的功能截图和文档页面。
|
||||
- 修复高分辨率桌面端管理员设置页面底部内容被裁切的问题,并收紧中继卡片的宽度约束。
|
||||
|
||||
### English
|
||||
|
||||
- Added member-management entry points: drag-and-drop remains available, while the context menu now provides a “Move to” submenu with a “My channel” shortcut.
|
||||
- Added permission-aware direct member moves: authorized users can move clients without redundant channel-password prompts, while the action is unavailable without the required TeamSpeak permission.
|
||||
- Added client-avatar display, microphone mute-state synchronization, and remembered-identity recovery, with improved pointer-drag compatibility.
|
||||
- Refreshed feature screenshots and documentation pages for all five supported languages.
|
||||
- Fixed clipped lower content in the high-resolution desktop admin settings page and tightened relay-card width constraints.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Neue Einstiege für die Mitgliederverwaltung: Ziehen und Ablegen bleibt verfügbar, zusätzlich bietet das Kontextmenü ein Untermenü „Verschieben nach“ mit dem Eintrag „Mein Kanal“.
|
||||
- Direkte, berechtigungsabhängige Mitgliederverschiebung ergänzt: Benutzer mit den erforderlichen TeamSpeak-Rechten benötigen keine erneute Kanalpasswortabfrage; ohne diese Rechte steht die Aktion nicht zur Verfügung.
|
||||
- Anzeige von Client-Avataren, Synchronisierung des Mikrofon-Stummschaltstatus und Wiederherstellung gespeicherter Identitäten ergänzt; Zeigerbedienung verbessert.
|
||||
- Funktionsscreenshots und Dokumentationsseiten für alle fünf unterstützten Sprachen aktualisiert.
|
||||
- Das Abschneiden unterer Inhalte in den Admin-Einstellungen bei hoher Desktop-Auflösung behoben und die Breitenbegrenzung der Relay-Karten verbessert.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлены способы управления участниками: перетаскивание сохранено, а в контекстном меню появился пункт «Переместить в» с быстрым вариантом «Мой канал».
|
||||
- Добавлено прямое перемещение с учётом прав TeamSpeak: пользователям с нужными правами не нужно повторно вводить пароль канала, а без этих прав действие недоступно.
|
||||
- Добавлены отображение аватаров клиентов, синхронизация состояния микрофона и восстановление сохранённой идентичности; улучшено перетаскивание указателем.
|
||||
- Обновлены функциональные скриншоты и страницы документации для всех пяти поддерживаемых языков.
|
||||
- Исправлено обрезание нижнего содержимого настроек администратора на десктопах с высоким разрешением и ограничена ширина карточек ретрансляторов.
|
||||
|
||||
### 日本語
|
||||
|
||||
- メンバー操作を追加しました。ドラッグ&ドロップに加えて、コンテキストメニューに「移動先」サブメニューと「自分のチャンネル」ショートカットを用意しました。
|
||||
- TeamSpeak 権限に応じた直接移動を追加しました。必要な権限があればチャンネルパスワードを再入力せずに移動でき、権限がなければ操作は表示されません。
|
||||
- クライアントアバターの表示、マイクミュート状態の同期、保存した ID の復元に対応し、ポインター操作も改善しました。
|
||||
- 対応する 5 言語すべての機能スクリーンショットとドキュメントページを更新しました。
|
||||
- 高解像度デスクトップで管理設定の下部が切れる問題を修正し、中継カードの幅制約を改善しました。
|
||||
|
||||
## [0.2.2] — 2026-09-17
|
||||
|
||||
### 中文
|
||||
|
||||
- 提供可开关的浏览器端麦克风降噪功能。
|
||||
- 优化前端音量交互逻辑:桌面端悬停麦克风和整体音量按钮即可调整,降噪开关收纳在麦克风菜单中。
|
||||
- 在 PR #2 基础上优化错误提示和错误代码显示。
|
||||
- 提供俄语和日语界面支持,并支持按语言单独调整欢迎文字。
|
||||
|
||||
### English
|
||||
|
||||
- Added optional browser-side microphone noise suppression.
|
||||
- Refined volume interaction: desktop microphone and master-volume controls open on hover, with noise suppression in the microphone menu.
|
||||
- Improved error messages and error-code display on top of PR #2.
|
||||
- Added Russian and Japanese UI support and per-language welcome text configuration.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Optionale browserseitige Mikrofon-Geräuschunterdrückung hinzugefügt.
|
||||
- Lautstärkeinteraktion verbessert: Desktop-Mikrofon- und Gesamtlautstärkeregler öffnen sich beim Überfahren; die Geräuschunterdrückung befindet sich im Mikrofonmenü.
|
||||
- Fehlertexte und Fehlercodes auf Basis von PR #2 verbessert.
|
||||
- Russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлено опциональное шумоподавление микрофона в браузере.
|
||||
- Улучшено управление громкостью: на компьютере регуляторы открываются при наведении, а шумоподавление находится в меню микрофона.
|
||||
- Улучшены сообщения и коды ошибок на основе PR #2.
|
||||
- Добавлены русский и японский интерфейсы и отдельная настройка приветствия для каждого языка.
|
||||
|
||||
### 日本語
|
||||
|
||||
- ブラウザ側で任意に使えるマイクノイズ抑制を追加しました。
|
||||
- 音量操作を改善し、デスクトップではマイクと全体音量のボタンにカーソルを合わせると調整画面を表示し、ノイズ抑制をマイクメニューにまとめました。
|
||||
- PR #2 を基にエラー表示とエラーコードを改善しました。
|
||||
- ロシア語・日本語 UI と言語別ウェルカム文の設定を追加しました。
|
||||
|
||||
## [0.2.1] — 2026-09-13
|
||||
|
||||
### 中文
|
||||
|
||||
- 统一首页连接错误显示:保留错误代码,未知错误安全截断,并显示可追溯的服务端原因。
|
||||
- 默认支持 IPv6 TeamSpeak 目标,并补充主机、运行时和网络条件说明。
|
||||
|
||||
### English
|
||||
|
||||
- Unified connection-error display on the welcome page: preserve error codes, safely truncate unknown codes, and show traceable server reasons.
|
||||
- Added default IPv6 TeamSpeak target support and documented the required host, runtime, and network conditions.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Verbindungsfehler auf der Willkommensseite vereinheitlicht: Fehlercodes bleiben erhalten, unbekannte Codes werden sicher gekürzt und nachvollziehbare Serverursachen angezeigt.
|
||||
- IPv6-Ziele für TeamSpeak standardmäßig unterstützt und erforderliche Host-, Laufzeit- und Netzwerkbedingungen dokumentiert.
|
||||
|
||||
## [0.2.0] — 2026-09-10
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增 README“高级功能”章节,补充 WebRTC 与中继服务器的配置和使用步骤。
|
||||
- 明确 WebRTC 的 UDP 端口、安全组与防火墙要求,以及中继令牌和管理员控制台配置方式。
|
||||
- 标注中继服务为 WebSpeak 自带实现;同时注明 WebRTC 使用 MIT 许可的 `werift` 依赖,TeamSpeak 连接使用项目维护的 SDK fork。
|
||||
- 细分 TeamSpeak 连接失败原因,服务器需要密码时提示用户输入密码并重试。
|
||||
- 优化管理员历史连接日志:能够追溯时显示具体原因,无法追溯时使用通用失败提示,不猜测历史原因。
|
||||
- 新增正式中继部署模式:中继实例不提供前台和管理员后台,只接受带令牌的网关转发会话。
|
||||
- 管理员可配置多个中继节点,访客可在欢迎页为当前连接选择直连或指定中继。
|
||||
- 修复用户正常断开后被管理员运维日志误显示为“请求失败”的问题。
|
||||
|
||||
### English
|
||||
|
||||
- Added an “Advanced features” section to the README with WebRTC and relay configuration and usage steps.
|
||||
- Documented WebRTC UDP, security-group, and firewall requirements, plus relay-token and administration-console setup.
|
||||
- Clarified that the relay is built into WebSpeak, while WebRTC uses the MIT-licensed `werift` dependency and TeamSpeak connectivity uses the project-maintained SDK fork.
|
||||
- Classified TeamSpeak connection failures and prompt users for a server password with a retry when authentication requires one.
|
||||
- Improved administrator connection history: show a specific reason when available and use a generic failure message when older records cannot be traced, without guessing.
|
||||
- Added a formal relay deployment mode: relay instances expose no visitor or admin UI and accept only token-authenticated gateway sessions.
|
||||
- Administrators can configure multiple relay nodes, and visitors can choose direct access or a specific relay for each connection.
|
||||
- Fixed normal user disconnects being shown as “request failed” in administrator connection history.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Einen Abschnitt „Erweiterte Funktionen“ mit Anleitungen für WebRTC und Relay-Server zur README hinzugefügt.
|
||||
- UDP-, Sicherheitsgruppen- und Firewall-Anforderungen für WebRTC sowie Relay-Token und Administrationskonfiguration dokumentiert.
|
||||
- Klargestellt, dass das Relay Bestandteil von WebSpeak ist; WebRTC verwendet die MIT-lizenzierte Abhängigkeit `werift`, die TeamSpeak-Verbindung den projektgepflegten SDK-Fork.
|
||||
- TeamSpeak-Verbindungsfehler genauer klassifiziert und bei erforderlichem Serverpasswort eine Eingabe mit Wiederholung angeboten.
|
||||
- Den Verlauf der Administrator-Verbindungen verbessert: verfügbare Ursachen werden angezeigt, ältere nicht nachvollziehbare Einträge erhalten eine allgemeine Fehlermeldung statt einer Vermutung.
|
||||
- Einen dedizierten Relay-Bereitstellungsmodus ergänzt: Relay-Instanzen stellen keine Besucher- oder Admin-Oberfläche bereit und akzeptieren nur Gateway-Sitzungen mit Token.
|
||||
- Administratoren können mehrere Relay-Knoten konfigurieren; Besucher wählen pro Verbindung Direktzugriff oder ein bestimmtes Relay.
|
||||
- Behoben, dass normale Benutzertrennungen im Administrationsverlauf als „Anfrage fehlgeschlagen“ erschienen.
|
||||
|
||||
## [0.1.8] — 2026-09-08
|
||||
|
||||
### 中文
|
||||
|
||||
- Docker 默认使用 host 网络,支持网关访问同机 TeamSpeak 并直接暴露 WebRTC UDP 端口。
|
||||
- 开放模式统一校验用户提交的目标地址,包括管理员默认目标,修复本机与内网目标绕过限制的问题。
|
||||
- TeamSpeak SDK 连接握手增加 15 秒超时,失败连接会及时清理。
|
||||
- 网络性能面板改为持续监测,打开后每 3 秒更新一次延迟与丢包率。
|
||||
|
||||
### English
|
||||
|
||||
- Docker now uses host networking by default, allowing the gateway to reach a local TeamSpeak server and expose the WebRTC UDP range directly.
|
||||
- Open access now validates every submitted target, including the administrator default, closing loopback and private-network bypasses.
|
||||
- Added a 15-second TeamSpeak SDK handshake timeout with prompt cleanup after failed connections.
|
||||
- The network performance panel now measures continuously and refreshes latency and packet loss every 3 seconds while open.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Docker verwendet standardmäßig das Host-Netzwerk, damit das Gateway einen lokalen TeamSpeak-Server erreicht und den WebRTC-UDP-Bereich direkt bereitstellt.
|
||||
- Der offene Zugriffsmodus prüft nun jedes Ziel einschließlich des Administrator-Standards und schließt Umgehungen für Loopback- und private Netze.
|
||||
- Für den TeamSpeak-SDK-Handshake gilt jetzt ein Timeout von 15 Sekunden; fehlgeschlagene Verbindungen werden zeitnah bereinigt.
|
||||
- Das Netzwerkleistungsfeld misst bei geöffneter Ansicht fortlaufend und aktualisiert Latenz und Paketverlust alle 3 Sekunden.
|
||||
|
||||
## [0.1.7] — 2026-09-06
|
||||
|
||||
### 中文
|
||||
|
||||
- 增加 Deutsch 界面支持和 Telegram 群组入口。
|
||||
- 增加桌面端整体音量滑块,默认收起并在悬停时展开。
|
||||
- 修复伴奏音量忽大忽小的问题。
|
||||
- 增加可展开的网络性能面板,显示浏览器、WebSpeak 与 TeamSpeak 之间的延迟和丢包率。
|
||||
- 管理员连接测试改用服务端多次主机 Ping 并显示丢包率,不再创建临时 TeamSpeak 客户端。
|
||||
- 统一中文、English、Deutsch 的旗帜代码语言菜单。
|
||||
- 修复 TeamSpeak 使用 TCP 探测导致的误报丢包,并修正语言菜单异常留白。
|
||||
- 移除 WebRTC 桥接中的 RMS 静音帧过滤,安静帧仅用于发言状态指示,不再丢弃。
|
||||
- 修复 Docker 运行环境缺少 ICMP Ping 工具导致管理员测试误报 100% 丢包。
|
||||
|
||||
### English
|
||||
|
||||
- Added German UI support and a Telegram community link.
|
||||
- Added a compact desktop master-volume slider that expands on hover.
|
||||
- Fixed accompaniment volume fluctuations.
|
||||
- Added an expandable network performance panel with latency and packet loss across the browser, WebSpeak, and TeamSpeak path.
|
||||
- Updated the administrator connection test to use repeated host pings, report packet loss, and avoid creating temporary TeamSpeak clients.
|
||||
- Unified the Chinese, English, and German flag/code language menu.
|
||||
- Fixed false packet-loss reports caused by probing the TeamSpeak UDP service with TCP, and corrected excess space in the language menu.
|
||||
- Removed RMS-based silence filtering from the WebRTC bridge; quiet frames are now retained for the codec timeline.
|
||||
- Fixed Docker admin diagnostics falsely reporting 100% packet loss when the runtime lacked the ICMP ping tool.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Deutsche Benutzeroberfläche und Telegram-Community-Link hinzugefügt.
|
||||
- Kompakten Gesamtlautstärkeregler für den Desktop ergänzt, der sich beim Überfahren öffnet.
|
||||
- Schwankende Lautstärke bei der Begleittonfreigabe behoben.
|
||||
- Aufklappbares Netzwerkleistungsfeld mit Latenz und Paketverlust zwischen Browser, WebSpeak und TeamSpeak ergänzt.
|
||||
- Verbindungstest in der Administration auf wiederholte Host-Pings mit Paketverlustanzeige umgestellt, ohne temporäre TeamSpeak-Clients zu erzeugen.
|
||||
- Einheitliches Sprachmenü mit Flaggen und Sprachcodes für Chinesisch, Englisch und Deutsch ergänzt.
|
||||
- Falsche Paketverlustmeldungen durch TCP-Prüfung des UDP-Dienstes behoben und übermäßigen Leerraum im Sprachmenü korrigiert.
|
||||
- RMS-basierte Stillefilterung aus der WebRTC-Brücke entfernt; leise Frames bleiben nun im Codec-Zeitverlauf erhalten.
|
||||
- Falsche 100-%-Paketverlustmeldungen behoben, wenn dem Docker-Laufzeitimage das ICMP-Ping-Tool fehlte.
|
||||
|
||||
## [0.1.6] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增保持身份并发连接提醒,避免同一浏览器复用身份造成连接卡住。
|
||||
- 新增桌面端伴奏共享功能。
|
||||
- 新增网站 favicon,并更新仓库 README 主视觉。
|
||||
|
||||
### English
|
||||
|
||||
- Added a warning for concurrent remembered-identity connections in the same browser.
|
||||
- Added desktop accompaniment sharing.
|
||||
- Added a site favicon and refreshed the repository README branding.
|
||||
|
||||
## [0.1.5] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
|
||||
- 修复浏览器身份保存与退出后的保持逻辑。
|
||||
|
||||
### English
|
||||
|
||||
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
|
||||
- Fixed browser identity persistence across exit and return.
|
||||
|
||||
All notable changes to WebSpeak are documented here. Versions follow SemVer.
|
||||
|
||||
## [0.1.4] — 2026-09-03
|
||||
|
||||
### 中文
|
||||
|
||||
- 修复 WebRTC 语音收发与发言状态同步。
|
||||
- 修复频道文字消息在 WebSpeak 客户端之间无法互收。
|
||||
- 优化管理员页面、运行日志换行和移动端顶部布局。
|
||||
- 首页新增 Bilibili 入口,管理员登录页新增返回首页。
|
||||
|
||||
### English
|
||||
|
||||
- Fixed WebRTC voice transport and speaking-state synchronization.
|
||||
- Fixed channel text messages between WebSpeak clients.
|
||||
- Refined admin pages, log wrapping, and narrow-screen header layout.
|
||||
- Added the Bilibili profile link and the admin-login home link.
|
||||
|
||||
## [0.1.3] — 2026-09-03
|
||||
|
||||
### Added
|
||||
|
||||
- Optional WebRTC audio transport for deployments that need lower and more stable realtime voice latency.
|
||||
- A self-contained WebRTC media service controlled by one administrator switch; the gateway derives the media host from the current WebSpeak address and owns a fixed UDP range.
|
||||
- Migrated the TeamSpeak integration to the maintained `EchoSixHIYA/teamspeak-js` fork, including live directory snapshots and member/channel synchronization.
|
||||
|
||||
### Changed
|
||||
|
||||
- WebRTC audio uses negotiated Opus parameters and a bounded newest-frame mixer instead of allowing stale audio to accumulate.
|
||||
- The browser keeps the WebSocket path available for signaling, control, and compatibility fallback; Docker Compose publishes the built-in `40000–40099/UDP` media range alongside the web port.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Prevented duplicate playback when WebRTC and the WebSocket audio path overlap during negotiation or fallback.
|
||||
- Made WebRTC teardown and fallback explicit so a failed negotiation does not leave a server-side media session behind.
|
||||
- Corrected native Opus decoder usage and cleaned up negotiated payload handling for TeamSpeak-to-browser audio.
|
||||
|
||||
### Verification
|
||||
|
||||
- After allowing inbound `40000–40099/UDP` on the public WebSpeak host, two browser sessions were tested against the same TeamSpeak target with WebRTC enabled: audio frames flowed in both directions, packet drops remained at `0`, ingress frame gaps peaked at about `27 ms`, and egress gaps peaked at about `81–83 ms`.
|
||||
- The measured WebRTC path stayed below the previous WebSocket jitter peaks of about `268–376 ms` in the same browser test setup; these figures describe the observed test path, not a universal latency guarantee.
|
||||
|
||||
## [0.1.2] — 2026-09-02
|
||||
|
||||
### Added
|
||||
|
||||
- Current-version badge and a direct changelog link on the welcome page, next to the prominent GitHub repository button.
|
||||
- Mobile member actions through a three-dot menu, while desktop member actions remain available through the context menu.
|
||||
|
||||
### Changed
|
||||
|
||||
- Mobile and narrow-screen header controls now collapse longer labels into icons to preserve usable spacing.
|
||||
- The welcome page and connected workspace now present the GitHub, version, changelog, admin, theme, language, exit, and microphone controls as a consistent responsive control group.
|
||||
- The version shown on the welcome page is read from the gateway's public configuration so it stays aligned with the running backend.
|
||||
- Consolidated the post-0.1.1 mobile voice controls, microphone mute replacement for focus-dependent PTT, automatic protocol detection, simplified Docker Compose startup, and live-demo documentation.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Replaced the visually off-center settings glyph and normalized icon alignment for settings-related controls across the client.
|
||||
- Fixed narrow-screen exit and microphone controls so their text-collapse rules apply correctly.
|
||||
- Bounded browser and gateway voice buffering, reset stale browser playback queues, and exposed low-overhead in-memory audio counters for diagnosing jitter without per-frame log writes.
|
||||
- Moved microphone frame assembly to an `AudioWorklet` with a compatibility fallback to `ScriptProcessorNode`; both paths emit fixed 960-sample frames.
|
||||
|
||||
## [0.1.1] — 2026-09-02
|
||||
|
||||
### Added
|
||||
@@ -19,6 +298,8 @@ All notable changes to WebSpeak are documented here. Versions follow SemVer.
|
||||
- The README architecture section now uses GitHub-native Markdown instead of a Mermaid rich-display block.
|
||||
- The README badge set now uses stable static Shields badges without a repository-metadata 404 dependency.
|
||||
- Version tags publish Windows/Linux deployment packages to GitHub Releases and publish the matching Docker image.
|
||||
- Removed the focus-dependent normal browser Space-key PTT mode and replaced it with a one-click microphone mute/unmute control on desktop and mobile.
|
||||
- Persisted the microphone mute state in browser preferences and suppresses upstream audio before it is sent to TeamSpeak while muted.
|
||||
|
||||
### Fixed
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ Browser (PCM capture) → WebSocket → Node.js server (PCM→Opus) → TeamSpea
|
||||
Browser (playback) ← WebSocket ← Node.js server (Opus relay) ← TeamSpeak server
|
||||
```
|
||||
|
||||
- Each browser user = one independent TS3 virtual client via `@honeybbq/teamspeak-client`
|
||||
- Frontend captures PCM via `ScriptProcessorNode`, sends as Int16 binary over WebSocket
|
||||
- Each browser user = one independent TS3 virtual client via `@echosixhiya/teamspeak-client`
|
||||
- Frontend captures PCM in an `AudioWorklet` when available (with a `ScriptProcessorNode` fallback), assembles fixed 960-sample frames, and sends Int16 binary over WebSocket
|
||||
- Server encodes PCM → Opus using `@discordjs/opus` (CJS, loaded via `createRequire`)
|
||||
- Server sends Opus to TS via `client.sendVoice(data, codec=4)`
|
||||
- Incoming TS voice → Opus frames → binary WebSocket → browser `AudioDecoder` → playback
|
||||
@@ -30,16 +30,19 @@ src/
|
||||
server/
|
||||
server.ts # Express + HTTPS + WS setup
|
||||
voice-bridge.ts # /ws/voice endpoint, PCM→Opus encoding, WebQuery API
|
||||
ts-client.ts # TS3Client wrapper around @honeybbq/teamspeak-client
|
||||
ts-client.ts # TS3Client wrapper around @echosixhiya/teamspeak-client
|
||||
```
|
||||
|
||||
## Key Technical Details
|
||||
|
||||
### Audio Pipeline
|
||||
1. Browser mic → `getUserMedia` (48kHz mono) → `ScriptProcessorNode` (1024 samples)
|
||||
1. Browser mic → `getUserMedia` (48kHz mono) → `AudioWorklet` frame assembler (960 samples); older browsers use `ScriptProcessorNode` (1024-sample chunks) before the same assembler
|
||||
2. Float32 → Int16 conversion → PTT/VOX gate → WebSocket binary send
|
||||
3. Server accumulates PCM → every 1920 bytes (960 samples, 20ms) → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
|
||||
3. Server encodes each 1920-byte (960-sample, 20ms) PCM frame → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
|
||||
4. Incoming: TS → `voiceData` event → 3-byte header `[codec][clientId BE]` → WS binary → browser `AudioDecoder` → playback
|
||||
5. Browser uplink is capped at 10 PCM frames (about 200ms); gateway egress applies a bounded WebSocket byte guard; browser playback resets stale decoder/source queues above 120ms.
|
||||
|
||||
Audio flow counters are kept in memory and exposed in admin session summaries. Do not add per-frame persistent logging to the voice path.
|
||||
|
||||
### CJS Interop
|
||||
`@discordjs/opus` is CommonJS, loaded via:
|
||||
|
||||
@@ -2,14 +2,15 @@ FROM node:22-bookworm-slim AS build
|
||||
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates git python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY web/package.json web/package-lock.json ./web/
|
||||
# The root postinstall hook patches the TeamSpeak SDK during npm ci.
|
||||
COPY scripts ./scripts
|
||||
RUN npm ci
|
||||
RUN npm ci --ignore-scripts --no-audit --no-fund
|
||||
COPY scripts/prepare-sdk.mjs ./scripts/prepare-sdk.mjs
|
||||
RUN npm run prepare:sdk
|
||||
RUN npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
RUN npm --prefix web ci
|
||||
|
||||
COPY . .
|
||||
@@ -22,7 +23,7 @@ FROM node:22-bookworm-slim AS runtime
|
||||
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 iputils-ping \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /data \
|
||||
&& chown node:node /data
|
||||
@@ -37,8 +38,8 @@ COPY --from=build --chown=node:node /app/web/dist ./web/dist
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040
|
||||
EXPOSE 3040/tcp 39087/udp 40000-40099/udp
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD node -e "fetch('http://127.0.0.1:3040/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))"
|
||||
CMD ["sh", "-c", "if [ \"$WEBSPEAK_MODE\" = \"relay\" ]; then node -e \"process.exit(0)\"; else node -e \"fetch('http://127.0.0.1:3040/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))\"; fi"]
|
||||
|
||||
CMD ["node", "dist/index.js"]
|
||||
@@ -1,461 +1,89 @@
|
||||
<div align="center">
|
||||
<a id="readme-top"></a>
|
||||
|
||||
<img src="./image.png" alt="WebSpeak 项目横幅" width="100%" />
|
||||
|
||||
<h1>WebSpeak</h1>
|
||||
|
||||
<p><strong>让 TeamSpeak 自然地进入浏览器。</strong></p>
|
||||
<p>A self-hosted browser voice client for TeamSpeak 3 and TeamSpeak 6.</p>
|
||||
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/docker-publish.yml)
|
||||
[](./LICENSE)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers)
|
||||
<br />
|
||||
[](https://www.teamspeak.com/)
|
||||
[](https://nodejs.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://github.com/users/EchoSixHIYA/packages/container/package/webspeak)
|
||||
|
||||
<p>
|
||||
<a href="./docs/README.zh-CN.md">简体中文文档</a> ·
|
||||
<a href="./docs/README.en.md">English documentation</a> ·
|
||||
<a href="./docs/README.de.md">Deutsche Dokumentation</a> ·
|
||||
<a href="./docs/README.ru.md">Русская документация</a> ·
|
||||
<a href="./docs/README.ja.md">日本語ドキュメント</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## 项目简介 · Overview
|
||||
|
||||
| 逻辑 | 中文 | English |
|
||||
| --- | --- | --- |
|
||||
| **WHAT** | WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。 | WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. |
|
||||
| **WHY** | 无需安装桌面客户端,用户打开网页即可加入频道;部署者仍然掌控目标服务器、访问策略和数据。 | Users can join a voice channel from a browser without installing a desktop client, while the operator keeps control of servers, access, and data. |
|
||||
| **HOW** | 部署后在管理员控制台配置 TeamSpeak 目标和访问方式,浏览器负责交互与音频,WebSpeak 负责网关连接。 | Configure the TeamSpeak target and access policy in the administration console. The browser handles interaction and audio; WebSpeak provides the gateway connection. |
|
||||
|
||||
## 文档 · Documentation
|
||||
|
||||
- [简体中文](./docs/README.zh-CN.md)
|
||||
- [English](./docs/README.en.md)
|
||||
- [Deutsch](./docs/README.de.md)
|
||||
- [Русский](./docs/README.ru.md)
|
||||
- [日本語](./docs/README.ja.md)
|
||||
|
||||
## 社区 · Community
|
||||
|
||||
<div align="center">
|
||||
|
||||
# WebSpeak
|
||||
<a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475">
|
||||
<img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ 群二维码" width="290" />
|
||||
</a>
|
||||
|
||||
**让 TeamSpeak 真正进入浏览器。**
|
||||
**QQ群 / QQ group:`869500475`**
|
||||
|
||||
自托管的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音接入网关。无需安装桌面客户端,打开浏览器即可进入你的语音空间。
|
||||
[通过群聊链接直接加入 / Join directly](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
|
||||
A self-hosted TeamSpeak 3 / TeamSpeak 6 web client and voice gateway. Join your voice space from a modern browser without installing a desktop client.
|
||||
|
||||
[](LICENSE)
|
||||
[](https://nodejs.org/)
|
||||
[](https://www.teamspeak.com/)
|
||||
|
||||
**[中文](#中文)**<br />
|
||||
[更新日志](#更新日志) · [为什么是 WebSpeak](#为什么是-webspeak) · [核心能力](#核心能力) · [架构](#架构) · [快速开始](#快速开始) · [首次登录与默认目标](#首次登录与默认目标) · [访问模式与邀请](#访问模式与邀请) · [音频与设备](#音频与设备) · [数据与安全边界](#数据与安全边界) · [旧版本升级](#旧版本升级) · [健康检查](#健康检查开发与验证) · [项目结构](#项目结构) · [已知边界](#已知边界) · [社区](#社区)
|
||||
|
||||
**[English](#english)**<br />
|
||||
[Changelog](#changelog) · [Why WebSpeak](#why-webspeak) · [Core capabilities](#core-capabilities) · [Architecture](#architecture) · [Quick Start](#quick-start) · [First login](#first-login-and-default-target) · [Access modes](#access-modes-and-invites) · [Audio](#audio-and-devices) · [Security](#data-and-security-boundary) · [Upgrade](#upgrading-from-a-legacy-version) · [Health](#health-development-and-verification) · [Project layout](#project-layout) · [Known boundaries](#known-boundaries) · [License](#license) · [Community](#community)
|
||||
[Telegram 群组 / Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
</div>
|
||||
|
||||
> WebSpeak 是一个面向浏览器的 TeamSpeak 客户端,让频道、成员、文字与语音协作在网页中自然完成。
|
||||
## 友链项目 · Friend projects
|
||||
|
||||
> WebSpeak is a browser-based TeamSpeak client that brings channels, members, text chat, and voice collaboration into one web experience.
|
||||
### [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot)
|
||||
|
||||
## 中文
|
||||
面向 TeamSpeak 3/6 的多平台音乐点播机器人,支持网易云音乐、QQ 音乐和 Bilibili 音频播放,并提供 Web 控制台。<br />
|
||||
A multi-platform music bot for TeamSpeak 3/6 with Netease Cloud Music, QQ Music, and Bilibili playback, plus a web console.<br />
|
||||
Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music, QQ Music und Bilibili sowie Webkonsole.
|
||||
|
||||
### 更新日志
|
||||
## Contributors · 贡献者
|
||||
|
||||
#### 2026-09-02 · v0.1.1
|
||||
感谢提交 PR 的贡献者:
|
||||
|
||||
- 汇总并正式发布浏览器客户端、管理员控制台、受控邀请、Session 运维、审计记录、诊断报告和 SQLite 备份能力。
|
||||
- 修复晚进入 WebSpeak 的浏览器会话无法看到先进入成员的问题;连接建立后会完成目录同步,并合并分阶段成员事件。
|
||||
- 修复私聊消息到达后网页端断开连接的问题,完善成员右键菜单、悬停高亮和语音活动状态展示。
|
||||
- 完成中英文界面、默认 TeamSpeak 目标、旧版配置迁移和首次登录强制改密流程。
|
||||
- 发布流程稳定生成 Windows/Linux 部署包并同步发布 Docker 镜像;Docker 构建会正确处理依赖安装脚本。
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2):浏览器端报错翻译与提示改造。
|
||||
|
||||
#### 2026-08-31 · v0.1.0
|
||||
## 许可证 · License · Lizenz · Лицензия · ライセンス
|
||||
|
||||
- 首个规范化版本,提供浏览器客户端、TeamSpeak 3 / 6 网关、浏览器音频控制、访问模式、管理员运维能力和 AGPL-3.0-only 许可证。
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
|
||||
|
||||
### 为什么是 WebSpeak
|
||||
WebSpeak is released under the [GNU Affero General Public License v3.0 only](./LICENSE). If a modified version is offered to users over a network, its corresponding source code must be offered under AGPL-3.0.
|
||||
|
||||
| 体验 | WebSpeak 的答案 |
|
||||
| --- | --- |
|
||||
| 加入方式 | 浏览器打开链接即可加入,不安装桌面客户端 |
|
||||
| 兼容性 | 支持 TeamSpeak 3 / TeamSpeak 6,并自动识别协议 |
|
||||
| 连接模型 | HTTPS / WSS 连接 WebSpeak,WebSpeak 连接目标 TeamSpeak |
|
||||
| 入口控制 | 固定目标、开放目标、一次性受控邀请三种路径 |
|
||||
| 语言与主题 | 访客端和管理控制台均支持中英文与主题切换 |
|
||||
WebSpeak wird unter der [GNU Affero General Public License v3.0 only](./LICENSE) veröffentlicht. Bei Bereitstellung einer veränderten Version über ein Netzwerk muss der entsprechende Quellcode unter AGPL-3.0 angeboten werden.
|
||||
|
||||
### 核心能力
|
||||
WebSpeak распространяется по лицензии [GNU Affero General Public License v3.0 only](./LICENSE). Если изменённая версия предоставляется пользователям через сеть, соответствующий исходный код должен быть доступен этим пользователям на условиях AGPL-3.0.
|
||||
|
||||
| 领域 | 已提供 |
|
||||
| --- | --- |
|
||||
| 语音 | Opus / PCM 桥接、自由麦、按键说话、VOX、连接状态与重连提示 |
|
||||
| 设备 | 浏览器麦克风与扬声器选择、音量调节、实时输入电平、本地麦克风测试 |
|
||||
| 频道 | 频道树、频道切换、成员移动、频道文字聊天、服务器事件与状态展示 |
|
||||
| 成员 | 在线成员、发言绿色头像边框、Away 状态、私聊、Poke、昵称复制、成员音量 |
|
||||
| 管理 | 默认账号首次登录强制改密、默认 TeamSpeak 目标、站点信息、真实连接测试 |
|
||||
| 运维 | 活动 Session、邀请创建与撤销、审计事件、结构化日志、诊断报告、SQLite 备份 |
|
||||
| 浏览器体验 | 响应式布局、移动端按住说话、紧凑滚动布局、浏览器本地收藏与最近连接 |
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](./LICENSE) の下で公開されています。変更版をネットワーク経由でユーザーに提供する場合は、対応するソースコードを AGPL-3.0 に従ってユーザーに提供する必要があります。
|
||||
|
||||
### 架构
|
||||
|
||||
| 层级 | 职责 | 连接 |
|
||||
| --- | --- | --- |
|
||||
| 浏览器会话 | 昵称、设备、频道、成员、文字和语音交互 | HTTPS / WSS → WebSpeak |
|
||||
| WebSpeak 网关 | 会话管理、访问控制、语音桥接、目录同步、管理控制台 | TeamSpeak 客户端协议 |
|
||||
| TeamSpeak 3 / 6 | 提供频道、成员、文字和语音服务 | 目标地址与语音端口 |
|
||||
|
||||
### 快速开始
|
||||
|
||||
#### 方式 A:从 Dockerfile 构建
|
||||
|
||||
```bash
|
||||
docker build -t webspeak:local .
|
||||
docker volume create webspeak-data
|
||||
docker run -d \
|
||||
--name webspeak \
|
||||
--restart unless-stopped \
|
||||
-p 3040:3040 \
|
||||
-v webspeak-data:/data \
|
||||
webspeak:local
|
||||
```
|
||||
|
||||
容器固定监听 `3040`,SQLite 数据库、安装级主密钥和日志保存在 `/data`。公网部署时,请在前面配置 HTTPS 反向代理;麦克风和部分浏览器音频能力需要安全上下文。
|
||||
|
||||
#### 方式 B:源码运行
|
||||
|
||||
环境要求:
|
||||
|
||||
- Node.js `22.5.0` 或更高版本。
|
||||
- `@discordjs/opus` 所需的原生编译工具;Linux 通常需要 `python3`、`make`、`g++`。
|
||||
- 一台可访问的 TeamSpeak 3 或 TeamSpeak 6 服务端。
|
||||
- 较新的 Chrome 或 Edge;生产环境建议使用 HTTPS。
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
随后打开:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:3040/
|
||||
```
|
||||
|
||||
### 首次登录与默认目标
|
||||
|
||||
1. 打开 `/admin`。
|
||||
2. 使用默认账户 `admin / admin` 登录。
|
||||
3. 按页面要求设置一个至少 12 个字符的新管理员密码。
|
||||
4. 在“服务器”页面的“默认 TeamSpeak 目标”中填写服务器地址与语音端口。
|
||||
5. 执行连接测试并保存。
|
||||
|
||||
欢迎页没有邀请链接目标参数时,会使用管理员设置的默认 TeamSpeak 目标进行预填写。邀请链接参数优先;固定模式下访客只能进入管理员配置的目标,开放模式下访客可以输入经过安全校验的公网目标。
|
||||
|
||||
WebSpeak 的 HTTP 端口固定为 `3040`,TeamSpeak 默认语音端口为 `9987`。目标地址在界面中拆分为“地址”和“语音端口”两个字段;旧版 `地址:端口` 与 `地址#端口` 文本仍可兼容解析。
|
||||
|
||||
### 访问模式与邀请
|
||||
|
||||
| 模式 | 行为 | 适用场景 |
|
||||
| --- | --- | --- |
|
||||
| `fixed` | 访客不改变目标,服务端管理目标与服务器密码 | 私有社区、固定服务器 |
|
||||
| `open` | 访客可输入公网目标与本次会话密码 | 临时接入、多服务器入口 |
|
||||
| 受控邀请 | 管理员生成一次性、可过期、可限次、可撤销链接 | 活动、临时房间、定向分享 |
|
||||
|
||||
开放模式会在 DNS 解析后阻止 loopback、私网、链路本地、组播、广播和保留地址,并使用已验证的 IP 进行实际连接。服务器密码不会写入分享链接、浏览器本地存储或 WebSocket URL。
|
||||
|
||||
### 音频与设备
|
||||
|
||||
进入语音空间后,在设置中可以:
|
||||
|
||||
- 选择浏览器检测到的麦克风与扬声器;
|
||||
- 切换自由麦和按键说话;
|
||||
- 调整输入、输出、通知音量与 VOX 阈值;
|
||||
- 查看麦克风权限、实时输入电平和音频上下文状态;
|
||||
- 使用最多 5 秒的本地麦克风测试,录音只在浏览器本地播放,不发送到 TeamSpeak。
|
||||
|
||||
设备标签由浏览器权限模型决定。首次选择设备前,浏览器可能要求授予麦克风权限;输出设备选择依赖浏览器支持,不支持时会明确回退到默认扬声器。
|
||||
|
||||
### 数据与安全边界
|
||||
|
||||
运行数据默认位于 `data/`,Docker 环境默认位于 `/data`:
|
||||
|
||||
```text
|
||||
data/
|
||||
├── webspeak.db SQLite 配置、管理员凭据、邀请与有限审计事件
|
||||
├── master.key 32 字节安装级主密钥
|
||||
└── logs/ 本地轮转日志
|
||||
```
|
||||
|
||||
- 管理员密码使用 Node.js `crypto.scrypt`、随机 salt 与 constant-time compare。
|
||||
- TeamSpeak 服务器密码使用 AES-256-GCM 加密保存,管理 API 不返回明文。
|
||||
- 管理 Session 使用服务端会话、HttpOnly / SameSite Strict Cookie、同源校验与 CSRF token。
|
||||
- 管理登录具有固定窗口限速与失败延迟。
|
||||
- 普通用户 identity 只在当前 Join Ticket / Session 中使用;启用“记住此设备”后,私钥只保存在浏览器 IndexedDB,不上传到网关,也不会进入日志、诊断或数据库。
|
||||
- WebSpeak 不提供身份文件导入/导出界面;清除浏览器本地数据会移除本机记住的身份与偏好。
|
||||
- 日志、诊断报告与 Overview 不返回服务器密码、管理员密码或身份私钥。
|
||||
- 请同时备份 `webspeak.db` 与 `master.key`;只有数据库而没有主密钥时,加密的服务器密码无法恢复。
|
||||
|
||||
### 旧版本升级
|
||||
|
||||
如果升级启动时项目根目录仍有旧 `config.json`,WebSpeak 只做一次性导入:
|
||||
|
||||
- `tsHost`
|
||||
- `tsPort`
|
||||
- `tsServerPassword`
|
||||
|
||||
导入后 `data/webspeak.db` 成为唯一实时配置源;旧文件不会被删除或改写。旧版的 `port`、`tsServerProtocol`、`maxClients` 和 `trustProxy` 不再作为运行配置。
|
||||
|
||||
### 健康检查、开发与验证
|
||||
|
||||
无需认证的健康检查:
|
||||
|
||||
```text
|
||||
GET /health
|
||||
GET /api/health
|
||||
```
|
||||
|
||||
开发命令:
|
||||
|
||||
```bash
|
||||
# 后端:固定监听 3040
|
||||
npm run dev
|
||||
|
||||
# 前端:Vite 监听 5173,并将 /api 与 /ws 代理到 3040
|
||||
npm run web:dev
|
||||
|
||||
# 前端生产构建
|
||||
npm --prefix web run build
|
||||
|
||||
# 后端类型检查与构建
|
||||
npm run build
|
||||
|
||||
# 自动化测试
|
||||
npm test
|
||||
|
||||
# 依赖审计
|
||||
npm audit
|
||||
```
|
||||
|
||||
`/demo` 是不连接真实 TeamSpeak 的交互式演示页面,仅用于界面预览、录屏和前端回归,不能替代真实 TS3 / TS6 验证。
|
||||
|
||||
### 项目结构
|
||||
|
||||
```text
|
||||
src/
|
||||
├── admin/ 管理服务、登录、Session、邀请与运维接口
|
||||
├── persistence/ SQLite schema、repository 与迁移边界
|
||||
├── security/ 主密钥、秘密加密、密码与开放目标策略
|
||||
├── domain/ TeamSpeak 目标地址与端口解析
|
||||
└── server/ TeamSpeak 适配器、Session、票据与语音桥
|
||||
|
||||
web/src/
|
||||
├── views/WebClient.vue 访客端、语音空间、聊天与音频设置
|
||||
├── views/AdminView.vue 管理登录、服务器、概览与运维控制台
|
||||
├── composables/ WebSocket 与语音状态
|
||||
└── services/ 主题、本地持久化与目标解析
|
||||
```
|
||||
|
||||
### 已知边界
|
||||
|
||||
- 服务端固定限制最多 100 个活动连接。
|
||||
- 管理员模型目前是单管理员,不提供用户列表、角色或权限管理后台。
|
||||
- 浏览器麦克风权限、HTTPS 与浏览器对音频输出设备的支持会影响最终体验。
|
||||
- TeamSpeak 服务端自身的版本、协议兼容性和网络可达性不由 WebSpeak 代替管理。
|
||||
|
||||
### 社区
|
||||
|
||||
QQ群:`869500475`
|
||||
|
||||
加入 QQ 群获取使用帮助、版本更新和交流支持:
|
||||
|
||||

|
||||
|
||||
## English
|
||||
|
||||
WebSpeak brings TeamSpeak voice spaces to the browser. It is a self-hosted gateway and web client for TeamSpeak 3 and TeamSpeak 6: open a link, choose a nickname, and join from a modern browser without installing a desktop client.
|
||||
|
||||
### Changelog
|
||||
|
||||
#### 2026-09-02 · v0.1.1
|
||||
|
||||
- Consolidated and officially released the browser client, administrator console, managed invites, session operations, audit records, diagnostics, and SQLite backup support.
|
||||
- Fixed late WebSpeak browser sessions missing members who joined earlier by reconciling the directory after connect and merging staged member events.
|
||||
- Fixed browser sessions disconnecting after receiving a private message, and improved member context menus, hover highlighting, and speaking-state presentation.
|
||||
- Added the bilingual interface, default TeamSpeak target, legacy configuration migration, and mandatory first-login password rotation.
|
||||
- Stabilized release publishing for Windows/Linux packages and the matching Docker image; Docker builds now handle the dependency patch script correctly.
|
||||
|
||||
#### 2026-08-31 · v0.1.0
|
||||
|
||||
- First normalized release with the browser client, TeamSpeak 3 / 6 gateway, browser audio controls, access modes, administrator operations, and AGPL-3.0-only licensing.
|
||||
|
||||
### Why WebSpeak
|
||||
|
||||
| Experience | WebSpeak's answer |
|
||||
| --- | --- |
|
||||
| Joining | Open a browser link and join without installing the desktop client |
|
||||
| Compatibility | Supports TeamSpeak 3 and TeamSpeak 6 with automatic protocol detection |
|
||||
| Connection model | The browser connects to WebSpeak over HTTPS / WSS, and WebSpeak connects to TeamSpeak |
|
||||
| Access control | Fixed targets, open targets, and one-time managed invites |
|
||||
| Language and theme | Chinese and English interfaces with theme switching for guests and administrators |
|
||||
|
||||
### Core capabilities
|
||||
|
||||
| Area | Included |
|
||||
| --- | --- |
|
||||
| Voice | Opus / PCM bridging, free mic, push-to-talk, VOX, connection state, reconnect feedback, and speaking indicators |
|
||||
| Devices | Browser microphone and speaker selection, volume controls, live input level, and a local microphone test |
|
||||
| Channels | Channel tree, channel switching, member movement, channel text chat, server events, and status display |
|
||||
| Members | Online members, green speaking borders, Away state, private messages, Poke, nickname copy, and per-member volume |
|
||||
| Administration | Mandatory first-login password rotation, default TeamSpeak target, site information, and real connection tests |
|
||||
| Operations | Active sessions, invite creation and revocation, audit events, structured logs, diagnostics, and SQLite backup |
|
||||
| Browser experience | Responsive layouts, press-and-hold mobile PTT, compact scrolling regions, local favorites, and recent connections |
|
||||
|
||||
### Architecture
|
||||
|
||||
| Layer | Responsibility | Connection |
|
||||
| --- | --- | --- |
|
||||
| Browser session | Nickname, device, channel, member, text, and voice interactions | HTTPS / WSS → WebSpeak |
|
||||
| WebSpeak gateway | Session management, access control, voice bridging, directory synchronization, and admin console | TeamSpeak client protocol |
|
||||
| TeamSpeak 3 / 6 | Channel, member, text, and voice services | Configured host and voice port |
|
||||
|
||||
### Quick Start
|
||||
|
||||
#### Option A: Build with Docker
|
||||
|
||||
```bash
|
||||
docker build -t webspeak:local .
|
||||
docker volume create webspeak-data
|
||||
docker run -d \
|
||||
--name webspeak \
|
||||
--restart unless-stopped \
|
||||
-p 3040:3040 \
|
||||
-v webspeak-data:/data \
|
||||
webspeak:local
|
||||
```
|
||||
|
||||
The container listens on `3040`. SQLite data, the installation master key, and logs are stored in `/data`. If `certs/cert.pem` and `certs/key.pem` are present, the service enables HTTPS directly; for public deployments, an HTTPS reverse proxy is recommended. Microphone access and some browser audio features require a secure context.
|
||||
|
||||
#### Option B: Run from source
|
||||
|
||||
Requirements:
|
||||
|
||||
- Node.js `22.5.0` or newer.
|
||||
- Native build tools required by `@discordjs/opus`; Linux installations typically need `python3`, `make`, and `g++`.
|
||||
- An accessible TeamSpeak 3 or TeamSpeak 6 server.
|
||||
- A recent Chrome or Edge release; HTTPS is recommended for production.
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Then open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:3040/
|
||||
```
|
||||
|
||||
Use `https://127.0.0.1:3040/` when direct certificates are enabled. On first run, WebSpeak creates its SQLite database and installation master key in the data directory.
|
||||
|
||||
### First login and default target
|
||||
|
||||
1. Open `/admin`.
|
||||
2. Sign in with the default account `admin / admin`.
|
||||
3. Follow the prompt to set a new administrator password of at least 12 characters.
|
||||
4. In **Servers**, configure the **Default TeamSpeak target** with a host and voice port.
|
||||
5. Run the connection test and save the settings.
|
||||
|
||||
When a welcome link has no target parameters, the welcome page pre-fills the administrator's default TeamSpeak target. Invite parameters take precedence. In fixed mode, guests stay on the administrator-configured target; in open mode, guests may enter a public target that passes the network policy.
|
||||
|
||||
WebSpeak's web port is fixed at `3040`, and TeamSpeak's default voice port is `9987`. The web fields use separate host and voice-port inputs; legacy `host:port` and `host#port` text remains accepted by the parser.
|
||||
|
||||
### Access modes and invites
|
||||
|
||||
| Mode | Behavior | Typical use |
|
||||
| --- | --- | --- |
|
||||
| `fixed` | Guests cannot change the target; the server and password are managed by the administrator | Private communities and a single permanent server |
|
||||
| `open` | Guests may enter a public target and a password for that session | Temporary access and multi-server entry points |
|
||||
| Managed invite | An administrator creates a one-time, expiring, usage-limited, revocable link | Events, temporary rooms, and targeted sharing |
|
||||
|
||||
In open mode, DNS resolution is followed by blocking loopback, private, link-local, multicast, broadcast, and reserved addresses. The verified IP is used for the actual connection. Server passwords never appear in share links, browser storage, or WebSocket URLs.
|
||||
|
||||
### Audio and devices
|
||||
|
||||
Inside a voice space, the settings panel lets users:
|
||||
|
||||
- Choose a microphone and speaker detected by the browser.
|
||||
- Switch between free mic and push-to-talk.
|
||||
- Adjust input, output, notification, and VOX-threshold volumes.
|
||||
- Inspect microphone permission, live input level, and audio-context state.
|
||||
- Run a local microphone test of up to five seconds; the recording is played in the browser and is not sent to TeamSpeak.
|
||||
|
||||
Device labels are controlled by the browser permission model. The first device selection may request microphone permission. Output-device selection depends on browser support; unsupported browsers clearly fall back to the default speaker.
|
||||
|
||||
### Data and Security Boundary
|
||||
|
||||
Runtime data is stored in `data/` by default and in `/data` in Docker:
|
||||
|
||||
```text
|
||||
data/
|
||||
├── webspeak.db SQLite settings, admin credentials, invites, and bounded audit events
|
||||
├── master.key 32-byte installation master key
|
||||
└── logs/ Locally rotated logs
|
||||
```
|
||||
|
||||
- Administrator passwords use Node.js `crypto.scrypt`, a random salt, and constant-time comparison.
|
||||
- TeamSpeak server passwords are encrypted with AES-256-GCM; admin APIs never return them in plaintext.
|
||||
- Admin sessions use server-side sessions, HttpOnly / SameSite Strict cookies, same-origin checks, and CSRF tokens.
|
||||
- Admin login applies bounded-window rate limiting and failure delays.
|
||||
- A user identity is used only by the current join ticket and session. When “remember this device” is enabled, the private key stays in browser IndexedDB and is not uploaded to the gateway or written to logs, diagnostics, or the database.
|
||||
- WebSpeak has no identity-file import/export controls; clearing browser data removes the remembered identity and local preferences.
|
||||
- Logs, diagnostic reports, and the overview do not return server passwords, admin passwords, or private identity keys.
|
||||
- Back up `webspeak.db` together with `master.key`; an encrypted TeamSpeak password cannot be recovered from the database alone.
|
||||
|
||||
### Upgrading from a legacy version
|
||||
|
||||
If an old `config.json` is still present in the project root at startup, WebSpeak imports these fields once:
|
||||
|
||||
- `tsHost`
|
||||
- `tsPort`
|
||||
- `tsServerPassword`
|
||||
|
||||
After the import, `data/webspeak.db` is the only live configuration source. The legacy file is not deleted or rewritten. Legacy `port`, `tsServerProtocol`, `maxClients`, and `trustProxy` values are no longer runtime controls.
|
||||
|
||||
### Health, development, and verification
|
||||
|
||||
Unauthenticated health endpoints:
|
||||
|
||||
```text
|
||||
GET /health
|
||||
GET /api/health
|
||||
```
|
||||
|
||||
Development commands:
|
||||
|
||||
```bash
|
||||
# Backend: fixed port 3040
|
||||
npm run dev
|
||||
|
||||
# Frontend: Vite on 5173, proxying /api and /ws to 3040
|
||||
npm run web:dev
|
||||
|
||||
# Frontend production build
|
||||
npm --prefix web run build
|
||||
|
||||
# Backend type check and build
|
||||
npm run build
|
||||
|
||||
# Automated tests
|
||||
npm test
|
||||
|
||||
# Dependency audit
|
||||
npm audit
|
||||
```
|
||||
|
||||
`/demo` is an interactive simulated page that never connects to a real TeamSpeak server. It is useful for UI previews, recordings, and frontend regression checks, but does not replace real TS3 / TS6 verification.
|
||||
|
||||
### Project layout
|
||||
|
||||
```text
|
||||
src/
|
||||
├── admin/ Admin service, login, sessions, invites, and operations APIs
|
||||
├── persistence/ SQLite schema, repositories, and migration boundaries
|
||||
├── security/ Master key, secret encryption, passwords, and target policy
|
||||
├── domain/ TeamSpeak target and port parsing
|
||||
└── server/ TeamSpeak adapter, sessions, tickets, and voice bridge
|
||||
|
||||
web/src/
|
||||
├── views/WebClient.vue Guest client, voice space, chat, and audio settings
|
||||
├── views/AdminView.vue Admin login, server, overview, and operations console
|
||||
├── composables/ WebSocket and voice state
|
||||
└── services/ Theme, local persistence, and target parsing
|
||||
```
|
||||
|
||||
### Known boundaries
|
||||
|
||||
- The server has a fixed limit of 100 active connections.
|
||||
- The current administrator model is single-admin; there is no user, role, or permission-management panel.
|
||||
- Browser microphone permissions, HTTPS, and browser support for output-device selection affect the final experience.
|
||||
- WebSpeak does not replace TeamSpeak server version, protocol-compatibility, or network-reachability management.
|
||||
|
||||
### License
|
||||
|
||||
WebSpeak is licensed under the [GNU Affero General Public License v3.0 only](LICENSE) (`AGPL-3.0-only`). If you run a modified version as a network service, provide the corresponding source under the terms of the license.
|
||||
|
||||
### Community
|
||||
|
||||
QQ group: `869500475`
|
||||
|
||||

|
||||
<div align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></div>
|
||||
@@ -1,10 +1,11 @@
|
||||
services:
|
||||
webspeak:
|
||||
image: ghcr.io/EchoSixHIYA/webspeak:latest
|
||||
container_name: webspeak
|
||||
image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest}
|
||||
pull_policy: missing
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3040:3040"
|
||||
# WebSpeak needs to reach a TeamSpeak server running on the same host.
|
||||
# Host networking also exposes the configured WebRTC UDP range directly.
|
||||
network_mode: host
|
||||
volumes:
|
||||
- webspeak-data:/data
|
||||
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
# WebSpeak · Deutsch
|
||||
|
||||
[Projektstartseite](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak ist ein selbst gehosteter Webclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer können ohne Desktop-Client im Browser Kanälen beitreten; Administratoren verwalten Zielserver, Zugriff und Laufzeitstatus über die Webkonsole.
|
||||
|
||||
## Live-Demo
|
||||
|
||||
Adresse: <https://webspeak.example.invalid>
|
||||
|
||||
Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung können instabil sein; Latenz, Verbindungsabbrüche oder kurze Ausfälle beschreiben nicht jede eigene Bereitstellung.
|
||||
|
||||
## ✨ Funktionen
|
||||
|
||||
| Funktion | Beschreibung |
|
||||
| --- | --- |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll automatisch. |
|
||||
| IPv6-Ziele | IPv6-TeamSpeak-Ziele und über DNS aufgelöste IPv6-Adressen werden standardmäßig unterstützt. |
|
||||
| Kanäle und Mitglieder | Kanalstruktur und aktuelle Mitglieder anzeigen und Kanäle wechseln. |
|
||||
| Echtzeit-Sprache | Opus-Audio mit kompatiblem Transport und optional integriertem WebRTC für geringere Latenz. |
|
||||
| Audiosteuerung | Mikrofon und Lautsprecher auswählen, Lautstärke regeln, testen, stummschalten, VOX und individuelle Mitgliedslautstärke. |
|
||||
| Browserseitige Geräuschunterdrückung | Optionale Mikrofon-Geräuschunterdrückung in der Browseraufnahme, ohne zusätzliche serverseitige Audioverarbeitung. |
|
||||
| Nachrichten und Aktionen | Kanal- und Serverchat, private Nachrichten, Anstupsen und Flüsterziele. |
|
||||
| Desktop-Begleitton | Audio eines freigegebenen Fensters oder Browser-Tabs im aktuellen Kanal teilen. |
|
||||
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele und widerrufbare Einladungslinks mit Ablaufzeit. |
|
||||
| Administration | Ziele, Zugriff, WebRTC, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
|
||||
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche, helle/dunkle Designs sowie responsive Desktop-/Mobilansicht. |
|
||||
| Selbsthosting | Daten bleiben beim Betreiber; Docker-, Windows-x64- und Linux-x64-Bereitstellung sind verfügbar. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
Die Screenshots zeigen die deutsche Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitgliedermenü.
|
||||
|
||||
### Willkommensseite
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-home.png" alt="WebSpeak deutsche Willkommensseite" width="100%" /></p>
|
||||
|
||||
### Sprachbereich
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de.png" alt="WebSpeak deutscher Sprachbereich" width="100%" /></p>
|
||||
|
||||
### Audiosteuerung
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-audio.png" alt="WebSpeak deutsche Audiosteuerung" width="100%" /></p>
|
||||
|
||||
### Mitgliedermenü
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-menu.png" alt="WebSpeak deutsches Mitgliedermenü" width="100%" /></p>
|
||||
|
||||
## 🧩 Erweiterte Funktionen
|
||||
|
||||
Diese Funktionen sind optional. Ohne sie arbeitet WebSpeak weiterhin mit dem kompatiblen Sprachtransport. Die Einstellungen befinden sich unter **Administration → Server** und gelten für neue Verbindungen.
|
||||
|
||||
### 1. WebRTC-Sprache mit niedriger Latenz
|
||||
|
||||
WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht außerdem Desktop-Begleitton. Das aktuelle WebSpeak-Gateway stellt WebRTC selbst bereit; ein zusätzlicher Medienserver ist nicht erforderlich.
|
||||
|
||||
1. Unter `/admin` anmelden und auf der Seite **Server** die **Erweiterten Einstellungen** öffnen.
|
||||
2. Bei deaktiviertem WebRTC Start- und Endport für UDP festlegen. Der Standardbereich ist `40000–40099`.
|
||||
3. Den gesamten UDP-Bereich in Sicherheitsgruppe und Firewall des WebSpeak-Hosts freigeben.
|
||||
4. **WebRTC** aktivieren und speichern. Nicht unterstützte Browser oder Netzwerke wechseln automatisch zum kompatiblen Transport.
|
||||
|
||||
Der Portbereich ist bei aktiviertem WebRTC gesperrt. Zum Ändern WebRTC zuerst deaktivieren und speichern, danach die Firewall-Regeln anpassen. Für öffentliche Bereitstellungen ist HTTPS erforderlich.
|
||||
|
||||
### 2. Relay-Modus
|
||||
|
||||
Ein Relay hilft, wenn ein TeamSpeak-Server Verbindungen aus einer anderen Region ablehnt oder der direkte Weg instabil ist. Es ist kein VPN, sondern leitet nur den TeamSpeak-Verkehr der aktuellen WebSpeak-Sitzung weiter.
|
||||
|
||||
Eine Relay-Instanz ist ein dedizierter Weiterleitungsdienst ohne Besucher- oder Administrationsseite. Sie akzeptiert nur Gateway-Sitzungen mit passendem Token. Ein zufälliges Token mit mindestens 16 Zeichen verwenden.
|
||||
|
||||
#### Aus dem Quellcode starten
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### Aus einem Release-Paket starten
|
||||
|
||||
Das passende Paket aus den [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und entpacken:
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
Unter Windows PowerShell dieselben Variablen setzen und `.\runtime\node.exe .\dist\index.js` ausführen.
|
||||
|
||||
#### Mit Docker starten
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Den UDP-Listening-Port des Relay-Hosts freigeben, standardmäßig `39087`.
|
||||
|
||||
#### Im Gateway aktivieren
|
||||
|
||||
1. **Administration → Server → Relay-Server** öffnen und einen oder mehrere Knoten hinzufügen.
|
||||
2. Für jeden Knoten einen Anzeigenamen, einen Endpunkt wie `relay.example.com#39087` und das passende Token eintragen und speichern.
|
||||
3. Besucher können auf der Willkommensseite Direktzugriff oder einen konfigurierten Relay-Knoten auswählen.
|
||||
|
||||
Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entfernen.
|
||||
|
||||
### 3. Abhängigkeiten und Hinweise zur Herkunft
|
||||
|
||||
- Der Relay-Dienst ist Bestandteil von WebSpeak und verwendet Node.js-Standardbibliotheken; GOST, sing-box oder ein anderes Proxy-Framework werden nicht verwendet.
|
||||
- WebRTC verwendet [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`; das Upstream-Projekt steht unter MIT-Lizenz.
|
||||
- Die TeamSpeak-Protokollverbindung verwendet den projektgepflegten [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js)-SDK-Fork.
|
||||
|
||||
## 🧾 Änderungsprotokoll
|
||||
|
||||
| Version | Datum | Zusammenfassung |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Mitgliederplanung und direkte Verschiebung nach Berechtigung ergänzt; Avatar-, Stummschaltstatus- und Identitätsunterstützung hinzugefügt; Screenshots und Dokumentation für alle fünf Sprachen aktualisiert. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Browserseitige Mikrofon-Geräuschunterdrückung, russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt; Lautstärkeinteraktion und Fehlertexte/-codes auf Basis von PR #2 verbessert. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Verbindungsfehler auf der Willkommensseite verbessert, Fehlercodes erhalten und sicher gekürzt sowie IPv6-Ziele standardmäßig unterstützt. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Passwortabfrage, dedizierter Relay-Modus, Auswahl mehrerer Relays und Ursachendarstellung in der Administration ergänzt. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Docker-Bereitstellung vereinfacht, lokale TeamSpeak-Ziele unterstützt, 15-Sekunden-Timeout ergänzt und kontinuierliche Netzwerküberwachung eingeführt. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Deutsch, Telegram, Netzwerkleistung und Gesamtlautstärke ergänzt; Lautstärkeschwankungen beim Begleitton behoben. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Desktop-Begleitton, Hinweise zur gespeicherten Identität und Website-Symbol ergänzt; WebRTC-Mitgliederlautstärke korrigiert. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Identitätsspeicherung korrigiert und Designumschaltung verbessert. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | WebRTC und Kanalchat korrigiert sowie Administration, Protokolle und Mobilansicht verbessert. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Integriertes WebRTC, aktualisiertes TeamSpeak-SDK und bessere Mitgliedersynchronisierung und Sprachpufferung. |
|
||||
|
||||
Vollständige Historie: [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## 🚀 Bereitstellung
|
||||
|
||||
| Methode | Geeignet für | Umgebung |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (empfohlen) | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
|
||||
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64 |
|
||||
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.5+, Git und native Build-Werkzeuge |
|
||||
|
||||
### Docker Compose (empfohlen)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Nach dem Start ist WebSpeak unter `http://<dein-host>:3040` erreichbar. Bei einem Reverse Proxy auf diese Adresse zeigen; für WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben. Die Daten liegen im Volume `webspeak-data`.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
`docker compose down -v` nicht ausführen, da dadurch Datenbank und Administratoreinstellungen gelöscht werden.
|
||||
|
||||
### Release-Paket
|
||||
|
||||
Das passende `windows-x64.zip` oder `linux-x64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen, in ein eigenes Verzeichnis entpacken und `start-webspeak.cmd` bzw. `./start-webspeak.sh` starten. Die Pakete enthalten Node.js und Produktionsabhängigkeiten.
|
||||
|
||||
### Aus dem Quellcode
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain benötigt.
|
||||
|
||||
### Erste Konfiguration
|
||||
|
||||
1. `http://<dein-host>:3040/admin` öffnen.
|
||||
2. Mit `admin` / `admin` anmelden und sofort ein neues Passwort mit mindestens 12 Zeichen setzen.
|
||||
3. Unter **Server** TeamSpeak-Ziel und Zugriffsmethode konfigurieren, zum Beispiel `voice.example.com#9987`.
|
||||
4. Für öffentliche Nutzung HTTPS einrichten; bei aktiviertem WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben.
|
||||
|
||||
## ⚠️ Voraussetzungen und Hinweise
|
||||
|
||||
| Bereich | Hinweis |
|
||||
| --- | --- |
|
||||
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Mikrofon- und Fenster-Audio benötigen normalerweise HTTPS. |
|
||||
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können; der Standard-Sprachport ist `9987`. |
|
||||
| Webnetzwerk | Der Dienst verwendet `3040/TCP`; öffentlich sollte ein HTTPS-Reverse-Proxy für Seite und WebSocket verwendet werden. |
|
||||
| IPv6 | Literale Ziele als `[2001:db8::1]#9987` eintragen. Host/Container benötigen geroutetes IPv6, aktiviertes IPv6 in Betriebssystem und Node.js sowie passende Firewall-Regeln. |
|
||||
| WebRTC | Standardbereich `40000–40099/UDP`; den gesamten Bereich freigeben und WebRTC vor einer Änderung deaktivieren. |
|
||||
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung halten. Für parallele Verbindungen deaktivieren oder ein anderes Browserprofil verwenden. |
|
||||
| Begleitton | Nur auf dem Desktop verfügbar und WebRTC erforderlich. Bei Fenster- oder Tab-Freigabe auch Audio freigeben. |
|
||||
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
|
||||
| Sitzungslimit | Eine Instanz akzeptiert bis zu 100 aktive Browser-Sitzungen. |
|
||||
@@ -0,0 +1,227 @@
|
||||
# WebSpeak · English
|
||||
|
||||
[Project home](../README.md) · [简体中文](./README.zh-CN.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors can join channels without installing a desktop client, while administrators manage the target servers, access policy, and runtime state from the web console.
|
||||
|
||||
## Live demo
|
||||
|
||||
URL: <https://webspeak.example.invalid>
|
||||
|
||||
The public demo is hosted in Hong Kong and its network conditions and load may be unstable. Latency, disconnections, or temporary downtime do not represent every self-hosted deployment.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
| Capability | Description |
|
||||
| --- | --- |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target protocol. |
|
||||
| IPv6 targets | IPv6 TeamSpeak targets and IPv6 addresses resolved from hostnames are supported by default. |
|
||||
| Channels and members | Browse the channel tree, see live member states, and switch channels. |
|
||||
| Realtime voice | Opus audio with a compatibility transport and optional bundled WebRTC low-latency transport. |
|
||||
| Audio controls | Select microphones and speakers, adjust volume, test the microphone, mute, use VOX, and control member volume. |
|
||||
| Browser-side noise suppression | Optional microphone noise suppression runs at the browser capture stage, without adding server-side audio processing. |
|
||||
| Messaging and actions | Channel chat, server chat, private messages, poke actions, and whisper targets. |
|
||||
| Desktop accompaniment | Select an audio-enabled window or browser tab and share its sound with the current channel. |
|
||||
| Identity and access | Remembered identity, visitor-defined targets, and revocable expiring invite links. |
|
||||
| Administration | Manage targets, access policy, WebRTC, relays, invites, sessions, logs, diagnostics, and backups. |
|
||||
| User experience | Chinese, English, German, Russian, and Japanese UI, light/dark themes, and responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; Docker, Windows x64, and Linux x64 deployment options are provided. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
The screenshots show the English welcome page, voice workspace, audio controls, and member menu.
|
||||
|
||||
### Welcome page
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-home.png" alt="WebSpeak English welcome page" width="100%" /></p>
|
||||
|
||||
### Voice workspace
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en.png" alt="WebSpeak English voice workspace" width="100%" /></p>
|
||||
|
||||
### Audio controls
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-audio.png" alt="WebSpeak English audio controls" width="100%" /></p>
|
||||
|
||||
### Member menu
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-menu.png" alt="WebSpeak English member menu" width="100%" /></p>
|
||||
|
||||
## 🧩 Advanced features
|
||||
|
||||
These features are optional. WebSpeak continues to work with the compatibility voice transport when they are disabled. Configure them under **Administration → Servers**; saved changes apply to new connections.
|
||||
|
||||
### 1. WebRTC low-latency voice
|
||||
|
||||
WebRTC moves browser voice to a realtime media path and also enables desktop accompaniment. The current WebSpeak gateway provides it directly; no separate media server is required.
|
||||
|
||||
1. Sign in at `/admin` and open **Advanced settings** on the **Servers** page.
|
||||
2. While WebRTC is disabled, choose the UDP start and end ports. The default range is `40000–40099`.
|
||||
3. Allow the complete UDP range in the WebSpeak host's security group and firewall.
|
||||
4. Enable **WebRTC** and save. New visitors will negotiate WebRTC; unsupported browsers and networks fall back to the compatibility transport.
|
||||
|
||||
The port range is locked while WebRTC is enabled. Disable and save WebRTC before changing it, then update the firewall rules. Public deployments also need HTTPS.
|
||||
|
||||
### 2. Relay mode
|
||||
|
||||
Use a relay when a TeamSpeak server rejects connections from another region or when the direct path is unstable. It is not a VPN: it forwards only the TeamSpeak traffic of the current WebSpeak session, while the visitor still chooses the target server in the web page.
|
||||
|
||||
A relay instance is a dedicated forwarding service with no visitor page or administration console. It accepts only gateway sessions with a matching token. Use a random token of at least 16 characters.
|
||||
|
||||
#### Run from source
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### Run from a release package
|
||||
|
||||
Download and extract the appropriate package from [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest):
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
On Windows PowerShell, set the same variables and run `.\runtime\node.exe .\dist\index.js`.
|
||||
|
||||
#### Run with Docker
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Allow the relay host's UDP listen port, `39087` by default.
|
||||
|
||||
#### Enable it in the gateway
|
||||
|
||||
1. Open **Administration → Servers → Relay server** and add one or more nodes.
|
||||
2. Set a custom display name, endpoint such as `relay.example.com#39087`, and matching token for each node, then save.
|
||||
3. Visitors can choose direct access or one of the configured relays on the welcome page.
|
||||
|
||||
Disable and save the relay configuration to remove the relay option from the welcome page.
|
||||
|
||||
### 3. Dependencies and attribution
|
||||
|
||||
- The relay service is built into WebSpeak with Node.js standard libraries; it does not use GOST, sing-box, or another proxy framework.
|
||||
- WebRTC uses [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`, whose upstream project is licensed under MIT.
|
||||
- TeamSpeak protocol connectivity uses the project-maintained [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork.
|
||||
|
||||
## 🧾 Changelog
|
||||
|
||||
| Version | Date | Summary |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Added channel member scheduling and permission-aware direct moves; added avatar, mute-state, and remembered-identity support; refreshed feature screenshots and documentation for all five languages. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Added browser-side microphone noise suppression, Russian and Japanese UI, and per-language welcome text; refined volume interaction and error messages/codes on top of PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Improved welcome-page connection errors, preserved and safely truncated error codes, and added default IPv6 target support. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Added server-password prompts, formal relay mode, multiple relay selection, and administrator connection-reason reporting. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Simplified Docker deployment, supported local TeamSpeak targets, added a 15-second connection timeout, and made network monitoring continuous. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Added German, Telegram, network performance, and master-volume features; fixed accompaniment volume fluctuation. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Added desktop accompaniment, remembered-identity guidance, and the site icon; fixed WebRTC member volume. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Fixed identity persistence and refined the theme toggle. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | Fixed WebRTC and channel chat and refined administration, logs, and mobile layouts. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Added bundled WebRTC, migrated the TeamSpeak SDK, and improved member synchronization and voice buffering. |
|
||||
|
||||
See the complete history in [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## 🚀 Deployment
|
||||
|
||||
| Method | Best for | Environment |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (recommended) | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
|
||||
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64 |
|
||||
| From source | Development, debugging, and customization | Node.js 22.5+, Git, and native build tools |
|
||||
|
||||
### Docker Compose (recommended)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://<your-host>:3040` after startup. If using a reverse proxy, point it to that address. When WebRTC is enabled, allow the UDP range shown in the administration console. Data is stored in the `webspeak-data` volume.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Do not run `docker compose down -v`; it removes the database and administrator settings.
|
||||
|
||||
### Release package
|
||||
|
||||
Download the matching `windows-x64.zip` or `linux-x64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), extract it into a dedicated directory, and run `start-webspeak.cmd` on Windows or `./start-webspeak.sh` on Linux. Packages include the Node.js runtime and production dependencies.
|
||||
|
||||
### From source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
|
||||
|
||||
### First-time setup
|
||||
|
||||
1. Open `http://<your-host>:3040/admin`.
|
||||
2. Sign in with `admin` / `admin` and immediately set a new password of at least 12 characters.
|
||||
3. Configure the TeamSpeak target and access mode under **Servers**, for example `voice.example.com#9987`.
|
||||
4. Configure HTTPS for public access; when WebRTC is enabled, allow the UDP range shown in the console.
|
||||
|
||||
## ⚠️ Requirements and notes
|
||||
|
||||
| Area | Requirement or note |
|
||||
| --- | --- |
|
||||
| Browser | Use a current Chrome, Edge, or other modern browser with WebRTC support. Microphone and window audio normally require HTTPS. |
|
||||
| TeamSpeak network | The WebSpeak host must reach the target TeamSpeak server; the default voice port is `9987`. |
|
||||
| Web network | The service uses `3040/TCP`; public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
|
||||
| IPv6 | Write literal targets as `[2001:db8::1]#9987`. The host/container needs routed IPv6, IPv6 enabled in the OS and Node.js, and the relevant firewall rules. |
|
||||
| WebRTC | The default range is `40000–40099/UDP`; allow it and disable WebRTC before changing the range. |
|
||||
| Remembered identity | One browser identity can hold one active remembered connection. Disable it for parallel connections or use another browser profile. |
|
||||
| Accompaniment | Desktop only and requires WebRTC. Enable audio sharing when selecting a window or tab. |
|
||||
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
|
||||
| Session limit | One instance accepts up to 100 active browser sessions. |
|
||||
@@ -0,0 +1,132 @@
|
||||
# WebSpeak · 日本語
|
||||
|
||||
[プロジェクトトップ](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md)
|
||||
|
||||
## プロジェクト概要
|
||||
|
||||
| 観点 | 説明 |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak は TeamSpeak 3 / TeamSpeak 6 向けのセルフホスト型ブラウザクライアント兼音声ゲートウェイです。 |
|
||||
| **WHY** | デスクトップクライアントをインストールせず、ブラウザからチャンネルに参加できます。運用者はサーバーとデータを管理できます。 |
|
||||
| **HOW** | 起動後、管理コンソールで TeamSpeak の接続先とアクセス方針を設定します。ブラウザが画面と音声を担当し、WebSpeak がゲートウェイとして接続します。 |
|
||||
|
||||
## オンラインデモ
|
||||
|
||||
アドレス: <https://webspeak.example.invalid>
|
||||
|
||||
デモは香港にあります。ネットワークと負荷が不安定な場合があるため、遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
|
||||
|
||||
## ✨ 機能
|
||||
|
||||
| 機能 | 説明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak | TeamSpeak 3 / 6 に対応し、対象プロトコルを自動検出します。 |
|
||||
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
|
||||
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
|
||||
| リアルタイム音声 | Opus、互換トランスポート、内蔵 WebRTC による低遅延音声。 |
|
||||
| 音声操作 | マイク、スピーカー、音量、VOX、ミュート、メンバーごとの音量調整。 |
|
||||
| ブラウザ側ノイズ抑制 | マイクのノイズ抑制をブラウザの音声取得段階で任意に使用でき、サーバー側の追加処理は不要です。 |
|
||||
| チャットと操作 | チャンネル/サーバーチャット、個人メッセージ、つつく、ウィスパー対象。 |
|
||||
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
|
||||
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンク。 |
|
||||
| 管理コンソール | 接続先、アクセス、WebRTC、中継、招待、セッション、ログ、診断、バックアップ。 |
|
||||
| インターフェース | 中文、English、Deutsch、Русский、日本語、ライト/ダークテーマ、レスポンシブ表示。 |
|
||||
|
||||
## 🖼️ インターフェースのスクリーンショット
|
||||
|
||||
日本語のホーム、音声ワークスペース、オーディオ設定、メンバー操作メニューを掲載しています。
|
||||
|
||||
### ホーム
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-home.png" alt="WebSpeak 日本語ホーム" width="100%" /></p>
|
||||
|
||||
### 音声ワークスペース
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja.png" alt="WebSpeak 日本語音声ワークスペース" width="100%" /></p>
|
||||
|
||||
### オーディオ設定
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-audio.png" alt="WebSpeak 日本語オーディオ設定" width="100%" /></p>
|
||||
|
||||
### メンバーメニュー
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-menu.png" alt="WebSpeak 日本語メンバーメニュー" width="100%" /></p>
|
||||
|
||||
## 🧩 高度な機能
|
||||
|
||||
### WebRTC
|
||||
|
||||
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
|
||||
|
||||
### 中継サーバー
|
||||
|
||||
中継は現在の WebSpeak セッションの TeamSpeak 通信だけを転送し、VPN ではありません。管理コンソールで複数のノードに名前、アドレス、トークンを設定すると、ユーザーは直接接続または中継を選択できます。中継モードは専用の転送サービスとして動作し、ゲスト画面や管理コンソールを提供しません。
|
||||
|
||||
中継サービスは WebSpeak に組み込まれており、Node.js の標準ライブラリを使用します。GOST や sing-box などのプロキシフレームワークは不要です。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc)、TeamSpeak 接続はプロジェクトが保守する [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK を使用します。
|
||||
|
||||
## 🚀 デプロイ
|
||||
|
||||
| 方法 | 用途 |
|
||||
| --- | --- |
|
||||
| Docker Compose | 常時稼働サーバーと簡単な更新 |
|
||||
| Release パッケージ | Node.js やビルドツールを使わない起動 |
|
||||
| ソースから | 開発やカスタマイズ |
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
起動後に `http://<your-host>:3040/admin` を開き、`admin` / `admin` でログインして直ちにパスワードを変更し、TeamSpeak を設定します。データは `webspeak-data` volume に保存されます。データベースを消さない場合は `docker compose down -v` を実行しないでください。
|
||||
|
||||
### Release パッケージ
|
||||
|
||||
[Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) から Windows x64 または Linux x64 のパッケージを取得し、専用フォルダーに展開して `start-webspeak.cmd` または `./start-webspeak.sh` を実行します。
|
||||
|
||||
### ソースから
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ 要件と注意
|
||||
|
||||
- ソースからのビルドには Node.js `>=22.5` が必要です。Docker と Release には必要な実行環境が含まれます。
|
||||
- WebRTC に対応した最新の Chrome、Edge などを使用してください。マイクとウィンドウ音声には通常 HTTPS が必要です。
|
||||
- WebSpeak のホストから TeamSpeak に到達できる必要があります。標準音声ポートは `9987` です。
|
||||
- Web サービスは `3040/TCP` を使用します。公開時は HTTPS と WebSocket をリバースプロキシ経由で公開してください。
|
||||
- IPv6 にはルーティング可能な IPv6、OS/コンテナで有効な IPv6、適切なファイアウォール設定が必要です。リテラルは `[2001:db8::1]#9987` の形式です。
|
||||
- 保存したブラウザ ID は同じブラウザで同時に1接続だけ使用できます。
|
||||
- BGM共有はデスクトップのみで、WebRTC が必要です。
|
||||
|
||||
## コミュニティと関連プロジェクト
|
||||
|
||||
- [QQ グループ](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram グループ](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — Web コンソール付き TeamSpeak 音楽ボット。
|
||||
|
||||
## 🧾 更新履歴
|
||||
|
||||
| バージョン | 内容 |
|
||||
| --- | --- |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | チャンネルメンバーの移動操作と権限に応じた直接移動を追加し、アバター表示、ミュート状態の同期、保存 ID の復元に対応しました。5 言語のスクリーンショットとドキュメントも更新しました。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | ブラウザ側マイクノイズ抑制、ロシア語・日本語 UI、言語別ウェルカム文を追加。音量操作と PR #2 を基にしたエラー表示・エラーコードを改善しました。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 接続エラー表示を改善し、IPv6 接続先を標準対応しました。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | パスワード案内、正式な中継モード、複数中継選択、接続診断を追加しました。 |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | Docker 起動を簡略化し、15秒の接続タイムアウトと継続的なネットワーク監視を追加しました。 |
|
||||
|
||||
完全な履歴は [CHANGELOG.md](../CHANGELOG.md) を参照してください。
|
||||
|
||||
## ライセンス
|
||||
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で公開されています。
|
||||
@@ -0,0 +1,132 @@
|
||||
# WebSpeak · Русский
|
||||
|
||||
[Главная проекта](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [日本語](./README.ja.md)
|
||||
|
||||
## О проекте
|
||||
|
||||
| Логика | Описание |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak — самостоятельно размещаемый веб-клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. |
|
||||
| **WHY** | Пользователям не нужно устанавливать настольный клиент: достаточно открыть браузер, а оператор сохраняет контроль над сервером и данными. |
|
||||
| **HOW** | После запуска настройте цель TeamSpeak и политику доступа в панели администратора. Браузер отвечает за интерфейс и аудио, WebSpeak — за шлюз. |
|
||||
|
||||
## Онлайн-демо
|
||||
|
||||
Адрес: <https://webspeak.example.invalid>
|
||||
|
||||
Демо-сервер находится в Гонконге; сеть и нагрузка могут быть нестабильными. Задержки, разрывы или временная недоступность демо не характеризуют самостоятельное развертывание.
|
||||
|
||||
## ✨ Возможности
|
||||
|
||||
| Возможность | Описание |
|
||||
| --- | --- |
|
||||
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола. |
|
||||
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
|
||||
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
|
||||
| Голос в реальном времени | Opus, совместимый транспорт и встроенный WebRTC с низкой задержкой. |
|
||||
| Управление аудио | Микрофон, динамики, громкость, VOX, отключение микрофона и отдельная громкость участников. |
|
||||
| Шумоподавление в браузере | Опциональное шумоподавление микрофона на этапе захвата в браузере без дополнительной обработки звука на сервере. |
|
||||
| Чат и действия | Чат канала и сервера, личные сообщения, толчки и цели шёпота. |
|
||||
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
|
||||
| Идентичность и доступ | Сохранение идентичности, собственные цели и приглашения с ограничением срока и числа использований. |
|
||||
| Панель администратора | Цели, доступ, WebRTC, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
|
||||
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, светлая/тёмная тема и адаптивная верстка. |
|
||||
|
||||
## 🖼️ Скриншоты интерфейса
|
||||
|
||||
Скриншоты показывают русскую главную страницу, голосовое пространство, настройки аудио и меню участника.
|
||||
|
||||
### Главная страница
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-home.png" alt="Главная страница WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Голосовое пространство
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru.png" alt="Русское голосовое пространство WebSpeak" width="100%" /></p>
|
||||
|
||||
### Настройки аудио
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-audio.png" alt="Настройки аудио WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Меню участника
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-menu.png" alt="Меню участника WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
## 🧩 Расширенные функции
|
||||
|
||||
### WebRTC
|
||||
|
||||
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
|
||||
|
||||
### Ретрансляторы
|
||||
|
||||
Ретранслятор передаёт только TeamSpeak-трафик текущей сессии и не является VPN. В панели администратора добавьте один или несколько узлов, задайте имя, адрес и токен. Пользователь сможет выбрать прямое подключение или настроенный ретранслятор. Режим ретранслятора запускается отдельно и не предоставляет страницу посетителя или панель администратора.
|
||||
|
||||
Сервис ретрансляции встроен в WebSpeak и использует стандартные библиотеки Node.js; GOST, sing-box и другие прокси-фреймворки не требуются. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc), а TeamSpeak — поддерживаемый проектом [SDK EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js).
|
||||
|
||||
## 🚀 Развертывание
|
||||
|
||||
| Способ | Подходит для |
|
||||
| --- | --- |
|
||||
| Docker Compose | Постоянного сервера и простых обновлений |
|
||||
| Пакет Release | Запуска без Node.js и инструментов сборки |
|
||||
| Из исходников | Разработки и настройки проекта |
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
После запуска откройте `http://<ваш-хост>:3040/admin`, войдите с `admin` / `admin`, сразу смените пароль и настройте TeamSpeak. Данные хранятся в volume `webspeak-data`. Не используйте `docker compose down -v`, если не хотите удалить базу и настройки.
|
||||
|
||||
### Пакет Release
|
||||
|
||||
Скачайте подходящий пакет Windows x64 или Linux x64 из [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), распакуйте в отдельную папку и запустите `start-webspeak.cmd` или `./start-webspeak.sh`.
|
||||
|
||||
### Из исходников
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ Требования и замечания
|
||||
|
||||
- Node.js `>=22.5` нужен для сборки из исходников; Docker и Release уже содержат необходимые компоненты.
|
||||
- Нужен современный Chrome, Edge или другой браузер с WebRTC. Микрофон и звук окна обычно требуют HTTPS.
|
||||
- WebSpeak должен иметь доступ к TeamSpeak; стандартный голосовой порт — `9987`.
|
||||
- Веб-сервис использует `3040/TCP`; для публичного сайта направьте HTTPS и WebSocket через обратный прокси.
|
||||
- Для IPv6 нужен маршрутизируемый IPv6, включённый IPv6 в ОС/контейнере и правила firewall. Литерал задаётся как `[2001:db8::1]#9987`.
|
||||
- Одна сохранённая браузерная идентичность может использоваться только одним активным подключением.
|
||||
- Фоновая музыка доступна только на компьютере и требует WebRTC.
|
||||
|
||||
## Сообщество и проекты
|
||||
|
||||
- [QQ-группа](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram-группа](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — музыкальный бот для TeamSpeak с веб-консолью.
|
||||
|
||||
## 🧾 История изменений
|
||||
|
||||
| Версия | Изменения |
|
||||
| --- | --- |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | Добавлены управление перемещением участников и прямое перемещение с учётом прав; поддержаны аватары, синхронизация микрофона и восстановление идентичности; обновлены скриншоты и документация для пяти языков. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | Добавлены браузерное шумоподавление микрофона, русский и японский интерфейсы и отдельные тексты приветствия; улучшены управление громкостью и сообщения/коды ошибок на основе PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | Улучшены ошибки на странице входа и добавлена поддержка IPv6-целей по умолчанию. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | Добавлены подсказки пароля, режим ретранслятора, выбор нескольких узлов и диагностика подключений. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | Упрощён Docker-запуск, добавлен тайм-аут подключения 15 секунд и непрерывный сетевой мониторинг. |
|
||||
|
||||
Полная история находится в [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## Лицензия
|
||||
|
||||
WebSpeak распространяется по [GNU Affero General Public License v3.0 only](../LICENSE).
|
||||
@@ -0,0 +1,227 @@
|
||||
# WebSpeak · 简体中文
|
||||
|
||||
[返回项目首页](../README.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户无需安装桌面客户端即可从浏览器加入频道,管理员可以在控制台管理目标服务器、访问方式和运行状态。
|
||||
|
||||
## 在线 Demo
|
||||
|
||||
地址:<https://webspeak.example.invalid>
|
||||
|
||||
公共 Demo 位于香港,网络和负载可能不稳定。延迟、断线或暂时不可用不代表自行部署后的实际表现。
|
||||
|
||||
## ✨ 特性
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
|
||||
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
|
||||
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
|
||||
| 实时语音 | 使用 Opus,支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
|
||||
| 音频控制 | 选择麦克风与扬声器、调节音量、测试麦克风、闭麦、VOX 和成员独立音量。 |
|
||||
| 浏览器端降噪 | 提供可开关的麦克风降噪,在浏览器采集端处理,不增加服务器端音频处理压力。 |
|
||||
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
|
||||
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
|
||||
| 身份与访问 | 支持身份保持、访客自定义目标和可撤销、可过期的邀请链接。 |
|
||||
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
|
||||
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語、浅色/深色主题及响应式桌面/移动布局。 |
|
||||
| 自托管 | 数据由部署者保存,提供 Docker、Windows x64 和 Linux x64 方案。 |
|
||||
|
||||
## 🖼️ 界面截图
|
||||
|
||||
以下截图展示中文界面的欢迎页、语音工作区、音量控制和成员操作菜单。
|
||||
|
||||
### 欢迎页
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-home.png" alt="WebSpeak 中文欢迎页" width="100%" /></p>
|
||||
|
||||
### 语音工作区
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh.png" alt="WebSpeak 中文语音工作区" width="100%" /></p>
|
||||
|
||||
### 音量控制
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-audio.png" alt="WebSpeak 中文音量控制" width="100%" /></p>
|
||||
|
||||
### 成员菜单
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-menu.png" alt="WebSpeak 中文成员菜单" width="100%" /></p>
|
||||
|
||||
## 🧩 高级功能
|
||||
|
||||
高级功能均为可选项;关闭时仍可使用兼容语音传输。配置入口在管理员控制台的“服务器”页,保存后对新连接生效。
|
||||
|
||||
### 1. WebRTC 低延迟语音
|
||||
|
||||
WebRTC 将浏览器语音切换到实时媒体通道,也支持桌面端伴奏。媒体服务由当前 WebSpeak 网关直接提供,不需要另设媒体服务器。
|
||||
|
||||
1. 登录 `/admin`,打开“服务器”页的“高级参数”。
|
||||
2. 关闭 WebRTC 时设置 UDP 起止端口,默认范围为 `40000–40099`。
|
||||
3. 在 WebSpeak 主机的安全组和防火墙中放行整个 UDP 范围。
|
||||
4. 勾选“启用 WebRTC”并保存,用户重新进入后即可协商;不支持时会回退到兼容传输。
|
||||
|
||||
WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并保存,再修改端口并同步防火墙规则。公网使用还需要 HTTPS。
|
||||
|
||||
### 2. 中继模式
|
||||
|
||||
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
|
||||
|
||||
中继实例是专用转发服务,不提供前台和管理员后台,只接受带匹配令牌的 WebSpeak 网关会话。令牌至少使用 16 个字符的随机值。
|
||||
|
||||
#### 源码启动
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### 发布包启动
|
||||
|
||||
从 [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载并解压对应平台的包:
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell 使用同名环境变量后运行 `.\runtime\node.exe .\dist\index.js`。
|
||||
|
||||
#### Docker 启动
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
放行中继主机的 UDP 监听端口,默认是 `39087`。
|
||||
|
||||
#### 在网关中启用
|
||||
|
||||
1. 管理员控制台 → “服务器” → “中继服务器”,添加一个或多个节点。
|
||||
2. 为每个节点填写自定义名称、地址(例如 `relay.example.com#39087`)和匹配令牌并保存。
|
||||
3. 访客欢迎页即可选择直连或其中一个中继。
|
||||
|
||||
关闭并保存中继配置后,访客页面不会显示中继选项。
|
||||
|
||||
### 3. 依赖与归属
|
||||
|
||||
- 中继服务是 WebSpeak 自带实现,使用 Node.js 标准库,不依赖 GOST、sing-box 或其他代理框架。
|
||||
- WebRTC 使用 [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`,上游采用 MIT 许可证。
|
||||
- TeamSpeak 协议使用项目维护的 [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork。
|
||||
|
||||
## 🧾 更新日志
|
||||
|
||||
| 版本 | 日期 | 摘要 |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | 新增频道成员调度与按权限直接移动;支持头像、静音状态同步和身份恢复;更新五种语言的功能截图与文档。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | 提供浏览器端麦克风降噪、俄语和日语支持及按语言欢迎词配置;优化音量交互和 PR #2 基础上的错误提示与错误代码。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | 优化首页连接错误显示,保留并安全截断错误代码;默认支持 IPv6 TeamSpeak 目标。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | 增加服务器密码提示、正式中继部署模式、多中继选择和管理员日志原因显示。 |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | 简化 Docker 部署,支持同机 TeamSpeak,增加 15 秒连接超时和持续网络监测。 |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | 增加德语、Telegram、网络性能面板和整体音量;修复伴奏音量波动。 |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | 增加桌面端伴奏、身份保持提醒和网站图标;修复 WebRTC 成员独立音量。 |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | 修复身份保存逻辑并优化主题切换。 |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | 修复 WebRTC、频道聊天并优化管理页、日志和移动端布局。 |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | 引入内置 WebRTC、迁移 TeamSpeak SDK 并改善成员同步和语音缓冲。 |
|
||||
|
||||
完整记录见 [CHANGELOG.md](../CHANGELOG.md)。
|
||||
|
||||
## 🚀 部署方案
|
||||
|
||||
| 方案 | 适用场景 | 环境 |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
|
||||
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64 |
|
||||
| 源码运行 | 开发、调试和二次开发 | Node.js 22.5+、Git 和本地编译工具 |
|
||||
|
||||
### Docker Compose(推荐)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
启动后访问 `http://<你的主机>:3040`。使用反向代理时将上游指向该地址;启用 WebRTC 时放行控制台显示的 UDP 端口范围。数据保存在 `webspeak-data` volume 中。
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
升级:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
不要执行 `docker compose down -v`,否则会删除数据库和管理员设置。
|
||||
|
||||
### 发布包
|
||||
|
||||
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载对应的 `windows-x64.zip` 或 `linux-x64.tar.gz`,解压后运行 Windows 的 `start-webspeak.cmd` 或 Linux 的 `./start-webspeak.sh`。发布包自带 Node.js 运行时和生产依赖。
|
||||
|
||||
### 源码运行
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
|
||||
|
||||
### 首次配置
|
||||
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
2. 使用默认账号 `admin` / `admin` 登录,并立即设置至少 12 位的新密码。
|
||||
3. 在“服务器”页配置 TeamSpeak 目标和访问方式,例如 `voice.example.com#9987`。
|
||||
4. 公网使用时配置 HTTPS;启用 WebRTC 时放行控制台显示的 UDP 范围。
|
||||
|
||||
## ⚠️ 要求和注意事项
|
||||
|
||||
| 项目 | 要求或注意事项 |
|
||||
| --- | --- |
|
||||
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和窗口音频通常要求 HTTPS。 |
|
||||
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak;默认语音端口为 `9987`。 |
|
||||
| Web 服务网络 | 服务使用 `3040/TCP`,公网建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
|
||||
| IPv6 | IPv6 字面量写为 `[2001:db8::1]#9987`。主机/容器需要可路由 IPv6、启用 IPv6 的操作系统和 Node.js,以及相应防火墙放行。 |
|
||||
| WebRTC | 默认使用 `40000–40099/UDP`,启用后需放行整个范围;修改范围前先关闭 WebRTC。 |
|
||||
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接;并行连接请关闭第二条的身份保持或使用其他浏览器配置文件。 |
|
||||
| 伴奏 | 仅桌面端提供且要求 WebRTC;选择窗口或标签页时还要勾选共享音频。 |
|
||||
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
|
||||
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 61 KiB |
@@ -1,19 +1,19 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.1",
|
||||
"version": "0.2.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.1",
|
||||
"hasInstallScript": true,
|
||||
"version": "0.2.3",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak-client": "^0.2.2",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#0fd526637c44b9ddc83ea89793aca76765399a6a",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -61,6 +61,17 @@
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@echosixhiya/teamspeak-client": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#0fd526637c44b9ddc83ea89793aca76765399a6a",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||
@@ -503,16 +514,26 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@honeybbq/teamspeak-client": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak-client/-/teamspeak-client-0.2.2.tgz",
|
||||
"integrity": "sha512-JQ4yHEUwAxK2kHmIxelEf3grzMM8lVeuf7RzxK1g24U6XH8ZJO28S477FUtSTRe68PwUBkAlsa1Z/7BhLKh+AA==",
|
||||
"node_modules/@fidm/asn1": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@fidm/asn1/-/asn1-1.0.4.tgz",
|
||||
"integrity": "sha512-esd1jyNvRb2HVaQGq2Gg8Z0kbQPXzV9Tq5Z14KNIov6KfFD6PTaRIO8UpcsYiTNzOqJpmyzWgVTrUwFV3UF4TQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@fidm/x509": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@fidm/x509/-/x509-1.2.1.tgz",
|
||||
"integrity": "sha512-nwc2iesjyc9hkuzcrMCBXQRn653XuAUKorfWM8PZyJawiy1QzLj4vahwzaI25+pfpwOLvMzbJ0uKpWLDNmo16w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
"@fidm/asn1": "^1.0.4",
|
||||
"tweetnacl": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/fs-minipass": {
|
||||
@@ -527,6 +548,12 @@
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@leichtgewicht/ip-codec": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",
|
||||
"integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@noble/curves": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.2.0.tgz",
|
||||
@@ -554,12 +581,212 @@
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-cms": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.9.4.tgz",
|
||||
"integrity": "sha512-cben7oxmQsUGZqotus7yt0srYdncOT6RNWcTQ77T2RFOXejYVYkXadrfePdRcrVpO9K95IRLKKglG2k38jKXuw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"@peculiar/asn1-x509-attr": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-csr": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.9.4.tgz",
|
||||
"integrity": "sha512-xd4YN4vpRjkDAQWVfZZkeu12IEND7DOpkqaHSIHxZl1uggUNa9Ju0QxY2jHvDAS9pP0zhRBytg8ifsnGo3V0jw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-ecc": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.9.4.tgz",
|
||||
"integrity": "sha512-JJXefFshRAuVAjWQo/39bkg1ywc1VaiO44S8RRC+Ykvf/u2KDmYffoDb0ZBPCR5uJy4AGKQhl8mX+Q8ShcWaXQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-pfx": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.9.4.tgz",
|
||||
"integrity": "sha512-khuGzHTzNzk4GDlIBEILyIs6Lce0yn0ZBdoI9v93kmNncfZRhD+AQ5ODFqdhvoE8cMJF/JMTQ8yA+t1D14kqCw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-cms": "^2.9.4",
|
||||
"@peculiar/asn1-pkcs8": "^2.9.4",
|
||||
"@peculiar/asn1-rsa": "^2.9.4",
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-pkcs8": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.9.4.tgz",
|
||||
"integrity": "sha512-duRdotlUx9eDZe6QrQpQKl61RbWykCHBCkKayP8V8XdEFwlKHZ8qGGDMyS6Pye7OX7nLFttTTpRkJeet78ckwQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-pkcs9": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.9.4.tgz",
|
||||
"integrity": "sha512-kaL4cNxBpdQE2dKlyZBqz4ygCrwffO+8wfoxTEqM1Z8RadvCeELBRzcv0dzM8aY9azHMwODO5nxU65zXmhToOQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-cms": "^2.9.4",
|
||||
"@peculiar/asn1-pfx": "^2.9.4",
|
||||
"@peculiar/asn1-pkcs8": "^2.9.4",
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"@peculiar/asn1-x509-attr": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-rsa": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.9.4.tgz",
|
||||
"integrity": "sha512-pZ96eD1PptovcWQ/GSmuNFXd/7EQJNlKfDaNCyE2rx3W0v6QFelkzquVqRSRyyDXXCYD69ZXJDzZ8GhIiQzKoA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-schema": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.9.4.tgz",
|
||||
"integrity": "sha512-GjzePcT9Iw8NzeOPf73iNS9xM+TBhd/FilAfP+RQGkTMQJTVWtytN3JHJACCjf/ABNau5S7mS3g+DcuxmRgYEg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/utils": "^2.0.2",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-x509": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.9.4.tgz",
|
||||
"integrity": "sha512-CxhBo/RdEbMMob7T31ZdQjGuoyRFLVwrDzTn25bihzBasRg9kRm/0IxIPvhgQtcK/9dNcO1XQL2fuPugwELL0Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/utils": "^2.0.2",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/asn1-x509-attr": {
|
||||
"version": "2.9.4",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.9.4.tgz",
|
||||
"integrity": "sha512-ehQXbpQaQYycgu8OrvigwSPTFfVRcu0ECNYCWw+yzBp02Lw5paRqzzhUpfOgO2K38+WfFZuEz/0RPtam5g0OMg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.9.4",
|
||||
"@peculiar/asn1-x509": "^2.9.4",
|
||||
"asn1js": "^3.0.10",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/utils": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz",
|
||||
"integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@peculiar/x509": {
|
||||
"version": "1.14.3",
|
||||
"resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz",
|
||||
"integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-cms": "^2.6.0",
|
||||
"@peculiar/asn1-csr": "^2.6.0",
|
||||
"@peculiar/asn1-ecc": "^2.6.0",
|
||||
"@peculiar/asn1-pkcs9": "^2.6.0",
|
||||
"@peculiar/asn1-rsa": "^2.6.0",
|
||||
"@peculiar/asn1-schema": "^2.6.0",
|
||||
"@peculiar/asn1-x509": "^2.6.0",
|
||||
"pvtsutils": "^1.3.6",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"tslib": "^2.8.1",
|
||||
"tsyringe": "^4.10.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@pinojs/redact": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
|
||||
"integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@shinyoshiaki/binary-data": {
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@shinyoshiaki/binary-data/-/binary-data-0.6.1.tgz",
|
||||
"integrity": "sha512-7HDb/fQAop2bCmvDIzU5+69i+UJaFgIVp99h1VzK1mpg1JwSODOkjbqD7ilTYnqlnadF8C4XjpwpepxDsGY6+w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"generate-function": "^2.3.1",
|
||||
"is-plain-object": "^2.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/body-parser": {
|
||||
"version": "1.19.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
|
||||
@@ -581,6 +808,21 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/dom-mediacapture-transform": {
|
||||
"version": "0.1.12",
|
||||
"resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",
|
||||
"integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/dom-webcodecs": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/dom-webcodecs": {
|
||||
"version": "0.1.13",
|
||||
"resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
|
||||
"integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/express": {
|
||||
"version": "5.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
|
||||
@@ -728,6 +970,20 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1js": {
|
||||
"version": "3.0.10",
|
||||
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",
|
||||
"integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"pvtsutils": "^1.3.6",
|
||||
"pvutils": "^1.1.5",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/atomic-sleep": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
|
||||
@@ -743,6 +999,26 @@
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
|
||||
@@ -790,6 +1066,30 @@
|
||||
"concat-map": "0.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
@@ -939,6 +1239,18 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/dns-packet": {
|
||||
"version": "5.6.1",
|
||||
"resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz",
|
||||
"integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@leichtgewicht/ip-codec": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
@@ -1194,6 +1506,15 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/generate-function": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
|
||||
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-property": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
@@ -1343,6 +1664,26 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/inflight": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
||||
@@ -1378,12 +1719,39 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/is-plain-object": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz",
|
||||
"integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"isobject": "^3.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-promise": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
|
||||
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/is-property": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
|
||||
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/isobject": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
|
||||
"integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/make-dir": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
|
||||
@@ -1426,6 +1794,24 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/mediabunny": {
|
||||
"version": "1.55.5",
|
||||
"resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.55.5.tgz",
|
||||
"integrity": "sha512-m0v6y8FGXiK+HKOc3AZqU+kJPLYsSKaLitmQNQIIHZKIGlTwQ34OF+X6Ul0K8iV4b03oPse10apwuoqbvmKeAA==",
|
||||
"license": "MPL-2.0",
|
||||
"workspaces": [
|
||||
".",
|
||||
"packages/*"
|
||||
],
|
||||
"dependencies": {
|
||||
"@types/dom-mediacapture-transform": "^0.1.11",
|
||||
"@types/dom-webcodecs": "0.1.13"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/Vanilagy"
|
||||
}
|
||||
},
|
||||
"node_modules/merge-descriptors": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
|
||||
@@ -1502,6 +1888,19 @@
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/multicast-dns": {
|
||||
"version": "7.2.5",
|
||||
"resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz",
|
||||
"integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dns-packet": "^5.2.2",
|
||||
"thunky": "^1.0.2"
|
||||
},
|
||||
"bin": {
|
||||
"multicast-dns": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/negotiator": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
|
||||
@@ -1713,6 +2112,24 @@
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/pvtsutils": {
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
|
||||
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.1"
|
||||
}
|
||||
},
|
||||
"node_modules/pvutils": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
|
||||
"integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.15.2",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",
|
||||
@@ -1781,6 +2198,12 @@
|
||||
"node": ">= 12.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/reflect-metadata": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
|
||||
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/rimraf": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
|
||||
@@ -2091,6 +2514,12 @@
|
||||
"integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/thunky": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz",
|
||||
"integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/toidentifier": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||
@@ -2106,6 +2535,12 @@
|
||||
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tsx": {
|
||||
"version": "4.22.3",
|
||||
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.3.tgz",
|
||||
@@ -2125,6 +2560,30 @@
|
||||
"fsevents": "~2.3.3"
|
||||
}
|
||||
},
|
||||
"node_modules/tsyringe": {
|
||||
"version": "4.10.0",
|
||||
"resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz",
|
||||
"integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^1.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tsyringe/node_modules/tslib": {
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
|
||||
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tweetnacl": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
|
||||
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
|
||||
"license": "Unlicense"
|
||||
},
|
||||
"node_modules/type-is": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
|
||||
@@ -2207,6 +2666,70 @@
|
||||
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/werift": {
|
||||
"version": "0.24.4",
|
||||
"resolved": "https://registry.npmjs.org/werift/-/werift-0.24.4.tgz",
|
||||
"integrity": "sha512-NoROZ11L/ZqAB5ombCB4VBuVNdIZfwI493zlxlIX7BlwfWRy55eDJdtWMC2VX35yBXFaWwA8NtYbmJ8qWtVk9Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@fidm/x509": "^1.2.1",
|
||||
"@noble/curves": "^1.8.1",
|
||||
"@peculiar/x509": "^1.12.3",
|
||||
"@shinyoshiaki/binary-data": "^0.6.1",
|
||||
"buffer": "^6.0.3",
|
||||
"debug": "4.4.0",
|
||||
"mediabunny": "^1.45.2",
|
||||
"multicast-dns": "^7.2.5",
|
||||
"tweetnacl": "^1.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/werift/node_modules/@noble/curves": {
|
||||
"version": "1.9.7",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz",
|
||||
"integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "1.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^14.21.3 || >=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/werift/node_modules/@noble/hashes": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
|
||||
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^14.21.3 || >=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/werift/node_modules/debug": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
|
||||
"integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"supports-color": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-url": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.1",
|
||||
"version": "0.2.3",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -11,17 +11,21 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "tsx --test \"test/**/*.test.ts\"",
|
||||
"start": "node dist/index.js",
|
||||
"postinstall": "node scripts/patch-teamspeak-sdk.mjs",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "cd web && npx vite build"
|
||||
"web:build": "cd web && npx vite build",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs",
|
||||
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
|
||||
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
|
||||
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
|
||||
"acceleration:relay": "node dist/relay.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak-client": "^0.2.2",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#0fd526637c44b9ddc83ea89793aca76765399a6a",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# WebSpeak 加速通道 PoC
|
||||
|
||||
这是第一版隔离测试 Demo,不属于 WebSpeak 生产运行链路,也不会被复制到 Docker 镜像或发布包中。
|
||||
|
||||
它验证以下核心能力:
|
||||
|
||||
- 香港侧客户端向上海侧中继发起认证;
|
||||
- 每个会话动态指定 TeamSpeak 目标地址;
|
||||
- 双向 UDP 数据报转发,并保持数据包边界;
|
||||
- 会话之间按随机 ID 隔离;
|
||||
- 错误密钥不能建立会话;
|
||||
- 不修改系统路由,因此不是 VPN。
|
||||
|
||||
## 本地冒烟
|
||||
|
||||
在仓库根目录运行:
|
||||
|
||||
```bash
|
||||
npm run acceleration:poc
|
||||
```
|
||||
|
||||
成功时会输出 `ACCELERATION_POC_OK`,并显示数据包数量、丢包率和往返延迟。
|
||||
|
||||
IPv6 回环验证:
|
||||
|
||||
```bash
|
||||
npm run acceleration:ipv6-smoke
|
||||
```
|
||||
|
||||
## 通过隧道连接上海 TeamSpeak
|
||||
|
||||
下面的命令会让 SDK 连接本地代理端口,再由 PoC 中继把 UDP 数据转发到指定 TeamSpeak。它不进入指定频道,只验证 TeamSpeak 握手和断开:
|
||||
|
||||
```bash
|
||||
$env:WEBSPEAK_ACCEL_TS_TARGET="203.0.113.10#9987"
|
||||
npm run acceleration:sdk-smoke
|
||||
```
|
||||
|
||||
跨机器验证时,需要在上海启动 `relay-server.mjs`,再把 `WEBSPEAK_ACCEL_RELAY` 指向上海中继地址。当前项目不会自动部署或启动该远程进程。
|
||||
|
||||
## 手动启动中继
|
||||
|
||||
仅用于实验,不要直接暴露到公网:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_ACCEL_TOKEN="change-this-to-a-long-random-token" \
|
||||
WEBSPEAK_ACCEL_HOST="0.0.0.0" \
|
||||
WEBSPEAK_ACCEL_PORT="39087" \
|
||||
node scripts/acceleration-poc/relay-server.mjs
|
||||
```
|
||||
|
||||
当前 Demo 的 UDP 帧协议是实验协议,尚未接入 SDK,也没有替代 GOST 的生产安全审计。正式接入前仍需验证 TeamSpeak 长时间语音、并发会话、IPv6、断线重连和目标地址安全策略。
|
||||
@@ -0,0 +1,116 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
export const VERSION = 1;
|
||||
export const HEADER_SIZE = 34;
|
||||
export const MAX_PAYLOAD_SIZE = 60_000;
|
||||
|
||||
export const FrameType = Object.freeze({
|
||||
OPEN: 1,
|
||||
OPEN_OK: 2,
|
||||
OPEN_ERR: 3,
|
||||
DATA: 4,
|
||||
CLOSE: 5,
|
||||
PING: 6,
|
||||
PONG: 7,
|
||||
});
|
||||
|
||||
function asSecret(secret) {
|
||||
if (typeof secret !== "string" || secret.length < 16) {
|
||||
throw new Error("The PoC token must contain at least 16 characters");
|
||||
}
|
||||
return Buffer.from(secret, "utf8");
|
||||
}
|
||||
|
||||
function signFrame(frame, secret, payload) {
|
||||
return createHmac("sha256", asSecret(secret))
|
||||
.update(frame.subarray(0, 18))
|
||||
.update(payload)
|
||||
.digest()
|
||||
.subarray(0, 16);
|
||||
}
|
||||
|
||||
export function encodeFrame(type, sessionId, sequence, payload = Buffer.alloc(0), secret) {
|
||||
const body = Buffer.from(payload);
|
||||
if (!Number.isInteger(type) || type < 1 || type > 255) throw new Error("Invalid frame type");
|
||||
if (!Number.isInteger(sessionId) || sessionId < 0 || sessionId > 0xffffffff) throw new Error("Invalid session id");
|
||||
if (!Number.isInteger(sequence) || sequence < 0 || sequence > 0xffffffff) throw new Error("Invalid sequence");
|
||||
if (body.length > MAX_PAYLOAD_SIZE) throw new Error(`Payload exceeds ${MAX_PAYLOAD_SIZE} bytes`);
|
||||
|
||||
const frame = Buffer.alloc(HEADER_SIZE + body.length);
|
||||
MAGIC.copy(frame, 0);
|
||||
frame[4] = VERSION;
|
||||
frame[5] = type;
|
||||
frame.writeUInt16BE(0, 6);
|
||||
frame.writeUInt32BE(sessionId >>> 0, 8);
|
||||
frame.writeUInt32BE(sequence >>> 0, 12);
|
||||
frame.writeUInt16BE(body.length, 16);
|
||||
body.copy(frame, HEADER_SIZE);
|
||||
signFrame(frame, secret, body).copy(frame, 18);
|
||||
return frame;
|
||||
}
|
||||
|
||||
export function decodeFrame(packet) {
|
||||
const frame = Buffer.from(packet);
|
||||
if (frame.length < HEADER_SIZE || !frame.subarray(0, 4).equals(MAGIC)) return null;
|
||||
if (frame[4] !== VERSION) return null;
|
||||
const payloadLength = frame.readUInt16BE(16);
|
||||
if (frame.length !== HEADER_SIZE + payloadLength || payloadLength > MAX_PAYLOAD_SIZE) return null;
|
||||
return {
|
||||
type: frame[5],
|
||||
sessionId: frame.readUInt32BE(8),
|
||||
sequence: frame.readUInt32BE(12),
|
||||
payload: frame.subarray(HEADER_SIZE),
|
||||
auth: frame.subarray(18, HEADER_SIZE),
|
||||
raw: frame,
|
||||
};
|
||||
}
|
||||
|
||||
export function verifyFrame(frame, secret) {
|
||||
const expected = signFrame(frame.raw, secret, frame.payload);
|
||||
return timingSafeEqual(expected, frame.auth);
|
||||
}
|
||||
|
||||
export function randomSessionId() {
|
||||
let id = randomBytes(4).readUInt32BE(0);
|
||||
if (id === 0) id = 1;
|
||||
return id;
|
||||
}
|
||||
|
||||
export function jsonPayload(value) {
|
||||
return Buffer.from(JSON.stringify(value), "utf8");
|
||||
}
|
||||
|
||||
export function parseJsonPayload(payload) {
|
||||
try {
|
||||
return JSON.parse(Buffer.from(payload).toString("utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseEndpoint(value, defaultPort) {
|
||||
if (typeof value !== "string" || !value.trim()) throw new Error("Endpoint is required");
|
||||
const text = value.trim();
|
||||
if (text.startsWith("[")) {
|
||||
const end = text.indexOf("]");
|
||||
if (end < 0) throw new Error(`Invalid endpoint: ${value}`);
|
||||
const host = text.slice(1, end);
|
||||
const portText = text.slice(end + 1).replace(/^[:#]/, "");
|
||||
return { host, port: parsePort(portText || defaultPort, value) };
|
||||
}
|
||||
const hash = text.lastIndexOf("#");
|
||||
if (hash > 0) return { host: text.slice(0, hash), port: parsePort(text.slice(hash + 1), value) };
|
||||
const colon = text.lastIndexOf(":");
|
||||
if (colon > 0 && text.indexOf(":") === colon) {
|
||||
return { host: text.slice(0, colon), port: parsePort(text.slice(colon + 1), value) };
|
||||
}
|
||||
return { host: text, port: parsePort(defaultPort, value) };
|
||||
}
|
||||
|
||||
function parsePort(value, original) {
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid port in endpoint: ${original}`);
|
||||
return port;
|
||||
}
|
||||
|
||||
const MAGIC = Buffer.from("WSAT");
|
||||
@@ -0,0 +1,106 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { isIP } from "node:net";
|
||||
import { decodeFrame, encodeFrame, FrameType, jsonPayload, randomSessionId, parseEndpoint, verifyFrame } from "./protocol.mjs";
|
||||
|
||||
export async function createRelayClient({
|
||||
relayHost,
|
||||
relayPort,
|
||||
targetHost,
|
||||
targetPort,
|
||||
token,
|
||||
localHost = "127.0.0.1",
|
||||
localPort = 0,
|
||||
timeoutMs = 5_000,
|
||||
} = {}) {
|
||||
if (!relayHost || !Number.isInteger(relayPort)) throw new Error("Relay endpoint is required");
|
||||
if (!targetHost || !Number.isInteger(targetPort)) throw new Error("Target endpoint is required");
|
||||
const relayFamily = isIP(relayHost) === 6 ? "udp6" : "udp4";
|
||||
const localFamily = isIP(localHost) === 6 ? "udp6" : "udp4";
|
||||
const relaySocket = createSocket(relayFamily);
|
||||
const localSocket = createSocket(localFamily);
|
||||
const sessionId = randomSessionId();
|
||||
let sequence = 1;
|
||||
let peer = null;
|
||||
let ready = false;
|
||||
let closed = false;
|
||||
let resolveReady;
|
||||
let rejectReady;
|
||||
const readyPromise = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
|
||||
function sendFrame(type, payload = Buffer.alloc(0)) {
|
||||
const packet = encodeFrame(type, sessionId, sequence++, payload, token);
|
||||
relaySocket.send(packet, relayPort, relayHost);
|
||||
}
|
||||
|
||||
function closeSockets() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
try { relaySocket.close(); } catch {}
|
||||
try { localSocket.close(); } catch {}
|
||||
}
|
||||
|
||||
relaySocket.on("message", (packet) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || frame.sessionId !== sessionId || !verifyFrame(frame, token)) return;
|
||||
if (frame.type === FrameType.OPEN_OK) {
|
||||
ready = true;
|
||||
resolveReady();
|
||||
} else if (frame.type === FrameType.OPEN_ERR) {
|
||||
const detail = (() => { try { return JSON.parse(frame.payload.toString("utf8")); } catch { return {}; } })();
|
||||
rejectReady(new Error(detail.code ?? "ACCELERATION_OPEN_FAILED"));
|
||||
closeSockets();
|
||||
} else if (frame.type === FrameType.DATA && peer) {
|
||||
localSocket.send(frame.payload, peer.port, peer.address);
|
||||
} else if (frame.type === FrameType.CLOSE) {
|
||||
closeSockets();
|
||||
}
|
||||
});
|
||||
|
||||
const onSocketError = (error) => {
|
||||
if (!ready) rejectReady(error);
|
||||
closeSockets();
|
||||
};
|
||||
relaySocket.once("error", onSocketError);
|
||||
localSocket.once("error", onSocketError);
|
||||
|
||||
await Promise.all([
|
||||
new Promise((resolve) => relaySocket.bind(0, relayFamily === "udp6" ? "::" : "0.0.0.0", resolve)),
|
||||
new Promise((resolve) => localSocket.bind(localPort, localHost, resolve)),
|
||||
]);
|
||||
|
||||
localSocket.on("message", (payload, rinfo) => {
|
||||
if (closed) return;
|
||||
peer = { address: rinfo.address, port: rinfo.port };
|
||||
if (ready) sendFrame(FrameType.DATA, payload);
|
||||
});
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
rejectReady(new Error("ACCELERATION_OPEN_TIMEOUT"));
|
||||
closeSockets();
|
||||
}, timeoutMs);
|
||||
sendFrame(FrameType.OPEN, jsonPayload({ targetHost, targetPort }));
|
||||
try {
|
||||
await readyPromise;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
const localAddress = localSocket.address();
|
||||
return {
|
||||
sessionId,
|
||||
localHost,
|
||||
localPort: typeof localAddress === "object" ? localAddress.port : localPort,
|
||||
waitReady: () => readyPromise,
|
||||
close() {
|
||||
if (closed) return;
|
||||
if (ready) {
|
||||
try { sendFrame(FrameType.CLOSE); } catch {}
|
||||
}
|
||||
closeSockets();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function parseRelayEndpoint(value) {
|
||||
return parseEndpoint(value, 39087);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { decodeFrame, encodeFrame, FrameType, jsonPayload, parseJsonPayload, verifyFrame } from "./protocol.mjs";
|
||||
|
||||
function endpointKey(address, port) {
|
||||
return `${address}/${port}`;
|
||||
}
|
||||
|
||||
function isPrivateAddress(host) {
|
||||
const family = isIP(host);
|
||||
if (family === 4) {
|
||||
const octets = host.split(".").map(Number);
|
||||
return octets[0] === 10
|
||||
|| (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31)
|
||||
|| octets[0] === 192 && octets[1] === 168
|
||||
|| octets[0] === 127
|
||||
|| octets[0] === 169 && octets[1] === 254
|
||||
|| octets[0] === 0;
|
||||
}
|
||||
if (family === 6) {
|
||||
const normalized = host.toLowerCase();
|
||||
return normalized === "::1"
|
||||
|| normalized === "::"
|
||||
|| normalized.startsWith("fc")
|
||||
|| normalized.startsWith("fd")
|
||||
|| normalized.startsWith("fe8")
|
||||
|| normalized.startsWith("fe9")
|
||||
|| normalized.startsWith("fea")
|
||||
|| normalized.startsWith("feb");
|
||||
}
|
||||
return host === "localhost" || host.endsWith(".localhost");
|
||||
}
|
||||
|
||||
async function resolveTarget(host) {
|
||||
const family = isIP(host);
|
||||
if (family) return { host, family };
|
||||
const records = await lookup(host, { all: true, verbatim: true });
|
||||
const record = records.find((item) => item.family === 4) ?? records[0];
|
||||
if (!record) throw new Error("TARGET_DNS_EMPTY");
|
||||
return { host: record.address, family: record.family };
|
||||
}
|
||||
|
||||
export async function createRelayServer({
|
||||
host = "127.0.0.1",
|
||||
port = 0,
|
||||
token,
|
||||
allowPrivate = false,
|
||||
idleTimeoutMs = 30_000,
|
||||
} = {}) {
|
||||
const serverFamily = isIP(host) === 6 ? "udp6" : "udp4";
|
||||
const socket = createSocket(serverFamily);
|
||||
const sessions = new Map();
|
||||
let closed = false;
|
||||
|
||||
function sendToClient(session, type, payload = Buffer.alloc(0)) {
|
||||
if (closed) return;
|
||||
const packet = encodeFrame(type, session.id, session.outSequence++, payload, token);
|
||||
socket.send(packet, session.client.port, session.client.address);
|
||||
}
|
||||
|
||||
function cleanup(session) {
|
||||
if (!session || session.closed) return;
|
||||
session.closed = true;
|
||||
sessions.delete(session.id);
|
||||
session.targetSocket?.close();
|
||||
}
|
||||
|
||||
async function openSession(frame, client) {
|
||||
const request = parseJsonPayload(frame.payload);
|
||||
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) {
|
||||
return;
|
||||
}
|
||||
if (!allowPrivate && (isPrivateAddress(request.targetHost) || request.targetHost === "localhost")) {
|
||||
const error = { code: "PRIVATE_TARGET_BLOCKED" };
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address);
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = sessions.get(frame.sessionId);
|
||||
if (existing) cleanup(existing);
|
||||
const session = {
|
||||
id: frame.sessionId,
|
||||
client,
|
||||
clientKey: endpointKey(client.address, client.port),
|
||||
outSequence: 1,
|
||||
lastActivity: Date.now(),
|
||||
targetSocket: null,
|
||||
closed: false,
|
||||
};
|
||||
sessions.set(session.id, session);
|
||||
|
||||
try {
|
||||
const target = await resolveTarget(request.targetHost);
|
||||
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
|
||||
session.targetSocket = targetSocket;
|
||||
targetSocket.on("message", (payload) => {
|
||||
session.lastActivity = Date.now();
|
||||
sendToClient(session, FrameType.DATA, payload);
|
||||
});
|
||||
targetSocket.on("error", (error) => {
|
||||
if (!session.closed) sendToClient(session, FrameType.OPEN_ERR, jsonPayload({ code: "TARGET_SOCKET_ERROR", message: error.message }));
|
||||
cleanup(session);
|
||||
});
|
||||
targetSocket.connect(request.targetPort, target.host, () => {
|
||||
session.lastActivity = Date.now();
|
||||
sendToClient(session, FrameType.OPEN_OK, jsonPayload({ targetHost: target.host, targetPort: request.targetPort }));
|
||||
});
|
||||
} catch (error) {
|
||||
cleanup(session);
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "TARGET_OPEN_FAILED", message: error.message }), token), client.port, client.address);
|
||||
}
|
||||
}
|
||||
|
||||
socket.on("message", (packet, rinfo) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || !verifyFrame(frame, token)) return;
|
||||
const client = { address: rinfo.address, port: rinfo.port };
|
||||
if (frame.type === FrameType.OPEN) {
|
||||
void openSession(frame, client);
|
||||
return;
|
||||
}
|
||||
|
||||
const session = sessions.get(frame.sessionId);
|
||||
if (!session || session.clientKey !== endpointKey(rinfo.address, rinfo.port)) return;
|
||||
session.lastActivity = Date.now();
|
||||
if (frame.type === FrameType.DATA && session.targetSocket) {
|
||||
session.targetSocket.send(frame.payload);
|
||||
} else if (frame.type === FrameType.CLOSE) {
|
||||
sendToClient(session, FrameType.CLOSE);
|
||||
cleanup(session);
|
||||
} else if (frame.type === FrameType.PING) {
|
||||
sendToClient(session, FrameType.PONG);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("error", (error) => {
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
if (!closed) throw error;
|
||||
});
|
||||
|
||||
const sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const session of sessions.values()) {
|
||||
if (now - session.lastActivity > idleTimeoutMs) cleanup(session);
|
||||
}
|
||||
}, Math.max(1000, Math.min(idleTimeoutMs, 5000)));
|
||||
sweep.unref();
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const onError = (error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
|
||||
const address = socket.address();
|
||||
return {
|
||||
host,
|
||||
port: typeof address === "object" ? address.port : port,
|
||||
family: serverFamily,
|
||||
close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(sweep);
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
socket.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]?.replaceAll("\\", "/")}`) {
|
||||
const token = process.env.WEBSPEAK_ACCEL_TOKEN;
|
||||
if (!token) throw new Error("Set WEBSPEAK_ACCEL_TOKEN before starting the PoC relay");
|
||||
const host = process.env.WEBSPEAK_ACCEL_HOST ?? "0.0.0.0";
|
||||
const port = Number(process.env.WEBSPEAK_ACCEL_PORT ?? 39087);
|
||||
const server = await createRelayServer({ host, port, token });
|
||||
console.log(`ACCELERATION_RELAY_LISTEN ${server.host}:${server.port}`);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Client, generateIdentity } from "../../../teamspeak-js/dist/index.mjs";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { parseEndpoint } from "./protocol.mjs";
|
||||
|
||||
const token = process.env.WEBSPEAK_ACCEL_TOKEN ?? "local-acceleration-poc-token";
|
||||
const target = parseEndpoint(process.env.WEBSPEAK_ACCEL_TS_TARGET ?? "203.0.113.10#9987", 9987);
|
||||
const relayEndpoint = process.env.WEBSPEAK_ACCEL_RELAY;
|
||||
let relayServer = null;
|
||||
let relayClient = null;
|
||||
let tsClient = null;
|
||||
|
||||
function withTimeout(promise, timeoutMs, label) {
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error(`${label}_TIMEOUT`)), timeoutMs)),
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
let relay;
|
||||
if (relayEndpoint) {
|
||||
relay = parseEndpoint(relayEndpoint, 39087);
|
||||
} else {
|
||||
relayServer = await createRelayServer({ host: "127.0.0.1", port: 0, token, allowPrivate: true });
|
||||
relay = { host: "127.0.0.1", port: relayServer.port };
|
||||
}
|
||||
|
||||
relayClient = await createRelayClient({
|
||||
relayHost: relay.host,
|
||||
relayPort: relay.port,
|
||||
targetHost: target.host,
|
||||
targetPort: target.port,
|
||||
token,
|
||||
});
|
||||
|
||||
tsClient = new Client(generateIdentity(8), `127.0.0.1:${relayClient.localPort}`, "acceleration-sdk-smoke");
|
||||
await withTimeout(tsClient.connect(), 15_000, "TS_CONNECT");
|
||||
console.log(`TS_ACCEL_CONNECTED target=${target.host}#${target.port}`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
await tsClient.disconnect();
|
||||
console.log("TS_ACCEL_DISCONNECTED");
|
||||
} catch (error) {
|
||||
console.error("TS_ACCEL_SMOKE_FAILED", error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
try { await tsClient?.disconnect(); } catch {}
|
||||
relayClient?.close();
|
||||
relayServer?.close();
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
|
||||
const TOKEN = "local-ipv6-acceleration-poc-token";
|
||||
const PACKET_COUNT = 50;
|
||||
|
||||
function bind(socket, port = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.bind(port, "::1", () => {
|
||||
socket.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const target = createSocket("udp6");
|
||||
target.on("message", (payload, rinfo) => target.send(payload, rinfo.port, rinfo.address));
|
||||
await bind(target);
|
||||
const targetPort = target.address().port;
|
||||
|
||||
const relay = await createRelayServer({ host: "::1", port: 0, token: TOKEN, allowPrivate: true });
|
||||
const client = await createRelayClient({
|
||||
relayHost: "::1",
|
||||
relayPort: relay.port,
|
||||
targetHost: "::1",
|
||||
targetPort,
|
||||
token: TOKEN,
|
||||
localHost: "::1",
|
||||
});
|
||||
|
||||
const sender = createSocket("udp6");
|
||||
await bind(sender);
|
||||
const pending = new Set(Array.from({ length: PACKET_COUNT }, (_, index) => index));
|
||||
sender.on("message", (payload) => pending.delete(payload.readUInt32BE(0)));
|
||||
for (let index = 0; index < PACKET_COUNT; index++) {
|
||||
const payload = Buffer.alloc(512, index & 0xff);
|
||||
payload.writeUInt32BE(index, 0);
|
||||
sender.send(payload, client.localPort, "::1");
|
||||
}
|
||||
|
||||
const deadline = Date.now() + 3000;
|
||||
while (pending.size && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
const received = PACKET_COUNT - pending.size;
|
||||
|
||||
sender.close();
|
||||
client.close();
|
||||
relay.close();
|
||||
target.close();
|
||||
console.log(`ipv6_packets=${PACKET_COUNT} received=${received} loss=${((pending.size / PACKET_COUNT) * 100).toFixed(2)}%`);
|
||||
if (received !== PACKET_COUNT) throw new Error("IPV6_ACCELERATION_POC_FAILED");
|
||||
console.log("IPV6_ACCELERATION_POC_OK");
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
|
||||
const TOKEN = "local-acceleration-poc-token";
|
||||
const PACKET_COUNT = 200;
|
||||
const PACKET_SIZE = 1920;
|
||||
|
||||
function bind(socket, port = 0) {
|
||||
return new Promise((resolve) => socket.bind(port, "127.0.0.1", resolve));
|
||||
}
|
||||
|
||||
function close(socket) {
|
||||
try { socket.close(); } catch {}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const target = createSocket("udp4");
|
||||
target.on("message", (payload, rinfo) => {
|
||||
target.send(payload, rinfo.port, rinfo.address);
|
||||
});
|
||||
await bind(target);
|
||||
const targetAddress = target.address();
|
||||
|
||||
const relay = await createRelayServer({
|
||||
host: "127.0.0.1",
|
||||
port: 0,
|
||||
token: TOKEN,
|
||||
allowPrivate: true,
|
||||
});
|
||||
const client = await createRelayClient({
|
||||
relayHost: "127.0.0.1",
|
||||
relayPort: relay.port,
|
||||
targetHost: "127.0.0.1",
|
||||
targetPort: targetAddress.port,
|
||||
token: TOKEN,
|
||||
});
|
||||
|
||||
let rejectedBadToken = false;
|
||||
try {
|
||||
const badClient = await createRelayClient({
|
||||
relayHost: "127.0.0.1",
|
||||
relayPort: relay.port,
|
||||
targetHost: "127.0.0.1",
|
||||
targetPort: targetAddress.port,
|
||||
token: "wrong-token-that-is-long-enough",
|
||||
timeoutMs: 250,
|
||||
});
|
||||
badClient.close();
|
||||
} catch {
|
||||
rejectedBadToken = true;
|
||||
}
|
||||
|
||||
const sender = createSocket("udp4");
|
||||
await bind(sender);
|
||||
const pending = new Map();
|
||||
const samples = [];
|
||||
sender.on("message", (payload) => {
|
||||
const id = payload.readUInt32BE(0);
|
||||
const sentAt = pending.get(id);
|
||||
if (sentAt !== undefined) {
|
||||
pending.delete(id);
|
||||
samples.push(Number(process.hrtime.bigint() - sentAt) / 1_000_000);
|
||||
}
|
||||
});
|
||||
|
||||
for (let id = 0; id < PACKET_COUNT; id++) {
|
||||
const payload = Buffer.alloc(PACKET_SIZE, id & 0xff);
|
||||
payload.writeUInt32BE(id, 0);
|
||||
pending.set(id, process.hrtime.bigint());
|
||||
sender.send(payload, client.localPort, "127.0.0.1");
|
||||
await new Promise((resolve) => setTimeout(resolve, 1));
|
||||
}
|
||||
|
||||
const deadline = Date.now() + 5_000;
|
||||
while (pending.size && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
const received = samples.length;
|
||||
const loss = ((PACKET_COUNT - received) / PACKET_COUNT) * 100;
|
||||
const sorted = [...samples].sort((a, b) => a - b);
|
||||
const percentile = (ratio) => sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * ratio))] : 0;
|
||||
const average = sorted.length ? sorted.reduce((sum, value) => sum + value, 0) / sorted.length : 0;
|
||||
|
||||
sender.close();
|
||||
client.close();
|
||||
relay.close();
|
||||
target.close();
|
||||
|
||||
console.log(`relay=127.0.0.1:${relay.port}`);
|
||||
console.log(`packets=${PACKET_COUNT} received=${received} loss=${loss.toFixed(2)}%`);
|
||||
console.log(`rtt_ms_avg=${average.toFixed(3)} p95=${Number(percentile(0.95)).toFixed(3)} max=${Number(percentile(0.99)).toFixed(3)}`);
|
||||
console.log(`bad_token_rejected=${rejectedBadToken}`);
|
||||
if (received !== PACKET_COUNT || !rejectedBadToken) throw new Error("ACCELERATION_POC_FAILED");
|
||||
console.log("ACCELERATION_POC_OK");
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -1,183 +0,0 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const packageRoot = path.join(root, "node_modules", "@honeybbq", "teamspeak-client");
|
||||
const marker = "webspeak-directory-snapshot-v2";
|
||||
const whisperMarker = "webspeak-team-whisper-v1";
|
||||
|
||||
const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
|
||||
if (packageJson.version !== "0.2.2") {
|
||||
throw new Error(`Unsupported @honeybbq/teamspeak-client version: ${packageJson.version}`);
|
||||
}
|
||||
|
||||
const cjsPath = path.join(packageRoot, "dist", "index.cjs");
|
||||
const mjsPath = path.join(packageRoot, "dist", "index.mjs");
|
||||
const handlerCjsPath = path.join(packageRoot, "dist", "handler-CqCD93f0.cjs");
|
||||
const handlerMjsPath = path.join(packageRoot, "dist", "handler-C_JhqGTd.js");
|
||||
const [cjs, mjs, handlerCjs, handlerMjs] = await Promise.all([
|
||||
readFile(cjsPath, "utf8"),
|
||||
readFile(mjsPath, "utf8"),
|
||||
readFile(handlerCjsPath, "utf8"),
|
||||
readFile(handlerMjsPath, "utf8"),
|
||||
]);
|
||||
|
||||
const patchedCjs = patchWhisperClient(patchCjs(cjs), "cjs");
|
||||
const patchedMjs = patchWhisperClient(patchMjs(mjs), "mjs");
|
||||
const patchedHandlerCjs = patchWhisperHandler(handlerCjs, "cjs");
|
||||
const patchedHandlerMjs = patchWhisperHandler(handlerMjs, "mjs");
|
||||
await Promise.all([
|
||||
writeFile(cjsPath, patchedCjs, "utf8"),
|
||||
writeFile(mjsPath, patchedMjs, "utf8"),
|
||||
writeFile(handlerCjsPath, patchedHandlerCjs, "utf8"),
|
||||
writeFile(handlerMjsPath, patchedHandlerMjs, "utf8"),
|
||||
]);
|
||||
|
||||
function patchWhisperClient(source, format) {
|
||||
if (source.includes(whisperMarker)) return source;
|
||||
if (format === "cjs") {
|
||||
const needle = "sendVoice(e,t){this.handler.sendVoicePacket(e,t)}";
|
||||
if (!source.includes(needle)) throw new Error("Could not patch CJS SDK client whisper method");
|
||||
return source.replace(needle, `${needle}sendWhisper(e,t,n){this.handler.sendWhisperPacket(e,t,n)}`) + `/* ${whisperMarker} */`;
|
||||
}
|
||||
const needle = "\tsendVoice(e, t) {\n\t\tthis.handler.sendVoicePacket(e, t);\n\t}\n";
|
||||
if (!source.includes(needle)) throw new Error("Could not patch MJS SDK client whisper method");
|
||||
return source.replace(needle, `${needle}\tsendWhisper(e, t, n) {\n\t\tthis.handler.sendWhisperPacket(e, t, n);\n\t}\n`) + `/* ${whisperMarker} */`;
|
||||
}
|
||||
|
||||
function patchWhisperHandler(source, format) {
|
||||
if (source.includes(whisperMarker)) return source;
|
||||
if (format === "cjs") {
|
||||
const needle = "this.#b(u)}close(){";
|
||||
if (!source.includes(needle)) throw new Error("Could not patch CJS SDK whisper packet handler");
|
||||
const method = `/* ${whisperMarker} */sendWhisperPacket(e,t,n){if(t.length>32)throw new Error(\`too many whisper targets\`);let a=this.#c[r.VoiceWhisper],o=this.#l[r.VoiceWhisper];this.#c[r.VoiceWhisper]=a+1&65535,this.#c[r.VoiceWhisper]===0&&this.#l[r.VoiceWhisper]++;let s=5+2*t.length+e.length,l=new Uint8Array(s),u=new DataView(l.buffer);u.setUint16(0,a,!1),l[2]=n,l[3]=0,l[4]=t.length;for(let n=0;n<t.length;n++)u.setUint16(5+2*n,t[n],!1);l.set(e,5+2*t.length);let c0=c({typeFlagged:r.VoiceWhisper|i.Unencrypted,id:a,clientID:this.#r,generationID:o,data:l,receivedAt:0}),d=new Uint8Array(x+b+s);d.set(this.#e.fakeSignature,0),d.set(c0,x),d.set(l,x+b),this.#b(d)}`;
|
||||
return source.replace(needle, `this.#b(u)}${method}close(){`);
|
||||
}
|
||||
const needle = "this.#b(u);\n\t}\n\tclose() {";
|
||||
if (!source.includes(needle)) throw new Error("Could not patch MJS SDK whisper packet handler");
|
||||
const method = `\t/* ${whisperMarker} */\n\tsendWhisperPacket(e, t, n) {\n\t\tif (t.length > 32) throw new Error("too many whisper targets");\n\t\tlet a = this.#c[r.VoiceWhisper], o = this.#l[r.VoiceWhisper];\n\t\tthis.#c[r.VoiceWhisper] = a + 1 & 65535;\n\t\tif (this.#c[r.VoiceWhisper] === 0) this.#l[r.VoiceWhisper]++;\n\t\tconst s = 5 + 2 * t.length + e.length, l = new Uint8Array(s), u = new DataView(l.buffer);\n\t\tu.setUint16(0, a, false);\n\t\tl[2] = n;\n\t\tl[3] = 0;\n\t\tl[4] = t.length;\n\t\tfor (let n = 0; n < t.length; n++) u.setUint16(5 + 2 * n, t[n], false);\n\t\tl.set(e, 5 + 2 * t.length);\n\t\tconst c0 = c({ typeFlagged: r.VoiceWhisper | i.Unencrypted, id: a, clientID: this.#r, generationID: o, data: l, receivedAt: 0 });\n\t\tconst d = new Uint8Array(x + b + s);\n\t\td.set(this.#e.fakeSignature, 0);\n\t\td.set(c0, x);\n\t\td.set(l, x + b);\n\t\tthis.#b(d);\n\t}\n\tclose() {`;
|
||||
return source.replace(needle, `this.#b(u);\n\t}\n${method}`);
|
||||
}
|
||||
|
||||
function patchCjs(source) {
|
||||
if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source;
|
||||
|
||||
const helper = `/* ${marker} */
|
||||
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
|
||||
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
|
||||
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}}
|
||||
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
|
||||
`;
|
||||
source = source.replace("var K=class", `${helper}var K=class`);
|
||||
|
||||
// TS6 reports a client that moved out of our current view as
|
||||
// notifyclientleftview with a non-zero ctid. Preserve that client and apply
|
||||
// the target channel; ctid=0 is the actual server leave case.
|
||||
const replacements = [
|
||||
[
|
||||
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t;return r!==0&&n.delete(r),{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
|
||||
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t,o=A(e.params.ctid??``),s=o!==0n;if(r!==0)if(s){let e=n.get(r);e&&n.set(r,{...e,channelID:o})}else n.delete(r);return s?{kind:`clientMoved`,event:{id:r,targetChannelID:o,reasonID:i,invokerID:j(e.params.invokerid??``),invokerName:e.params.invokername??``,invokerUID:e.params.invokeruid??``}}:{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
|
||||
],
|
||||
[
|
||||
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
|
||||
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#q=new Map;#R=[];#L=!1;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
|
||||
],
|
||||
[
|
||||
"case`voiceData`:this.#h.push(t);break;case`connected`:",
|
||||
"case`voiceData`:this.#h.push(t);break;case`directorySnapshot`:this.#R.push(t);break;case`connected`:",
|
||||
],
|
||||
[
|
||||
"this.#o.reset(),this.#s.reset(),this.#c.clear(),this.clid=0",
|
||||
"this.#o.reset(),this.#s.reset(),this.#q.clear(),this.#c.clear(),this.#L=!1,this.clid=0",
|
||||
],
|
||||
[
|
||||
"case`initserver`:w(this,t.params);break;case`error`:this.#A(t.params);break;default:{",
|
||||
"case`initserver`:w(this,t.params);break;case`channellist`:{let e=webSpeakDirectoryChannel(t.params,a.i);e&&this.#q.set(e.id,e),this.#Y();break}case`channelclientlist`:{let e=webSpeakDirectoryClient(t.params,a.i);e&&this.#c.set(e.id,e),this.#Y();break}case`error`:this.#A(t.params);break;default:{",
|
||||
],
|
||||
[
|
||||
"if(t.name.startsWith(`notify`)){let e=F(t,this.clid,this.#c,this.nickname);this.#j(e,t.params);return}",
|
||||
"if(t.name.startsWith(`notify`)){let e=webSpeakDirectoryChannelNotification(t.name,t.params,a.i,this.#q),n=F(t,this.clid,this.#c,this.nickname);this.#j(n,t.params),e&&this.#Y();return}",
|
||||
],
|
||||
[
|
||||
"case`clientEnter`:{let t=e.info;t.id!==0&&N(this.nickname,t.nickname)&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete()),this.#M(`clientEnter`,t);break}",
|
||||
"case`clientEnter`:{let t=e.info,r=webSpeakDirectoryBigInt(arguments[1]?.cid??arguments[1]?.ctid??\"0\");r!==0n&&(t={...t,channelID:r},this.#c.set(t.id,t));let n=this.#c.get(t.id);n&&t.channelID===0n&&n.channelID!==0n&&(t={...t,channelID:n.channelID},this.#c.set(t.id,t));let i=t.id!==0&&N(this.nickname,t.nickname);i&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete(),this.#Y()),this.#M(`clientEnter`,t),!i&&this.#i===2&&this.#Y();break}",
|
||||
],
|
||||
[
|
||||
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event);break;",
|
||||
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),this.#i===2&&this.#Y(),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event),this.#i===2&&this.#Y();break;",
|
||||
],
|
||||
[
|
||||
"#M(e,t){this.#S(t)}#N(e,t){",
|
||||
"#Y(){if(this.#L)return;this.#L=!0,setImmediate(()=>{this.#L=!1;const e={channels:Array.from(this.#q.values()).map(e=>({...e})),clients:Array.from(this.#c.values()).map(e=>({...e,serverGroups:[...(e.serverGroups??[])]}))};for(const t of this.#R)setImmediate(()=>t(e))})}#M(e,t){this.#S(t)}#N(e,t){",
|
||||
],
|
||||
];
|
||||
|
||||
for (const [before, after] of replacements) {
|
||||
if (!source.includes(before)) throw new Error(`Could not patch CJS SDK segment: ${before.slice(0, 80)}`);
|
||||
source = source.replace(before, after);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function patchMjs(source) {
|
||||
if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source;
|
||||
|
||||
const helper = `/* ${marker} */
|
||||
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
|
||||
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
|
||||
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}}
|
||||
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
|
||||
`;
|
||||
source = source.replace("var k = class", `${helper}var k = class`);
|
||||
|
||||
// Keep the readable ESM build behavior identical to the minified CJS build.
|
||||
const replacements = [
|
||||
[
|
||||
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t;\n\treturn r !== 0 && n.delete(r), {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
|
||||
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t, targetChannelID = J(e.params.ctid ?? \"\"), moved = targetChannelID !== 0n;\n\tif (r !== 0) {\n\t\tif (moved) {\n\t\t\tconst current = n.get(r);\n\t\t\tif (current) n.set(r, { ...current, channelID: targetChannelID });\n\t\t} else {\n\t\t\tn.delete(r);\n\t\t}\n\t}\n\treturn moved ? {\n\t\tkind: \"clientMoved\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\ttargetChannelID,\n\t\t\treasonID: i,\n\t\t\tinvokerID: Y(e.params.invokerid ?? \"\"),\n\t\t\tinvokerName: e.params.invokername ?? \"\",\n\t\t\tinvokerUID: e.params.invokeruid ?? \"\"\n\t\t}\n\t} : {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
|
||||
],
|
||||
[
|
||||
"\t#c = /* @__PURE__ */ new Map();\n\t#l = [];",
|
||||
"\t#c = /* @__PURE__ */ new Map();\n\t#q = /* @__PURE__ */ new Map();\n\t#R = [];\n\t#L = false;\n\t#l = [];",
|
||||
],
|
||||
[
|
||||
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
|
||||
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"directorySnapshot\":\n\t\t\t\tthis.#R.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
|
||||
],
|
||||
[
|
||||
"this.#o.reset(), this.#s.reset(), this.#c.clear(), this.clid = 0",
|
||||
"this.#o.reset(), this.#s.reset(), this.#q.clear(), this.#c.clear(), this.#L = false, this.clid = 0",
|
||||
],
|
||||
[
|
||||
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":",
|
||||
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"channellist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryChannel(t.params, S);\n\t\t\t\t\tif (e) this.#q.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"channelclientlist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryClient(t.params, S);\n\t\t\t\t\tif (e) this.#c.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"error\":",
|
||||
],
|
||||
[
|
||||
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\treturn;\n\t\t\t}",
|
||||
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tconst directoryChanged = webSpeakDirectoryChannelNotification(t.name, t.params, S, this.#q);\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\tif (directoryChanged) this.#Y();\n\t\t\t\treturn;\n\t\t\t}",
|
||||
],
|
||||
[
|
||||
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tt.id !== 0 && Z(this.nickname, t.nickname) && (this.clid = t.id, this.handler.setClientID(t.id), this.#o.signalWelcomeComplete()), this.#M(\"clientEnter\", t);\n\t\t\t\tbreak;\n\t\t\t}",
|
||||
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tconst rawChannelID = webSpeakDirectoryBigInt(arguments[1]?.cid ?? arguments[1]?.ctid ?? \"0\");\n\t\t\t\tif (rawChannelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: rawChannelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst cached = this.#c.get(t.id);\n\t\t\t\tif (cached && t.channelID === 0n && cached.channelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: cached.channelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst own = t.id !== 0 && Z(this.nickname, t.nickname);\n\t\t\t\tif (own) {\n\t\t\t\t\tthis.clid = t.id;\n\t\t\t\t\tthis.handler.setClientID(t.id);\n\t\t\t\t\tthis.#o.signalWelcomeComplete();\n\t\t\t\t\tthis.#Y();\n\t\t\t\t}\n\t\t\t\tthis.#M(\"clientEnter\", t);\n\t\t\t\tif (!own && this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;\n\t\t\t}",
|
||||
],
|
||||
[
|
||||
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
|
||||
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), this.#i === n.Connected && this.#Y(), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
|
||||
],
|
||||
[
|
||||
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tbreak;",
|
||||
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tif (this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;",
|
||||
],
|
||||
[
|
||||
"\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
|
||||
"\t#Y() {\n\t\tif (this.#L) return;\n\t\tthis.#L = true;\n\t\tsetImmediate(() => {\n\t\t\tthis.#L = false;\n\t\t\tconst e = {\n\t\t\t\tchannels: Array.from(this.#q.values()).map((item) => ({ ...item })),\n\t\t\t\tclients: Array.from(this.#c.values()).map((item) => ({ ...item, serverGroups: [...(item.serverGroups ?? [])] })),\n\t\t\t};\n\t\t\tfor (const handler of this.#R) setImmediate(() => handler(e));\n\t\t});\n\t}\n\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
|
||||
],
|
||||
];
|
||||
|
||||
for (const [before, after] of replacements) {
|
||||
if (!source.includes(before)) throw new Error(`Could not patch MJS SDK segment: ${before.slice(0, 80)}`);
|
||||
source = source.replace(before, after);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { cpSync, existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import process from "node:process";
|
||||
|
||||
const root = process.cwd();
|
||||
const sdkPackage = "@echosixhiya/teamspeak-client";
|
||||
const packageJson = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
||||
const dependency = packageJson.dependencies?.[sdkPackage];
|
||||
const match = typeof dependency === "string" ? /^git\+(.+?)#(.+)$/.exec(dependency) : null;
|
||||
|
||||
if (!match) {
|
||||
throw new Error(`${sdkPackage} must be pinned to a Git repository commit`);
|
||||
}
|
||||
|
||||
const [, repository, commit] = match;
|
||||
const temporaryRoot = mkdtempSync(join(tmpdir(), "webspeak-sdk-build-"));
|
||||
const destination = join(root, "node_modules", "@echosixhiya", "teamspeak-client", "dist");
|
||||
|
||||
try {
|
||||
execFileSync("git", ["clone", "--no-checkout", repository, temporaryRoot], { stdio: "inherit" });
|
||||
execFileSync("git", ["checkout", "--detach", commit], { cwd: temporaryRoot, stdio: "inherit" });
|
||||
const npmOptions = { cwd: temporaryRoot, stdio: "inherit" };
|
||||
const runNpm = (args) => {
|
||||
if (process.platform === "win32") {
|
||||
execFileSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `npm.cmd ${args.join(" ")}`], npmOptions);
|
||||
} else {
|
||||
execFileSync("npm", args, npmOptions);
|
||||
}
|
||||
};
|
||||
runNpm(["install", "--ignore-scripts", "--no-audit", "--no-fund"]);
|
||||
runNpm(["run", "build"]);
|
||||
|
||||
const source = join(temporaryRoot, "dist");
|
||||
if (!existsSync(join(source, "index.mjs"))) {
|
||||
throw new Error(`SDK build did not produce ${join(source, "index.mjs")}`);
|
||||
}
|
||||
|
||||
mkdirSync(dirname(destination), { recursive: true });
|
||||
mkdirSync(destination, { recursive: true });
|
||||
for (const entry of readdirSync(source)) {
|
||||
cpSync(join(source, entry), join(destination, entry), { recursive: true, force: true });
|
||||
}
|
||||
console.log(`Prepared ${sdkPackage} from ${commit}`);
|
||||
} finally {
|
||||
rmSync(temporaryRoot, { recursive: true, force: true });
|
||||
}
|
||||
@@ -1,12 +1,28 @@
|
||||
import { Router, type NextFunction, type Request, type Response } from "express";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput } from "./admin-service.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput } from "./admin-service.js";
|
||||
import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
|
||||
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
|
||||
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import type { AdminSessionSummary } from "../server/voice-bridge.js";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
nickname: string;
|
||||
clientIp: string;
|
||||
target: string;
|
||||
relayName: string | null;
|
||||
relayTarget: string | null;
|
||||
startedAt: string;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: "active" | "connecting" | "disconnected" | "failed";
|
||||
reason: string | null;
|
||||
failureDetail: string | null;
|
||||
}
|
||||
|
||||
export interface AdminRouterOptions {
|
||||
service: AdminService;
|
||||
sessions: AdminSessionStore;
|
||||
@@ -155,7 +171,12 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
});
|
||||
|
||||
router.get("/logs", (request, response) => {
|
||||
response.json({ available: Boolean(options.logFile && existsSync(options.logFile)), entries: readRecentLogs(options.logFile, readLimit(request.query.limit, 100)) });
|
||||
const limit = readLimit(request.query.limit, 100);
|
||||
response.json({
|
||||
available: Boolean(options.logFile && existsSync(options.logFile)),
|
||||
entries: readRecentLogs(options.logFile, limit),
|
||||
sessions: readConnectionHistory(options.logFile, limit),
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/diagnostics", (_request, response) => {
|
||||
@@ -208,7 +229,6 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
},
|
||||
teamSpeak: {
|
||||
status: overview.teamSpeak.status,
|
||||
protocol: overview.teamSpeak.protocol,
|
||||
lastTestAt: overview.teamSpeak.lastTestAt,
|
||||
latencyMs: overview.teamSpeak.latencyMs,
|
||||
lastError: overview.teamSpeak.lastError,
|
||||
@@ -326,6 +346,19 @@ async function runProbe(
|
||||
}
|
||||
|
||||
function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
const relayNodes = Array.isArray(body.relayNodes)
|
||||
? body.relayNodes.map((value): RelayNodeInput => {
|
||||
const node = asRecord(value);
|
||||
return {
|
||||
id: typeof node.id === "string" ? node.id.slice(0, 110) : undefined,
|
||||
name: typeof node.name === "string" ? node.name.slice(0, 80) : "",
|
||||
target: typeof node.target === "string" ? node.target.slice(0, 300) : "",
|
||||
enabled: node.enabled === true,
|
||||
token: typeof node.token === "string" ? node.token.slice(0, 512) : undefined,
|
||||
tokenAction: readPasswordAction(node.tokenAction),
|
||||
};
|
||||
})
|
||||
: undefined;
|
||||
return {
|
||||
target: readString(body, "target", 300),
|
||||
serverPassword: typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : undefined,
|
||||
@@ -333,9 +366,27 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
accessMode: body.accessMode === "open" ? "open" : body.accessMode === "fixed" ? "fixed" : body.accessMode as never,
|
||||
siteName: readString(body, "siteName", 80),
|
||||
welcomeText: readOptionalString(body, "welcomeText", 500),
|
||||
welcomeTextEn: typeof body.welcomeTextEn === "string" ? body.welcomeTextEn.slice(0, 500) : undefined,
|
||||
welcomeTextDe: typeof body.welcomeTextDe === "string" ? body.welcomeTextDe.slice(0, 500) : undefined,
|
||||
welcomeTextRu: typeof body.welcomeTextRu === "string" ? body.welcomeTextRu.slice(0, 500) : undefined,
|
||||
welcomeTextJa: typeof body.welcomeTextJa === "string" ? body.welcomeTextJa.slice(0, 500) : undefined,
|
||||
webRtcEnabled: body.webRtcEnabled === true,
|
||||
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
|
||||
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
|
||||
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
|
||||
relayEnabled: body.relayEnabled === true,
|
||||
relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined,
|
||||
relayTarget: typeof body.relayTarget === "string" ? body.relayTarget.slice(0, 300) : undefined,
|
||||
relayToken: typeof body.relayToken === "string" ? body.relayToken.slice(0, 512) : undefined,
|
||||
relayTokenAction: readPasswordAction(body.relayTokenAction),
|
||||
relayNodes,
|
||||
};
|
||||
}
|
||||
|
||||
function readRelaySettingsAction(value: unknown): "keep" | "replace" | "remove" {
|
||||
return value === "replace" || value === "remove" ? value : "keep";
|
||||
}
|
||||
|
||||
function readPasswordAction(value: unknown): "keep" | "replace" | "remove" {
|
||||
return value === "replace" || value === "remove" ? value : "keep";
|
||||
}
|
||||
@@ -350,6 +401,14 @@ function readString(body: Record<string, unknown>, key: string, max: number): st
|
||||
return body[key];
|
||||
}
|
||||
|
||||
function readOptionalInteger(body: Record<string, unknown>, key: string): number | undefined {
|
||||
if (body[key] === undefined) return undefined;
|
||||
if (typeof body[key] !== "number" || !Number.isSafeInteger(body[key])) {
|
||||
throw new AdminInputError("INVALID_REQUEST", `${key} is invalid`);
|
||||
}
|
||||
return body[key];
|
||||
}
|
||||
|
||||
function readOptionalString(body: Record<string, unknown>, key: string, max: number): string {
|
||||
return typeof body[key] === "string" ? body[key].slice(0, max) : "";
|
||||
}
|
||||
@@ -378,7 +437,7 @@ function readRecentLogs(logFile: string | undefined, limit: number): AdminLogEnt
|
||||
try {
|
||||
const raw = JSON.parse(line) as Record<string, unknown>;
|
||||
const context: Record<string, string | number | boolean> = {};
|
||||
for (const key of ["component", "entryId", "code", "reason", "attempt", "target", "nickname", "channel", "reconnect", "port"]) {
|
||||
for (const key of ["component", "entryId", "code", "reason", "attempt", "target", "nickname", "clientIp", "relayName", "relayTarget", "channel", "reconnect", "port"]) {
|
||||
const value = raw[key];
|
||||
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") context[key] = value;
|
||||
}
|
||||
@@ -397,12 +456,150 @@ function readRecentLogs(logFile: string | undefined, limit: number): AdminLogEnt
|
||||
}
|
||||
}
|
||||
|
||||
interface StructuredLogEntry {
|
||||
timestamp: string | null;
|
||||
message: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function readConnectionHistory(logFile: string | undefined, limit: number): AdminConnectionRecord[] {
|
||||
if (!logFile) return [];
|
||||
const records = new Map<string, {
|
||||
id: string;
|
||||
nickname: string;
|
||||
clientIp: string;
|
||||
target: string;
|
||||
relayName: string;
|
||||
relayTarget: string;
|
||||
startedAt: string | null;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: AdminConnectionRecord["status"];
|
||||
reason: string | null;
|
||||
failureDetail: string | null;
|
||||
}>();
|
||||
for (const log of readStructuredLogs(logFile)) {
|
||||
const entryId = typeof log.raw.entryId === "string" ? log.raw.entryId : "";
|
||||
if (!entryId || !log.timestamp) continue;
|
||||
const current = records.get(entryId) ?? {
|
||||
id: entryId,
|
||||
nickname: "",
|
||||
clientIp: "",
|
||||
target: "",
|
||||
relayName: "",
|
||||
relayTarget: "",
|
||||
startedAt: null,
|
||||
connectedAt: null,
|
||||
disconnectedAt: null,
|
||||
durationSeconds: null,
|
||||
status: "connecting" as const,
|
||||
reason: null,
|
||||
failureDetail: null,
|
||||
};
|
||||
const nickname = typeof log.raw.nickname === "string" ? log.raw.nickname : "";
|
||||
const clientIp = typeof log.raw.clientIp === "string" ? log.raw.clientIp : "";
|
||||
const target = typeof log.raw.target === "string" ? log.raw.target : "";
|
||||
const relayName = typeof log.raw.relayName === "string" ? log.raw.relayName : "";
|
||||
const relayTarget = typeof log.raw.relayTarget === "string" ? log.raw.relayTarget : "";
|
||||
if (nickname) current.nickname = nickname;
|
||||
if (clientIp) current.clientIp = clientIp;
|
||||
if (target) current.target = target;
|
||||
if (relayName) current.relayName = relayName;
|
||||
if (relayTarget) current.relayTarget = relayTarget;
|
||||
if (typeof log.raw.failureDetail === "string" && log.raw.failureDetail) current.failureDetail = log.raw.failureDetail;
|
||||
if (log.message === "WebClient connecting") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.status = "connecting";
|
||||
} else if (log.message === "TS connect failed") {
|
||||
current.reason = typeof log.raw.code === "string" ? log.raw.code : current.reason;
|
||||
current.status = "failed";
|
||||
} else if (log.message === "Web client connected to TeamSpeak") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.connectedAt = log.timestamp;
|
||||
current.status = "active";
|
||||
} else if (log.message === "Client session torn down") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.disconnectedAt = log.timestamp;
|
||||
current.durationSeconds = current.connectedAt && typeof log.raw.durationSeconds === "number"
|
||||
? Math.max(0, Math.floor(log.raw.durationSeconds))
|
||||
: current.connectedAt
|
||||
? Math.max(0, Math.floor((Date.parse(log.timestamp) - Date.parse(current.connectedAt)) / 1000))
|
||||
: null;
|
||||
current.status = current.connectedAt ? "disconnected" : "failed";
|
||||
// `reason` is also used for ordinary lifecycle teardown (for example
|
||||
// websocket-close when a user clicks Leave). Only preserve an explicit
|
||||
// TeamSpeak failure code here; otherwise a normal disconnect would be
|
||||
// rendered by the admin UI as the generic request-failed message.
|
||||
current.reason = typeof log.raw.failureCode === "string" && log.raw.failureCode
|
||||
? log.raw.failureCode
|
||||
: current.reason;
|
||||
}
|
||||
records.set(entryId, current);
|
||||
}
|
||||
const now = Date.now();
|
||||
return [...records.values()]
|
||||
.filter((record): record is typeof record & { startedAt: string } => Boolean(record.startedAt))
|
||||
.map((record) => {
|
||||
const start = record.connectedAt ?? record.startedAt;
|
||||
const end = record.disconnectedAt ? Date.parse(record.disconnectedAt) : now;
|
||||
return {
|
||||
id: record.id,
|
||||
nickname: record.nickname || "—",
|
||||
clientIp: record.clientIp || "—",
|
||||
target: record.target || "—",
|
||||
relayName: record.relayName || null,
|
||||
relayTarget: record.relayTarget || null,
|
||||
startedAt: record.startedAt,
|
||||
connectedAt: record.connectedAt,
|
||||
disconnectedAt: record.disconnectedAt,
|
||||
durationSeconds: record.durationSeconds ?? (record.status === "active" || record.status === "connecting"
|
||||
? Math.max(0, Math.floor((end - Date.parse(start)) / 1000))
|
||||
: null),
|
||||
status: record.status,
|
||||
// Older sessions may only contain a teardown record without a
|
||||
// structured failure code. Keep normal disconnects quiet, but make
|
||||
// an untraceable failed connection explicitly visible as the generic
|
||||
// request-failed message instead of implying a guessed cause.
|
||||
reason: record.reason ?? (record.status === "failed" ? "CONNECTION_FAILED" : null),
|
||||
failureDetail: record.failureDetail,
|
||||
};
|
||||
})
|
||||
.sort((left, right) => Date.parse(right.disconnectedAt ?? right.startedAt) - Date.parse(left.disconnectedAt ?? left.startedAt))
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
function readStructuredLogs(logFile: string): StructuredLogEntry[] {
|
||||
const paths = [logFile, `${logFile}.1`, `${logFile}.2`, `${logFile}.3`].filter((value, index, all) => value && all.indexOf(value) === index);
|
||||
const entries: StructuredLogEntry[] = [];
|
||||
for (const path of paths) {
|
||||
if (!existsSync(path)) continue;
|
||||
try {
|
||||
for (const line of readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean)) {
|
||||
try {
|
||||
const raw = JSON.parse(line) as Record<string, unknown>;
|
||||
entries.push({
|
||||
timestamp: typeof raw.time === "string" ? raw.time : null,
|
||||
message: typeof raw.msg === "string" ? raw.msg : "",
|
||||
raw,
|
||||
});
|
||||
} catch {
|
||||
// Non-JSON lines are still shown by the normal log viewer, but cannot
|
||||
// be associated with a user session safely.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A rotated file can disappear between existsSync and readFileSync.
|
||||
}
|
||||
}
|
||||
return entries.sort((left, right) => Date.parse(left.timestamp ?? "") - Date.parse(right.timestamp ?? ""));
|
||||
}
|
||||
|
||||
interface AdminOverview {
|
||||
gateway: { uptimeSeconds: number };
|
||||
teamSpeak: {
|
||||
target: string;
|
||||
status: string;
|
||||
protocol: string | null;
|
||||
lastTestAt: string | null;
|
||||
latencyMs: number | null;
|
||||
lastError: string | null;
|
||||
|
||||
@@ -3,10 +3,15 @@ import { existsSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { loadConfig } from "../config.js";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { type AccessMode, type ManagedInviteRecord, type PersistedRelayNode, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError, type TeamSpeakProbeResult } from "../server/teamspeak-probe.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import { pingTeamSpeakHost } from "../server/network-probe.js";
|
||||
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
|
||||
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
|
||||
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
|
||||
|
||||
export interface AdminSettingsInput {
|
||||
target: string;
|
||||
@@ -15,6 +20,29 @@ export interface AdminSettingsInput {
|
||||
accessMode: AccessMode;
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relaySettingsAction?: "keep" | "replace" | "remove";
|
||||
relayEnabled?: boolean;
|
||||
relayName?: string;
|
||||
relayTarget?: string;
|
||||
relayToken?: string;
|
||||
relayTokenAction?: "keep" | "replace" | "remove";
|
||||
relayNodes?: RelayNodeInput[];
|
||||
}
|
||||
|
||||
export interface RelayNodeInput {
|
||||
id?: string;
|
||||
name: string;
|
||||
target: string;
|
||||
enabled: boolean;
|
||||
token?: string;
|
||||
tokenAction?: "keep" | "replace" | "remove";
|
||||
}
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
@@ -87,10 +115,22 @@ export class AdminService {
|
||||
|
||||
getPublicConfig(): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
const welcomeTexts = resolveWelcomeTexts({
|
||||
zh: settings.welcomeText,
|
||||
en: settings.welcomeTextEn,
|
||||
de: settings.welcomeTextDe,
|
||||
ru: settings.welcomeTextRu,
|
||||
ja: settings.welcomeTextJa,
|
||||
});
|
||||
return {
|
||||
version: this.version,
|
||||
initialized: this.isInitialized(),
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
// Keep the old fields for older clients, but return the complete,
|
||||
// already-fallback-resolved map for current clients.
|
||||
welcomeText: welcomeTexts.zh,
|
||||
welcomeTextEn: welcomeTexts.en,
|
||||
welcomeTexts,
|
||||
accessMode: settings.accessMode,
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
};
|
||||
@@ -104,20 +144,65 @@ export class AdminService {
|
||||
accessMode: settings.accessMode,
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
detectedProtocol: settings.detectedProtocol,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
welcomeTextDe: settings.welcomeTextDe,
|
||||
welcomeTextRu: settings.welcomeTextRu,
|
||||
welcomeTextJa: settings.welcomeTextJa,
|
||||
welcomeDefaults: DEFAULT_WELCOME_TEXTS,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
relayTarget: settings.relayHost ? formatRelayTarget(settings.relayHost, settings.relayPort) : "",
|
||||
hasRelayToken: Boolean(settings.relayTokenEncrypted),
|
||||
relayNodes: this.getRelayNodeViews(),
|
||||
internalPort: 3040,
|
||||
updatedAt: settings.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
getWebRtcAudioOptions(): WebRtcAudioOptions {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
enabled: settings.webRtcEnabled,
|
||||
udpPortRange: [settings.webRtcUdpStart, settings.webRtcUdpEnd],
|
||||
};
|
||||
}
|
||||
|
||||
getAccelerationRelayOptions(): ConfiguredAccelerationRelay[] {
|
||||
const relays: ConfiguredAccelerationRelay[] = [];
|
||||
for (const node of this.database.listRelayNodes()) {
|
||||
if (!node.enabled || !node.host || !node.tokenEncrypted) continue;
|
||||
try {
|
||||
const token = decryptSecret(node.tokenEncrypted, this.masterSecret);
|
||||
relays.push({ id: node.id, name: node.name, relayHost: node.host, relayPort: node.port, token });
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error), relayId: node.id }, "Stored acceleration relay token could not be decrypted");
|
||||
}
|
||||
}
|
||||
return relays;
|
||||
}
|
||||
|
||||
getAccelerationRelayName(): string | undefined {
|
||||
return this.getAccelerationRelayOptions()[0]?.name;
|
||||
}
|
||||
|
||||
updateSettings(input: AdminSettingsInput): void {
|
||||
const current = this.database.getSettings();
|
||||
const settings = this.normalizeSettings(input, current);
|
||||
const relayNodes = input.relayNodes === undefined ? undefined : this.normalizeRelayNodes(input.relayNodes);
|
||||
const settings = this.normalizeSettings(input, current, relayNodes);
|
||||
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort;
|
||||
this.database.updateSettings(settings);
|
||||
if (relayNodes !== undefined) {
|
||||
this.database.replaceRelayNodes(relayNodes);
|
||||
} else if (input.relaySettingsAction && input.relaySettingsAction !== "keep") {
|
||||
this.database.replaceRelayNodes(this.legacyRelayNodesFromSettings(settings));
|
||||
}
|
||||
if (targetChanged) this.database.clearConnectionTest();
|
||||
}
|
||||
|
||||
@@ -136,7 +221,7 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<TeamSpeakProbeResult> {
|
||||
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<{ ok: boolean; checkType: "network" | "protocol"; passwordVerified: boolean; latencyMs: number; serverName: string | null; requiresPassword: boolean; packetLossPercent?: number; attempts?: number; successfulAttempts?: number; errorCode?: string }> {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(targetText);
|
||||
@@ -144,12 +229,41 @@ export class AdminService {
|
||||
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
|
||||
}
|
||||
try {
|
||||
// The admin connection test must not create a temporary TeamSpeak
|
||||
// client: that client becomes visible in the target channel. Use the
|
||||
// WebSpeak host's ICMP route measurement instead. The injected probe is
|
||||
// retained for unit tests and explicit protocol-probe callers.
|
||||
if (this.probe === probeTeamSpeak) {
|
||||
const result = await pingTeamSpeakHost(target.host, { attempts: 4 });
|
||||
const publicResult = {
|
||||
ok: result.ok,
|
||||
checkType: "network" as const,
|
||||
passwordVerified: false,
|
||||
latencyMs: result.latencyMs ?? 0,
|
||||
serverName: null,
|
||||
requiresPassword: false,
|
||||
packetLossPercent: result.packetLossPercent,
|
||||
attempts: result.attempts,
|
||||
successfulAttempts: result.successfulAttempts,
|
||||
...(result.errorCode ? { errorCode: result.errorCode } : {}),
|
||||
};
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: null, latencyMs: result.latencyMs, error: result.ok ? null : (result.errorCode ?? "UNREACHABLE") });
|
||||
this.database.addAudit(result.ok ? "CONNECTION_TEST_SUCCEEDED" : "CONNECTION_TEST_FAILED", {
|
||||
latencyMs: result.latencyMs,
|
||||
packetLossPercent: result.packetLossPercent,
|
||||
...(result.errorCode ? { code: result.errorCode } : {}),
|
||||
});
|
||||
}
|
||||
return publicResult;
|
||||
}
|
||||
const result = await this.probe(target, password, this.logger);
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: result.protocol, latencyMs: result.latencyMs, error: null });
|
||||
this.database.addAudit("CONNECTION_TEST_SUCCEEDED", { protocol: result.protocol, latencyMs: result.latencyMs });
|
||||
}
|
||||
return result;
|
||||
const { protocol: _protocol, ...publicResult } = result;
|
||||
return { ...publicResult, checkType: "protocol", passwordVerified: true };
|
||||
} catch (error: unknown) {
|
||||
const probeError = error instanceof TeamSpeakProbeError
|
||||
? error
|
||||
@@ -173,7 +287,6 @@ export class AdminService {
|
||||
teamSpeak: {
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
status: settings.lastTestError ? "unreachable" : settings.lastTestAt ? "reachable" : "unknown",
|
||||
protocol: settings.detectedProtocol,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
latencyMs: settings.lastTestLatencyMs,
|
||||
lastError: settings.lastTestError,
|
||||
@@ -238,7 +351,7 @@ export class AdminService {
|
||||
this.database.setMeta("legacy_import_notice_pending", "0");
|
||||
}
|
||||
|
||||
private normalizeSettings(input: AdminSettingsInput, current: ReturnType<WebSpeakDatabase["getSettings"]>): SettingsUpdate {
|
||||
private normalizeSettings(input: AdminSettingsInput, current: ReturnType<WebSpeakDatabase["getSettings"]>, relayNodes?: PersistedRelayNode[]): SettingsUpdate {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(input.target);
|
||||
@@ -247,26 +360,189 @@ export class AdminService {
|
||||
}
|
||||
const siteName = input.siteName.trim();
|
||||
const welcomeText = input.welcomeText.trim();
|
||||
const welcomeTextEn = typeof input.welcomeTextEn === "string" ? input.welcomeTextEn.trim() : current.welcomeTextEn;
|
||||
const welcomeTextDe = typeof input.welcomeTextDe === "string" ? input.welcomeTextDe.trim() : current.welcomeTextDe;
|
||||
const welcomeTextRu = typeof input.welcomeTextRu === "string" ? input.welcomeTextRu.trim() : current.welcomeTextRu;
|
||||
const welcomeTextJa = typeof input.welcomeTextJa === "string" ? input.welcomeTextJa.trim() : current.welcomeTextJa;
|
||||
if (!siteName || siteName.length > 80) throw new AdminInputError("INVALID_SITE_NAME", "Site name must contain 1 to 80 characters");
|
||||
if (welcomeText.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT", "Welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextEn.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_EN", "English welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextDe.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_DE", "German welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextRu.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_RU", "Russian welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextJa.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_JA", "Japanese welcome text cannot exceed 500 characters");
|
||||
if (input.accessMode !== "fixed" && input.accessMode !== "open") {
|
||||
throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid");
|
||||
}
|
||||
if (typeof input.webRtcEnabled !== "boolean") {
|
||||
throw new AdminInputError("INVALID_WEBRTC_ENABLED", "WebRTC enabled value is invalid");
|
||||
}
|
||||
const webRtcUdpStart = input.webRtcUdpStart ?? current.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0];
|
||||
const webRtcUdpEnd = input.webRtcUdpEnd ?? current.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1];
|
||||
if (!Number.isInteger(webRtcUdpStart) || webRtcUdpStart < WEBRTC_UDP_PORT_MIN || webRtcUdpStart > WEBRTC_UDP_PORT_MAX) {
|
||||
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP start port must be between 1024 and 65535");
|
||||
}
|
||||
if (!Number.isInteger(webRtcUdpEnd) || webRtcUdpEnd < WEBRTC_UDP_PORT_MIN || webRtcUdpEnd > WEBRTC_UDP_PORT_MAX) {
|
||||
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP end port must be between 1024 and 65535");
|
||||
}
|
||||
if (webRtcUdpStart > webRtcUdpEnd) {
|
||||
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP start port must not exceed the end port");
|
||||
}
|
||||
if (current.webRtcEnabled && (webRtcUdpStart !== current.webRtcUdpStart || webRtcUdpEnd !== current.webRtcUdpEnd)) {
|
||||
throw new AdminInputError("WEBRTC_PORT_LOCKED", "Disable WebRTC and save before changing its UDP port range");
|
||||
}
|
||||
|
||||
let encryptedPassword = current.tsPasswordEncrypted;
|
||||
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
|
||||
if (action === "remove") encryptedPassword = null;
|
||||
if (action === "replace") encryptedPassword = input.serverPassword ? encryptSecret(input.serverPassword, this.masterSecret) : null;
|
||||
|
||||
let relayConfigured = current.relayConfigured;
|
||||
let relayEnabled = current.relayEnabled;
|
||||
let relayName = current.relayName;
|
||||
let relayHost = current.relayHost;
|
||||
let relayPort = current.relayPort || DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
let relayTokenEncrypted = current.relayTokenEncrypted;
|
||||
const relaySettingsAction = input.relaySettingsAction ?? "keep";
|
||||
if (relaySettingsAction === "remove") {
|
||||
relayConfigured = true;
|
||||
relayEnabled = false;
|
||||
relayName = "";
|
||||
relayHost = "";
|
||||
relayPort = DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
relayTokenEncrypted = null;
|
||||
} else if (relaySettingsAction === "replace") {
|
||||
const relayTarget = (input.relayTarget ?? "").trim();
|
||||
relayEnabled = input.relayEnabled === true;
|
||||
relayName = (input.relayName ?? "").trim();
|
||||
if (relayName.length > 80) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name must contain 80 characters or fewer");
|
||||
if (relayEnabled && !relayName) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name is required when the relay is enabled");
|
||||
if (relayEnabled && !relayTarget) throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is required when the relay is enabled");
|
||||
if (relayTarget) {
|
||||
try {
|
||||
const relay = parseTeamSpeakTarget(relayTarget, DEFAULT_ACCELERATION_RELAY_PORT);
|
||||
relayHost = relay.host;
|
||||
relayPort = relay.port;
|
||||
} catch {
|
||||
throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid");
|
||||
}
|
||||
} else {
|
||||
relayHost = "";
|
||||
relayPort = DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
}
|
||||
const relayTokenAction = input.relayTokenAction ?? (input.relayToken === undefined ? "keep" : "replace");
|
||||
if (relayTokenAction === "remove") relayTokenEncrypted = null;
|
||||
if (relayTokenAction === "replace") relayTokenEncrypted = input.relayToken ? encryptSecret(input.relayToken, this.masterSecret) : null;
|
||||
if (relayEnabled && !relayTokenEncrypted) throw new AdminInputError("INVALID_RELAY_TOKEN", "Relay token is required when the relay is enabled");
|
||||
relayConfigured = true;
|
||||
}
|
||||
if (relayNodes) {
|
||||
const primary = relayNodes.find((node) => node.enabled) ?? relayNodes[0];
|
||||
relayConfigured = relayNodes.length > 0;
|
||||
relayEnabled = primary?.enabled === true;
|
||||
relayName = primary?.name ?? "";
|
||||
relayHost = primary?.host ?? "";
|
||||
relayPort = primary?.port ?? DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
relayTokenEncrypted = primary?.tokenEncrypted ?? null;
|
||||
}
|
||||
return {
|
||||
siteName,
|
||||
welcomeText,
|
||||
welcomeTextEn,
|
||||
welcomeTextDe,
|
||||
welcomeTextRu,
|
||||
welcomeTextJa,
|
||||
accessMode: input.accessMode,
|
||||
tsHost: target.host,
|
||||
tsPort: target.port,
|
||||
tsPasswordEncrypted: encryptedPassword,
|
||||
webRtcEnabled: input.webRtcEnabled,
|
||||
webRtcUdpStart,
|
||||
webRtcUdpEnd,
|
||||
relayConfigured,
|
||||
relayEnabled,
|
||||
relayName,
|
||||
relayHost,
|
||||
relayPort,
|
||||
relayTokenEncrypted,
|
||||
};
|
||||
}
|
||||
|
||||
private normalizeRelayNodes(inputs: RelayNodeInput[]): PersistedRelayNode[] {
|
||||
if (!Array.isArray(inputs) || inputs.length > 16) throw new AdminInputError("INVALID_RELAY_NODES", "At most 16 relay nodes may be configured");
|
||||
const current = new Map(this.database.listRelayNodes().map((node) => [node.id, node]));
|
||||
const seen = new Set<string>();
|
||||
const now = new Date().toISOString();
|
||||
return inputs.map((input) => {
|
||||
const name = typeof input.name === "string" ? input.name.trim() : "";
|
||||
const targetText = typeof input.target === "string" ? input.target.trim() : "";
|
||||
if (!name || name.length > 80) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name must contain 1 to 80 characters");
|
||||
if (!targetText || targetText.length > 300) throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid");
|
||||
let target: TeamSpeakTarget;
|
||||
try { target = parseTeamSpeakTarget(targetText, DEFAULT_ACCELERATION_RELAY_PORT); }
|
||||
catch { throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid"); }
|
||||
const id = typeof input.id === "string" && /^relay-[a-z0-9-]{1,100}$/i.test(input.id)
|
||||
? input.id
|
||||
: `relay-${randomBytes(8).toString("hex")}`;
|
||||
if (seen.has(id)) throw new AdminInputError("INVALID_RELAY_ID", "Relay id must be unique");
|
||||
seen.add(id);
|
||||
const previous = current.get(id);
|
||||
const tokenAction = input.tokenAction ?? (input.token === undefined ? "keep" : "replace");
|
||||
let tokenEncrypted = previous?.tokenEncrypted ?? null;
|
||||
if (tokenAction === "remove") tokenEncrypted = null;
|
||||
if (tokenAction === "replace") {
|
||||
const token = typeof input.token === "string" ? input.token.trim() : "";
|
||||
tokenEncrypted = token ? encryptSecret(token, this.masterSecret) : null;
|
||||
}
|
||||
if (input.enabled === true && (!tokenEncrypted || !this.canDecryptToken(tokenEncrypted))) {
|
||||
throw new AdminInputError("INVALID_RELAY_TOKEN", "A relay token of at least 16 characters is required when the relay is enabled");
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
enabled: input.enabled === true,
|
||||
host: target.host,
|
||||
port: target.port,
|
||||
tokenEncrypted,
|
||||
createdAt: previous?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private canDecryptToken(encrypted: string): boolean {
|
||||
try {
|
||||
return decryptSecret(encrypted, this.masterSecret).length >= 16;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private getRelayNodeViews(): Array<{ id: string; name: string; enabled: boolean; target: string; hasToken: boolean }> {
|
||||
return this.database.listRelayNodes().map((node) => ({
|
||||
id: node.id,
|
||||
name: node.name,
|
||||
enabled: node.enabled,
|
||||
target: formatRelayTarget(node.host, node.port),
|
||||
hasToken: Boolean(node.tokenEncrypted),
|
||||
}));
|
||||
}
|
||||
|
||||
private legacyRelayNodesFromSettings(settings: SettingsUpdate): PersistedRelayNode[] {
|
||||
if (!settings.relayConfigured || !settings.relayHost || !settings.relayTokenEncrypted) return [];
|
||||
const previous = this.database.listRelayNodes()[0];
|
||||
const now = new Date().toISOString();
|
||||
return [{
|
||||
id: previous?.id ?? "relay-default",
|
||||
name: settings.relayName || "中继加速",
|
||||
enabled: settings.relayEnabled,
|
||||
host: settings.relayHost,
|
||||
port: settings.relayPort || DEFAULT_ACCELERATION_RELAY_PORT,
|
||||
tokenEncrypted: settings.relayTokenEncrypted,
|
||||
createdAt: previous?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
}];
|
||||
}
|
||||
|
||||
private toInviteView(record: ManagedInviteRecord): ManagedInviteView {
|
||||
const now = Date.now();
|
||||
const expired = Date.parse(record.expiresAt) <= now;
|
||||
@@ -288,10 +564,23 @@ export class AdminService {
|
||||
return {
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
welcomeTextDe: settings.welcomeTextDe,
|
||||
welcomeTextRu: settings.welcomeTextRu,
|
||||
welcomeTextJa: settings.welcomeTextJa,
|
||||
accessMode: settings.accessMode,
|
||||
tsHost: settings.tsHost,
|
||||
tsPort: settings.tsPort,
|
||||
tsPasswordEncrypted: settings.tsPasswordEncrypted,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
relayHost: settings.relayHost,
|
||||
relayPort: settings.relayPort,
|
||||
relayTokenEncrypted: settings.relayTokenEncrypted,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -303,10 +592,23 @@ export class AdminService {
|
||||
this.database.updateSettings({
|
||||
siteName: current.siteName,
|
||||
welcomeText: current.welcomeText,
|
||||
welcomeTextEn: current.welcomeTextEn,
|
||||
welcomeTextDe: current.welcomeTextDe,
|
||||
welcomeTextRu: current.welcomeTextRu,
|
||||
welcomeTextJa: current.welcomeTextJa,
|
||||
accessMode: current.accessMode,
|
||||
tsHost: legacy.tsHost,
|
||||
tsPort: legacy.tsPort,
|
||||
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
|
||||
webRtcEnabled: current.webRtcEnabled,
|
||||
webRtcUdpStart: current.webRtcUdpStart,
|
||||
webRtcUdpEnd: current.webRtcUdpEnd,
|
||||
relayConfigured: current.relayConfigured,
|
||||
relayEnabled: current.relayEnabled,
|
||||
relayName: current.relayName,
|
||||
relayHost: current.relayHost,
|
||||
relayPort: current.relayPort,
|
||||
relayTokenEncrypted: current.relayTokenEncrypted,
|
||||
}, "LEGACY_CONFIG_IMPORTED");
|
||||
this.database.setMeta("legacy_config_imported", "1");
|
||||
this.database.setMeta("legacy_import_notice_pending", "1");
|
||||
@@ -320,6 +622,10 @@ function hashInviteToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
function formatRelayTarget(host: string, port: number): string {
|
||||
return `${host.includes(":") ? `[${host}]` : host}#${port}`;
|
||||
}
|
||||
|
||||
export class AdminInputError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
|
||||
@@ -1,45 +1,416 @@
|
||||
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"
|
||||
| "CONNECTION_RESET"
|
||||
| "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"
|
||||
| "CONNECTION_INITIALISATION_FAILED"
|
||||
| "CONNECTION_FAILED";
|
||||
|
||||
export interface TeamSpeakErrorDiagnostics {
|
||||
name?: string;
|
||||
code?: string;
|
||||
id?: string;
|
||||
serverMessage?: string;
|
||||
message?: string;
|
||||
syscall?: string;
|
||||
address?: string;
|
||||
port?: number | string;
|
||||
cause?: string;
|
||||
}
|
||||
|
||||
export class WebSpeakError extends Error {
|
||||
readonly code: WebSpeakErrorCode;
|
||||
readonly retryable: boolean;
|
||||
readonly cause?: unknown;
|
||||
readonly diagnostics: TeamSpeakErrorDiagnostics;
|
||||
|
||||
constructor(code: WebSpeakErrorCode, message: string, retryable: boolean, cause?: unknown) {
|
||||
constructor(code: WebSpeakErrorCode, message: string, retryable: boolean, cause?: unknown, diagnostics: TeamSpeakErrorDiagnostics = {}) {
|
||||
super(message);
|
||||
this.name = "WebSpeakError";
|
||||
this.code = code;
|
||||
this.retryable = retryable;
|
||||
this.cause = cause;
|
||||
this.diagnostics = diagnostics;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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). 1541 is the generic "invalid parameter size" error;
|
||||
// connection-specific classification decides whether that means a nickname.
|
||||
"1536": "invalid_parameter_size",
|
||||
"1537": "invalid_parameter_size",
|
||||
"1538": "invalid_parameter_size",
|
||||
"1539": "invalid_parameter_size",
|
||||
"1540": "invalid_parameter_size",
|
||||
"1541": "invalid_parameter_size",
|
||||
"1542": "invalid_parameter_size",
|
||||
"1543": "protocol_negotiation_failed",
|
||||
// Connection (0x07xx). Keep only ids whose official meaning matches the
|
||||
// normalized code; unrelated SDK operation errors must not be relabelled.
|
||||
"1797": "connection_initialisation_failed",
|
||||
"1798": "host_not_found",
|
||||
"1805": "protocol_negotiation_failed",
|
||||
"1806": "protocol_negotiation_failed",
|
||||
// Server (0x04xx).
|
||||
"1026": "server_shutting_down",
|
||||
"1027": "server_full",
|
||||
"1028": "authentication_failed",
|
||||
"781": "channel_password_required",
|
||||
// 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",
|
||||
// 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 candidate = error as { code?: unknown; message?: unknown } | null;
|
||||
const code = typeof candidate?.code === "string" ? candidate.code : "";
|
||||
const message = typeof candidate?.message === "string" ? candidate.message : String(error);
|
||||
const text = `${code} ${message}`.toLocaleLowerCase();
|
||||
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);
|
||||
// 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
|
||||
// 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 (/nickname.{0,20}(length|size)/.test(text)) {
|
||||
return createTeamSpeakError("invalid_nickname", error, diagnostics);
|
||||
}
|
||||
if (/timeout|timed out|ack timeout|idle timeout/.test(text)) {
|
||||
return new WebSpeakError("timeout", "TeamSpeak connection timed out", true, error);
|
||||
if (/invalid[\s_-]*parameter[\s_-]*size|parameter.{0,20}(size|out of range)/.test(text)) {
|
||||
return createTeamSpeakError("invalid_parameter_size", error, diagnostics);
|
||||
}
|
||||
if (/econnrefused|enotfound|ehostunreach|enetunreach|network|socket|dns/.test(text)) {
|
||||
return new WebSpeakError("unreachable", "TeamSpeak server is unreachable", true, error);
|
||||
if (/nickname.{0,30}(in use|already (in )?use|taken|exists)|nickname_in_use/.test(text)) {
|
||||
return createTeamSpeakError("nickname_in_use", error, diagnostics);
|
||||
}
|
||||
if (/protocol|handshake|crypto|init1/.test(text)) {
|
||||
return new WebSpeakError("protocol_negotiation_failed", "TeamSpeak protocol negotiation failed", true, error);
|
||||
if (/channel.{0,30}password|password.{0,30}channel|i_channel_password/.test(text)) {
|
||||
return createTeamSpeakError("channel_password_required", error, diagnostics);
|
||||
}
|
||||
return new WebSpeakError("unknown", "TeamSpeak connection failed", false, error);
|
||||
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 createTeamSpeakError("connection_refused", 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 createTeamSpeakError("timeout", 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 (/handshake|protocol|eax|crypto ?(init|handshake|setup)|init1|signature|license/.test(text)) {
|
||||
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
|
||||
}
|
||||
return createTeamSpeakError("unknown", error, diagnostics);
|
||||
}
|
||||
|
||||
export function clientConnectionFailureCode(error: WebSpeakError, serverPassword = ""): ClientConnectionFailureCode {
|
||||
if (error.code === "authentication_failed") {
|
||||
return serverPassword.trim() ? "INVALID_SERVER_PASSWORD" : "SERVER_PASSWORD_REQUIRED";
|
||||
}
|
||||
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",
|
||||
// During the initial connect handshake this generic TeamSpeak id is most
|
||||
// commonly emitted for an invalid nickname length/format. Operation errors
|
||||
// still retain the generic invalid_parameter_size message.
|
||||
invalid_parameter_size: "INVALID_NICKNAME",
|
||||
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
|
||||
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;
|
||||
const parts = [
|
||||
details.name,
|
||||
details.code,
|
||||
details.id ? `id=${details.id}` : "",
|
||||
details.serverMessage,
|
||||
details.syscall,
|
||||
details.address ? `address=${details.address}` : "",
|
||||
details.port !== undefined ? `port=${details.port}` : "",
|
||||
details.cause,
|
||||
details.message,
|
||||
].filter(Boolean);
|
||||
return parts.length ? parts.join("; ") : error.message;
|
||||
}
|
||||
|
||||
function diagnosticText(error: unknown): string {
|
||||
const values: string[] = [];
|
||||
let current: unknown = error;
|
||||
const seen = new Set<unknown>();
|
||||
for (let depth = 0; depth < 4 && current && !seen.has(current); depth += 1) {
|
||||
seen.add(current);
|
||||
if (current instanceof Error) values.push(current.name, current.message);
|
||||
else values.push(String(current));
|
||||
if (typeof current === "object") {
|
||||
const candidate = current as { code?: unknown; id?: unknown; serverMessage?: unknown; cause?: unknown };
|
||||
for (const value of [candidate.code, candidate.id, candidate.serverMessage]) if (value !== undefined) values.push(String(value));
|
||||
current = candidate.cause;
|
||||
} else break;
|
||||
}
|
||||
return values.join(" ");
|
||||
}
|
||||
|
||||
function collectDiagnostics(error: unknown): TeamSpeakErrorDiagnostics {
|
||||
const result: TeamSpeakErrorDiagnostics = {};
|
||||
let current: unknown = error;
|
||||
const seen = new Set<unknown>();
|
||||
for (let depth = 0; depth < 4 && current && !seen.has(current); depth += 1) {
|
||||
seen.add(current);
|
||||
if (current instanceof Error) {
|
||||
result.name ??= current.name;
|
||||
result.message ??= current.message;
|
||||
const errorRecord = current as Error & Record<string, unknown>;
|
||||
if (typeof errorRecord.code === "string" || typeof errorRecord.code === "number") result.code ??= String(errorRecord.code);
|
||||
if (typeof errorRecord.id === "string" || typeof errorRecord.id === "number") result.id ??= String(errorRecord.id);
|
||||
if (typeof errorRecord.serverMessage === "string") result.serverMessage ??= errorRecord.serverMessage;
|
||||
if (typeof errorRecord.syscall === "string") result.syscall ??= errorRecord.syscall;
|
||||
if (typeof errorRecord.address === "string") result.address ??= errorRecord.address;
|
||||
if (typeof errorRecord.port === "string" || typeof errorRecord.port === "number") result.port ??= errorRecord.port;
|
||||
const cause = current.cause;
|
||||
if (cause && cause !== current) { current = cause; continue; }
|
||||
break;
|
||||
}
|
||||
if (typeof current !== "object") { result.cause ??= String(current); break; }
|
||||
const candidate = current as Record<string, unknown>;
|
||||
if (typeof candidate.name === "string") result.name ??= candidate.name;
|
||||
if (typeof candidate.code === "string" || typeof candidate.code === "number") result.code ??= String(candidate.code);
|
||||
if (typeof candidate.id === "string" || typeof candidate.id === "number") result.id ??= String(candidate.id);
|
||||
if (typeof candidate.serverMessage === "string") result.serverMessage ??= candidate.serverMessage;
|
||||
if (typeof candidate.message === "string") result.message ??= candidate.message;
|
||||
if (typeof candidate.syscall === "string") result.syscall ??= candidate.syscall;
|
||||
if (typeof candidate.address === "string") result.address ??= candidate.address;
|
||||
if (typeof candidate.port === "string" || typeof candidate.port === "number") result.port ??= candidate.port;
|
||||
const cause = candidate.cause;
|
||||
if (cause && cause !== current) { current = cause; continue; }
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1,13 +1,7 @@
|
||||
import path from "node:path";
|
||||
import { existsSync, readFileSync, unlinkSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createLogger } from "./logger.js";
|
||||
import { createWebServer } from "./server/server.js";
|
||||
import { APP_PORT } from "./constants.js";
|
||||
import { WebSpeakDatabase } from "./persistence/database.js";
|
||||
import { loadOrCreateMasterSecret } from "./security/master-secret.js";
|
||||
import { AdminService } from "./admin/admin-service.js";
|
||||
import { JoinTicketStore } from "./server/join-ticket.js";
|
||||
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT_DIR = path.resolve(__dirname, "..");
|
||||
@@ -21,6 +15,19 @@ const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
|
||||
const APP_VERSION = readPackageVersion();
|
||||
|
||||
async function main() {
|
||||
if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") {
|
||||
await runRelayMode();
|
||||
return;
|
||||
}
|
||||
const [{ createLogger }, { createWebServer }, { APP_PORT }, { WebSpeakDatabase }, { loadOrCreateMasterSecret }, { AdminService }, { JoinTicketStore }] = await Promise.all([
|
||||
import("./logger.js"),
|
||||
import("./server/server.js"),
|
||||
import("./constants.js"),
|
||||
import("./persistence/database.js"),
|
||||
import("./security/master-secret.js"),
|
||||
import("./admin/admin-service.js"),
|
||||
import("./server/join-ticket.js"),
|
||||
]);
|
||||
const logger = createLogger(LOG_DIR);
|
||||
const database = new WebSpeakDatabase(path.join(DATA_DIR, "webspeak.db"));
|
||||
const masterSecret = loadOrCreateMasterSecret(path.join(DATA_DIR, "master.key"));
|
||||
@@ -48,6 +55,13 @@ async function main() {
|
||||
certDir: hasCert ? CERT_DIR : undefined,
|
||||
voiceBridgeOptions: {
|
||||
joinTickets,
|
||||
webRtc: () => adminService.getWebRtcAudioOptions(),
|
||||
// The public gateway only uses the relay configuration explicitly
|
||||
// saved in the admin console. Environment variables belong to the
|
||||
// standalone relay process and must never make the relay option appear
|
||||
// in the visitor UI after an administrator disables it.
|
||||
acceleration: () => adminService.getAccelerationRelayOptions(),
|
||||
accelerationName: () => adminService.getAccelerationRelayName(),
|
||||
},
|
||||
adminService,
|
||||
logger,
|
||||
@@ -66,6 +80,22 @@ async function main() {
|
||||
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||
}
|
||||
|
||||
async function runRelayMode(): Promise<void> {
|
||||
const token = (process.env.WEBSPEAK_RELAY_TOKEN || process.env.WEBSPEAK_ACCELERATION_RELAY_TOKEN)?.trim();
|
||||
if (!token) throw new Error("WEBSPEAK_RELAY_TOKEN is required in relay mode");
|
||||
const host = (process.env.WEBSPEAK_RELAY_HOST || process.env.WEBSPEAK_ACCELERATION_RELAY_HOST)?.trim() || "0.0.0.0";
|
||||
const port = parsePort(process.env.WEBSPEAK_RELAY_PORT || process.env.WEBSPEAK_ACCELERATION_RELAY_PORT, 39087);
|
||||
const allowPrivate = parseBoolean(process.env.WEBSPEAK_RELAY_ALLOW_PRIVATE || process.env.WEBSPEAK_ACCELERATION_RELAY_ALLOW_PRIVATE);
|
||||
const server = await createAccelerationRelayServer({ host, port, token, allowPrivate });
|
||||
console.log(`WebSpeak relay mode listening on ${server.host}:${server.port}`);
|
||||
const shutdown = (): void => {
|
||||
server.close();
|
||||
process.exit(0);
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
process.once("SIGTERM", shutdown);
|
||||
}
|
||||
|
||||
function readPackageVersion(): string {
|
||||
try {
|
||||
const packageJson = JSON.parse(readFileSync(path.join(ROOT_DIR, "package.json"), "utf8")) as { version?: unknown };
|
||||
@@ -83,6 +113,16 @@ function removeObsoleteBootstrapFile(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function parsePort(value: string | undefined, fallback: number): number {
|
||||
const port = value ? Number(value) : fallback;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid relay port");
|
||||
return port;
|
||||
}
|
||||
|
||||
function parseBoolean(value: string | undefined): boolean {
|
||||
return value === "1" || value?.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fatal error:", err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -4,13 +4,18 @@ import { dirname } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import type { AdminCredential } from "../security/admin-password.js";
|
||||
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
|
||||
|
||||
export const DATABASE_SCHEMA_VERSION = 2;
|
||||
export const DATABASE_SCHEMA_VERSION = 7;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn: string;
|
||||
welcomeTextDe: string;
|
||||
welcomeTextRu: string;
|
||||
welcomeTextJa: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
@@ -19,16 +24,49 @@ export interface PersistedSettings {
|
||||
lastTestAt: string | null;
|
||||
lastTestLatencyMs: number | null;
|
||||
lastTestError: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart: number;
|
||||
webRtcUdpEnd: number;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
relayTokenEncrypted: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SettingsUpdate {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
tsPasswordEncrypted: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
relayTokenEncrypted: string | null;
|
||||
}
|
||||
|
||||
export interface PersistedRelayNode {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
host: string;
|
||||
port: number;
|
||||
tokenEncrypted: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ManagedInviteRecord {
|
||||
@@ -62,6 +100,10 @@ interface ManagedInviteRow extends Record<string, unknown> {
|
||||
interface SettingsRow extends Record<string, unknown> {
|
||||
site_name: string;
|
||||
welcome_text: string;
|
||||
welcome_text_en: string;
|
||||
welcome_text_de: string;
|
||||
welcome_text_ru: string;
|
||||
welcome_text_ja: string;
|
||||
access_mode: string;
|
||||
ts_host: string;
|
||||
ts_port: number;
|
||||
@@ -70,6 +112,27 @@ interface SettingsRow extends Record<string, unknown> {
|
||||
last_test_at: string | null;
|
||||
last_test_latency_ms: number | null;
|
||||
last_test_error: string | null;
|
||||
webrtc_enabled: number;
|
||||
webrtc_public_host: string;
|
||||
webrtc_udp_start: number;
|
||||
webrtc_udp_end: number;
|
||||
relay_configured: number;
|
||||
relay_enabled: number;
|
||||
relay_name: string;
|
||||
relay_host: string;
|
||||
relay_port: number;
|
||||
relay_token_encrypted: string | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface RelayNodeRow extends Record<string, unknown> {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: number;
|
||||
host: string;
|
||||
port: number;
|
||||
token_encrypted: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
@@ -132,6 +195,10 @@ export class WebSpeakDatabase {
|
||||
return {
|
||||
siteName: row.site_name,
|
||||
welcomeText: row.welcome_text,
|
||||
welcomeTextEn: row.welcome_text_en,
|
||||
welcomeTextDe: row.welcome_text_de,
|
||||
welcomeTextRu: row.welcome_text_ru,
|
||||
welcomeTextJa: row.welcome_text_ja,
|
||||
accessMode: row.access_mode === "open" ? "open" : "fixed",
|
||||
tsHost: row.ts_host,
|
||||
tsPort: row.ts_port,
|
||||
@@ -140,10 +207,58 @@ export class WebSpeakDatabase {
|
||||
lastTestAt: row.last_test_at,
|
||||
lastTestLatencyMs: row.last_test_latency_ms,
|
||||
lastTestError: row.last_test_error,
|
||||
webRtcEnabled: row.webrtc_enabled === 1,
|
||||
webRtcUdpStart: row.webrtc_udp_start,
|
||||
webRtcUdpEnd: row.webrtc_udp_end,
|
||||
relayConfigured: row.relay_configured === 1,
|
||||
relayEnabled: row.relay_enabled === 1,
|
||||
relayName: row.relay_name,
|
||||
relayHost: row.relay_host,
|
||||
relayPort: row.relay_port,
|
||||
relayTokenEncrypted: row.relay_token_encrypted,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
listRelayNodes(): PersistedRelayNode[] {
|
||||
const rows = this.database.prepare(
|
||||
"SELECT * FROM relay_nodes ORDER BY created_at ASC, id ASC",
|
||||
).all() as RelayNodeRow[];
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
enabled: row.enabled === 1,
|
||||
host: row.host,
|
||||
port: row.port,
|
||||
tokenEncrypted: row.token_encrypted,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}));
|
||||
}
|
||||
|
||||
replaceRelayNodes(nodes: Array<Omit<PersistedRelayNode, "createdAt" | "updatedAt"> & { createdAt?: string; updatedAt?: string }>): void {
|
||||
const now = new Date().toISOString();
|
||||
this.transaction(() => {
|
||||
this.database.exec("DELETE FROM relay_nodes");
|
||||
const insert = this.database.prepare(
|
||||
`INSERT INTO relay_nodes (id, name, enabled, host, port, token_encrypted, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
);
|
||||
for (const node of nodes) {
|
||||
insert.run(
|
||||
node.id,
|
||||
node.name,
|
||||
node.enabled ? 1 : 0,
|
||||
node.host,
|
||||
node.port,
|
||||
node.tokenEncrypted,
|
||||
node.createdAt ?? now,
|
||||
node.updatedAt ?? now,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
updateSettings(settings: SettingsUpdate, auditEvent = "SETTINGS_CHANGED"): void {
|
||||
const now = new Date().toISOString();
|
||||
this.transaction(() => {
|
||||
@@ -349,22 +464,130 @@ export class WebSpeakDatabase {
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 2");
|
||||
});
|
||||
version = 2;
|
||||
}
|
||||
if (version === 2) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
-- WebRTC media ports are stored with the administrator settings so the
|
||||
-- same range is used by the gateway and shown in the admin console.
|
||||
ALTER TABLE settings ADD COLUMN webrtc_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_enabled IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN webrtc_public_host TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN webrtc_udp_start INTEGER NOT NULL DEFAULT 40000 CHECK (webrtc_udp_start BETWEEN 1 AND 65535);
|
||||
ALTER TABLE settings ADD COLUMN webrtc_udp_end INTEGER NOT NULL DEFAULT 40099 CHECK (webrtc_udp_end BETWEEN 1 AND 65535);
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 3");
|
||||
});
|
||||
version = 3;
|
||||
}
|
||||
if (version === 3) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_en TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 4");
|
||||
});
|
||||
version = 4;
|
||||
}
|
||||
if (version === 4) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN relay_configured INTEGER NOT NULL DEFAULT 0 CHECK (relay_configured IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN relay_enabled INTEGER NOT NULL DEFAULT 0 CHECK (relay_enabled IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN relay_name TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN relay_host TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN relay_port INTEGER NOT NULL DEFAULT 39087 CHECK (relay_port BETWEEN 1 AND 65535);
|
||||
ALTER TABLE settings ADD COLUMN relay_token_encrypted TEXT;
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 5");
|
||||
});
|
||||
version = 5;
|
||||
}
|
||||
if (version === 5) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
CREATE TABLE relay_nodes (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 0 CHECK (enabled IN (0, 1)),
|
||||
host TEXT NOT NULL,
|
||||
port INTEGER NOT NULL CHECK (port BETWEEN 1 AND 65535),
|
||||
token_encrypted TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX relay_nodes_enabled_idx ON relay_nodes(enabled);
|
||||
`);
|
||||
const legacy = this.database.prepare(
|
||||
`SELECT relay_configured, relay_enabled, relay_name, relay_host, relay_port, relay_token_encrypted
|
||||
FROM settings WHERE id = 1`,
|
||||
).get() as {
|
||||
relay_configured?: number;
|
||||
relay_enabled?: number;
|
||||
relay_name?: string;
|
||||
relay_host?: string;
|
||||
relay_port?: number;
|
||||
relay_token_encrypted?: string | null;
|
||||
} | undefined;
|
||||
if (legacy?.relay_configured === 1 && legacy.relay_host && legacy.relay_token_encrypted) {
|
||||
const now = new Date().toISOString();
|
||||
this.database.prepare(
|
||||
`INSERT INTO relay_nodes (id, name, enabled, host, port, token_encrypted, created_at, updated_at)
|
||||
VALUES ('relay-default', ?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
legacy.relay_name || "中继加速",
|
||||
legacy.relay_enabled === 1 ? 1 : 0,
|
||||
legacy.relay_host,
|
||||
legacy.relay_port || 39087,
|
||||
legacy.relay_token_encrypted,
|
||||
now,
|
||||
now,
|
||||
);
|
||||
}
|
||||
this.database.exec("PRAGMA user_version = 6");
|
||||
});
|
||||
version = 6;
|
||||
}
|
||||
if (version === 6) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_de TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_ru TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_ja TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 7");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private writeSettings(settings: SettingsUpdate, now: string): void {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, updated_at = ?
|
||||
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_udp_start = ?,
|
||||
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
|
||||
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
).run(
|
||||
settings.siteName,
|
||||
settings.welcomeText,
|
||||
settings.welcomeTextEn ?? "",
|
||||
settings.welcomeTextDe ?? "",
|
||||
settings.welcomeTextRu ?? "",
|
||||
settings.welcomeTextJa ?? "",
|
||||
settings.accessMode,
|
||||
settings.tsHost,
|
||||
settings.tsPort,
|
||||
settings.tsPasswordEncrypted,
|
||||
settings.webRtcEnabled ? 1 : 0,
|
||||
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
|
||||
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
|
||||
settings.relayConfigured ? 1 : 0,
|
||||
settings.relayEnabled ? 1 : 0,
|
||||
settings.relayName,
|
||||
settings.relayHost,
|
||||
settings.relayPort,
|
||||
settings.relayTokenEncrypted,
|
||||
now,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
|
||||
const token = process.env.WEBSPEAK_ACCELERATION_RELAY_TOKEN?.trim();
|
||||
if (!token) throw new Error("WEBSPEAK_ACCELERATION_RELAY_TOKEN is required");
|
||||
|
||||
const server = await createAccelerationRelayServer({
|
||||
host: process.env.WEBSPEAK_ACCELERATION_RELAY_HOST?.trim() || "0.0.0.0",
|
||||
port: parsePort(process.env.WEBSPEAK_ACCELERATION_RELAY_PORT, 39087),
|
||||
token,
|
||||
allowPrivate: parseBoolean(process.env.WEBSPEAK_ACCELERATION_RELAY_ALLOW_PRIVATE),
|
||||
});
|
||||
|
||||
console.log(`WebSpeak acceleration relay listening on ${server.host}:${server.port}`);
|
||||
|
||||
const shutdown = (): void => {
|
||||
server.close();
|
||||
process.exit(0);
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
process.once("SIGTERM", shutdown);
|
||||
|
||||
function parsePort(value: string | undefined, fallback: number): number {
|
||||
const port = value ? Number(value) : fallback;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid WEBSPEAK_ACCELERATION_RELAY_PORT");
|
||||
return port;
|
||||
}
|
||||
|
||||
function parseBoolean(value: string | undefined): boolean {
|
||||
return value === "1" || value?.toLowerCase() === "true";
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { createSocket } from "node:dgram";
|
||||
import { isIP } from "node:net";
|
||||
import { lookup } from "node:dns/promises";
|
||||
|
||||
const MAGIC = Buffer.from("WSAT");
|
||||
const VERSION = 1;
|
||||
const HEADER_SIZE = 34;
|
||||
const MAX_PAYLOAD_SIZE = 60_000;
|
||||
export const DEFAULT_ACCELERATION_RELAY_PORT = 39087;
|
||||
|
||||
const enum FrameType {
|
||||
OPEN = 1,
|
||||
OPEN_OK = 2,
|
||||
OPEN_ERR = 3,
|
||||
DATA = 4,
|
||||
CLOSE = 5,
|
||||
PING = 6,
|
||||
PONG = 7,
|
||||
}
|
||||
|
||||
export interface AccelerationRelayOptions {
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
token: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface ConfiguredAccelerationRelay extends AccelerationRelayOptions {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AccelerationTarget {
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
export interface AccelerationRelayClient {
|
||||
readonly localHost: string;
|
||||
readonly localPort: number;
|
||||
readonly sessionId: number;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
interface Frame {
|
||||
type: FrameType;
|
||||
sessionId: number;
|
||||
sequence: number;
|
||||
payload: Buffer;
|
||||
auth: Buffer;
|
||||
raw: Buffer;
|
||||
}
|
||||
|
||||
export async function createAccelerationRelayClient(
|
||||
options: AccelerationRelayOptions & AccelerationTarget,
|
||||
): Promise<AccelerationRelayClient> {
|
||||
validateRelayOptions(options);
|
||||
const relayFamily = isIP(options.relayHost) === 6 ? "udp6" : "udp4";
|
||||
const relaySocket = createSocket(relayFamily);
|
||||
const localSocket = createSocket("udp4");
|
||||
const sessionId = randomSessionId();
|
||||
let sequence = 1;
|
||||
let ready = false;
|
||||
let closed = false;
|
||||
let resolveReady: () => void = () => undefined;
|
||||
let rejectReady: (error: Error) => void = () => undefined;
|
||||
let keepAlive: ReturnType<typeof setInterval> | null = null;
|
||||
const readyPromise = new Promise<void>((resolve, reject) => {
|
||||
resolveReady = resolve;
|
||||
rejectReady = reject;
|
||||
});
|
||||
|
||||
const sendFrame = (type: FrameType, payload: Buffer<ArrayBufferLike> = Buffer.alloc(0)): void => {
|
||||
if (closed) return;
|
||||
const packet = encodeFrame(type, sessionId, sequence++, payload, options.token);
|
||||
try {
|
||||
relaySocket.send(packet, options.relayPort, options.relayHost);
|
||||
} catch (error) {
|
||||
if (!ready) rejectReady(asError(error));
|
||||
}
|
||||
};
|
||||
|
||||
const closeSockets = (): void => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (keepAlive) clearInterval(keepAlive);
|
||||
keepAlive = null;
|
||||
try { relaySocket.close(); } catch { /* already closed */ }
|
||||
try { localSocket.close(); } catch { /* already closed */ }
|
||||
};
|
||||
|
||||
const onSocketError = (error: Error): void => {
|
||||
if (!ready) rejectReady(error);
|
||||
closeSockets();
|
||||
};
|
||||
relaySocket.once("error", onSocketError);
|
||||
localSocket.once("error", onSocketError);
|
||||
|
||||
let peer: { address: string; port: number } | null = null;
|
||||
relaySocket.on("message", (packet) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || frame.sessionId !== sessionId || !verifyFrame(frame, options.token)) return;
|
||||
if (frame.type === FrameType.OPEN_OK) {
|
||||
if (ready) return;
|
||||
ready = true;
|
||||
keepAlive = setInterval(() => sendFrame(FrameType.PING), 10_000);
|
||||
keepAlive.unref?.();
|
||||
resolveReady();
|
||||
return;
|
||||
}
|
||||
if (frame.type === FrameType.OPEN_ERR) {
|
||||
const detail = parseJson(frame.payload);
|
||||
rejectReady(new Error(typeof detail?.code === "string" ? detail.code : "ACCELERATION_OPEN_FAILED"));
|
||||
closeSockets();
|
||||
return;
|
||||
}
|
||||
if (frame.type === FrameType.DATA && peer) {
|
||||
try { localSocket.send(frame.payload, peer.port, peer.address); } catch { /* peer is gone */ }
|
||||
return;
|
||||
}
|
||||
if (frame.type === FrameType.CLOSE) closeSockets();
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
bindSocket(relaySocket, relayFamily === "udp6" ? "::" : "0.0.0.0"),
|
||||
bindSocket(localSocket, "127.0.0.1"),
|
||||
]);
|
||||
|
||||
localSocket.on("message", (payload, rinfo) => {
|
||||
if (closed) return;
|
||||
peer = { address: rinfo.address, port: rinfo.port };
|
||||
if (ready) sendFrame(FrameType.DATA, payload);
|
||||
});
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
rejectReady(new Error("ACCELERATION_OPEN_TIMEOUT"));
|
||||
closeSockets();
|
||||
}, options.timeoutMs ?? 15_000);
|
||||
timer.unref?.();
|
||||
sendFrame(FrameType.OPEN, jsonPayload({ targetHost: options.host, targetPort: options.port }));
|
||||
try {
|
||||
await readyPromise;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
const address = localSocket.address();
|
||||
return {
|
||||
localHost: "127.0.0.1",
|
||||
localPort: typeof address === "object" ? address.port : 0,
|
||||
sessionId,
|
||||
close(): void {
|
||||
if (!closed && ready) {
|
||||
try { sendFrame(FrameType.CLOSE); } catch { /* best effort */ }
|
||||
}
|
||||
closeSockets();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function createAccelerationRelayServer({
|
||||
host = "0.0.0.0",
|
||||
port = 39087,
|
||||
token,
|
||||
allowPrivate = false,
|
||||
idleTimeoutMs = 30_000,
|
||||
}: {
|
||||
host?: string;
|
||||
port?: number;
|
||||
token: string;
|
||||
allowPrivate?: boolean;
|
||||
idleTimeoutMs?: number;
|
||||
}): Promise<{ host: string; port: number; close(): void }> {
|
||||
if (!token || token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters");
|
||||
const socket = createSocket(isIP(host) === 6 ? "udp6" : "udp4");
|
||||
const sessions = new Map<number, RelaySession>();
|
||||
let closed = false;
|
||||
|
||||
const send = (session: RelaySession, type: FrameType, payload: Buffer<ArrayBufferLike> = Buffer.alloc(0)): void => {
|
||||
if (closed) return;
|
||||
try { socket.send(encodeFrame(type, session.id, session.outSequence++, payload, token), session.client.port, session.client.address); } catch { /* client is gone */ }
|
||||
};
|
||||
const cleanup = (session: RelaySession): void => {
|
||||
if (session.closed) return;
|
||||
session.closed = true;
|
||||
sessions.delete(session.id);
|
||||
session.targetSocket?.close();
|
||||
};
|
||||
|
||||
socket.on("message", (packet, rinfo) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || !verifyFrame(frame, token)) return;
|
||||
const client = { address: rinfo.address, port: rinfo.port };
|
||||
if (frame.type === FrameType.OPEN) {
|
||||
void openRelaySession(frame, client, socket, sessions, token, allowPrivate, send, cleanup);
|
||||
return;
|
||||
}
|
||||
const session = sessions.get(frame.sessionId);
|
||||
if (!session || session.client.address !== rinfo.address || session.client.port !== rinfo.port) return;
|
||||
session.lastActivity = Date.now();
|
||||
if (frame.type === FrameType.DATA && session.targetSocket) session.targetSocket.send(frame.payload);
|
||||
else if (frame.type === FrameType.PING) send(session, FrameType.PONG);
|
||||
else if (frame.type === FrameType.CLOSE) { send(session, FrameType.CLOSE); cleanup(session); }
|
||||
});
|
||||
socket.on("error", (error) => {
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
if (!closed) throw error;
|
||||
});
|
||||
|
||||
const sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const session of sessions.values()) if (now - session.lastActivity > idleTimeoutMs) cleanup(session);
|
||||
}, Math.max(1000, Math.min(idleTimeoutMs, 5000)));
|
||||
sweep.unref?.();
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onError = (error: Error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
const address = socket.address();
|
||||
return {
|
||||
host,
|
||||
port: typeof address === "object" ? address.port : port,
|
||||
close(): void {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(sweep);
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
socket.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface RelaySession {
|
||||
id: number;
|
||||
client: { address: string; port: number };
|
||||
targetSocket: ReturnType<typeof createSocket> | null;
|
||||
outSequence: number;
|
||||
lastActivity: number;
|
||||
closed: boolean;
|
||||
}
|
||||
|
||||
async function openRelaySession(
|
||||
frame: Frame,
|
||||
client: { address: string; port: number },
|
||||
socket: ReturnType<typeof createSocket>,
|
||||
sessions: Map<number, RelaySession>,
|
||||
token: string,
|
||||
allowPrivate: boolean,
|
||||
send: (session: RelaySession, type: FrameType, payload?: Buffer) => void,
|
||||
cleanup: (session: RelaySession) => void,
|
||||
): Promise<void> {
|
||||
const request = parseJson(frame.payload);
|
||||
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) return;
|
||||
const targetPort = request.targetPort as number;
|
||||
if (!allowPrivate && isPrivateAddress(request.targetHost)) {
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "PRIVATE_TARGET_BLOCKED" }), token), client.port, client.address);
|
||||
return;
|
||||
}
|
||||
const previous = sessions.get(frame.sessionId);
|
||||
if (previous) cleanup(previous);
|
||||
const session: RelaySession = { id: frame.sessionId, client, targetSocket: null, outSequence: 1, lastActivity: Date.now(), closed: false };
|
||||
sessions.set(session.id, session);
|
||||
try {
|
||||
const target = await resolveTarget(request.targetHost);
|
||||
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
|
||||
session.targetSocket = targetSocket;
|
||||
targetSocket.on("message", (payload) => { session.lastActivity = Date.now(); send(session, FrameType.DATA, payload); });
|
||||
targetSocket.on("error", (error) => { if (!session.closed) send(session, FrameType.OPEN_ERR, jsonPayload({ code: "TARGET_SOCKET_ERROR", message: error.message })); cleanup(session); });
|
||||
targetSocket.connect(targetPort, target.host, () => {
|
||||
session.lastActivity = Date.now();
|
||||
send(session, FrameType.OPEN_OK, jsonPayload({ targetHost: target.host, targetPort }));
|
||||
});
|
||||
} catch (error) {
|
||||
cleanup(session);
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "TARGET_OPEN_FAILED", message: asError(error).message }), token), client.port, client.address);
|
||||
}
|
||||
}
|
||||
|
||||
function validateRelayOptions(options: AccelerationRelayOptions & AccelerationTarget): void {
|
||||
if (!options.relayHost || !Number.isInteger(options.relayPort) || options.relayPort < 1 || options.relayPort > 65535) throw new Error("Invalid acceleration relay endpoint");
|
||||
if (!options.host || !Number.isInteger(options.port) || options.port < 1 || options.port > 65535) throw new Error("Invalid accelerated TeamSpeak target");
|
||||
if (!options.token || options.token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters");
|
||||
}
|
||||
|
||||
function bindSocket(socket: ReturnType<typeof createSocket>, address: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (error: Error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind(0, address);
|
||||
});
|
||||
}
|
||||
|
||||
function encodeFrame(type: FrameType, sessionId: number, sequence: number, payload: Buffer, token: string): Buffer {
|
||||
if (payload.length > MAX_PAYLOAD_SIZE) throw new Error("Acceleration relay payload is too large");
|
||||
const frame = Buffer.alloc(HEADER_SIZE + payload.length);
|
||||
MAGIC.copy(frame, 0);
|
||||
frame[4] = VERSION;
|
||||
frame[5] = type;
|
||||
frame.writeUInt32BE(sessionId >>> 0, 8);
|
||||
frame.writeUInt32BE(sequence >>> 0, 12);
|
||||
frame.writeUInt16BE(payload.length, 16);
|
||||
payload.copy(frame, HEADER_SIZE);
|
||||
signFrame(frame, payload, token).copy(frame, 18);
|
||||
return frame;
|
||||
}
|
||||
|
||||
function decodeFrame(packet: Buffer): Frame | null {
|
||||
if (packet.length < HEADER_SIZE || !packet.subarray(0, 4).equals(MAGIC) || packet[4] !== VERSION) return null;
|
||||
const payloadLength = packet.readUInt16BE(16);
|
||||
if (packet.length !== HEADER_SIZE + payloadLength || payloadLength > MAX_PAYLOAD_SIZE) return null;
|
||||
return { type: packet[5] as FrameType, sessionId: packet.readUInt32BE(8), sequence: packet.readUInt32BE(12), payload: packet.subarray(HEADER_SIZE), auth: packet.subarray(18, HEADER_SIZE), raw: packet };
|
||||
}
|
||||
|
||||
function verifyFrame(frame: Frame, token: string): boolean {
|
||||
const expected = signFrame(frame.raw, frame.payload, token);
|
||||
return expected.length === frame.auth.length && timingSafeEqual(expected, frame.auth);
|
||||
}
|
||||
|
||||
function signFrame(frame: Buffer, payload: Buffer, token: string): Buffer {
|
||||
return createHmac("sha256", Buffer.from(token, "utf8")).update(frame.subarray(0, 18)).update(payload).digest().subarray(0, 16);
|
||||
}
|
||||
|
||||
function randomSessionId(): number {
|
||||
const id = randomBytes(4).readUInt32BE(0);
|
||||
return id === 0 ? 1 : id;
|
||||
}
|
||||
|
||||
function jsonPayload(value: unknown): Buffer { return Buffer.from(JSON.stringify(value), "utf8"); }
|
||||
|
||||
function parseJson(payload: Buffer): Record<string, unknown> | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(payload.toString("utf8"));
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function isPrivateAddress(host: string): boolean {
|
||||
const family = isIP(host);
|
||||
if (family === 4) {
|
||||
const parts = host.split(".").map(Number);
|
||||
return parts[0] === 10 || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 192 && parts[1] === 168) || parts[0] === 127 || (parts[0] === 169 && parts[1] === 254) || parts[0] === 0;
|
||||
}
|
||||
if (family === 6) {
|
||||
const normalized = host.toLocaleLowerCase();
|
||||
return normalized === "::" || normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb");
|
||||
}
|
||||
return host === "localhost" || host.endsWith(".localhost");
|
||||
}
|
||||
|
||||
async function resolveTarget(host: string): Promise<{ host: string; family: number }> {
|
||||
const family = isIP(host);
|
||||
if (family) return { host, family };
|
||||
const records = await lookup(host, { all: true, verbatim: true });
|
||||
const record = records.find((item) => item.family === 4) ?? records[0];
|
||||
if (!record) throw new Error("TARGET_DNS_EMPTY");
|
||||
return { host: record.address, family: record.family };
|
||||
}
|
||||
|
||||
function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); }
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { ClientInfo } from "@honeybbq/teamspeak-client";
|
||||
import type { ClientInfo, DirectoryClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
type DirectoryDelta =
|
||||
| { type: "clientEnter"; info: ClientInfo }
|
||||
| { type: "clientLeave"; id: number }
|
||||
| { type: "clientMoved"; id: number; channelID: bigint };
|
||||
| { type: "clientMoved"; id: number; channelID: bigint }
|
||||
| { type: "clientUpdated"; info: DirectoryClientInfo };
|
||||
|
||||
/**
|
||||
* Merges staged welcome snapshots with events received while the snapshot is
|
||||
@@ -14,7 +15,7 @@ type DirectoryDelta =
|
||||
*/
|
||||
export class DirectorySynchronizer {
|
||||
private snapshot: TSDirectorySnapshot | null = null;
|
||||
private clients = new Map<number, ClientInfo>();
|
||||
private clients = new Map<number, DirectoryClientInfo>();
|
||||
private pending: DirectoryDelta[] = [];
|
||||
|
||||
get ready(): boolean {
|
||||
@@ -43,6 +44,10 @@ export class DirectorySynchronizer {
|
||||
this.applyOrQueue({ type: "clientMoved", id, channelID });
|
||||
}
|
||||
|
||||
applyClientUpdated(info: DirectoryClientInfo): void {
|
||||
this.applyOrQueue({ type: "clientUpdated", info });
|
||||
}
|
||||
|
||||
getSnapshot(): TSDirectorySnapshot | null {
|
||||
if (!this.snapshot) return null;
|
||||
return {
|
||||
@@ -74,6 +79,11 @@ export class DirectorySynchronizer {
|
||||
this.clients.delete(delta.id);
|
||||
return;
|
||||
}
|
||||
if (delta.type === "clientUpdated") {
|
||||
const current = this.clients.get(delta.info.id);
|
||||
this.clients.set(delta.info.id, current ? { ...current, ...delta.info } : delta.info);
|
||||
return;
|
||||
}
|
||||
const current = this.clients.get(delta.id);
|
||||
if (current) this.clients.set(delta.id, { ...current, channelID: delta.channelID });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Prevents one persisted TeamSpeak identity from being used by two live
|
||||
* browser sessions at the same target at the same time.
|
||||
*/
|
||||
export class IdentityLeaseStore {
|
||||
private readonly owners = new Map<string, string>();
|
||||
|
||||
acquire(key: string, owner: string): boolean {
|
||||
const currentOwner = this.owners.get(key);
|
||||
if (currentOwner && currentOwner !== owner) return false;
|
||||
this.owners.set(key, owner);
|
||||
return true;
|
||||
}
|
||||
|
||||
release(key: string, owner: string): void {
|
||||
if (this.owners.get(key) === owner) this.owners.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ export interface JoinTicketPayload {
|
||||
channel?: string;
|
||||
identity?: string;
|
||||
rememberIdentity?: boolean;
|
||||
accelerated?: boolean;
|
||||
accelerationRelayId?: string;
|
||||
}
|
||||
|
||||
interface StoredTicket {
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export type TeamSpeakPingErrorCode =
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "TIMEOUT"
|
||||
| "PING_UNAVAILABLE"
|
||||
| "INVALID_PASSWORD"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "SERVER_REJECTED"
|
||||
| "INTERNAL_ERROR";
|
||||
|
||||
export interface TeamSpeakPingAttempt {
|
||||
ok: boolean;
|
||||
latencyMs: number | null;
|
||||
errorCode?: TeamSpeakPingErrorCode;
|
||||
}
|
||||
|
||||
export interface TeamSpeakPingResult {
|
||||
ok: boolean;
|
||||
latencyMs: number | null;
|
||||
packetLossPercent: number;
|
||||
attempts: number;
|
||||
successfulAttempts: number;
|
||||
samples: number[];
|
||||
errorCode?: TeamSpeakPingErrorCode;
|
||||
}
|
||||
|
||||
export type TeamSpeakCommandExecutor = (command: string, timeoutMs?: number) => Promise<unknown>;
|
||||
|
||||
export type HostPingExecutor = (host: string, timeoutMs: number) => Promise<number>;
|
||||
|
||||
/**
|
||||
* Measure an already connected TeamSpeak session using the protocol's own
|
||||
* command channel. TeamSpeak voice/query traffic is UDP; a TCP connect to
|
||||
* port 9987 is therefore not a valid reachability test and reports false
|
||||
* packet loss even while voice works normally.
|
||||
*/
|
||||
export async function pingTeamSpeakSession(
|
||||
execute: TeamSpeakCommandExecutor,
|
||||
timeoutMs = 1_500,
|
||||
): Promise<TeamSpeakPingAttempt> {
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
// `version` is read-only and is handled by both TS3 and TS6.
|
||||
await execute("version", timeoutMs);
|
||||
return { ok: true, latencyMs: Math.max(0, Date.now() - startedAt) };
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: null,
|
||||
errorCode: classifyProbeError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function collectTeamSpeakPings(
|
||||
probe: () => Promise<TeamSpeakPingAttempt>,
|
||||
options: { attempts?: number } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
const attempts = Math.max(1, Math.min(8, Math.floor(options.attempts ?? 4)));
|
||||
const results: TeamSpeakPingAttempt[] = [];
|
||||
// Keep attempts sequential. This measures the real protocol path without
|
||||
// opening several temporary TeamSpeak sessions at the same time.
|
||||
for (let index = 0; index < attempts; index += 1) {
|
||||
results.push(await probe());
|
||||
}
|
||||
return summarizeTeamSpeakPings(results, attempts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ping the TeamSpeak host from the WebSpeak machine without creating a
|
||||
* TeamSpeak client. This is intentionally a host/network diagnostic: the
|
||||
* TeamSpeak voice port is UDP, so a TCP socket probe is not meaningful and a
|
||||
* client-protocol probe would create an extra visible member.
|
||||
*/
|
||||
export async function pingTeamSpeakHost(
|
||||
host: string,
|
||||
options: { attempts?: number; timeoutMs?: number; execute?: HostPingExecutor } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
const timeoutMs = Math.max(250, Math.min(5_000, Math.floor(options.timeoutMs ?? 1_000)));
|
||||
const execute = options.execute ?? pingHostOnce;
|
||||
return collectTeamSpeakPings(async () => {
|
||||
try {
|
||||
return { ok: true, latencyMs: await execute(host, timeoutMs) };
|
||||
} catch (error: unknown) {
|
||||
return { ok: false, latencyMs: null, errorCode: classifyProbeError(error) };
|
||||
}
|
||||
}, { attempts: options.attempts ?? 4 });
|
||||
}
|
||||
|
||||
export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempts = results.length): TeamSpeakPingResult {
|
||||
const normalizedAttempts = Math.max(1, attempts);
|
||||
const samples = results
|
||||
.filter((result): result is TeamSpeakPingAttempt & { latencyMs: number } => result.ok && result.latencyMs !== null)
|
||||
.map((result) => result.latencyMs)
|
||||
.sort((left, right) => left - right);
|
||||
const errorCode = results.find((result) => result.errorCode)?.errorCode;
|
||||
|
||||
return {
|
||||
ok: samples.length > 0,
|
||||
latencyMs: samples.length ? samples[Math.floor(samples.length / 2)] : null,
|
||||
packetLossPercent: Math.round(((normalizedAttempts - samples.length) / normalizedAttempts) * 100),
|
||||
attempts: normalizedAttempts,
|
||||
successfulAttempts: samples.length,
|
||||
samples,
|
||||
...(errorCode ? { errorCode } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const lower = text.toLocaleLowerCase();
|
||||
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";
|
||||
// 关键词刻意收窄:裸的 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";
|
||||
}
|
||||
|
||||
function pingHostOnce(host: string, timeoutMs: number): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const windows = process.platform === "win32";
|
||||
const command = windows ? "ping.exe" : "ping";
|
||||
const args = windows
|
||||
? ["-n", "1", "-w", String(timeoutMs), host]
|
||||
: ["-c", "1", "-W", String(Math.max(1, Math.ceil(timeoutMs / 1_000))), host];
|
||||
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let output = "";
|
||||
let settled = false;
|
||||
const finish = (callback: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
callback();
|
||||
};
|
||||
const timer = setTimeout(() => finish(() => {
|
||||
child.kill();
|
||||
reject(new Error("ping timeout"));
|
||||
}), timeoutMs + 250);
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => { output += chunk; });
|
||||
child.stderr.on("data", (chunk: string) => { output += chunk; });
|
||||
child.once("error", (error) => finish(() => reject(error)));
|
||||
child.once("close", (code) => finish(() => {
|
||||
const match = output.match(/(?:time|时间)\s*[=<]\s*([\d.,]+)\s*(?:ms|毫秒)?/i);
|
||||
if (code === 0 && match) {
|
||||
const latencyMs = Number.parseFloat(match[1].replace(",", "."));
|
||||
if (Number.isFinite(latencyMs)) {
|
||||
resolve(Math.max(0, latencyMs));
|
||||
return;
|
||||
}
|
||||
}
|
||||
reject(new Error(output.trim() || `ping exited with code ${code ?? "unknown"}`));
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a small compatibility helper for callers that only need one protocol
|
||||
* attempt. It deliberately has no host/port argument because the connected
|
||||
* TeamSpeak session owns the actual resolved endpoint.
|
||||
*/
|
||||
export function pingTeamSpeakPort(
|
||||
execute: TeamSpeakCommandExecutor,
|
||||
timeoutMs = 1_500,
|
||||
): Promise<TeamSpeakPingAttempt> {
|
||||
return pingTeamSpeakSession(execute, timeoutMs);
|
||||
}
|
||||
|
||||
/*
|
||||
* This function used to open a raw TCP socket to the TeamSpeak voice port.
|
||||
* That transport is not TeamSpeak's client protocol and must not be used for
|
||||
* reachability measurements. Keep the aggregation logic above independent of
|
||||
* the connection setup so admin tests can supply a real protocol probe.
|
||||
*/
|
||||
export async function pingTeamSpeak(
|
||||
probe: () => Promise<TeamSpeakPingAttempt>,
|
||||
options: { attempts?: number } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
return collectTeamSpeakPings(probe, options);
|
||||
}
|
||||
@@ -10,8 +10,9 @@ import { createAdminRouter } from "../admin/admin-router.js";
|
||||
import type { AdminService } from "../admin/admin-service.js";
|
||||
import { AdminSessionStore } from "../admin/admin-session.js";
|
||||
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
|
||||
import { identityFromString } from "@honeybbq/teamspeak-client";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { JoinRateLimiter } from "./join-rate-limit.js";
|
||||
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
@@ -59,7 +60,12 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
|
||||
app.get("/api/public-config", (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.json(options.adminService.getPublicConfig());
|
||||
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
|
||||
response.json({
|
||||
...options.adminService.getPublicConfig(),
|
||||
accelerationAvailable: acceleration.length > 0,
|
||||
accelerationRelays: acceleration.map((relay) => ({ id: relay.id, name: relay.name })),
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/api/join-ticket", async (request, response) => {
|
||||
@@ -104,15 +110,34 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
let target = managedInvite?.target ?? policy.defaultTarget;
|
||||
let serverPassword = managedInvite?.serverPassword ?? policy.serverPassword;
|
||||
const channel = requestedChannel || managedInvite?.channel || "";
|
||||
const requestedRelayId = typeof body.accelerationRelayId === "string" ? body.accelerationRelayId.trim().slice(0, 110) : "";
|
||||
const accelerationRequested = body.accelerated === true || Boolean(requestedRelayId);
|
||||
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
|
||||
if (accelerationRequested && acceleration.length === 0) {
|
||||
response.status(400).json({ ok: false, code: "ACCELERATION_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
if (requestedRelayId && !acceleration.some((relay) => relay.id === requestedRelayId)) {
|
||||
response.status(400).json({ ok: false, code: "ACCELERATION_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
if (!managedInvite) {
|
||||
try {
|
||||
if (policy.accessMode === "open" && typeof body.target === "string" && body.target.trim()) {
|
||||
target = parseTeamSpeakTarget(body.target);
|
||||
const isDefault = teamSpeakTargetKey(target) === teamSpeakTargetKey(policy.defaultTarget);
|
||||
if (!isDefault) {
|
||||
target = await resolveSafeOpenTarget(target);
|
||||
serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
|
||||
}
|
||||
// Open mode must protect the gateway even when a user submits the
|
||||
// same address configured as the administrator's default target.
|
||||
// The default target only controls which server is prefilled; it is
|
||||
// not a trust boundary and must not bypass SSRF protection.
|
||||
target = await resolveSafeOpenTarget(target);
|
||||
if (!isDefault) serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
|
||||
else if (typeof body.serverPassword === "string" && body.serverPassword.trim()) serverPassword = body.serverPassword.slice(0, 512);
|
||||
} else if (policy.accessMode === "fixed" && typeof body.serverPassword === "string" && body.serverPassword.trim()) {
|
||||
// The fixed target remains administrator-controlled, but a user may
|
||||
// retry its server password after the gateway reports that one is
|
||||
// required. The target itself is never taken from this request.
|
||||
serverPassword = body.serverPassword.slice(0, 512);
|
||||
}
|
||||
} catch {
|
||||
response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" });
|
||||
@@ -126,6 +151,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
nickname,
|
||||
...(channel ? { channel } : {}),
|
||||
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
|
||||
...(accelerationRequested ? { accelerated: true, ...(requestedRelayId ? { accelerationRelayId: requestedRelayId } : {}) } : {}),
|
||||
});
|
||||
response.status(201).json({ ok: true, ticket });
|
||||
});
|
||||
@@ -173,6 +199,14 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAccelerationOptions(
|
||||
configured: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]) | undefined,
|
||||
): ConfiguredAccelerationRelay[] {
|
||||
const value = typeof configured === "function" ? configured() : configured;
|
||||
if (!value) return [];
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ export type SessionTeardownReason =
|
||||
| "websocket-error"
|
||||
| "protocol-error"
|
||||
| "teamSpeak-disconnect"
|
||||
| "teamSpeak-kicked" // 会话被 TeamSpeak 服务器踢出/封禁时拆除
|
||||
| "teamSpeak-connect-failed"
|
||||
| "heartbeat-timeout"
|
||||
| "admin-terminated"
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
generateIdentity,
|
||||
type ClientOptions,
|
||||
type Identity,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -57,6 +57,8 @@ export class EndpointProtocolCache {
|
||||
|
||||
export const endpointProtocolCache = new EndpointProtocolCache();
|
||||
|
||||
const TEAM_SPEAK_CONNECT_TIMEOUT_MS = 15_000;
|
||||
|
||||
export interface TeamSpeakAdapterOptions {
|
||||
target: TeamSpeakTarget;
|
||||
nickname: string;
|
||||
@@ -109,8 +111,9 @@ export class TeamSpeakAdapter {
|
||||
this.logger.info({ target: formatTeamSpeakTarget(this.target), cachedProtocol }, "Connecting through TeamSpeak adapter");
|
||||
try {
|
||||
await this.client.connect();
|
||||
await this.client.waitConnected();
|
||||
await this.client.waitConnected(AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS));
|
||||
} catch (error: unknown) {
|
||||
await this.client.disconnect().catch(() => undefined);
|
||||
throw normalizeTeamSpeakError(error);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError, type WebSpeakErrorCode } from "../errors.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
import { TSClient } from "./ts-client.js";
|
||||
import type { TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
|
||||
export type ProbeErrorCode =
|
||||
| "INVALID_NICKNAME"
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "CONNECTION_REFUSED"
|
||||
| "CONNECTION_RESET"
|
||||
| "TIMEOUT"
|
||||
| "PASSWORD_REQUIRED"
|
||||
| "INVALID_PASSWORD"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "SERVER_REJECTED"
|
||||
@@ -30,8 +35,10 @@ export class TeamSpeakProbeError extends Error {
|
||||
interface ProbeAdapter {
|
||||
connect(): Promise<void>;
|
||||
disconnect(): Promise<void>;
|
||||
readonly protocol: TeamSpeakProtocol | null;
|
||||
readonly client: {
|
||||
readonly protocol?: TeamSpeakProtocol | null;
|
||||
getProtocol?(): TeamSpeakProtocol | null;
|
||||
execCommandWithResponse?(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
|
||||
readonly client?: {
|
||||
execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
|
||||
};
|
||||
}
|
||||
@@ -47,7 +54,15 @@ export async function probeTeamSpeak(
|
||||
password: string,
|
||||
logger: Logger,
|
||||
factory: ProbeAdapterFactory = ({ target: probeTarget, password: probePassword, logger: probeLogger }) =>
|
||||
new TeamSpeakAdapter({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger),
|
||||
(() => {
|
||||
const client = new TSClient({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger);
|
||||
return {
|
||||
connect: () => client.connect(),
|
||||
disconnect: () => client.disconnect(),
|
||||
getProtocol: () => client.getProtocol(),
|
||||
execCommandWithResponse: (command: string, timeoutMs?: number) => client.execCommandWithResponse(command, timeoutMs),
|
||||
};
|
||||
})(),
|
||||
): Promise<TeamSpeakProbeResult> {
|
||||
const startedAt = Date.now();
|
||||
const adapter = factory({ target, password, logger: logger.child({ component: "teamspeak-probe" }) });
|
||||
@@ -55,7 +70,9 @@ export async function probeTeamSpeak(
|
||||
await adapter.connect();
|
||||
let serverName: string | null = null;
|
||||
try {
|
||||
const rows = await adapter.client.execCommandWithResponse("serverinfo", 3000);
|
||||
const execute = adapter.execCommandWithResponse?.bind(adapter) ?? adapter.client?.execCommandWithResponse.bind(adapter.client);
|
||||
if (!execute) throw new Error("Probe adapter does not support commands");
|
||||
const rows = await execute("serverinfo", 3000);
|
||||
const first = rows[0] ?? {};
|
||||
serverName = first.virtualserver_name ?? first.server_name ?? first.name ?? null;
|
||||
} catch {
|
||||
@@ -63,13 +80,13 @@ export async function probeTeamSpeak(
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
protocol: adapter.protocol,
|
||||
protocol: adapter.protocol ?? adapter.getProtocol?.() ?? null,
|
||||
latencyMs: Math.max(0, Date.now() - startedAt),
|
||||
serverName,
|
||||
requiresPassword: Boolean(password),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
throw toProbeError(error);
|
||||
throw toProbeError(error, password);
|
||||
} finally {
|
||||
try {
|
||||
await adapter.disconnect();
|
||||
@@ -79,18 +96,38 @@ export async function probeTeamSpeak(
|
||||
}
|
||||
}
|
||||
|
||||
export function toProbeError(error: unknown): TeamSpeakProbeError {
|
||||
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();
|
||||
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: "INVALID_PASSWORD",
|
||||
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",
|
||||
@@ -100,6 +137,6 @@ export function toProbeError(error: unknown): TeamSpeakProbeError {
|
||||
|
||||
function extractErrorText(error: unknown): string {
|
||||
if (!error || typeof error !== "object") return String(error ?? "");
|
||||
const candidate = error as { code?: unknown; message?: unknown };
|
||||
return `${typeof candidate.code === "string" ? candidate.code : ""} ${typeof candidate.message === "string" ? candidate.message : ""}`;
|
||||
const candidate = error as { code?: unknown; id?: unknown; serverMessage?: unknown; message?: unknown };
|
||||
return `${typeof candidate.code === "string" ? candidate.code : ""} ${typeof candidate.id === "string" || typeof candidate.id === "number" ? candidate.id : ""} ${typeof candidate.serverMessage === "string" ? candidate.serverMessage : ""} ${typeof candidate.message === "string" ? candidate.message : ""}`;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Writable } from "node:stream";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
clientMove as tsClientMove,
|
||||
@@ -9,13 +10,15 @@ import {
|
||||
generateIdentity,
|
||||
type Identity,
|
||||
type VoiceData,
|
||||
type ChannelInfo,
|
||||
type ClientInfo,
|
||||
type DirectoryClientInfo,
|
||||
type DirectorySnapshot,
|
||||
type TextMessage,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import type { Logger } from "../logger.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";
|
||||
|
||||
export interface TSClientOptions {
|
||||
target: TeamSpeakTarget;
|
||||
@@ -24,6 +27,7 @@ export interface TSClientOptions {
|
||||
defaultChannel?: string;
|
||||
channelPassword?: string;
|
||||
identity?: Identity;
|
||||
acceleration?: AccelerationRelayOptions;
|
||||
}
|
||||
|
||||
export interface TSVoiceData {
|
||||
@@ -32,18 +36,19 @@ export interface TSVoiceData {
|
||||
data: Buffer;
|
||||
}
|
||||
|
||||
export interface TSDirectorySnapshot {
|
||||
channels: ChannelInfo[];
|
||||
clients: TSDirectoryClient[];
|
||||
export interface TSClientAvatar {
|
||||
/** TeamSpeak's avatar content marker, used to invalidate a cached avatar. */
|
||||
cacheKey: string;
|
||||
data: Buffer;
|
||||
}
|
||||
|
||||
export interface TSDirectoryClient extends ClientInfo {
|
||||
away?: boolean;
|
||||
awayMessage?: string;
|
||||
inputMuted?: boolean;
|
||||
outputMuted?: boolean;
|
||||
channelCommander?: boolean;
|
||||
}
|
||||
// Keep enough room for avatars produced by the native client. The previous
|
||||
// 120 KiB limit rejected the 134 KiB PNG used by the Shanghai test account,
|
||||
// so every avatar silently fell back to its initial letter.
|
||||
const MAX_CLIENT_AVATAR_BYTES = 256 * 1024;
|
||||
|
||||
export type TSDirectorySnapshot = DirectorySnapshot;
|
||||
export type TSDirectoryClient = DirectoryClientInfo;
|
||||
|
||||
export type TSChatScope = "channel" | "server" | "private";
|
||||
|
||||
@@ -80,6 +85,11 @@ export class TSClient extends EventEmitter {
|
||||
private clientId = 0;
|
||||
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();
|
||||
@@ -88,9 +98,19 @@ export class TSClient extends EventEmitter {
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.selfLeaveReasonId = null;
|
||||
if (!this.adapter || !this.client) {
|
||||
let transportTarget = this.options.target;
|
||||
if (this.options.acceleration && !this.accelerationClient) {
|
||||
this.accelerationClient = await createAccelerationRelayClient({
|
||||
...this.options.acceleration,
|
||||
host: this.options.target.host,
|
||||
port: this.options.target.port,
|
||||
});
|
||||
transportTarget = { host: this.accelerationClient.localHost, port: this.accelerationClient.localPort };
|
||||
}
|
||||
this.adapter = new TeamSpeakAdapter({
|
||||
target: this.options.target,
|
||||
target: transportTarget,
|
||||
nickname: this.options.nickname,
|
||||
identity: this.identity,
|
||||
serverPassword: this.options.serverPassword,
|
||||
@@ -136,8 +156,9 @@ export class TSClient extends EventEmitter {
|
||||
this.emit("directorySnapshot", { channels, clients });
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Could not reconcile the TeamSpeak directory snapshot");
|
||||
failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE",
|
||||
failureDetail: error instanceof Error ? error.message : String(error),
|
||||
}, "TeamSpeak directory snapshot unavailable");
|
||||
}
|
||||
|
||||
const connectedChannelId = client.channelID();
|
||||
@@ -163,6 +184,46 @@ export class TSClient extends EventEmitter {
|
||||
this.emit("connected", this.clientId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a visible client's TeamSpeak avatar through the client protocol.
|
||||
*
|
||||
* TeamSpeak does not include the avatar bytes in directory notifications.
|
||||
* `clientinfo` exposes the avatar marker and the per-identity filename; the
|
||||
* file itself is then read through the normal TeamSpeak file-transfer port.
|
||||
* A missing permission, missing avatar, blocked file-transfer port, or an
|
||||
* oversized image is intentionally reported as `null` so the web client can
|
||||
* keep its generated initial avatar.
|
||||
*/
|
||||
async getClientAvatar(clientId: number, expectedUid = ""): Promise<TSClientAvatar | null> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
|
||||
const rows = await this.client.execCommandWithResponse(`clientinfo clid=${clientId}`, 5_000);
|
||||
const info = rows.find((row) => {
|
||||
if (expectedUid && row.client_unique_identifier !== expectedUid) return false;
|
||||
return typeof row.client_flag_avatar === "string" && typeof row.client_base64HashClientUID === "string";
|
||||
});
|
||||
if (!info) return null;
|
||||
const cacheKey = info.client_flag_avatar?.trim() ?? "";
|
||||
const avatarFileKey = info.client_base64HashClientUID?.trim() ?? "";
|
||||
if (!cacheKey || !/^[A-Za-z0-9+/=_-]{8,256}$/.test(avatarFileKey)) return null;
|
||||
|
||||
const transfer = await this.client.fileTransferInitDownload(0n, `/avatar_${avatarFileKey}`, "");
|
||||
const size = Number(transfer.size);
|
||||
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_CLIENT_AVATAR_BYTES) return null;
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer | string, _encoding, callback) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
callback();
|
||||
},
|
||||
});
|
||||
await this.client.downloadFileData(this.options.target.host, transfer, destination);
|
||||
const data = Buffer.concat(chunks);
|
||||
if (data.length === 0 || data.length > MAX_CLIENT_AVATAR_BYTES) return null;
|
||||
return { cacheKey, data };
|
||||
}
|
||||
|
||||
private attachClientListeners(client: TS3FullClient): void {
|
||||
client.on("voiceData", (data: VoiceData) => {
|
||||
this.emit("voiceData", {
|
||||
@@ -172,12 +233,10 @@ export class TSClient extends EventEmitter {
|
||||
} as TSVoiceData);
|
||||
});
|
||||
|
||||
// The SDK patch exposes the directory that TeamSpeak sends during the
|
||||
// normal client welcome sequence. The connect path also reconciles this
|
||||
// event stream with a complete client-protocol snapshot.
|
||||
(client as unknown as {
|
||||
on(event: "directorySnapshot", handler: (snapshot: TSDirectorySnapshot) => void): unknown;
|
||||
}).on("directorySnapshot", (snapshot) => {
|
||||
// The SDK exposes the directory that TeamSpeak sends during the normal
|
||||
// client welcome sequence. The connect path also reconciles this event
|
||||
// stream with a complete client-protocol snapshot.
|
||||
client.on("directorySnapshot", (snapshot) => {
|
||||
this.emit("directorySnapshot", {
|
||||
channels: snapshot.channels.slice(),
|
||||
clients: snapshot.clients.slice(),
|
||||
@@ -193,7 +252,15 @@ export class TSClient extends EventEmitter {
|
||||
});
|
||||
|
||||
client.on("disconnected", (err) => {
|
||||
this.logger.warn({ err: err?.message }, "Disconnected from TS");
|
||||
if (err) {
|
||||
const normalized = normalizeTeamSpeakError(err);
|
||||
this.logger.warn({
|
||||
failureCode: normalized.code.toUpperCase(),
|
||||
failureDetail: describeTeamSpeakError(normalized),
|
||||
}, "TeamSpeak transport disconnected unexpectedly");
|
||||
} else {
|
||||
this.logger.info("TeamSpeak transport disconnected");
|
||||
}
|
||||
this.connected = false;
|
||||
this.clientId = 0;
|
||||
this.emit("disconnected", err);
|
||||
@@ -204,13 +271,31 @@ 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);
|
||||
});
|
||||
|
||||
client.on("clientUpdated", (event) => {
|
||||
this.emit("clientUpdated", event.info);
|
||||
});
|
||||
}
|
||||
|
||||
sendVoice(data: Buffer, codec: number = 4): void {
|
||||
@@ -222,13 +307,7 @@ export class TSClient extends EventEmitter {
|
||||
if (!this.client || !this.connected) return;
|
||||
const targets = [...new Set(clientIds)].filter((clientId) => Number.isInteger(clientId) && clientId > 0 && clientId <= 65535 && clientId !== this.getClientId());
|
||||
if (!targets.length) throw new Error("Whisper requires at least one valid target");
|
||||
const whisperClient = this.client as unknown as {
|
||||
sendWhisper?: (voiceData: Uint8Array, targetClientIds: number[], voiceCodec: number) => void;
|
||||
};
|
||||
if (typeof whisperClient.sendWhisper !== "function") {
|
||||
throw new Error("TeamSpeak SDK whisper support is unavailable");
|
||||
}
|
||||
whisperClient.sendWhisper(data, targets, codec);
|
||||
this.client.sendWhisper(data, targets, codec);
|
||||
}
|
||||
|
||||
async sendTextMessage(scope: TSChatScope, message: string, targetId = 0n): Promise<void> {
|
||||
@@ -248,12 +327,39 @@ export class TSClient extends EventEmitter {
|
||||
await this.client.execCommand(`clientupdate client_away=${away ? 1 : 0} client_away_message=${escaped}`);
|
||||
}
|
||||
|
||||
async setInputMuted(muted: boolean): Promise<void> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
await this.client.execCommand(`clientupdate client_input_muted=${muted ? 1 : 0}`);
|
||||
}
|
||||
|
||||
async switchChannel(channelId: bigint, password?: string): Promise<void> {
|
||||
if (!this.client || !this.connected) return;
|
||||
await tsClientMove(this.client, this.clientId, channelId, password);
|
||||
this.preferredChannelId = channelId;
|
||||
}
|
||||
|
||||
/** Move another visible TeamSpeak client; the server enforces both move powers. */
|
||||
async moveClient(clientId: number, channelId: bigint, password?: string): Promise<void> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
|
||||
await tsClientMove(this.client, clientId, channelId, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe whether this identity may move a visible client into a channel.
|
||||
*
|
||||
* The browser client protocol does not expose ServerQuery's `permget`, so
|
||||
* the only authoritative capability check available through this session is
|
||||
* the same `clientmove` operation the UI will use. The bridge calls this
|
||||
* with the client's current channel, making the probe a no-op when accepted;
|
||||
* TeamSpeak still evaluates both move-power permissions.
|
||||
*/
|
||||
async probeMovePermission(clientId: number, channelId: bigint): Promise<void> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
|
||||
await tsClientMove(this.client, clientId, channelId);
|
||||
}
|
||||
|
||||
getClientId(): number {
|
||||
// The SDK learns the real client id during the welcome sequence, before
|
||||
// TSClient.connect() resumes. Reading it from the SDK prevents the first
|
||||
@@ -265,6 +371,11 @@ export class TSClient extends EventEmitter {
|
||||
return this.adapter?.protocol ?? null;
|
||||
}
|
||||
|
||||
async execCommandWithResponse(command: string, timeoutMs = 3000): Promise<Record<string, string>[]> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
return this.client.execCommandWithResponse(command, timeoutMs);
|
||||
}
|
||||
|
||||
getIdentityString(): string {
|
||||
return this.identity.toString();
|
||||
}
|
||||
@@ -281,10 +392,16 @@ export class TSClient extends EventEmitter {
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.connected = false;
|
||||
if (this.adapter) await this.adapter.disconnect();
|
||||
this.adapter = null;
|
||||
this.client = null;
|
||||
this.clientId = 0;
|
||||
this.selfLeaveReasonId = null;
|
||||
try {
|
||||
if (this.adapter) await this.adapter.disconnect();
|
||||
} finally {
|
||||
this.accelerationClient?.close();
|
||||
this.accelerationClient = null;
|
||||
this.adapter = null;
|
||||
this.client = null;
|
||||
this.clientId = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface ClientCommand {
|
||||
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive";
|
||||
type: "switchChannel" | "moveClient" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe";
|
||||
requestId?: string;
|
||||
payload: Record<string, unknown>;
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
|
||||
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
|
||||
}
|
||||
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive"]);
|
||||
const supportedTypes = new Set(["switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
|
||||
if (!supportedTypes.has(value.type)) {
|
||||
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
|
||||
}
|
||||
@@ -32,6 +32,15 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "switchChannel" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
|
||||
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
|
||||
}
|
||||
if (value.type === "moveClient" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535)) {
|
||||
return { error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" } };
|
||||
}
|
||||
if (value.type === "moveClient" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
|
||||
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
|
||||
}
|
||||
if (value.type === "moveClient" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
|
||||
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
|
||||
}
|
||||
if (value.type === "sendTextMessage" && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
|
||||
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
|
||||
}
|
||||
@@ -56,6 +65,18 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "setWhisperActive" && typeof value.payload.active !== "boolean") {
|
||||
return { error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" } };
|
||||
}
|
||||
if (value.type === "setMicrophoneMuted" && typeof value.payload.muted !== "boolean") {
|
||||
return { error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" } };
|
||||
}
|
||||
if (value.type === "setAccompanimentActive" && typeof value.payload.active !== "boolean") {
|
||||
return { error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" } };
|
||||
}
|
||||
if (value.type === "setMemberVolume" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535 || typeof value.payload.volume !== "number" || !Number.isFinite(value.payload.volume) || value.payload.volume < 0 || value.payload.volume > 4)) {
|
||||
return { error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" } };
|
||||
}
|
||||
if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
|
||||
return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } };
|
||||
}
|
||||
return {
|
||||
type: value.type as ClientCommand["type"],
|
||||
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
|
||||
|
||||
@@ -0,0 +1,474 @@
|
||||
import { randomInt } from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
import {
|
||||
MediaStreamTrack,
|
||||
RtpHeader,
|
||||
RtpPacket,
|
||||
RTCPeerConnection,
|
||||
} from "werift";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import type { TSVoiceData } from "./ts-client.js";
|
||||
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
|
||||
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
OpusEncoder: new (sampleRate: number, channels: number) => {
|
||||
decode(data: Buffer): Buffer;
|
||||
encode(data: Buffer): Buffer;
|
||||
};
|
||||
};
|
||||
|
||||
const AUDIO_SAMPLE_RATE = 48_000;
|
||||
const AUDIO_FRAME_SAMPLES = 960;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
||||
const MAX_MIXER_QUEUE_FRAMES = 4;
|
||||
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
|
||||
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
|
||||
const MIXER_UNDERRUN_WINDOW_MS = 200;
|
||||
// This threshold is used only for the speaking indicator. It must never decide
|
||||
// whether a media packet is forwarded or queued: quiet/comfort-noise Opus
|
||||
// packets are still valid media and dropping them can break decoder continuity.
|
||||
const SPEAKER_ACTIVITY_RMS = 160;
|
||||
|
||||
// WebRTC is served by the WebSpeak process itself. The default range is also
|
||||
// published by the bundled Docker Compose file; advanced administrators can
|
||||
// change it in the admin console before enabling WebRTC.
|
||||
export interface WebRtcAudioOptions {
|
||||
enabled: boolean;
|
||||
udpPortRange?: [number, number];
|
||||
}
|
||||
|
||||
export interface WebRtcSessionDescription {
|
||||
type: "offer" | "answer";
|
||||
sdp: string;
|
||||
muted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioSessionOptions {
|
||||
connectionId: string;
|
||||
publicHost?: string;
|
||||
udpPortRange?: [number, number];
|
||||
logger: LoggerType;
|
||||
microphoneMuted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||
onVoiceActivity: (clientIds: number[]) => void;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioStats {
|
||||
webrtcIngressRtpFrames: number;
|
||||
webrtcIngressRtpFirstAt: number | null;
|
||||
webrtcIngressRtpLastAt: number | null;
|
||||
webrtcIngressRtpMaxGapMs: number;
|
||||
webrtcEgressRtpFrames: number;
|
||||
webrtcEgressRtpFirstAt: number | null;
|
||||
webrtcEgressRtpLastAt: number | null;
|
||||
webrtcEgressRtpMaxGapMs: number;
|
||||
webrtcQueuePeakFrames: number;
|
||||
webrtcQueueDroppedFrames: number;
|
||||
webrtcQueueUnderrunTicks: number;
|
||||
webrtcPacerLateTicks: number;
|
||||
webrtcQueueCurrentFrames: number;
|
||||
webrtcIngressQuietFrames: number;
|
||||
webrtcIngressDecodeErrors: number;
|
||||
webrtcDownlinkDecodedFrames: number;
|
||||
webrtcDownlinkDecodeErrors: number;
|
||||
webrtcDownlinkShortFrames: number;
|
||||
}
|
||||
|
||||
interface PendingAudioFrame {
|
||||
pcm: Buffer;
|
||||
receivedAt: number;
|
||||
/** Preserve a native 20 ms Opus frame when no mix is required. */
|
||||
opus?: Buffer;
|
||||
}
|
||||
|
||||
interface SelectedAudioFrame extends PendingAudioFrame {
|
||||
clientId: number;
|
||||
volume: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* One low-latency WebRTC audio session for one browser connection.
|
||||
*
|
||||
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
|
||||
* audio track in this first transport, so this class mixes one 20 ms frame
|
||||
* from each active speaker and packetizes the result as RTP. Each speaker has
|
||||
* a very small bounded queue so bursts from the TeamSpeak adapter can be
|
||||
* smoothed without turning into an ever-growing playback delay.
|
||||
*/
|
||||
export class WebRtcAudioSession {
|
||||
readonly peer: RTCPeerConnection;
|
||||
private readonly logger: LoggerType;
|
||||
private readonly onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||
private readonly onVoiceActivity: (clientIds: number[]) => void;
|
||||
private readonly outgoingTrack: MediaStreamTrack;
|
||||
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
|
||||
private readonly partialPcmByClient = new Map<number, Buffer>();
|
||||
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
|
||||
private readonly memberVolumes = new Map<number, number>();
|
||||
private readonly activeSpeakerIds = new Set<number>();
|
||||
private readonly opusPayloadTypes = new Set<number>();
|
||||
private audioTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly activityTimer: ReturnType<typeof setInterval>;
|
||||
private encoder: { encode(data: Buffer): Buffer } | null;
|
||||
private sequenceNumber = randomInt(0, 65_536);
|
||||
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
|
||||
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
|
||||
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
|
||||
private closed = false;
|
||||
private nextAudioDeadline = 0;
|
||||
private lastIngressRtpAt: number | null = null;
|
||||
private lastEgressRtpAt: number | null = null;
|
||||
private lastQueueEnqueuedAt: number | null = null;
|
||||
private microphoneMuted: boolean;
|
||||
private accompanimentActive: boolean;
|
||||
private readonly stats: WebRtcAudioStats = {
|
||||
webrtcIngressRtpFrames: 0,
|
||||
webrtcIngressRtpFirstAt: null,
|
||||
webrtcIngressRtpLastAt: null,
|
||||
webrtcIngressRtpMaxGapMs: 0,
|
||||
webrtcEgressRtpFrames: 0,
|
||||
webrtcEgressRtpFirstAt: null,
|
||||
webrtcEgressRtpLastAt: null,
|
||||
webrtcEgressRtpMaxGapMs: 0,
|
||||
webrtcQueuePeakFrames: 0,
|
||||
webrtcQueueDroppedFrames: 0,
|
||||
webrtcQueueUnderrunTicks: 0,
|
||||
webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 0,
|
||||
webrtcIngressQuietFrames: 0,
|
||||
webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 0,
|
||||
webrtcDownlinkDecodeErrors: 0,
|
||||
webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
|
||||
constructor(options: WebRtcAudioSessionOptions) {
|
||||
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
||||
this.onVoiceFrame = options.onVoiceFrame;
|
||||
this.onVoiceActivity = options.onVoiceActivity;
|
||||
this.microphoneMuted = options.microphoneMuted === true;
|
||||
this.accompanimentActive = options.accompanimentActive === true;
|
||||
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
||||
|
||||
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
|
||||
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
|
||||
this.peer = new RTCPeerConnection({
|
||||
iceServers: [],
|
||||
iceUseIpv4: true,
|
||||
iceUseIpv6: false,
|
||||
iceUseTcp: false,
|
||||
icePortRange: [...udpPortRange] as [number, number],
|
||||
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
|
||||
});
|
||||
|
||||
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
|
||||
audio.onTrack.subscribe((track) => {
|
||||
track.onReceiveRtp.subscribe((rtp) => {
|
||||
if (this.closed) return;
|
||||
const receivedAt = performance.now();
|
||||
if (this.lastIngressRtpAt !== null) this.stats.webrtcIngressRtpMaxGapMs = Math.max(this.stats.webrtcIngressRtpMaxGapMs, Math.round(receivedAt - this.lastIngressRtpAt));
|
||||
this.lastIngressRtpAt = receivedAt;
|
||||
this.stats.webrtcIngressRtpFirstAt ??= Date.now();
|
||||
this.stats.webrtcIngressRtpLastAt = Date.now();
|
||||
this.stats.webrtcIngressRtpFrames++;
|
||||
if (!this.opusPayloadTypes.has(rtp.header.payloadType)) return;
|
||||
const payload = Buffer.from(rtp.payload);
|
||||
// A muted microphone must stop the browser user's TeamSpeak voice
|
||||
// packets at the gateway. Browser-side track.enabled/gain changes
|
||||
// still produce RTP comfort-silence on some browsers, and forwarding
|
||||
// those packets makes TeamSpeak keep the user in the speaking state.
|
||||
// When accompaniment is active, keep forwarding the mixed track: the
|
||||
// browser has already removed only the microphone component.
|
||||
if (this.microphoneMuted && !this.accompanimentActive) return;
|
||||
// Forward every valid negotiated Opus payload unchanged. Do not
|
||||
// decode it for RMS analysis or pass it through a speech/silence gate:
|
||||
// quiet frames are still part of the codec timeline and dropping them
|
||||
// can cause downstream gaps, clicks, or decoder recovery artifacts.
|
||||
this.onVoiceFrame(payload, this.accompanimentActive ? 5 : 4);
|
||||
});
|
||||
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track");
|
||||
});
|
||||
});
|
||||
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
|
||||
});
|
||||
|
||||
try {
|
||||
this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
} catch (error: unknown) {
|
||||
this.encoder = null;
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder");
|
||||
}
|
||||
if (!this.encoder) {
|
||||
this.outgoingTrack.stop();
|
||||
throw new Error("WebRTC Opus codec is unavailable");
|
||||
}
|
||||
|
||||
this.nextAudioDeadline = performance.now();
|
||||
this.scheduleAudioTick();
|
||||
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
|
||||
this.activityTimer.unref?.();
|
||||
this.peer.onconnectionstatechange = () => {
|
||||
this.logger.info({ state: this.peer.connectionState }, "WebRTC connection state changed");
|
||||
};
|
||||
}
|
||||
|
||||
getStats(): WebRtcAudioStats {
|
||||
return { ...this.stats, webrtcQueueCurrentFrames: this.getQueueFrameCount() };
|
||||
}
|
||||
|
||||
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
|
||||
if (this.closed) throw new Error("WebRTC session is closed");
|
||||
this.setOpusPayloadTypes(offer.sdp);
|
||||
await this.peer.setRemoteDescription(offer);
|
||||
const transceiver = this.peer.getTransceivers().find((candidate) => candidate.kind === "audio");
|
||||
if (transceiver) await transceiver.sender.replaceTrack(this.outgoingTrack);
|
||||
const answer = await this.peer.createAnswer();
|
||||
await this.peer.setLocalDescription(answer);
|
||||
const description = this.peer.localDescription;
|
||||
if (!description) throw new Error("WebRTC answer was not created");
|
||||
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
|
||||
return { type: description.type, sdp: description.sdp };
|
||||
}
|
||||
|
||||
pushTeamSpeakVoice(data: TSVoiceData): void {
|
||||
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
|
||||
let decoder = this.decoderByClient.get(data.clientId);
|
||||
if (!decoder) {
|
||||
try {
|
||||
// @discordjs/opus exposes decoding on OpusEncoder instances too;
|
||||
// there is no separate OpusDecoder constructor in that package.
|
||||
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
this.decoderByClient.set(data.clientId, decoder);
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const pcm = decoder.decode(data.data);
|
||||
this.stats.webrtcDownlinkDecodedFrames++;
|
||||
if (pcm.length < 2) {
|
||||
this.stats.webrtcDownlinkShortFrames++;
|
||||
return;
|
||||
}
|
||||
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
|
||||
// decoded frame per speaker and split every decoded buffer into the
|
||||
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
|
||||
// anything after the first 20 ms.
|
||||
const pendingPcm = this.partialPcmByClient.get(data.clientId);
|
||||
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
|
||||
const rms = this.calculateRms(pcm);
|
||||
// RMS is used only for the UI speaking indicator. Every decoded frame,
|
||||
// including quiet/comfort-noise frames, continues into the queue so the
|
||||
// receiver keeps an uninterrupted codec timeline.
|
||||
if (rms >= SPEAKER_ACTIVITY_RMS) this.activeSpeakerIds.add(data.clientId);
|
||||
const canForwardOpus = !pendingPcm && pcm.length === AUDIO_FRAME_BYTES;
|
||||
let offset = 0;
|
||||
let enqueued = false;
|
||||
let queue = this.pendingFrames.get(data.clientId);
|
||||
while (offset + AUDIO_FRAME_BYTES <= combined.length) {
|
||||
if (!queue) {
|
||||
queue = [];
|
||||
this.pendingFrames.set(data.clientId, queue);
|
||||
}
|
||||
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
queue.push({
|
||||
pcm: Buffer.from(combined.subarray(offset, offset + AUDIO_FRAME_BYTES)),
|
||||
receivedAt: performance.now(),
|
||||
...(canForwardOpus && offset === 0 ? { opus: Buffer.from(data.data) } : {}),
|
||||
});
|
||||
enqueued = true;
|
||||
offset += AUDIO_FRAME_BYTES;
|
||||
}
|
||||
if (offset < combined.length) this.partialPcmByClient.set(data.clientId, Buffer.from(combined.subarray(offset)));
|
||||
else this.partialPcmByClient.delete(data.clientId);
|
||||
if (enqueued) {
|
||||
this.lastQueueEnqueuedAt = performance.now();
|
||||
this.stats.webrtcQueuePeakFrames = Math.max(this.stats.webrtcQueuePeakFrames, this.getQueueFrameCount());
|
||||
}
|
||||
} catch {
|
||||
this.stats.webrtcDownlinkDecodeErrors++;
|
||||
// A malformed or codec-transition packet is discarded without touching
|
||||
// the peer connection. The next valid Opus frame can recover the stream.
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
if (this.audioTimer) clearTimeout(this.audioTimer);
|
||||
this.audioTimer = null;
|
||||
clearInterval(this.activityTimer);
|
||||
this.pendingFrames.clear();
|
||||
this.memberVolumes.clear();
|
||||
this.partialPcmByClient.clear();
|
||||
this.activeSpeakerIds.clear();
|
||||
this.decoderByClient.clear();
|
||||
this.encoder = null;
|
||||
this.outgoingTrack.stop();
|
||||
await this.peer.close();
|
||||
}
|
||||
|
||||
private scheduleAudioTick(): void {
|
||||
if (this.closed) return;
|
||||
const delay = Math.max(0, this.nextAudioDeadline - performance.now());
|
||||
this.audioTimer = setTimeout(() => this.flushAudio(), delay);
|
||||
this.audioTimer.unref?.();
|
||||
}
|
||||
|
||||
private flushAudio(): void {
|
||||
if (this.closed) return;
|
||||
const now = performance.now();
|
||||
if (now > this.nextAudioDeadline + MAX_MIXER_PACER_LAG_MS) {
|
||||
this.stats.webrtcPacerLateTicks++;
|
||||
this.nextAudioDeadline = now;
|
||||
this.trimQueuesAfterLateTick();
|
||||
}
|
||||
this.nextAudioDeadline += AUDIO_CLOCK_INTERVAL_MS;
|
||||
this.audioTimer = null;
|
||||
this.mixAndSendAudio();
|
||||
this.scheduleAudioTick();
|
||||
}
|
||||
|
||||
private mixAndSendAudio(): void {
|
||||
if (!this.encoder) {
|
||||
return;
|
||||
}
|
||||
if (!this.pendingFrames.size) {
|
||||
if (this.lastQueueEnqueuedAt !== null && performance.now() - this.lastQueueEnqueuedAt <= MIXER_UNDERRUN_WINDOW_MS) {
|
||||
this.stats.webrtcQueueUnderrunTicks++;
|
||||
}
|
||||
}
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
|
||||
const selectedFrames: SelectedAudioFrame[] = [];
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
const frame = queue.shift();
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
if (!frame) continue;
|
||||
const volume = this.memberVolumes.get(clientId) ?? 1;
|
||||
selectedFrames.push({ ...frame, clientId, volume });
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedFrames.length === 1 && selectedFrames[0]?.opus && selectedFrames[0].volume === 1) {
|
||||
this.sendRtpAudio(selectedFrames[0].opus);
|
||||
return;
|
||||
}
|
||||
|
||||
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
|
||||
// the waveform's apparent loudness as the source level changes, which
|
||||
// is especially noticeable on music. Only clip actual overflow caused
|
||||
// by simultaneous speakers; never normalize by the active speaker count.
|
||||
const sample = Math.max(-32_768, Math.min(32_767, mixed[index]!));
|
||||
pcm.writeInt16LE(sample, index * 2);
|
||||
}
|
||||
try {
|
||||
const encoded = this.encoder.encode(pcm);
|
||||
this.sendRtpAudio(encoded);
|
||||
} catch {
|
||||
// A peer closing concurrently may reject a packet; teardown owns the
|
||||
// session lifecycle and no per-frame error needs to reach the logs.
|
||||
}
|
||||
}
|
||||
|
||||
private sendRtpAudio(encoded: Buffer): void {
|
||||
const packet = new RtpPacket(new RtpHeader({
|
||||
payloadType: this.outgoingPayloadType,
|
||||
sequenceNumber: this.sequenceNumber,
|
||||
timestamp: this.timestamp,
|
||||
ssrc: this.ssrc,
|
||||
marker: true,
|
||||
}), encoded);
|
||||
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
|
||||
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
|
||||
this.outgoingTrack.writeRtp(packet);
|
||||
const sentAt = performance.now();
|
||||
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
|
||||
this.lastEgressRtpAt = sentAt;
|
||||
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
|
||||
this.stats.webrtcEgressRtpLastAt = Date.now();
|
||||
this.stats.webrtcEgressRtpFrames++;
|
||||
}
|
||||
|
||||
private flushSpeakerActivity(): void {
|
||||
if (this.closed || !this.activeSpeakerIds.size) return;
|
||||
const ids = [...this.activeSpeakerIds];
|
||||
this.activeSpeakerIds.clear();
|
||||
this.onVoiceActivity(ids);
|
||||
}
|
||||
|
||||
setMicrophoneMuted(muted: boolean): void {
|
||||
this.microphoneMuted = muted;
|
||||
}
|
||||
|
||||
setAccompanimentActive(active: boolean): void {
|
||||
this.accompanimentActive = active;
|
||||
}
|
||||
|
||||
setMemberVolume(clientId: number, volume: number): void {
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535 || !Number.isFinite(volume)) return;
|
||||
const normalized = Math.max(0, Math.min(4, volume));
|
||||
if (normalized === 1) this.memberVolumes.delete(clientId);
|
||||
else this.memberVolumes.set(clientId, normalized);
|
||||
}
|
||||
|
||||
private calculateRms(pcm: Buffer): number {
|
||||
let sum = 0;
|
||||
let samples = 0;
|
||||
for (let index = 0; index + 1 < pcm.length; index += 2) {
|
||||
const sample = pcm.readInt16LE(index);
|
||||
sum += sample * sample;
|
||||
samples++;
|
||||
}
|
||||
return samples ? Math.sqrt(sum / samples) : 0;
|
||||
}
|
||||
|
||||
private trimQueuesAfterLateTick(): void {
|
||||
const now = performance.now();
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
while (queue.length > 1) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
private getQueueFrameCount(): number {
|
||||
let count = 0;
|
||||
for (const queue of this.pendingFrames.values()) count += queue.length;
|
||||
return count;
|
||||
}
|
||||
|
||||
private setOpusPayloadTypes(sdp: string): void {
|
||||
this.opusPayloadTypes.clear();
|
||||
for (const match of sdp.matchAll(/^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?/gim)) {
|
||||
const payloadType = Number(match[1]);
|
||||
if (!Number.isInteger(payloadType) || payloadType < 0 || payloadType > 127) continue;
|
||||
this.opusPayloadTypes.add(payloadType);
|
||||
this.outgoingPayloadType = payloadType;
|
||||
}
|
||||
if (!this.opusPayloadTypes.size) this.opusPayloadTypes.add(DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Default WebRTC media port range used by WebSpeak and its Docker image. */
|
||||
export const DEFAULT_WEBRTC_UDP_PORT_RANGE: [number, number] = [40000, 40099];
|
||||
|
||||
// Kept as a public alias for callers that used the original fixed-range name.
|
||||
export const WEBRTC_UDP_PORT_RANGE = DEFAULT_WEBRTC_UDP_PORT_RANGE;
|
||||
export const WEBRTC_UDP_PORT_MIN = 1024;
|
||||
export const WEBRTC_UDP_PORT_MAX = 65535;
|
||||
@@ -0,0 +1,24 @@
|
||||
export type SiteLanguage = "zh" | "en" | "de" | "ru" | "ja";
|
||||
|
||||
/**
|
||||
* Built-in welcome-page templates. An empty administrator value always falls
|
||||
* back to one of these strings, so adding a language never leaves the page
|
||||
* with a blank welcome message.
|
||||
*/
|
||||
export const DEFAULT_WELCOME_TEXTS: Record<SiteLanguage, string> = {
|
||||
zh: "无需安装 TeamSpeak 客户端,打开浏览器即可加入语音频道。低延迟、轻量、专注于每一次对话。",
|
||||
en: "No TeamSpeak client installation required. Open your browser and join a voice channel with low-latency audio built for conversation.",
|
||||
de: "Keine Installation des TeamSpeak-Clients nötig. Öffne den Browser und tritt einem Sprachkanal bei – leichtgewichtig und mit geringer Latenz.",
|
||||
ru: "Устанавливать клиент TeamSpeak не нужно: откройте браузер и присоединитесь к голосовому каналу. Низкая задержка и удобное общение в каждом разговоре.",
|
||||
ja: "TeamSpeak クライアントのインストールは不要です。ブラウザを開くだけで音声チャンネルに参加できます。低遅延で軽快な会話を楽しめます。",
|
||||
};
|
||||
|
||||
export function resolveWelcomeTexts(values: Partial<Record<SiteLanguage, string>>): Record<SiteLanguage, string> {
|
||||
return {
|
||||
zh: values.zh?.trim() || DEFAULT_WELCOME_TEXTS.zh,
|
||||
en: values.en?.trim() || DEFAULT_WELCOME_TEXTS.en,
|
||||
de: values.de?.trim() || DEFAULT_WELCOME_TEXTS.de,
|
||||
ru: values.ru?.trim() || DEFAULT_WELCOME_TEXTS.ru,
|
||||
ja: values.ja?.trim() || DEFAULT_WELCOME_TEXTS.ja,
|
||||
};
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { createServer } from "node:http";
|
||||
import test from "node:test";
|
||||
import express from "express";
|
||||
import { createAdminRouter } from "../src/admin/admin-router.js";
|
||||
import { AdminService } from "../src/admin/admin-service.js";
|
||||
import { AdminSessionStore } from "../src/admin/admin-session.js";
|
||||
import { WebSpeakDatabase } from "../src/persistence/database.js";
|
||||
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
|
||||
import { silentLogger } from "./helpers/logger.js";
|
||||
|
||||
test("admin API requires the default password to be changed before administration", async (context) => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-api-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const service = new AdminService(
|
||||
database,
|
||||
loadOrCreateMasterSecret(path.join(directory, "master.key")),
|
||||
silentLogger,
|
||||
path.join(directory, "missing-config.json"),
|
||||
async (_target, password) => ({ ok: true, protocol: "ts6", latencyMs: 7, serverName: "Mock Server", requiresPassword: Boolean(password) }),
|
||||
);
|
||||
await service.initialize();
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use("/api/admin", createAdminRouter({
|
||||
service,
|
||||
sessions: new AdminSessionStore(),
|
||||
logger: silentLogger,
|
||||
getActiveSessions: () => 2,
|
||||
getPeakSessions: () => 4,
|
||||
startedAt: Date.now() - 5000,
|
||||
}));
|
||||
const server = createServer(app);
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
context.after(async () => {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
database.close();
|
||||
});
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address === "object");
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
|
||||
const status = await request(origin, "/api/admin/status");
|
||||
assert.equal(status.response.status, 200);
|
||||
assert.equal(status.response.headers.get("cache-control"), "no-store");
|
||||
assert.equal(status.body.initialized, true);
|
||||
assert.equal("setupDefaults" in status.body, false);
|
||||
|
||||
const login = await request(origin, "/api/admin/login", {
|
||||
method: "POST",
|
||||
body: { username: "admin", password: "admin" },
|
||||
});
|
||||
assert.equal(login.response.status, 200);
|
||||
assert.equal(login.body.mustChangePassword, true);
|
||||
assert.equal(typeof login.body.csrfToken, "string");
|
||||
const cookie = login.response.headers.get("set-cookie")?.split(";", 1)[0];
|
||||
assert.ok(cookie?.startsWith("webspeak_admin="));
|
||||
assert.match(login.response.headers.get("set-cookie") ?? "", /HttpOnly/i);
|
||||
assert.match(login.response.headers.get("set-cookie") ?? "", /SameSite=Strict/i);
|
||||
|
||||
const session = await request(origin, "/api/admin/session", { cookie });
|
||||
assert.equal(session.body.authenticated, true);
|
||||
assert.equal(session.body.mustChangePassword, true);
|
||||
|
||||
const blockedOverview = await request(origin, "/api/admin/overview", { cookie });
|
||||
assert.equal(blockedOverview.response.status, 403);
|
||||
assert.equal(blockedOverview.body.code, "PASSWORD_CHANGE_REQUIRED");
|
||||
|
||||
const shortPassword = await request(origin, "/api/admin/change-password", {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: { newPassword: "too-short" },
|
||||
});
|
||||
assert.equal(shortPassword.response.status, 400);
|
||||
assert.equal(shortPassword.body.code, "INVALID_ADMIN_PASSWORD");
|
||||
|
||||
const changed = await request(origin, "/api/admin/change-password", {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: { newPassword: "integration-admin-password" },
|
||||
});
|
||||
assert.equal(changed.response.status, 200);
|
||||
assert.equal(changed.body.mustChangePassword, false);
|
||||
|
||||
const updatedSession = await request(origin, "/api/admin/session", { cookie });
|
||||
assert.equal(updatedSession.body.mustChangePassword, false);
|
||||
const overview = await request(origin, "/api/admin/overview", { cookie });
|
||||
assert.deepEqual(overview.body.sessions, { active: 2, peak: 4, limit: 100 });
|
||||
|
||||
const rejectedMutation = await request(origin, "/api/admin/server", {
|
||||
method: "PUT",
|
||||
cookie,
|
||||
body: { target: "voice.example.com:9988", accessMode: "open", siteName: "Changed", welcomeText: "" },
|
||||
});
|
||||
assert.equal(rejectedMutation.response.status, 403);
|
||||
assert.equal(rejectedMutation.body.code, "CSRF_REJECTED");
|
||||
|
||||
const saved = await request(origin, "/api/admin/server", {
|
||||
method: "PUT",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: {
|
||||
target: "voice.example.com:9988",
|
||||
passwordAction: "remove",
|
||||
accessMode: "open",
|
||||
siteName: "Changed",
|
||||
welcomeText: "Open access",
|
||||
},
|
||||
});
|
||||
assert.equal(saved.body.ok, true);
|
||||
assert.equal(saved.body.settings.accessMode, "open");
|
||||
assert.equal(saved.body.settings.hasPassword, false);
|
||||
|
||||
const invite = await request(origin, "/api/admin/invites", {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: { channel: "Lobby", expiresInHours: 4, maxUses: 2 },
|
||||
});
|
||||
assert.equal(invite.response.status, 201);
|
||||
assert.equal(invite.body.ok, true);
|
||||
assert.match(invite.body.token, /^[A-Za-z0-9_-]{43}$/);
|
||||
assert.equal(invite.body.invite.channel, "Lobby");
|
||||
assert.equal("token" in invite.body.invite, false);
|
||||
|
||||
const invites = await request(origin, "/api/admin/invites", { cookie });
|
||||
assert.equal(invites.body.invites.length, 1);
|
||||
assert.equal(invites.body.invites[0].status, "active");
|
||||
assert.equal(invites.body.invites[0].target, "voice.example.com:9988");
|
||||
|
||||
const sessions = await request(origin, "/api/admin/sessions", { cookie });
|
||||
assert.deepEqual(sessions.body.sessions, []);
|
||||
const diagnostics = await request(origin, "/api/admin/diagnostics", { cookie });
|
||||
assert.equal(diagnostics.body.database.schemaVersion, 2);
|
||||
assert.equal("target" in diagnostics.body.teamSpeak, true);
|
||||
|
||||
const report = await request(origin, "/api/admin/diagnostics/report", { cookie });
|
||||
assert.equal(report.response.status, 200);
|
||||
assert.match(report.response.headers.get("content-disposition") ?? "", /diagnostic-report\.json/);
|
||||
assert.equal("target" in report.body.teamSpeak, false);
|
||||
assert.equal("serverPassword" in report.body, false);
|
||||
|
||||
const revoked = await request(origin, `/api/admin/invites/${encodeURIComponent(invite.body.invite.id)}/revoke`, {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: {},
|
||||
});
|
||||
assert.equal(revoked.body.ok, true);
|
||||
const revokedList = await request(origin, "/api/admin/invites", { cookie });
|
||||
assert.equal(revokedList.body.invites[0].status, "revoked");
|
||||
|
||||
const backup = await download(origin, "/api/admin/backup", cookie);
|
||||
assert.equal(backup.response.status, 200);
|
||||
assert.equal(backup.response.headers.get("content-type"), "application/octet-stream");
|
||||
assert.ok(backup.bytes.length > 100);
|
||||
assert.equal("serverPassword" in saved.body.settings, false);
|
||||
|
||||
const probe = await request(origin, "/api/admin/server/test", {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: { target: "voice.example.com:9988", passwordAction: "remove" },
|
||||
});
|
||||
assert.equal(probe.body.protocol, "ts6");
|
||||
const settings = await request(origin, "/api/admin/server", { cookie });
|
||||
assert.equal(settings.body.detectedProtocol, "ts6");
|
||||
assert.equal(settings.body.lastTestLatencyMs, 7);
|
||||
|
||||
const logout = await request(origin, "/api/admin/logout", { method: "POST", cookie, csrf: login.body.csrfToken, body: {} });
|
||||
assert.equal(logout.body.ok, true);
|
||||
const denied = await request(origin, "/api/admin/overview", { cookie });
|
||||
assert.equal(denied.response.status, 401);
|
||||
|
||||
const oldPassword = await request(origin, "/api/admin/login", {
|
||||
method: "POST",
|
||||
body: { username: "admin", password: "admin" },
|
||||
});
|
||||
assert.equal(oldPassword.response.status, 401);
|
||||
const newPassword = await request(origin, "/api/admin/login", {
|
||||
method: "POST",
|
||||
body: { username: "admin", password: "integration-admin-password" },
|
||||
});
|
||||
assert.equal(newPassword.response.status, 200);
|
||||
assert.equal(newPassword.body.mustChangePassword, false);
|
||||
});
|
||||
|
||||
async function request(
|
||||
origin: string,
|
||||
pathname: string,
|
||||
options: { method?: string; body?: unknown; cookie?: string; csrf?: string } = {},
|
||||
): Promise<{ response: Response; body: any }> {
|
||||
const method = options.method ?? "GET";
|
||||
const response = await fetch(`${origin}${pathname}`, {
|
||||
method,
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
...(method !== "GET" ? { "content-type": "application/json", origin } : {}),
|
||||
...(options.cookie ? { cookie: options.cookie } : {}),
|
||||
...(options.csrf ? { "x-csrf-token": options.csrf } : {}),
|
||||
},
|
||||
...(method !== "GET" ? { body: JSON.stringify(options.body ?? {}) } : {}),
|
||||
});
|
||||
return { response, body: await response.json() };
|
||||
}
|
||||
|
||||
async function download(origin: string, pathname: string, cookie?: string): Promise<{ response: Response; bytes: Uint8Array }> {
|
||||
const response = await fetch(`${origin}${pathname}`, {
|
||||
headers: { accept: "application/octet-stream", ...(cookie ? { cookie } : {}) },
|
||||
});
|
||||
return { response, bytes: new Uint8Array(await response.arrayBuffer()) };
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { AdminService } from "../src/admin/admin-service.js";
|
||||
import { WebSpeakDatabase } from "../src/persistence/database.js";
|
||||
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
|
||||
import { silentLogger } from "./helpers/logger.js";
|
||||
|
||||
test("legacy config imports once, seeds the default admin, and allows password rotation", async () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-service-"));
|
||||
const legacyPath = path.join(directory, "config.json");
|
||||
const legacyText = JSON.stringify({
|
||||
tsHost: "legacy.example.com",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "legacy-secret-value",
|
||||
tsServerProtocol: "ts6",
|
||||
maxClients: 9000,
|
||||
port: 9999,
|
||||
trustProxy: true,
|
||||
}, null, 2);
|
||||
writeFileSync(legacyPath, legacyText);
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const service = new AdminService(
|
||||
database,
|
||||
loadOrCreateMasterSecret(path.join(directory, "master.key")),
|
||||
silentLogger,
|
||||
legacyPath,
|
||||
async () => ({ ok: true, protocol: "ts6", latencyMs: 4, serverName: "Mock TS", requiresPassword: true }),
|
||||
);
|
||||
await service.initialize();
|
||||
|
||||
assert.equal(readFileSync(legacyPath, "utf8"), legacyText);
|
||||
assert.equal(database.getSettings().tsHost, "legacy.example.com");
|
||||
assert.equal(database.getSettings().tsPort, 9988);
|
||||
assert.equal(service.getConnectionPolicy().serverPassword, "legacy-secret-value");
|
||||
assert.equal(readFileSync(path.join(directory, "webspeak.db")).includes(Buffer.from("legacy-secret-value")), false);
|
||||
assert.equal(service.isInitialized(), true);
|
||||
assert.equal(await service.verifyPassword("admin", "admin"), true);
|
||||
assert.equal(await service.verifyPassword("wrong-user", "admin"), false);
|
||||
assert.equal(service.isPasswordChangeRequired(), true);
|
||||
await service.changePassword("a-secure-admin-password");
|
||||
assert.equal(await service.verifyPassword("admin", "a-secure-admin-password"), true);
|
||||
assert.equal(await service.verifyPassword("admin", "admin"), false);
|
||||
assert.equal(service.isPasswordChangeRequired(), false);
|
||||
assert.equal(service.getPublicConfig().accessMode, "fixed");
|
||||
assert.equal(service.getPublicConfig().target, "legacy.example.com:9988");
|
||||
|
||||
service.updateSettings({
|
||||
target: "public.example.com:9987",
|
||||
serverPassword: "replacement-secret",
|
||||
passwordAction: "replace",
|
||||
accessMode: "open",
|
||||
siteName: "Open WebSpeak",
|
||||
welcomeText: "Public gateway",
|
||||
});
|
||||
const publicConfig = service.getPublicConfig();
|
||||
assert.equal(publicConfig.target, "public.example.com:9987");
|
||||
assert.equal(publicConfig.accessMode, "open");
|
||||
assert.equal("serverPassword" in service.getAdminSettings(), false);
|
||||
assert.equal(service.getAdminSettings().hasPassword, true);
|
||||
assert.equal(service.getConnectionPolicy().serverPassword, "replacement-secret");
|
||||
database.close();
|
||||
});
|
||||
|
||||
test("managed invites are opaque, bounded, revocable, and included in database backups", async () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-invites-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const service = new AdminService(
|
||||
database,
|
||||
loadOrCreateMasterSecret(path.join(directory, "master.key")),
|
||||
silentLogger,
|
||||
path.join(directory, "missing-config.json"),
|
||||
);
|
||||
await service.initialize();
|
||||
|
||||
const created = service.createManagedInvite({ channel: "Lobby", expiresInHours: 2, maxUses: 1 });
|
||||
assert.match(created.token, /^[A-Za-z0-9_-]{43}$/);
|
||||
assert.equal(created.invite.channel, "Lobby");
|
||||
assert.equal(created.invite.status, "active");
|
||||
assert.equal("token" in created.invite, false);
|
||||
|
||||
const consumed = service.consumeManagedInvite(created.token);
|
||||
assert.deepEqual(consumed?.target, { host: "127.0.0.1", port: 9987 });
|
||||
assert.equal(consumed?.channel, "Lobby");
|
||||
assert.equal(service.consumeManagedInvite(created.token), null);
|
||||
assert.equal(service.listManagedInvites()[0]?.status, "exhausted");
|
||||
|
||||
database.createManagedInvite({
|
||||
id: "invite-expired-test",
|
||||
tokenHash: "expired-token-hash",
|
||||
targetHost: "127.0.0.1",
|
||||
targetPort: 9987,
|
||||
serverPasswordEncrypted: null,
|
||||
channel: "Expired",
|
||||
expiresAt: new Date(Date.now() - 1).toISOString(),
|
||||
maxUses: 0,
|
||||
});
|
||||
assert.equal(database.consumeManagedInvite("expired-token-hash"), null);
|
||||
const revocable = service.createManagedInvite({ channel: "Revocable", expiresInHours: 2, maxUses: 0 });
|
||||
assert.equal(service.revokeManagedInvite(revocable.invite.id), true);
|
||||
assert.equal(service.listManagedInvites().find((invite) => invite.id === revocable.invite.id)?.status, "revoked");
|
||||
|
||||
const backup = database.exportBackup();
|
||||
assert.ok(backup.length > 100);
|
||||
database.close();
|
||||
const reopened = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
assert.equal(reopened.schemaVersion, 2);
|
||||
assert.equal(reopened.listManagedInvites().length, 3);
|
||||
reopened.close();
|
||||
});
|
||||
@@ -1,71 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, it } from "node:test";
|
||||
import { migrateConfig, saveConfig } from "../src/config.js";
|
||||
|
||||
describe("legacy config migration", () => {
|
||||
it("drops deprecated runtime controls while preserving the TeamSpeak target", () => {
|
||||
assert.deepEqual(migrateConfig({
|
||||
port: 3999,
|
||||
tsHost: "TS.Example.COM",
|
||||
tsPort: "9988",
|
||||
tsServerPassword: "secret",
|
||||
tsServerProtocol: "ts6",
|
||||
maxClients: 3,
|
||||
trustProxy: true,
|
||||
}), {
|
||||
tsHost: "ts.example.com",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "secret",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts a host with an embedded port during migration", () => {
|
||||
assert.deepEqual(migrateConfig({ tsHost: "[2001:db8::1]:9988" }), {
|
||||
tsHost: "2001:db8::1",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts the address#port form during migration", () => {
|
||||
assert.deepEqual(migrateConfig({ tsHost: "voice.example.com#9988" }), {
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back safely for malformed legacy targets", () => {
|
||||
assert.deepEqual(migrateConfig({ tsHost: "bad host", tsPort: 0 }), {
|
||||
tsHost: "127.0.0.1",
|
||||
tsPort: 9987,
|
||||
tsServerPassword: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the migrated shape without deprecated runtime controls", () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "webspeak-m000-config-"));
|
||||
const path = join(directory, "config.json");
|
||||
try {
|
||||
writeFileSync(path, JSON.stringify({
|
||||
port: 3999,
|
||||
tsHost: "example.com",
|
||||
tsPort: 9988,
|
||||
tsServerProtocol: "ts3",
|
||||
maxClients: 2,
|
||||
trustProxy: true,
|
||||
}), "utf8");
|
||||
saveConfig(path, migrateConfig(JSON.parse(readFileSync(path, "utf8"))));
|
||||
assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), {
|
||||
tsHost: "example.com",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "",
|
||||
});
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { ChannelInfo, ClientInfo } from "@honeybbq/teamspeak-client";
|
||||
import { DirectorySynchronizer } from "../src/server/directory-sync.js";
|
||||
|
||||
const root: ChannelInfo = { id: 1n, parentID: 0n, name: "Lobby", description: "", };
|
||||
const games: ChannelInfo = { id: 2n, parentID: 1n, name: "Games", description: "", };
|
||||
|
||||
function client(id: number, nickname: string, channelID: bigint): ClientInfo {
|
||||
return { id, nickname, uid: `uid-${id}`, channelID, type: 1, serverGroups: [] };
|
||||
}
|
||||
|
||||
test("directory synchronizer merges welcome events that arrive before the snapshot", () => {
|
||||
const sync = new DirectorySynchronizer();
|
||||
sync.applyClientEnter(client(7, "Alice", 1n));
|
||||
sync.applyClientMoved(7, 2n);
|
||||
sync.applySnapshot({ channels: [root, games], clients: [client(3, "Bob", 1n)] });
|
||||
assert.equal(sync.ready, true);
|
||||
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n], [7, 2n]]);
|
||||
});
|
||||
|
||||
test("directory state and movement events remain isolated per session", () => {
|
||||
const first = new DirectorySynchronizer();
|
||||
const second = new DirectorySynchronizer();
|
||||
const snapshot = { channels: [root, games], clients: [client(3, "Bob", 1n)] };
|
||||
first.applySnapshot(snapshot);
|
||||
second.applySnapshot(snapshot);
|
||||
first.applyClientEnter(client(7, "Alice", 2n));
|
||||
first.applyClientMoved(3, 2n);
|
||||
first.applyClientLeave(7);
|
||||
assert.deepEqual(first.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 2n]]);
|
||||
assert.deepEqual(second.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n]]);
|
||||
});
|
||||
|
||||
test("directory synchronizer keeps clients across staged partial snapshots", () => {
|
||||
const sync = new DirectorySynchronizer();
|
||||
const alice = client(7, "Alice", 1n);
|
||||
const bob = client(8, "Bob", 1n);
|
||||
|
||||
sync.applySnapshot({ channels: [root], clients: [alice, bob] });
|
||||
sync.applySnapshot({ channels: [root], clients: [bob] });
|
||||
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => item.id), [7, 8]);
|
||||
|
||||
sync.applyClientLeave(alice.id);
|
||||
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => item.id), [8]);
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { normalizeTeamSpeakError } from "../src/errors.js";
|
||||
|
||||
describe("normalized connection errors", () => {
|
||||
it("classifies authentication failures as non-retryable", () => {
|
||||
const error = normalizeTeamSpeakError(new Error("invalid server password"));
|
||||
assert.equal(error.code, "authentication_failed");
|
||||
assert.equal(error.retryable, false);
|
||||
});
|
||||
|
||||
it("classifies network and timeout failures", () => {
|
||||
assert.equal(normalizeTeamSpeakError(Object.assign(new Error("refused"), { code: "ECONNREFUSED" })).code, "unreachable");
|
||||
assert.equal(normalizeTeamSpeakError(new Error("ack timeout")).code, "timeout");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
import type { Logger } from "../../src/logger.js";
|
||||
|
||||
export const silentLogger: Logger = {
|
||||
debug: () => undefined,
|
||||
info: () => undefined,
|
||||
warn: () => undefined,
|
||||
error: () => undefined,
|
||||
child: () => silentLogger,
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { JoinRateLimiter } from "../src/server/join-rate-limit.js";
|
||||
|
||||
test("join ticket creation is bounded per peer and resets after its window", () => {
|
||||
const limiter = new JoinRateLimiter(2);
|
||||
let now = 10_000;
|
||||
for (let attempt = 0; attempt < 30; attempt++) assert.equal(limiter.allow("peer-a", now), true);
|
||||
assert.equal(limiter.allow("peer-a", now), false);
|
||||
assert.equal(limiter.allow("peer-b", now), true);
|
||||
now += 60_000;
|
||||
assert.equal(limiter.allow("peer-a", now), true);
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { generateIdentity } from "@honeybbq/teamspeak-client";
|
||||
import { JoinTicketStore } from "../src/server/join-ticket.js";
|
||||
|
||||
test("join tickets are opaque, one-time, and expire", () => {
|
||||
const store = new JoinTicketStore(1000, 2);
|
||||
const payload = { target: { host: "example.com", port: 9987 }, serverPassword: "secret", nickname: "Guest" };
|
||||
const token = store.create(payload, 100);
|
||||
assert.equal(token.includes("secret"), false);
|
||||
assert.deepEqual(store.consume(token, 101), payload);
|
||||
assert.equal(store.consume(token, 102), null);
|
||||
const expired = store.create(payload, 200);
|
||||
assert.equal(store.consume(expired, 1201), null);
|
||||
});
|
||||
|
||||
test("join tickets carry identity only in memory and never expose it in the opaque token", () => {
|
||||
const store = new JoinTicketStore();
|
||||
const identity = generateIdentity(8).toString();
|
||||
const payload = { target: { host: "example.com", port: 9987 }, serverPassword: "secret", nickname: "Guest", identity, rememberIdentity: true };
|
||||
const token = store.create(payload);
|
||||
assert.equal(token.includes(identity), false);
|
||||
assert.deepEqual(store.consume(token), payload);
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../src/constants.js";
|
||||
|
||||
describe("session safety limit", () => {
|
||||
it("uses the fixed 100-session product limit", () => {
|
||||
assert.equal(MAX_ACTIVE_SESSIONS, 100);
|
||||
assert.equal(canAcceptSession(99), true);
|
||||
assert.equal(canAcceptSession(100), false);
|
||||
assert.equal(canAcceptSession(101), false);
|
||||
});
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { AdminLoginRateLimiter } from "../src/admin/login-rate-limit.js";
|
||||
|
||||
test("admin login limiter blocks repeated failures for one peer", () => {
|
||||
const limiter = new AdminLoginRateLimiter();
|
||||
const start = 1_000_000;
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) limiter.recordFailure("peer-a", start + attempt);
|
||||
assert.ok(limiter.retryAfterMs("peer-a", start + 5) > 0);
|
||||
assert.equal(limiter.retryAfterMs("peer-a", start + 5 * 60 * 1000), 0);
|
||||
});
|
||||
|
||||
test("admin login limiter evicts old peers when its bounded table is full", () => {
|
||||
const limiter = new AdminLoginRateLimiter(2);
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) limiter.recordFailure("oldest", 10 + attempt);
|
||||
limiter.recordFailure("second", 20);
|
||||
limiter.recordFailure("newest", 30);
|
||||
assert.equal(limiter.retryAfterMs("oldest", 31), 0);
|
||||
assert.equal(limiter.retryAfterMs("second", 31), 0);
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isRestrictedAddress, resolveSafeOpenTarget } from "../src/security/open-target-policy.js";
|
||||
|
||||
test("open mode blocks loopback, private, link-local, multicast and reserved ranges", () => {
|
||||
for (const address of [
|
||||
"0.0.0.0", "10.1.2.3", "100.64.0.1", "127.0.0.1", "169.254.1.2",
|
||||
"172.16.0.1", "192.168.1.2", "224.0.0.1", "255.255.255.255",
|
||||
"::", "::1", "::7f00:1", "fc00::1", "fe80::1", "fec0::1", "ff02::1", "2001:db8::1",
|
||||
]) assert.equal(isRestrictedAddress(address), true, address);
|
||||
assert.equal(isRestrictedAddress("8.8.8.8"), false);
|
||||
assert.equal(isRestrictedAddress("2606:4700:4700::1111"), false);
|
||||
});
|
||||
|
||||
test("validated literal target is returned for the actual connection", async () => {
|
||||
assert.deepEqual(await resolveSafeOpenTarget({ host: "8.8.8.8", port: 9987 }), { host: "8.8.8.8", port: 9987 });
|
||||
await assert.rejects(resolveSafeOpenTarget({ host: "127.0.0.1", port: 9987 }));
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import test from "node:test";
|
||||
import { WebSpeakDatabase, DATABASE_SCHEMA_VERSION } from "../src/persistence/database.js";
|
||||
import { hashAdminPassword } from "../src/security/admin-password.js";
|
||||
|
||||
test("SQLite persistence initializes schema and stores the single admin/settings model", async () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-"));
|
||||
const dbPath = path.join(directory, "webspeak.db");
|
||||
const database = new WebSpeakDatabase(dbPath);
|
||||
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
|
||||
assert.equal(database.hasAdmin(), false);
|
||||
assert.equal(database.getSettings().accessMode, "fixed");
|
||||
|
||||
const credential = await hashAdminPassword("database-admin-password");
|
||||
database.initializeAdmin(credential, {
|
||||
siteName: "Private Voice",
|
||||
welcomeText: "Welcome",
|
||||
accessMode: "open",
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
tsPasswordEncrypted: "v1:ciphertext",
|
||||
});
|
||||
assert.equal(database.hasAdmin(), true);
|
||||
assert.equal(database.getAdminCredential()?.hash, credential.hash);
|
||||
assert.deepEqual(database.getSettings(), {
|
||||
siteName: "Private Voice",
|
||||
welcomeText: "Welcome",
|
||||
accessMode: "open",
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
tsPasswordEncrypted: "v1:ciphertext",
|
||||
detectedProtocol: null,
|
||||
lastTestAt: null,
|
||||
lastTestLatencyMs: null,
|
||||
lastTestError: null,
|
||||
updatedAt: database.getSettings().updatedAt,
|
||||
});
|
||||
assert.equal(database.recentAudit()[0]?.event, "ADMIN_INITIALIZED");
|
||||
database.close();
|
||||
|
||||
const reopened = new WebSpeakDatabase(dbPath);
|
||||
assert.equal(reopened.hasAdmin(), true);
|
||||
assert.equal(reopened.getSettings().siteName, "Private Voice");
|
||||
reopened.close();
|
||||
});
|
||||
|
||||
test("SQLite schema v1 upgrades to v2 with a migration copy", () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-migration-"));
|
||||
const dbPath = path.join(directory, "webspeak.db");
|
||||
const legacy = new DatabaseSync(dbPath);
|
||||
legacy.exec(`
|
||||
CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE admin_credentials (id INTEGER PRIMARY KEY CHECK (id = 1), credential_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1), site_name TEXT NOT NULL, welcome_text TEXT NOT NULL,
|
||||
access_mode TEXT NOT NULL CHECK (access_mode IN ('fixed', 'open')), ts_host TEXT NOT NULL,
|
||||
ts_port INTEGER NOT NULL, ts_password_encrypted TEXT, detected_protocol TEXT,
|
||||
last_test_at TEXT, last_test_latency_ms INTEGER, last_test_error TEXT, updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE audit_events (id INTEGER PRIMARY KEY AUTOINCREMENT, event TEXT NOT NULL, details_json TEXT NOT NULL, created_at TEXT NOT NULL);
|
||||
INSERT INTO settings VALUES (1, 'Legacy', '', 'fixed', '127.0.0.1', 9987, NULL, NULL, NULL, NULL, NULL, '2026-01-01T00:00:00.000Z');
|
||||
PRAGMA user_version = 1;
|
||||
`);
|
||||
legacy.close();
|
||||
|
||||
const upgraded = new WebSpeakDatabase(dbPath);
|
||||
assert.equal(upgraded.schemaVersion, 2);
|
||||
assert.equal(upgraded.listManagedInvites().length, 0);
|
||||
assert.equal(existsSync(`${dbPath}.schema-1.bak`), true);
|
||||
upgraded.close();
|
||||
});
|
||||
@@ -1,49 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { probeTeamSpeak, toProbeError } from "../src/server/teamspeak-probe.js";
|
||||
import { silentLogger } from "./helpers/logger.js";
|
||||
|
||||
test("connection probe reports protocol/server and always tears down", async () => {
|
||||
let disconnected = false;
|
||||
const result = await probeTeamSpeak({ host: "example.com", port: 9987 }, "", silentLogger, () => ({
|
||||
protocol: "ts6",
|
||||
client: { execCommandWithResponse: async () => [{ virtualserver_name: "Example TS" }] },
|
||||
connect: async () => undefined,
|
||||
disconnect: async () => { disconnected = true; },
|
||||
}));
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.protocol, "ts6");
|
||||
assert.equal(result.serverName, "Example TS");
|
||||
assert.equal(disconnected, true);
|
||||
});
|
||||
|
||||
test("connection probe normalizes DNS errors and tears down failures", async () => {
|
||||
let disconnected = false;
|
||||
await assert.rejects(
|
||||
probeTeamSpeak({ host: "missing.invalid", port: 9987 }, "", silentLogger, () => ({
|
||||
protocol: null,
|
||||
client: { execCommandWithResponse: async () => [] },
|
||||
connect: async () => { throw Object.assign(new Error("getaddrinfo ENOTFOUND"), { code: "ENOTFOUND" }); },
|
||||
disconnect: async () => { disconnected = true; },
|
||||
})),
|
||||
(error: unknown) => Boolean(error && typeof error === "object" && "code" in error && error.code === "HOST_NOT_FOUND"),
|
||||
);
|
||||
assert.equal(disconnected, true);
|
||||
assert.equal(toProbeError(new Error("authentication invalid password")).code, "INVALID_PASSWORD");
|
||||
});
|
||||
|
||||
test("connection probe keeps a successful result when cleanup reports an error", async () => {
|
||||
const result = await probeTeamSpeak(
|
||||
{ host: "voice.example.com", port: 9987 },
|
||||
"",
|
||||
silentLogger,
|
||||
() => ({
|
||||
protocol: "ts6",
|
||||
client: { execCommandWithResponse: async () => [{ virtualserver_name: "Cleanup Test" }] },
|
||||
connect: async () => {},
|
||||
disconnect: async () => { throw new Error("already disconnected"); },
|
||||
}),
|
||||
);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.serverName, "Cleanup Test");
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { EndpointProtocolCache, detectTeamSpeakProtocol } from "../src/server/teamspeak-adapter.js";
|
||||
|
||||
describe("TeamSpeak protocol adapter", () => {
|
||||
it("detects TS3 and TS6 from the normal version response", () => {
|
||||
assert.equal(detectTeamSpeakProtocol("version=3.13.7 build=12345"), "ts3");
|
||||
assert.equal(detectTeamSpeakProtocol("TeamSpeak 6 version 6.0.0"), "ts6");
|
||||
assert.equal(detectTeamSpeakProtocol("unknown"), null);
|
||||
});
|
||||
|
||||
it("remembers a successful endpoint only for its bounded TTL", () => {
|
||||
const cache = new EndpointProtocolCache(1000, 2);
|
||||
const target = { host: "example.com", port: 9987 };
|
||||
cache.set(target, "ts6", 1000);
|
||||
assert.equal(cache.get(target, 1500), "ts6");
|
||||
assert.equal(cache.get(target, 2001), undefined);
|
||||
});
|
||||
|
||||
it("evicts the oldest endpoint when bounded", () => {
|
||||
const cache = new EndpointProtocolCache(60_000, 2);
|
||||
cache.set({ host: "one.example", port: 9987 }, "ts3", 1);
|
||||
cache.set({ host: "two.example", port: 9987 }, "ts3", 2);
|
||||
cache.set({ host: "three.example", port: 9987 }, "ts6", 3);
|
||||
assert.equal(cache.size, 2);
|
||||
assert.equal(cache.get({ host: "one.example", port: 9987 }, 4), undefined);
|
||||
});
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { WebSpeakError } from "../src/errors.js";
|
||||
import { RECONNECT_WINDOW_MS, isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "../src/server/reconnect-policy.js";
|
||||
|
||||
test("reconnect backoff follows the bounded policy and applies deterministic jitter", () => {
|
||||
assert.deepEqual([1, 2, 3, 4, 5, 6, 8].map((attempt) => reconnectDelayMs(attempt, () => 0.5)), [1000, 2000, 4000, 8000, 15000, 30000, 30000]);
|
||||
assert.equal(reconnectDelayMs(1, () => 0), 900);
|
||||
assert.equal(reconnectDelayMs(1, () => 1), 1100);
|
||||
assert.equal(reconnectDelayMs(0, () => 0.5), 1000);
|
||||
});
|
||||
|
||||
test("reconnect eligibility distinguishes transient failures from authentication failures", () => {
|
||||
assert.equal(isRecoverable(new WebSpeakError("unreachable", "offline", true)), true);
|
||||
assert.equal(isRecoverable(new WebSpeakError("authentication_failed", "bad password", false)), false);
|
||||
assert.equal(isRecoverable(null), true);
|
||||
assert.equal(reconnectWindowOpen(10_000, 10_000 + RECONNECT_WINDOW_MS - 1), true);
|
||||
assert.equal(reconnectWindowOpen(10_000, 10_000 + RECONNECT_WINDOW_MS), false);
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
|
||||
import { decryptSecret, encryptSecret } from "../src/security/secret-crypto.js";
|
||||
import { hashAdminPassword, verifyAdminPassword } from "../src/security/admin-password.js";
|
||||
|
||||
test("master secret is stable and protects authenticated ciphertext", () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-secret-"));
|
||||
const secretPath = path.join(directory, "master.key");
|
||||
const first = loadOrCreateMasterSecret(secretPath);
|
||||
const second = loadOrCreateMasterSecret(secretPath);
|
||||
assert.equal(first.length, 32);
|
||||
assert.deepEqual(first, second);
|
||||
|
||||
const encrypted = encryptSecret("never-store-this-password", first);
|
||||
assert.equal(encrypted.includes("never-store-this-password"), false);
|
||||
assert.equal(decryptSecret(encrypted, first), "never-store-this-password");
|
||||
const [version, nonce, tag, ciphertext] = encrypted.split(":") as [string, string, string, string];
|
||||
const tamperedTag = `${tag[0] === "A" ? "B" : "A"}${tag.slice(1)}`;
|
||||
assert.throws(() => decryptSecret([version, nonce, tamperedTag, ciphertext].join(":"), first));
|
||||
});
|
||||
|
||||
test("admin password uses a salted scrypt credential", async () => {
|
||||
const first = await hashAdminPassword("a-long-admin-password");
|
||||
const second = await hashAdminPassword("a-long-admin-password");
|
||||
assert.notEqual(first.salt, second.salt);
|
||||
assert.notEqual(first.hash, second.hash);
|
||||
assert.equal(await verifyAdminPassword("a-long-admin-password", first), true);
|
||||
assert.equal(await verifyAdminPassword("wrong-password-value", first), false);
|
||||
assert.equal(JSON.stringify(first).includes("a-long-admin-password"), false);
|
||||
|
||||
const pending = await hashAdminPassword("admin", { username: "admin", mustChangePassword: true, allowWeakPassword: true });
|
||||
assert.equal(pending.username, "admin");
|
||||
assert.equal(pending.mustChangePassword, true);
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { ConnectionStateMachine, SessionManager } from "../src/server/session-manager.js";
|
||||
|
||||
test("connection state machine accepts the normal lifecycle and rejects illegal jumps", () => {
|
||||
const machine = new ConnectionStateMachine();
|
||||
machine.transition("connecting");
|
||||
machine.transition("authenticating");
|
||||
machine.transition("syncing");
|
||||
machine.transition("connected");
|
||||
machine.transition("interrupted");
|
||||
machine.transition("reconnecting");
|
||||
machine.transition("connecting");
|
||||
assert.throws(() => machine.transition("connected"), /Illegal connection state transition/);
|
||||
});
|
||||
|
||||
test("connection state machine can retry a transient authentication phase", () => {
|
||||
const machine = new ConnectionStateMachine();
|
||||
machine.transition("connecting");
|
||||
machine.transition("authenticating");
|
||||
machine.transition("reconnecting");
|
||||
machine.transition("connecting");
|
||||
machine.transition("authenticating");
|
||||
machine.transition("syncing");
|
||||
machine.transition("connected");
|
||||
assert.equal(machine.state, "connected");
|
||||
});
|
||||
|
||||
test("managed session teardown is idempotent and reaches idle even when cleanup fails", async () => {
|
||||
const manager = new SessionManager();
|
||||
let cleanupCalls = 0;
|
||||
const session = manager.admit("session-a", async () => {
|
||||
cleanupCalls++;
|
||||
throw new Error("already closed");
|
||||
});
|
||||
assert.ok(session);
|
||||
session.transition("connecting");
|
||||
await Promise.all([session.teardown("websocket-close"), session.teardown("websocket-error")]);
|
||||
assert.equal(cleanupCalls, 1);
|
||||
assert.equal(session.state, "idle");
|
||||
assert.equal(manager.activeCount, 1);
|
||||
await manager.teardown("session-a", "websocket-close");
|
||||
assert.equal(manager.activeCount, 0);
|
||||
});
|
||||
|
||||
test("session manager admits 100 active sessions and rejects the 101st", async () => {
|
||||
const manager = new SessionManager();
|
||||
for (let index = 0; index < 100; index++) {
|
||||
assert.ok(manager.admit(`session-${index}`, async () => undefined));
|
||||
}
|
||||
assert.equal(manager.activeCount, 100);
|
||||
assert.equal(manager.admit("session-100", async () => undefined), null);
|
||||
assert.equal(manager.peakCount, 100);
|
||||
assert.equal(manager.createdCount, 100);
|
||||
await manager.shutdown();
|
||||
assert.equal(manager.activeCount, 0);
|
||||
assert.equal(manager.isAccepting, false);
|
||||
assert.equal(manager.admit("after-shutdown", async () => undefined), null);
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import {
|
||||
InvalidTeamSpeakTargetError,
|
||||
formatTeamSpeakTarget,
|
||||
parseTeamSpeakTarget,
|
||||
parseTeamSpeakTargetParts,
|
||||
teamSpeakTargetKey,
|
||||
} from "../src/domain/teamspeak-target.js";
|
||||
|
||||
describe("TeamSpeak target parser", () => {
|
||||
it("uses 9987 when the port is omitted", () => {
|
||||
assert.deepEqual(parseTeamSpeakTarget("Example.COM"), { host: "example.com", port: 9987 });
|
||||
});
|
||||
|
||||
it("parses a custom port", () => {
|
||||
assert.deepEqual(parseTeamSpeakTarget("ts.example.com:9988"), { host: "ts.example.com", port: 9988 });
|
||||
});
|
||||
|
||||
it("parses the address#port form used by the web fields", () => {
|
||||
assert.deepEqual(parseTeamSpeakTarget("ts.example.com#9988"), { host: "ts.example.com", port: 9988 });
|
||||
assert.deepEqual(parseTeamSpeakTarget("[2001:DB8::1]#9988"), { host: "2001:db8::1", port: 9988 });
|
||||
});
|
||||
|
||||
it("supports bracketed IPv6", () => {
|
||||
const target = parseTeamSpeakTarget("[2001:DB8::1]:9987");
|
||||
assert.deepEqual(target, { host: "2001:db8::1", port: 9987 });
|
||||
assert.equal(formatTeamSpeakTarget(target), "[2001:db8::1]:9987");
|
||||
});
|
||||
|
||||
it("accepts legacy split fields", () => {
|
||||
assert.deepEqual(parseTeamSpeakTargetParts("[::1]", "9988"), { host: "::1", port: 9988 });
|
||||
assert.deepEqual(parseTeamSpeakTargetParts("ts.example.com", undefined), { host: "ts.example.com", port: 9987 });
|
||||
});
|
||||
|
||||
it("rejects ambiguous raw IPv6 and invalid ports", () => {
|
||||
assert.throws(() => parseTeamSpeakTarget("2001:db8::1"), InvalidTeamSpeakTargetError);
|
||||
assert.throws(() => parseTeamSpeakTarget("example.com:0"), InvalidTeamSpeakTargetError);
|
||||
assert.throws(() => parseTeamSpeakTarget("example.com:65536"), InvalidTeamSpeakTargetError);
|
||||
});
|
||||
|
||||
it("creates a stable case-insensitive cache key", () => {
|
||||
assert.equal(teamSpeakTargetKey({ host: "TS.Example.COM", port: 9987 }), "ts.example.com:9987");
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { generateIdentity } from "@honeybbq/teamspeak-client";
|
||||
import { parseTeamSpeakTarget } from "../src/domain/teamspeak-target.js";
|
||||
import { TSClient, toTSChatMessage } from "../src/server/ts-client.js";
|
||||
import { silentLogger } from "./helpers/logger.js";
|
||||
|
||||
test("TSClient keeps the supplied identity material for reconnects", () => {
|
||||
const identity = generateIdentity(8);
|
||||
const client = new TSClient({ target: parseTeamSpeakTarget("example.com:9987"), nickname: "Guest", identity }, silentLogger);
|
||||
assert.equal(client.getIdentityString(), identity.toString());
|
||||
});
|
||||
|
||||
test("TSClient preserves the TeamSpeak target id for private chat events", () => {
|
||||
const message = toTSChatMessage({
|
||||
invokerName: "Alice",
|
||||
invokerUID: "uid-alice",
|
||||
message: "hello",
|
||||
invokerGroups: [],
|
||||
targetMode: 1,
|
||||
targetID: 42n,
|
||||
invokerID: 7,
|
||||
});
|
||||
|
||||
assert.equal(message.targetId, 42n);
|
||||
assert.equal(message.invokerId, 7);
|
||||
assert.equal(message.invokerUid, "uid-alice");
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { parseClientCommand } from "../src/server/voice-protocol.js";
|
||||
|
||||
test("voice protocol accepts the versioned command payload", () => {
|
||||
const command = parseClientCommand(JSON.stringify({
|
||||
type: "switchChannel",
|
||||
requestId: "switch-1",
|
||||
payload: { channelId: "42" },
|
||||
}));
|
||||
assert.deepEqual(command, {
|
||||
type: "switchChannel",
|
||||
requestId: "switch-1",
|
||||
payload: { channelId: "42" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol rejects malformed and unsupported commands", () => {
|
||||
assert.deepEqual(parseClientCommand("not-json"), {
|
||||
error: { code: "INVALID_JSON", message: "消息不是有效的 JSON" },
|
||||
});
|
||||
assert.equal("error" in parseClientCommand(JSON.stringify({ type: "unknown", payload: {} })), true);
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage" })), {
|
||||
error: { code: "INVALID_PAYLOAD", message: "消息参数无效" },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage", payload: { message: "x".repeat(501) } })), {
|
||||
error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol keeps chat scopes and status actions explicit", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendPrivateMessage", requestId: "pm-1", payload: { clientId: 7, message: "hello" } })), {
|
||||
type: "sendPrivateMessage",
|
||||
requestId: "pm-1",
|
||||
payload: { clientId: 7, message: "hello" },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: true, message: "back soon" } })), {
|
||||
type: "setAway",
|
||||
payload: { away: true, message: "back soon" },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "secret" } })), {
|
||||
type: "switchChannel",
|
||||
payload: { channelId: "42", password: "secret" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol rejects unsafe client and away payloads", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "poke", payload: { clientId: 0, message: "hi" } })), {
|
||||
error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: "yes" } })), {
|
||||
error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "x".repeat(513) } })), {
|
||||
error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol validates whisper targets and its independent push state", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperTargets", requestId: "whisper-1", payload: { targetIds: [7, 9] } })), {
|
||||
type: "setWhisperTargets",
|
||||
requestId: "whisper-1",
|
||||
payload: { targetIds: [7, 9] },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperActive", payload: { active: true } })), {
|
||||
type: "setWhisperActive",
|
||||
payload: { active: true },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperTargets", payload: { targetIds: [7, 7] } })), {
|
||||
error: { code: "INVALID_WHISPER_TARGETS", message: "私语目标无效" },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperActive", payload: { active: "yes" } })), {
|
||||
error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" },
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#006a64" />
|
||||
<meta name="description" content="WebSpeak — TeamSpeak browser voice workspace" />
|
||||
<link rel="icon" type="image/jpeg" href="/网站图标.jpg" />
|
||||
<title>WebSpeak · TeamSpeak Web Client</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"": {
|
||||
"name": "webspeak-webclient-frontend",
|
||||
"dependencies": {
|
||||
"@sapphi-red/web-noise-suppressor": "^0.4.0",
|
||||
"pinia": "^3.0.2",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.1"
|
||||
@@ -861,6 +862,16 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@sapphi-red/web-noise-suppressor": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@sapphi-red/web-noise-suppressor/-/web-noise-suppressor-0.4.0.tgz",
|
||||
"integrity": "sha512-vkBEL/VDkbeP3qqSRQFRtPLGa19a38JUzO6J0r5D/MQSumrlERy671DAMaETgY6etXjDCoJcD7JBIaXnuGVtVw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/sapphi-red"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/estree": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
|
||||
@@ -1343,6 +1354,7 @@
|
||||
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -1503,6 +1515,7 @@
|
||||
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -1517,6 +1530,7 @@
|
||||
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.4",
|
||||
@@ -1598,6 +1612,7 @@
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.34.tgz",
|
||||
"integrity": "sha512-WdLBG9gm02OgJIG9axd5Hpx0TFLdzVgfG2evFFu8Rur5O/IoGc5cMjnjh3tPL6GnRGsYvUhBSKVPYVcxRKpMCA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vue/compiler-dom": "3.5.34",
|
||||
"@vue/compiler-sfc": "3.5.34",
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sapphi-red/web-noise-suppressor": "^0.4.0",
|
||||
"pinia": "^3.0.2",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.1"
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
const FRAME_SAMPLES = 960;
|
||||
|
||||
class WebSpeakMicCaptureProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.frame = new Float32Array(FRAME_SAMPLES);
|
||||
this.offset = 0;
|
||||
}
|
||||
|
||||
process(inputs, outputs) {
|
||||
const input = inputs[0]?.[0];
|
||||
const output = outputs[0]?.[0];
|
||||
if (output) output.fill(0);
|
||||
if (!input) return true;
|
||||
|
||||
let inputOffset = 0;
|
||||
while (inputOffset < input.length) {
|
||||
const count = Math.min(input.length - inputOffset, FRAME_SAMPLES - this.offset);
|
||||
this.frame.set(input.subarray(inputOffset, inputOffset + count), this.offset);
|
||||
this.offset += count;
|
||||
inputOffset += count;
|
||||
if (this.offset !== FRAME_SAMPLES) continue;
|
||||
|
||||
let sum = 0;
|
||||
for (let index = 0; index < this.frame.length; index++) sum += this.frame[index] * this.frame[index];
|
||||
const frame = this.frame;
|
||||
this.frame = new Float32Array(FRAME_SAMPLES);
|
||||
this.offset = 0;
|
||||
this.port.postMessage({ samples: frame, rms: Math.sqrt(sum / FRAME_SAMPLES) }, [frame.buffer]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor("webspeak-mic-capture", WebSpeakMicCaptureProcessor);
|
||||
|
After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 55 KiB |
@@ -1,3 +1,16 @@
|
||||
<template>
|
||||
<router-view />
|
||||
</template>
|
||||
|
||||
<style>
|
||||
:root {
|
||||
--ui-scale: 1;
|
||||
}
|
||||
|
||||
/* Scale the complete application from the 1920×1080 reference viewport so
|
||||
typography, spacing, controls, and icons grow together instead of drifting
|
||||
apart when the browser has a high-resolution viewport. */
|
||||
#app {
|
||||
zoom: var(--ui-scale);
|
||||
}
|
||||
</style>
|
||||
@@ -26,12 +26,17 @@
|
||||
<path d="M12 3v12m0 0 4-4m-4 4-4-4M4 19v2h16v-2" />
|
||||
</template>
|
||||
<template v-else-if="name === 'settings'">
|
||||
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0L6.2 6.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-1.42 1.42-.06-.06a1.7 1.7 0 0 0-1.88-.34 1.7 1.7 0 0 0-1.03 1.56V20h-2v-.09a1.7 1.7 0 0 0-1.03-1.56 1.7 1.7 0 0 0-1.88.34l-.06.06-1.42-1.42.06-.06A1.7 1.7 0 0 0 9.4 15a1.7 1.7 0 0 0-1.56-1.03H7v-2h.84A1.7 1.7 0 0 0 9.4 11a1.7 1.7 0 0 0-.34-1.88L9 9.06l1.42-1.42.06.06a1.7 1.7 0 0 0 1.88.34A1.7 1.7 0 0 0 13.39 6.5V6h2v.5a1.7 1.7 0 0 0 1.03 1.54 1.7 1.7 0 0 0 1.88-.34l.06-.06 1.42 1.42-.06.06A1.7 1.7 0 0 0 19.4 11a1.7 1.7 0 0 0 1.56 1.03H21v2h-.04A1.7 1.7 0 0 0 19.4 15Z" />
|
||||
</template>
|
||||
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
|
||||
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
|
||||
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 0 1-1z" />
|
||||
<template v-else-if="name === 'music'">
|
||||
<path d="M9 18V5l10-2v13" />
|
||||
<circle cx="6" cy="18" r="3" />
|
||||
<circle cx="16" cy="16" r="3" />
|
||||
</template>
|
||||
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 1-1-1z" />
|
||||
<path v-else-if="name === 'volume'" d="M4 10v4h3l4 3V7l-4 3zm10.5-2.5a6 6 0 0 1 0 9m2-11a9 9 0 0 1 0 13" />
|
||||
<path v-else-if="name === 'volume-off'" d="m4 4 16 16M4 10v4h3l4 3V7l-4 3z" />
|
||||
<template v-else-if="name === 'search'">
|
||||
@@ -68,7 +73,23 @@
|
||||
<path v-else-if="name === 'door'" d="M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5m5 14 5-5-5-5m5 5H9" />
|
||||
<path v-else-if="name === 'waveform'" d="M3 12h2l2-6 3 12 3-9 2 6h6" />
|
||||
<path v-else-if="name === 'shield'" d="M12 21s8-3.5 8-10V5l-8-3-8 3v6c0 6.5 8 10 8 10Z" />
|
||||
<template v-else-if="name === 'sun'">
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42" />
|
||||
</template>
|
||||
<path v-else-if="name === 'moon'" d="M20.4 15.2A8.5 8.5 0 0 1 8.8 3.6 8.5 8.5 0 1 0 20.4 15.2Z" />
|
||||
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
|
||||
<path v-else-if="name === 'github'" fill="currentColor" stroke="none" d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.53-1.33-1.28-1.68-1.28-1.68-1.04-.71.08-.7.08-.7 1.15.08 1.75 1.18 1.75 1.18 1.02 1.75 2.68 1.24 3.33.95.1-.74.4-1.24.73-1.52-2.55-.29-5.23-1.28-5.23-5.68 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.45.11-3.03 0 0 .96-.31 3.15 1.17.91-.25 1.88-.38 2.85-.38.97 0 1.94.13 2.85.38 2.19-1.48 3.15-1.17 3.15-1.17.62 1.58.23 2.74.11 3.03.73.8 1.18 1.82 1.18 3.07 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.04.78 2.1 0 1.52-.01 2.75-.01 3.12 0 .3.21.67.8.56C20.71 21.39 24 17.08 24 12 24 5.65 18.35.5 12 .5Z" />
|
||||
<template v-else-if="name === 'qq'">
|
||||
<ellipse cx="12" cy="12.3" rx="7.25" ry="8.85" fill="#202a2a" stroke="none" />
|
||||
<ellipse cx="12" cy="14.8" rx="4.1" ry="5.55" fill="#fff" stroke="none" />
|
||||
<circle cx="9.45" cy="9.55" r="1.35" fill="#fff" stroke="none" />
|
||||
<circle cx="14.55" cy="9.55" r="1.35" fill="#fff" stroke="none" />
|
||||
<circle cx="9.45" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
|
||||
<circle cx="14.55" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
|
||||
<path d="m10 11.15 2-1.05 2 1.05-2 1.45z" fill="#f2a53d" stroke="none" />
|
||||
<path d="m5.8 18.55-2.1 2.1 3.75-.45m10.75-1.65 2.1 2.1-3.75-.45" fill="#f2a53d" stroke="#f2a53d" stroke-width="1.5" />
|
||||
</template>
|
||||
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
|
||||
<circle v-else cx="12" cy="12" r="8" />
|
||||
</svg>
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
<template>
|
||||
<div ref="root" class="language-switcher" :class="{ open }" @keydown.esc="close">
|
||||
<button
|
||||
type="button"
|
||||
class="language-trigger"
|
||||
:aria-label="menuLabel"
|
||||
aria-haspopup="listbox"
|
||||
:aria-expanded="open"
|
||||
:aria-controls="menuId"
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<span class="language-current-flag" aria-hidden="true">{{ currentLanguage.flag }}</span>
|
||||
<span class="language-current-code">{{ currentLanguage.code }}</span>
|
||||
<Icon name="chevron-down" :size="13" />
|
||||
</button>
|
||||
|
||||
<div v-if="open" :id="menuId" class="language-dropdown" role="listbox" :aria-label="menuLabel" @click.stop>
|
||||
<button
|
||||
v-for="option in options"
|
||||
:key="option.value"
|
||||
type="button"
|
||||
class="language-option"
|
||||
:class="{ selected: modelValue === option.value }"
|
||||
role="option"
|
||||
:aria-selected="modelValue === option.value"
|
||||
@pointerdown.stop.prevent="select(option.value)"
|
||||
@keydown.enter.prevent="select(option.value)"
|
||||
@keydown.space.prevent="select(option.value)"
|
||||
>
|
||||
<span class="language-option-flag" aria-hidden="true">{{ option.flag }}</span>
|
||||
<span class="language-option-copy">
|
||||
<strong>{{ option.label }}</strong>
|
||||
<small>{{ option.code }}</small>
|
||||
</span>
|
||||
<Icon v-if="modelValue === option.value" name="check" :size="14" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import Icon from "./Icon.vue";
|
||||
|
||||
type Language = "zh" | "en" | "de" | "ru" | "ja";
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: Language;
|
||||
menuLabel?: string;
|
||||
}>(), {
|
||||
menuLabel: "Language",
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: Language];
|
||||
change: [value: Language];
|
||||
}>();
|
||||
|
||||
const options: Array<{ value: Language; code: string; label: string; flag: string }> = [
|
||||
{ value: "zh", code: "ZH", label: "中文", flag: "🇨🇳" },
|
||||
{ value: "en", code: "EN", label: "English", flag: "🇬🇧" },
|
||||
{ value: "de", code: "DE", label: "Deutsch", flag: "🇩🇪" },
|
||||
{ value: "ru", code: "RU", label: "Русский", flag: "🇷🇺" },
|
||||
{ value: "ja", code: "JA", label: "日本語", flag: "🇯🇵" },
|
||||
];
|
||||
|
||||
const root = ref<HTMLElement | null>(null);
|
||||
const open = ref(false);
|
||||
const menuId = `language-menu-${Math.random().toString(36).slice(2, 9)}`;
|
||||
const currentLanguage = computed(() => options.find((option) => option.value === props.modelValue) ?? options[0]);
|
||||
|
||||
function toggle() {
|
||||
open.value = !open.value;
|
||||
}
|
||||
|
||||
function close() {
|
||||
open.value = false;
|
||||
}
|
||||
|
||||
function select(value: Language) {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", value);
|
||||
close();
|
||||
}
|
||||
|
||||
function onDocumentPointerDown(event: PointerEvent) {
|
||||
if (root.value && !root.value.contains(event.target as Node)) close();
|
||||
}
|
||||
|
||||
onMounted(() => document.addEventListener("pointerdown", onDocumentPointerDown));
|
||||
onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerDown));
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.language-switcher {
|
||||
position: relative;
|
||||
z-index: 20;
|
||||
flex: 0 0 auto;
|
||||
color: #006a64;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.language-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 70px;
|
||||
min-height: 32px;
|
||||
padding: 0 9px;
|
||||
color: #006a64;
|
||||
background: #e2f2ef;
|
||||
border: 1px solid #c8e6e1;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
cursor: pointer;
|
||||
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
|
||||
}
|
||||
|
||||
.language-trigger:hover,
|
||||
.language-switcher.open .language-trigger {
|
||||
color: #fff;
|
||||
background: #006a64;
|
||||
border-color: #006a64;
|
||||
box-shadow: 0 7px 16px rgba(0, 106, 100, .16);
|
||||
}
|
||||
|
||||
.language-trigger .ui-icon {
|
||||
margin-left: auto;
|
||||
transition: transform .16s;
|
||||
}
|
||||
|
||||
.language-switcher.open .language-trigger .ui-icon {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.language-current-flag,
|
||||
.language-option-flag {
|
||||
font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.language-current-flag {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.language-current-code {
|
||||
letter-spacing: .02em;
|
||||
}
|
||||
|
||||
.language-dropdown {
|
||||
position: absolute;
|
||||
top: calc(100% + 8px);
|
||||
right: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-auto-rows: minmax(38px, max-content);
|
||||
align-items: start;
|
||||
align-content: start;
|
||||
gap: 3px;
|
||||
width: min(360px, calc(100vw - 16px));
|
||||
height: auto;
|
||||
max-height: none;
|
||||
padding: 7px;
|
||||
overflow: visible;
|
||||
background: #fff;
|
||||
border: 1px solid #dce9e5;
|
||||
border-radius: 13px;
|
||||
box-shadow: 0 16px 36px rgba(23, 60, 54, .18), 0 3px 8px rgba(23, 60, 54, .06);
|
||||
animation: language-menu-in .14s ease-out;
|
||||
}
|
||||
|
||||
.language-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-self: start;
|
||||
min-width: 0;
|
||||
gap: 8px;
|
||||
min-height: 38px;
|
||||
padding: 6px 8px;
|
||||
color: #344540;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: color .14s, background .14s, border-color .14s;
|
||||
}
|
||||
|
||||
.language-option:hover,
|
||||
.language-option:focus-visible,
|
||||
.language-option.selected {
|
||||
color: #006a64;
|
||||
background: #edf8f5;
|
||||
border-color: #d4eee8;
|
||||
}
|
||||
|
||||
.language-option-flag {
|
||||
flex: 0 0 auto;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.language-option-copy {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.language-option strong,
|
||||
.language-option small {
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.language-option strong {
|
||||
flex: 0 0 auto;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.language-option small {
|
||||
flex: 0 0 auto;
|
||||
color: #91a19c;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.language-option > .ui-icon {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
@keyframes language-menu-in {
|
||||
from { opacity: 0; transform: translateY(-4px) scale(.98); }
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-trigger,
|
||||
:global(:root[data-theme="dark"]) .language-trigger {
|
||||
color: #a9d9d1;
|
||||
background: #203531;
|
||||
border-color: #38564f;
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-trigger:hover,
|
||||
:global(html[data-theme="dark"]) .language-switcher.open .language-trigger,
|
||||
:global(:root[data-theme="dark"]) .language-trigger:hover,
|
||||
:global(:root[data-theme="dark"]) .language-switcher.open .language-trigger {
|
||||
color: #10201d;
|
||||
background: #69d2c7;
|
||||
border-color: #69d2c7;
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-dropdown,
|
||||
:global(:root[data-theme="dark"]) .language-dropdown {
|
||||
background: #172321;
|
||||
border-color: #30413d;
|
||||
box-shadow: 0 16px 36px rgba(0, 0, 0, .32);
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-option,
|
||||
:global(:root[data-theme="dark"]) .language-option {
|
||||
color: #d7e7e3;
|
||||
}
|
||||
|
||||
:global(html[data-theme="dark"]) .language-option:hover,
|
||||
:global(html[data-theme="dark"]) .language-option:focus-visible,
|
||||
:global(html[data-theme="dark"]) .language-option.selected,
|
||||
:global(:root[data-theme="dark"]) .language-option:hover,
|
||||
:global(:root[data-theme="dark"]) .language-option:focus-visible,
|
||||
:global(:root[data-theme="dark"]) .language-option.selected {
|
||||
color: #69d2c7;
|
||||
background: #203531;
|
||||
border-color: #38564f;
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.language-trigger {
|
||||
min-width: 62px;
|
||||
min-height: 30px;
|
||||
padding-inline: 7px;
|
||||
}
|
||||
|
||||
.language-dropdown {
|
||||
width: min(360px, calc(100vw - 16px));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -7,6 +7,25 @@ import AdminView from "./views/AdminView.vue";
|
||||
import DemoView from "./views/DemoView.vue";
|
||||
import "./services/theme.js";
|
||||
|
||||
const BASELINE_WIDTH = 1920;
|
||||
const BASELINE_HEIGHT = 1080;
|
||||
const MAX_UI_SCALE = 1.5;
|
||||
|
||||
function applyUiScale(): void {
|
||||
// Keep the current 1080p layout as the reference. Only enlarge the UI when
|
||||
// both viewport dimensions provide more space; smaller windows keep the
|
||||
// existing responsive rules instead of shrinking text until it becomes hard
|
||||
// to read.
|
||||
const scale = Math.min(
|
||||
MAX_UI_SCALE,
|
||||
Math.max(1, Math.min(window.innerWidth / BASELINE_WIDTH, window.innerHeight / BASELINE_HEIGHT)),
|
||||
);
|
||||
document.documentElement.style.setProperty("--ui-scale", scale.toFixed(4));
|
||||
}
|
||||
|
||||
applyUiScale();
|
||||
window.addEventListener("resize", applyUiScale, { passive: true });
|
||||
|
||||
const routes = [
|
||||
{ path: "/", name: "webclient", component: WebClient },
|
||||
{ path: "/join", name: "join", component: WebClient },
|
||||
|
||||
@@ -33,9 +33,10 @@ export interface LocalPreferences {
|
||||
schemaVersion: 1;
|
||||
locale?: "auto" | "zh-CN" | "en";
|
||||
theme?: "system" | "light" | "dark";
|
||||
voiceMode?: "vox" | "ptt";
|
||||
microphoneMuted?: boolean;
|
||||
noiseSuppressionEnabled?: boolean;
|
||||
voxThreshold?: number;
|
||||
language?: "zh" | "en";
|
||||
language?: "zh" | "en" | "de" | "ru" | "ja";
|
||||
preferredInputDeviceId?: string;
|
||||
preferredOutputDeviceId?: string;
|
||||
inputGain?: number;
|
||||
@@ -118,6 +119,18 @@ export async function saveStoredIdentity(privateMaterial: string, label = "此
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeStoredIdentity(): Promise<void> {
|
||||
try {
|
||||
await request("identities", "readwrite", (store, resolve, reject) => {
|
||||
const remove = store.delete(CURRENT_IDENTITY_KEY);
|
||||
remove.onsuccess = () => resolve(undefined);
|
||||
remove.onerror = () => reject(remove.error);
|
||||
});
|
||||
} catch {
|
||||
// Identity removal is best effort when browser storage is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadLocalPreferences(): Promise<LocalPreferences> {
|
||||
const defaults: LocalPreferences = { schemaVersion: 1, volumesByUid: {} };
|
||||
try {
|
||||
|
||||
@@ -17,8 +17,16 @@ export function saveTheme(theme: ThemeMode): void {
|
||||
applyTheme(theme);
|
||||
}
|
||||
|
||||
export function isDarkTheme(theme: ThemeMode): boolean {
|
||||
if (theme === "dark") return true;
|
||||
if (theme === "light") return false;
|
||||
return typeof window !== "undefined" && typeof window.matchMedia === "function"
|
||||
? window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
: false;
|
||||
}
|
||||
|
||||
export function nextTheme(theme: ThemeMode): ThemeMode {
|
||||
return theme === "system" ? "light" : theme === "light" ? "dark" : "system";
|
||||
return isDarkTheme(theme) ? "light" : "dark";
|
||||
}
|
||||
|
||||
applyTheme(getStoredTheme());
|
||||