mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-01 02:52:49 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -8,6 +8,7 @@ web/dist
|
||||
data
|
||||
certs
|
||||
release-artifacts
|
||||
scripts/acceleration-poc
|
||||
*.tar.gz
|
||||
*.tar.xz
|
||||
claude.pem
|
||||
|
||||
@@ -26,9 +26,8 @@ jobs:
|
||||
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,5 +1,94 @@
|
||||
# Changelog
|
||||
|
||||
## [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
|
||||
|
||||
### 中文
|
||||
|
||||
+2
-2
@@ -38,8 +38,8 @@ COPY --from=build --chown=node:node /app/web/dist ./web/dist
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040/tcp 40000-40099/udp
|
||||
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,7 +1,7 @@
|
||||
<div align="center">
|
||||
<a id="readme-top"></a>
|
||||
|
||||
<img src="./image.png" alt="WebSpeak 项目图标"/>
|
||||
<img src="./仓库图标.png" alt="WebSpeak 项目图标" width="180" />
|
||||
|
||||
<h1>WebSpeak</h1>
|
||||
|
||||
@@ -18,70 +18,33 @@
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://github.com/users/EchoSixHIYA/packages/container/package/webspeak)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)
|
||||
|
||||
<p>
|
||||
<a href="#简体中文">简体中文</a> ·
|
||||
<a href="#english">English</a> ·
|
||||
<a href="#deutsch">Deutsch</a> ·
|
||||
<a href="#demo">在线 Demo</a> ·
|
||||
<a href="#community">社区 / Community</a> ·
|
||||
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest">下载</a>
|
||||
<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>
|
||||
|
||||
<details>
|
||||
<summary><kbd>目录 / Table of contents</kbd></summary>
|
||||
|
||||
- [项目简介 · Overview](#overview)
|
||||
- [在线 Demo · Live Demo](#demo)
|
||||
- [社区 · Community](#community)
|
||||
- [简体中文](#简体中文)
|
||||
- [界面截图](#zh-screenshots)
|
||||
- [特性](#zh-features)
|
||||
- [更新日志](#zh-changelog)
|
||||
- [部署方案](#zh-deployment)
|
||||
- [要求和注意事项](#zh-requirements)
|
||||
- [许可证](#zh-license)
|
||||
- [English](#english)
|
||||
- [Screenshots](#en-screenshots)
|
||||
- [Features](#en-features)
|
||||
- [Changelog](#en-changelog)
|
||||
- [Deployment](#en-deployment)
|
||||
- [Requirements and notes](#en-requirements)
|
||||
- [License](#en-license)
|
||||
- [Deutsch](#deutsch)
|
||||
- [Screenshots](#de-screenshots)
|
||||
- [Funktionen](#de-features)
|
||||
- [Änderungsprotokoll](#de-changelog)
|
||||
- [Bereitstellung](#de-deployment)
|
||||
- [Voraussetzungen und Hinweise](#de-requirements)
|
||||
- [Lizenz](#de-license)
|
||||
|
||||
</details>
|
||||
|
||||
<a id="overview"></a>
|
||||
|
||||
## 项目简介 · Overview
|
||||
|
||||
| 逻辑 | 中文 | English |
|
||||
| --- | --- | --- |
|
||||
| **WHAT** | WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户打开网页即可进入频道、交流和管理自己的音频设备。 | WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Users can join channels, communicate, and manage their audio devices directly in a browser. |
|
||||
| **WHY** | 它降低了临时加入 TeamSpeak 的门槛:无需安装桌面客户端,只需分享一个网页地址,同时仍由部署者控制目标服务器、访问方式和数据。 | It lowers the barrier to joining TeamSpeak: no desktop installation is required, only a web address, while the operator keeps control of targets, access policies, and data. |
|
||||
| **HOW** | 部署 WebSpeak 后,管理员在网页控制台设置默认 TeamSpeak 目标和访问策略。浏览器负责交互与音频,WebSpeak 负责连接 TeamSpeak;需要更低延迟时可启用内置 WebRTC。 | After deployment, the administrator configures the default TeamSpeak target and access policy in the web console. The browser handles interaction and audio, WebSpeak connects to TeamSpeak, and the bundled WebRTC path can be enabled for lower latency. |
|
||||
| **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. |
|
||||
|
||||
<a id="demo"></a>
|
||||
## 文档语言 · Documentation
|
||||
|
||||
## 在线 Demo · Live Demo
|
||||
详细的特性、截图、高级功能、部署方案、要求和更新日志已按语言拆分:
|
||||
|
||||
**在线地址 / Live URL:<https://webspeak.example.invalid>**
|
||||
|
||||
> [!WARNING]
|
||||
> **中文:** 公共演示服务器位于香港,网络和运行负载可能不稳定。延迟、断线或暂时不可用不代表自行部署后的实际表现,请勿将该节点用于重要或长期会话。
|
||||
>
|
||||
> **English:** 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 a self-hosted deployment. Do not rely on this node for important or long-running sessions.
|
||||
|
||||
<a id="community"></a>
|
||||
- [简体中文](./docs/README.zh-CN.md)
|
||||
- [English](./docs/README.en.md)
|
||||
- [Deutsch](./docs/README.de.md)
|
||||
- [Русский](./docs/README.ru.md)
|
||||
- [日本語](./docs/README.ja.md)
|
||||
|
||||
## 社区 · Community
|
||||
|
||||
@@ -91,471 +54,28 @@
|
||||
<img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ 群二维码" width="290" />
|
||||
</a>
|
||||
|
||||
**群号 / Group ID:`869500475`**
|
||||
**QQ群 / QQ group:`869500475`**
|
||||
|
||||
[通过群聊链接直接加入 / Join directly through the group link](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
[通过群聊链接直接加入 / Join directly](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
|
||||
中文:在群内获取部署帮助、版本通知和使用交流。<br />
|
||||
English: Join for deployment help, release announcements, and user discussion.<br />
|
||||
Deutsch: Hilfe bei der Bereitstellung, Versionsankündigungen und Austausch in der Community.<br />
|
||||
Telegram: [Join the Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
[Telegram 群组 / Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
## 友链项目 · Friend projects
|
||||
|
||||
<a id="简体中文"></a>
|
||||
### [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.
|
||||
|
||||
WebSpeak 面向希望通过网页提供 TeamSpeak 语音服务的个人、社区和服务器管理员。它提供完整的访客页面、语音工作区和管理控制台,并可使用 Docker、预编译包或源码部署。
|
||||
|
||||
<a id="zh-screenshots"></a>
|
||||
|
||||
### 🖼️ 界面截图
|
||||
|
||||
以下截图来自上海测试节点,展示中文界面下的欢迎页、语音工作区、音量控制和成员操作菜单。
|
||||
|
||||
#### 欢迎页
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-zh-home.png" alt="WebSpeak 中文欢迎页" width="100%" />
|
||||
</p>
|
||||
|
||||
#### 语音工作区
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-zh.png" alt="WebSpeak 中文语音工作区" width="100%" />
|
||||
</p>
|
||||
|
||||
#### 音量控制
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-zh-audio.png" alt="WebSpeak 中文音量控制" width="100%" />
|
||||
</p>
|
||||
|
||||
#### 成员右键菜单
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-zh-menu.png" alt="WebSpeak 中文成员右键菜单" width="100%" />
|
||||
</p>
|
||||
|
||||
<a id="zh-features"></a>
|
||||
|
||||
### ✨ 特性
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
|
||||
| 频道与成员 | 浏览完整频道树、查看各频道成员和实时状态,并可切换频道。 |
|
||||
| 实时语音 | 使用 Opus 语音;支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
|
||||
| 音频控制 | 选择麦克风与扬声器、调节输入/输出音量、测试麦克风、闭麦、VOX,以及单独调整成员音量。 |
|
||||
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
|
||||
| 桌面端伴奏 | 在桌面浏览器中选择带音频的窗口或标签页,将其声音分享给当前 TeamSpeak 频道。 |
|
||||
| 身份与访问 | 支持浏览器身份保持、默认目标、访客自定义目标及可撤销、可过期的邀请链接。 |
|
||||
| 管理控制台 | 管理默认目标、访问策略、WebRTC、邀请链接、活动会话、连接历史、日志、诊断与数据库备份。 |
|
||||
| 界面体验 | 提供中文、English 和 Deutsch 界面、浅色/深色主题,以及桌面端和移动端响应式布局。 |
|
||||
| 自托管 | 数据由部署者保存;提供 Docker 镜像、Windows x64 和 Linux x64 发布包。 |
|
||||
|
||||
<a id="zh-changelog"></a>
|
||||
|
||||
### 🧾 更新日志
|
||||
|
||||
| 版本 | 日期 | 摘要 |
|
||||
| --- | --- | --- |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Docker 默认使用 host 网络;开放模式加强目标校验;SDK 增加 15 秒连接超时;网络性能面板改为每 3 秒持续监测。 |
|
||||
| [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,并改善成员同步和语音缓冲。 |
|
||||
| [v0.1.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.2) | 2026-09-02 | 大幅改进移动端、设备选择、AudioWorklet 和响应式顶部操作。 |
|
||||
| [v0.1.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.1) | 2026-09-02 | 完成网页客户端、管理后台、邀请链接及运维能力的首轮规范化。 |
|
||||
| [v0.1.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.0) | 2026-08-31 | 首个规范化版本。 |
|
||||
|
||||
完整记录见 [CHANGELOG.md](./CHANGELOG.md)。
|
||||
|
||||
<a id="zh-deployment"></a>
|
||||
|
||||
### 🚀 部署方案
|
||||
|
||||
| 方案 | 适用场景 | 运行环境 |
|
||||
| --- | --- | --- |
|
||||
| **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
|
||||
```
|
||||
|
||||
Compose 使用 host 网络模式,WebSpeak 直接监听宿主机的 `3040/TCP`,并直接使用宿主机的 WebRTC UDP 端口范围;因此这里不再使用 Docker 端口映射。数据保存在 Docker volume `webspeak-data`。若反向代理也运行在容器中,上游应指向宿主机地址,而不是 `webspeak:3040`。查看状态:
|
||||
|
||||
```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`,否则会删除数据库、管理员设置和其他持久化数据。
|
||||
|
||||
如需修改宿主机网页端口,在仓库目录创建 `.env`:
|
||||
|
||||
```dotenv
|
||||
WEBSPEAK_PORT=3041
|
||||
```
|
||||
|
||||
#### Windows / Linux 发布包
|
||||
|
||||
1. 从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载对应的 `windows-x64.zip` 或 `linux-x64.tar.gz`。
|
||||
2. 解压到独立目录。
|
||||
3. Windows 运行 `start-webspeak.cmd`;Linux 运行 `./start-webspeak.sh`。
|
||||
4. 发布包自带 Node.js 运行时和生产依赖,无需再次执行 `npm install`。
|
||||
|
||||
#### 源码运行
|
||||
|
||||
```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++ 编译工具。开发模式可分别使用 `npm run dev` 与 `npm run web:dev`。
|
||||
|
||||
#### 首次配置(所有方案)
|
||||
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
2. 使用默认账号 `admin`、默认密码 `admin` 登录,并按提示立即设置至少 12 位的新密码。
|
||||
3. 在“服务器”页填写默认 TeamSpeak 目标和访问方式;目标可写为 `voice.example.com#9987`。
|
||||
4. 公网使用时为站点配置 HTTPS。若启用 WebRTC,还需放行管理后台显示的 UDP 端口范围。
|
||||
|
||||
<a id="zh-requirements"></a>
|
||||
|
||||
### ⚠️ 要求和注意事项
|
||||
|
||||
| 项目 | 要求或注意事项 |
|
||||
| --- | --- |
|
||||
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和屏幕音频通常要求 HTTPS 安全上下文。 |
|
||||
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak 服务器。目标默认语音端口为 `9987`,也可在网页中填写其他端口。 |
|
||||
| Web 服务网络 | Docker Compose 使用 host 网络模式,服务直接监听宿主机 `3040/TCP`。公网部署建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
|
||||
| WebRTC | 默认使用 `40000–40099/UDP`,host 网络模式会直接使用宿主机端口;云安全组和主机防火墙仍需放行。自定义范围时只需同步放行该范围。启用 WebRTC 后需先关闭它才能修改端口范围。 |
|
||||
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接。需要并行连接时,请取消第二条连接的“保持身份”,或使用另一个浏览器/浏览器配置文件。 |
|
||||
| 伴奏 | 仅桌面端提供,并要求启用 WebRTC。选择窗口或标签页时必须同时勾选共享音频;浏览器无法直接任意读取本地应用音频。 |
|
||||
| 数据 | Docker 数据位于 `webspeak-data` volume;发布包和源码运行的数据位于程序目录的 `data/`。升级或迁移前建议从管理后台导出数据库备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
|
||||
| 项目关系 | WebSpeak 是社区项目,不是 TeamSpeak 官方产品;TeamSpeak 名称及商标归其权利人所有。 |
|
||||
|
||||
<a id="zh-license"></a>
|
||||
|
||||
### 📜 许可证
|
||||
## 许可证 · License · Lizenz
|
||||
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
|
||||
|
||||
<div align="right"><a href="#readme-top">返回顶部 ↑</a></div>
|
||||
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 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.
|
||||
|
||||
<a id="english"></a>
|
||||
|
||||
## English
|
||||
|
||||
WebSpeak is built for individuals, communities, and server operators who want to offer TeamSpeak voice access through the web. It includes a complete visitor page, voice workspace, and administration console, with Docker, prebuilt-package, and source deployment options.
|
||||
|
||||
<a id="en-screenshots"></a>
|
||||
|
||||
### 🖼️ Screenshots
|
||||
|
||||
These screenshots come from the Shanghai test node and show the welcome page, voice workspace, audio controls, and member actions in English.
|
||||
|
||||
#### Welcome page
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-en-home.png" alt="WebSpeak English welcome page" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Voice workspace
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-en.png" alt="WebSpeak English voice workspace" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Audio controls
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-en-audio.png" alt="WebSpeak English audio controls" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Member context menu
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-en-menu.png" alt="WebSpeak English member context menu" width="100%" />
|
||||
</p>
|
||||
|
||||
<a id="en-features"></a>
|
||||
|
||||
### ✨ Features
|
||||
|
||||
| Capability | Description |
|
||||
| --- | --- |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target server protocol. |
|
||||
| Channels and members | Browse the complete channel tree, see members and live states in each channel, and switch channels. |
|
||||
| Realtime voice | Uses Opus audio with a compatibility transport and an optional bundled WebRTC low-latency transport. |
|
||||
| Audio controls | Select microphones and speakers, adjust input/output volume, test the microphone, mute, use VOX, and control each member's volume. |
|
||||
| Messaging and actions | Supports channel chat, server chat, private messages, poke actions, and whisper targets. |
|
||||
| Desktop accompaniment | Select an audio-enabled window or browser tab on desktop and share its sound with the current TeamSpeak channel. |
|
||||
| Identity and access | Supports remembered browser identities, a default target, visitor-defined targets, and revocable expiring invite links. |
|
||||
| Administration | Manage the default target, access policy, WebRTC, invites, active sessions, connection history, logs, diagnostics, and database backups. |
|
||||
| User experience | Chinese, English, and German interfaces, light/dark themes, and responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; Docker images and Windows x64 / Linux x64 packages are provided. |
|
||||
|
||||
<a id="en-changelog"></a>
|
||||
|
||||
### 🧾 Changelog
|
||||
|
||||
| Version | Date | Summary |
|
||||
| --- | --- | --- |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Docker now uses host networking; open-target validation is hardened; the SDK has a 15-second connection timeout; network metrics refresh continuously every 3 seconds. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Added German support, a Telegram community link, network performance and packet-loss checks; admin tests no longer create temporary clients, and language-menu spacing and accompaniment volume fluctuations were fixed. |
|
||||
| [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 per-member volume under WebRTC. |
|
||||
| [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 switch. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | Fixed WebRTC voice and channel chat; improved 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 sync and voice buffering. |
|
||||
| [v0.1.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.2) | 2026-09-02 | Major mobile, device-selection, AudioWorklet, and responsive-header improvements. |
|
||||
| [v0.1.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.1) | 2026-09-02 | First normalized browser client, admin console, invite, and operations feature set. |
|
||||
| [v0.1.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.0) | 2026-08-31 | First normalized release. |
|
||||
|
||||
See [CHANGELOG.md](./CHANGELOG.md) for the complete history.
|
||||
|
||||
<a id="en-deployment"></a>
|
||||
|
||||
### 🚀 Deployment
|
||||
|
||||
| Method | Best for | Runtime |
|
||||
| --- | --- | --- |
|
||||
| **Docker Compose (recommended)** | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
|
||||
| **Release packages** | Running without installing 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
|
||||
```
|
||||
|
||||
Docker Compose uses host networking: WebSpeak listens directly on the host at `3040/TCP` and uses the host's WebRTC UDP range without Docker port mappings. Persistent data is stored in the `webspeak-data` Docker volume. If the reverse proxy also runs in Docker, point it to the host address rather than `webspeak:3040`. Check the service with:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade with:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Do not run `docker compose down -v`; it removes the database, administrator settings, and other persistent data.
|
||||
|
||||
To change the host-side web port, create `.env` in the repository directory:
|
||||
|
||||
```dotenv
|
||||
WEBSPEAK_PORT=3041
|
||||
```
|
||||
|
||||
#### Windows / Linux release packages
|
||||
|
||||
1. Download the matching `windows-x64.zip` or `linux-x64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest).
|
||||
2. Extract it into a dedicated directory.
|
||||
3. Run `start-webspeak.cmd` on Windows or `./start-webspeak.sh` on Linux.
|
||||
4. Release packages include the Node.js runtime and production dependencies; do not run `npm install` inside them.
|
||||
|
||||
#### Run 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. For development, run `npm run dev` and `npm run web:dev` separately.
|
||||
|
||||
#### First-time setup (all methods)
|
||||
|
||||
1. Open `http://<your-host>:3040/admin`.
|
||||
2. Sign in with the default username `admin` and password `admin`, then immediately set a new password of at least 12 characters as prompted.
|
||||
3. Configure the default TeamSpeak target and access mode on the **Servers** page. A target can be written as `voice.example.com#9987`.
|
||||
4. Configure HTTPS for public access. If WebRTC is enabled, also allow the UDP range shown in the administration console.
|
||||
|
||||
<a id="en-requirements"></a>
|
||||
|
||||
### ⚠️ Requirements and notes
|
||||
|
||||
| Area | Requirement or note |
|
||||
| --- | --- |
|
||||
| Browser | Use a current Chrome, Edge, or another modern browser with WebRTC support. Microphone and shared-screen audio normally require an HTTPS secure context. |
|
||||
| TeamSpeak network | The WebSpeak host must be able to reach the target TeamSpeak server. The default voice port is `9987`, and other ports can be entered in the web interface. |
|
||||
| Web network | Docker Compose uses host networking and the service listens directly on the host at `3040/TCP`. Public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
|
||||
| WebRTC | The default range is `40000–40099/UDP`; host networking uses the host ports directly. The cloud security group and host firewall must still allow the range. For a custom range, only the firewall rules need to be updated. Disable WebRTC before changing the range. |
|
||||
| Remembered identity | One browser identity can hold only one active remembered connection at a time. For parallel connections, disable **Remember identity** on the second connection or use another browser/profile. |
|
||||
| Accompaniment | Desktop only and requires WebRTC. When selecting a window or tab, enable audio sharing as well. Browsers cannot arbitrarily capture every local application's audio. |
|
||||
| Data | Docker data is stored in the `webspeak-data` volume. Release packages and source installs store data in the program directory's `data/` folder. Export a database backup from the admin console before upgrades or migration. |
|
||||
| Session limit | One instance accepts up to 100 active browser sessions. |
|
||||
| Project relationship | WebSpeak is a community project and is not an official TeamSpeak product. TeamSpeak names and trademarks belong to their respective owners. |
|
||||
|
||||
<a id="en-license"></a>
|
||||
|
||||
### 📜 License
|
||||
|
||||
WebSpeak is released under the [GNU Affero General Public License v3.0 only](./LICENSE). You may use, study, modify, and redistribute the project. If a modified version is made available to users over a network, the corresponding source code must be offered to those users under AGPL-3.0.
|
||||
|
||||
<div align="right"><a href="#readme-top">Back to top ↑</a></div>
|
||||
|
||||
---
|
||||
|
||||
<a id="deutsch"></a>
|
||||
|
||||
## Deutsch
|
||||
|
||||
WebSpeak ist ein selbst gehosteter TeamSpeak-3-/TeamSpeak-6-Webclient und ein Sprach-Gateway. Nutzer können direkt im Browser Kanälen beitreten, sprechen und chatten; Administratoren verwalten Zielserver und Zugriff über die Webkonsole.
|
||||
|
||||
<a id="de-screenshots"></a>
|
||||
|
||||
### 🖼️ Screenshots
|
||||
|
||||
Diese Screenshots stammen vom Shanghai-Testknoten und zeigen die Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitglieder-Menü auf Deutsch.
|
||||
|
||||
#### Willkommensseite
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-de-home.png" alt="WebSpeak deutsche Willkommensseite" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Sprachbereich
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-de.png" alt="WebSpeak deutscher Sprachbereich" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Audiosteuerung
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-de-audio.png" alt="WebSpeak deutsche Audiosteuerung" width="100%" />
|
||||
</p>
|
||||
|
||||
#### Mitglieder-Menü
|
||||
|
||||
<p align="center">
|
||||
<img src="./docs/screenshots/webspeak-de-menu.png" alt="WebSpeak deutsches Mitglieder-Menü" width="100%" />
|
||||
</p>
|
||||
|
||||
<a id="de-features"></a>
|
||||
|
||||
### ✨ Funktionen
|
||||
|
||||
| Funktion | Beschreibung |
|
||||
| --- | --- |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Protokoll des Zielservers automatisch. |
|
||||
| Kanäle und Mitglieder | Zeigt die Kanalstruktur, Mitglieder und ihren aktuellen Status an. |
|
||||
| Echtzeit-Sprache | Opus-Audio mit kompatiblem Transport und optionalem integriertem WebRTC für geringere Latenz. |
|
||||
| Audiosteuerung | Mikrofon und Lautsprecher auswählen, Lautstärke anpassen, testen und einzelne Mitglieder regeln. |
|
||||
| Nachrichten und Interaktion | Kanal- und Serverchat, private Nachrichten, Anstupsen und Flüsterziele. |
|
||||
| Begleitton auf dem Desktop | Audio eines freigegebenen Fensters oder Browser-Tabs mit dem TeamSpeak-Kanal teilen. |
|
||||
| Identität und Zugriff | Geräteidentität speichern, Standardziele verwalten, eigene Ziele erlauben und zeitlich begrenzte Einladungen erstellen. |
|
||||
| Administrationskonsole | Ziele, Zugriff, WebRTC, Sitzungen, Verbindungen, Protokolle, Diagnosen und Datenbanksicherungen verwalten. |
|
||||
| Responsive Oberfläche | Deutsche, englische und chinesische Oberfläche, helle/dunkle Designs sowie Desktop- und Mobilansicht. |
|
||||
| Selbst gehostet | Die Daten bleiben beim Betreiber; Docker-, Windows-x64- und Linux-x64-Pakete sind verfügbar. |
|
||||
|
||||
<a id="de-changelog"></a>
|
||||
|
||||
### 🧾 Änderungsprotokoll
|
||||
|
||||
| Version | Datum | Zusammenfassung |
|
||||
| --- | --- | --- |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Docker verwendet jetzt das Host-Netzwerk; die Zielprüfung im offenen Modus wurde gehärtet; das SDK erhält ein 15-Sekunden-Verbindungs-Timeout; Netzwerkmetriken werden alle 3 Sekunden fortlaufend aktualisiert. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Deutsche Oberfläche, Telegram-Link sowie Netzwerk- und Paketverlustprüfung hinzugefügt; Admin-Tests erzeugen keine temporären Clients mehr, außerdem wurden Sprachmenü-Leerraum und Begleitton-Schwankungen behoben. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Desktop-Begleitton, Hinweise zur Identität und Website-Symbol hinzugefügt; individuelle Lautstärke unter WebRTC 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; Administrationsseite, 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. |
|
||||
|
||||
Vollständige Historie: [CHANGELOG.md](./CHANGELOG.md).
|
||||
|
||||
<a id="de-deployment"></a>
|
||||
|
||||
### 🚀 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
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
Docker Compose verwendet das Host-Netzwerk: WebSpeak lauscht direkt auf dem Host unter `3040/TCP` und nutzt den WebRTC-UDP-Bereich ohne Docker-Portzuordnung. Die persistenten Daten liegen im Docker-Volume `webspeak-data`. Läuft der Reverse Proxy ebenfalls in Docker, muss er auf die Host-Adresse statt auf `webspeak:3040` zeigen. Für WebRTC muss zusätzlich der im Adminbereich angezeigte UDP-Portbereich freigegeben werden.
|
||||
|
||||
#### Release-Pakete
|
||||
|
||||
Lade das passende Paket von [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), entpacke es in ein eigenes Verzeichnis und starte unter Windows `start-webspeak.cmd` bzw. unter Linux `./start-webspeak.sh`.
|
||||
|
||||
#### Erste Konfiguration
|
||||
|
||||
Öffne `/admin`, melde dich zunächst mit `admin` / `admin` an und ändere das Passwort. Konfiguriere anschließend das Standard-TeamSpeak-Ziel und die gewünschte Zugriffsmethode.
|
||||
|
||||
<a id="de-requirements"></a>
|
||||
|
||||
### ⚠️ Voraussetzungen und Hinweise
|
||||
|
||||
| Bereich | Hinweis |
|
||||
| --- | --- |
|
||||
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Für Mikrofon- und Bildschirm-Audio ist normalerweise HTTPS erforderlich. |
|
||||
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können. Der Standard-Sprachport ist `9987`; andere Ports können im Webinterface eingetragen werden. |
|
||||
| WebRTC | Der Standardbereich ist `40000–40099/UDP`; durch das Host-Netzwerk werden die Host-Ports direkt verwendet. Firewall und Sicherheitsgruppe müssen den gesamten Bereich erlauben. |
|
||||
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung gleichzeitig halten. Für parallele Verbindungen die Option deaktivieren oder ein anderes Browserprofil verwenden. |
|
||||
| Begleitton | Nur auf Desktop-Browsern verfügbar und WebRTC erforderlich. Bei der Freigabe eines Fensters oder Tabs muss auch Audio freigegeben werden. |
|
||||
| Selbsthosting | WebSpeak ist kein offizielles TeamSpeak-Produkt. Namen und Marken gehören den jeweiligen Rechteinhabern. |
|
||||
|
||||
<a id="de-license"></a>
|
||||
|
||||
### 📜 Lizenz
|
||||
|
||||
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 den Nutzern unter AGPL-3.0 angeboten werden.
|
||||
|
||||
<div align="right"><a href="#readme-top">Nach oben ↑</a></div>
|
||||
<div align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></div>
|
||||
@@ -0,0 +1,226 @@
|
||||
# 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.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,226 @@
|
||||
# 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.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,111 @@
|
||||
# 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、Русский、日本語、ライト/ダークテーマ、レスポンシブ表示。 |
|
||||
|
||||
## 🧩 高度な機能
|
||||
|
||||
### 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.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,111 @@
|
||||
# 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, Русский и 日本語, светлая/тёмная тема и адаптивная верстка. |
|
||||
|
||||
## 🧩 Расширенные функции
|
||||
|
||||
### 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.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,226 @@
|
||||
# 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.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 个活动网页会话。 |
|
||||
Generated
+4
-4
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.8",
|
||||
"version": "0.2.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.8",
|
||||
"version": "0.2.2",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#8d91c30",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
@@ -63,7 +63,7 @@
|
||||
},
|
||||
"node_modules/@echosixhiya/teamspeak-client": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#8d91c300438b45c2f5e96638daabbc68277f378b",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338c7a83044dee0951c412ad91292b570215",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
|
||||
+7
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.8",
|
||||
"version": "0.2.2",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -11,15 +11,18 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "tsx --test \"test/**/*.test.ts\"",
|
||||
"start": "node dist/index.js",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "cd web && npx vite build",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs"
|
||||
"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",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#8d91c30",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
|
||||
@@ -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,7 +1,7 @@
|
||||
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";
|
||||
@@ -10,13 +10,17 @@ 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 {
|
||||
@@ -342,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,
|
||||
@@ -350,12 +367,26 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
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";
|
||||
}
|
||||
@@ -406,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;
|
||||
}
|
||||
@@ -436,13 +467,17 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
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 : "";
|
||||
@@ -450,21 +485,35 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
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;
|
||||
@@ -477,8 +526,14 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
: current.connectedAt
|
||||
? Math.max(0, Math.floor((Date.parse(log.timestamp) - Date.parse(current.connectedAt)) / 1000))
|
||||
: null;
|
||||
current.reason = typeof log.raw.reason === "string" ? log.raw.reason : 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);
|
||||
}
|
||||
@@ -491,7 +546,10 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
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,
|
||||
@@ -499,7 +557,12 @@ export function readConnectionHistory(logFile: string | undefined, limit: number
|
||||
? Math.max(0, Math.floor((end - Date.parse(start)) / 1000))
|
||||
: null),
|
||||
status: record.status,
|
||||
reason: record.reason,
|
||||
// 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))
|
||||
|
||||
+236
-7
@@ -3,13 +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 } 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;
|
||||
@@ -19,9 +21,28 @@ export interface AdminSettingsInput {
|
||||
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 {
|
||||
@@ -94,12 +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,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
// 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 }),
|
||||
};
|
||||
@@ -114,12 +145,22 @@ export class AdminService {
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
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,
|
||||
};
|
||||
@@ -133,11 +174,35 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -156,7 +221,7 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<{ ok: boolean; latencyMs: number; serverName: string | null; requiresPassword: boolean; packetLossPercent?: number; attempts?: number; successfulAttempts?: number; errorCode?: string }> {
|
||||
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);
|
||||
@@ -172,6 +237,8 @@ export class AdminService {
|
||||
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,
|
||||
@@ -196,7 +263,7 @@ export class AdminService {
|
||||
this.database.addAudit("CONNECTION_TEST_SUCCEEDED", { protocol: result.protocol, latencyMs: result.latencyMs });
|
||||
}
|
||||
const { protocol: _protocol, ...publicResult } = result;
|
||||
return publicResult;
|
||||
return { ...publicResult, checkType: "protocol", passwordVerified: true };
|
||||
} catch (error: unknown) {
|
||||
const probeError = error instanceof TeamSpeakProbeError
|
||||
? error
|
||||
@@ -284,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);
|
||||
@@ -294,9 +361,15 @@ 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");
|
||||
}
|
||||
@@ -322,10 +395,62 @@ export class AdminService {
|
||||
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,
|
||||
@@ -333,9 +458,91 @@ export class AdminService {
|
||||
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;
|
||||
@@ -358,6 +565,9 @@ export class AdminService {
|
||||
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,
|
||||
@@ -365,6 +575,12 @@ export class AdminService {
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -377,6 +593,9 @@ export class AdminService {
|
||||
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,
|
||||
@@ -384,6 +603,12 @@ export class AdminService {
|
||||
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");
|
||||
@@ -397,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);
|
||||
|
||||
+386
-15
@@ -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;
|
||||
}
|
||||
+46
-7
@@ -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"));
|
||||
@@ -49,6 +56,12 @@ async function main() {
|
||||
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,
|
||||
@@ -67,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 };
|
||||
@@ -84,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);
|
||||
|
||||
+180
-3
@@ -6,13 +6,16 @@ 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 = 4;
|
||||
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;
|
||||
@@ -24,6 +27,12 @@ export interface PersistedSettings {
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart: number;
|
||||
webRtcUdpEnd: number;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
relayTokenEncrypted: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -31,6 +40,9 @@ export interface SettingsUpdate {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
@@ -38,6 +50,23 @@ export interface SettingsUpdate {
|
||||
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 {
|
||||
@@ -72,6 +101,9 @@ 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;
|
||||
@@ -84,6 +116,23 @@ interface SettingsRow extends Record<string, unknown> {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -147,6 +196,9 @@ export class WebSpeakDatabase {
|
||||
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,
|
||||
@@ -158,10 +210,55 @@ export class WebSpeakDatabase {
|
||||
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(() => {
|
||||
@@ -390,20 +487,94 @@ export class WebSpeakDatabase {
|
||||
`);
|
||||
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 = ?, welcome_text_en = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
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 = ?, updated_at = ?
|
||||
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,
|
||||
@@ -411,6 +582,12 @@ export class WebSpeakDatabase {
|
||||
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)); }
|
||||
@@ -8,6 +8,8 @@ export interface JoinTicketPayload {
|
||||
channel?: string;
|
||||
identity?: string;
|
||||
rememberIdentity?: boolean;
|
||||
accelerated?: boolean;
|
||||
accelerationRelayId?: string;
|
||||
}
|
||||
|
||||
interface StoredTicket {
|
||||
|
||||
@@ -114,9 +114,14 @@ function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
|
||||
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
|
||||
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
|
||||
if (/password|authentication|invalid.*credential/.test(lower)) return "INVALID_PASSWORD";
|
||||
if (/protocol|version|handshake|negotiat/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED";
|
||||
if (/reject|full|denied/.test(lower)) return "SERVER_REJECTED";
|
||||
// 关键词刻意收窄:裸的 password/version/denied 会出现在大量无关的 ping/传输
|
||||
// 输出中,误判会把用户引向错误的排查方向,只把明确的短语视为证据。
|
||||
// Keep the keywords narrow: a bare "password", "version" or "denied" appears in
|
||||
// plenty of unrelated ping/transport output, and guessing here used to send the
|
||||
// user to the wrong remedy. Only explicit phrases are treated as evidence.
|
||||
if (/invalid password|password (?:required|incorrect|wrong|rejected)|authentication failed|invalid credential/.test(lower)) return "INVALID_PASSWORD";
|
||||
if (/protocol (?:version )?(?:mismatch|not supported|error)|version (?:is )?(?:outdated|too old|not supported)|handshake (?:failed|error|timeout)|negotiation failed/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED";
|
||||
if (/server (?:is )?full|slot limit|client protocol limit|banned?|flooding|server rejected|connection (?:denied|refused) by (?:the )?server/.test(lower)) return "SERVER_REJECTED";
|
||||
return "UNREACHABLE";
|
||||
}
|
||||
|
||||
|
||||
+33
-1
@@ -12,6 +12,7 @@ import { AdminSessionStore } from "../admin/admin-session.js";
|
||||
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
|
||||
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,6 +110,17 @@ 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()) {
|
||||
@@ -115,6 +132,12 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
// 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" });
|
||||
@@ -128,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 });
|
||||
});
|
||||
@@ -175,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"
|
||||
|
||||
@@ -5,9 +5,13 @@ 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"
|
||||
@@ -82,7 +86,7 @@ export async function probeTeamSpeak(
|
||||
requiresPassword: Boolean(password),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
throw toProbeError(error);
|
||||
throw toProbeError(error, password);
|
||||
} finally {
|
||||
try {
|
||||
await adapter.disconnect();
|
||||
@@ -92,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",
|
||||
@@ -113,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 : ""}`;
|
||||
}
|
||||
+55
-8
@@ -14,8 +14,10 @@ import {
|
||||
type TextMessage,
|
||||
} 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 +26,7 @@ export interface TSClientOptions {
|
||||
defaultChannel?: string;
|
||||
channelPassword?: string;
|
||||
identity?: Identity;
|
||||
acceleration?: AccelerationRelayOptions;
|
||||
}
|
||||
|
||||
export interface TSVoiceData {
|
||||
@@ -70,6 +73,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();
|
||||
@@ -78,9 +86,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,
|
||||
@@ -126,8 +144,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();
|
||||
@@ -181,7 +200,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);
|
||||
@@ -192,9 +219,23 @@ export class TSClient extends EventEmitter {
|
||||
});
|
||||
|
||||
client.on("clientLeave", (info) => {
|
||||
// 仅记录本客户端的踢出(4)/踢出并封禁(5)退出原因,供 kicked 事件区分普通踢出与封禁
|
||||
if (info.id === this.clientId && (info.reasonID === 4 || info.reasonID === 5)) this.selfLeaveReasonId = info.reasonID;
|
||||
this.emit("clientLeave", info);
|
||||
});
|
||||
|
||||
// 转发 SDK 的 kicked 事件:不转发的话管理员填写的踢出原因会被丢弃,浏览器
|
||||
// 只能看到笼统的「连接失败」。这里把原因连同 reason id 一起归一化后向上抛。
|
||||
// The SDK emits `kicked` only for a self leave with reason 4 (kick) or 5
|
||||
// (kick with ban) and hands over the admin written reason message. Without
|
||||
// this listener the reason was dropped, so the browser degraded to a generic
|
||||
// "connection failed" right after the transport went away.
|
||||
client.on("kicked", (reasonMsg) => {
|
||||
const reasonId = this.selfLeaveReasonId;
|
||||
this.selfLeaveReasonId = null;
|
||||
this.emit("kicked", normalizeTeamSpeakKickedReason(reasonMsg, reasonId));
|
||||
});
|
||||
|
||||
client.on("clientMoved", (info) => {
|
||||
if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID;
|
||||
this.emit("clientMoved", info);
|
||||
@@ -268,10 +309,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+165
-12
@@ -1,11 +1,12 @@
|
||||
import { WebSocketServer, WebSocket } from "ws";
|
||||
import type { IncomingMessage, Server } from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import { isIP } from "node:net";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { DirectorySynchronizer } from "./directory-sync.js";
|
||||
import { TSClient, type TSDirectorySnapshot, type TSVoiceData } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError, teamSpeakServerErrorCode, type WebSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js";
|
||||
import { IdentityLeaseStore } from "./identity-lease.js";
|
||||
@@ -14,6 +15,7 @@ import { parseClientCommand, type ClientCommand } from "./voice-protocol.js";
|
||||
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js";
|
||||
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioStats, type WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
import { pingTeamSpeakSession } from "./network-probe.js";
|
||||
import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
@@ -30,9 +32,19 @@ const AUDIO_FRAME_BYTES = 1_920;
|
||||
// before scheduling decoded audio.
|
||||
const MAX_SERVER_AUDIO_BUFFERED_BYTES = 4_096;
|
||||
|
||||
function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>): string | undefined {
|
||||
const serverMessage = error.diagnostics.serverMessage?.trim();
|
||||
const serverId = error.diagnostics.id?.trim();
|
||||
const detail = [serverMessage, serverId ? `server error id=${serverId}` : ""].filter(Boolean).join("; ");
|
||||
const safe = detail.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 160);
|
||||
return safe || undefined;
|
||||
}
|
||||
|
||||
export interface VoiceBridgeOptions {
|
||||
joinTickets: JoinTicketStore;
|
||||
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
|
||||
acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]);
|
||||
accelerationName?: string | (() => string | undefined);
|
||||
}
|
||||
|
||||
export interface AdminSessionSummary {
|
||||
@@ -119,13 +131,17 @@ interface WebClientEntry {
|
||||
ws: WebSocket;
|
||||
nickname: string;
|
||||
rememberIdentity: boolean;
|
||||
clientIp: string;
|
||||
target: TeamSpeakTarget;
|
||||
accelerationRelay?: { name: string; target: string };
|
||||
acceleration?: AccelerationRelayOptions;
|
||||
identityLeaseKey?: string;
|
||||
webrtcPublicHost?: string;
|
||||
channelTree: unknown[];
|
||||
members: Map<number, ChannelMember>;
|
||||
eventLog: ServerEvent[];
|
||||
opusEncoder: { encode(pcm: Buffer): Buffer } | null;
|
||||
opusEncoderWarnedAt: number; // Opus 编码器不可用告警的时间戳,用于限流避免反复刷屏
|
||||
whisperTargetIds: Set<number>;
|
||||
whisperActive: boolean;
|
||||
isAlive: boolean;
|
||||
@@ -133,6 +149,7 @@ interface WebClientEntry {
|
||||
audio: AudioFlowStats;
|
||||
webrtc: WebRtcAudioSession | null;
|
||||
lastLatencyProbeAt: number;
|
||||
connectionFailureCode?: string;
|
||||
}
|
||||
|
||||
export class VoiceBridge {
|
||||
@@ -164,12 +181,21 @@ export class VoiceBridge {
|
||||
|
||||
const { target, serverPassword, nickname } = connection;
|
||||
const channelName = connection.channel;
|
||||
const acceleration = connection.accelerated ? this.getAccelerationOptions(connection.accelerationRelayId) : undefined;
|
||||
if (connection.accelerated && !acceleration) {
|
||||
ws.close(4006, "ACCELERATION_UNAVAILABLE");
|
||||
return;
|
||||
}
|
||||
const clientIp = resolveClientIp(req);
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req);
|
||||
let identity;
|
||||
try {
|
||||
identity = connection.identity ? identityFromString(connection.identity) : undefined;
|
||||
} catch {
|
||||
ws.close(4003, "Invalid identity");
|
||||
// Send a structured failure before the close so the browser can tell
|
||||
// an invalid remembered identity apart from a real connection failure.
|
||||
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "connectionFailed", code: "IDENTITY_INVALID", detail: "Invalid identity" }));
|
||||
ws.close(4003, "IDENTITY_INVALID");
|
||||
return;
|
||||
}
|
||||
const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
||||
@@ -193,15 +219,25 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.info({ entryId, nickname, channel: channelName, target: formatTeamSpeakTarget(target) }, "WebClient connecting");
|
||||
this.logger.info({
|
||||
entryId,
|
||||
nickname,
|
||||
clientIp,
|
||||
channel: channelName,
|
||||
target: formatTeamSpeakTarget(target),
|
||||
...(acceleration ? { relayName: acceleration.name, relayTarget: formatTeamSpeakTarget({ host: acceleration.relayHost, port: acceleration.relayPort }) } : {}),
|
||||
}, "WebClient connecting");
|
||||
let tsClient: TSClient;
|
||||
try {
|
||||
tsClient = new TSClient({ target, nickname, serverPassword, defaultChannel: channelName, identity }, this.logger);
|
||||
tsClient = new TSClient({ target, nickname, serverPassword, defaultChannel: channelName, identity, ...(acceleration ? { acceleration } : {}) }, this.logger);
|
||||
} catch (error: unknown) {
|
||||
if (identityLeaseKey) this.identityLeases.release(identityLeaseKey, entryId);
|
||||
this.logger.error({ err: error, entryId }, "Could not create TeamSpeak client");
|
||||
void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed");
|
||||
ws.close(4003, "TeamSpeak client unavailable");
|
||||
// A 4003 with a bare close used to be reported as "identity rejected".
|
||||
// Send a structured failure so the browser says the TeamSpeak client
|
||||
// could not be created (server down / unreachable) instead.
|
||||
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "connectionFailed", code: "TEAM_SPEAK_CLIENT_UNAVAILABLE", detail: "TeamSpeak client unavailable" }));
|
||||
ws.close(4003, "TEAM_SPEAK_CLIENT_UNAVAILABLE");
|
||||
return;
|
||||
}
|
||||
entry = {
|
||||
@@ -211,13 +247,17 @@ export class VoiceBridge {
|
||||
ws,
|
||||
nickname,
|
||||
rememberIdentity: connection.rememberIdentity === true,
|
||||
clientIp,
|
||||
target,
|
||||
...(acceleration ? { accelerationRelay: { name: acceleration.name, target: formatTeamSpeakTarget({ host: acceleration.relayHost, port: acceleration.relayPort }) } } : {}),
|
||||
...(acceleration ? { acceleration } : {}),
|
||||
...(identityLeaseKey ? { identityLeaseKey } : {}),
|
||||
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
|
||||
channelTree: [],
|
||||
members: new Map(),
|
||||
eventLog: [],
|
||||
opusEncoder: null,
|
||||
opusEncoderWarnedAt: 0,
|
||||
whisperTargetIds: new Set(),
|
||||
whisperActive: false,
|
||||
isAlive: true,
|
||||
@@ -242,6 +282,10 @@ export class VoiceBridge {
|
||||
let audioReady = true;
|
||||
let realtimeReady = false;
|
||||
let hasConnectedOnce = false;
|
||||
// Set when the server kicks or bans this client. The kick and the transport
|
||||
// drop can arrive in either order, so the reason is parked here and consumed
|
||||
// by whichever handler runs second.
|
||||
let pendingKickReason: WebSpeakError | null = null;
|
||||
let reconnectStartedAt = 0;
|
||||
let reconnectAttempt = 0;
|
||||
const directory = new DirectorySynchronizer();
|
||||
@@ -306,11 +350,19 @@ export class VoiceBridge {
|
||||
initialStateSent = true;
|
||||
const wasReconnecting = hasConnectedOnce;
|
||||
hasConnectedOnce = true;
|
||||
// A previous kick reason never applies to a fresh, successful session.
|
||||
pendingKickReason = null;
|
||||
reconnectAttempt = 0;
|
||||
reconnectStartedAt = 0;
|
||||
if (!wasReconnecting) {
|
||||
entry!.eventLog.push({ id: `event-${Date.now().toString(36)}-connected`, kind: "connection", message: "已连接到服务器", timestamp: Date.now() });
|
||||
this.logger.info({ entryId: entry!.id, nickname: entry!.nickname, target: formatTeamSpeakTarget(entry!.target) }, "Web client connected to TeamSpeak");
|
||||
this.logger.info({
|
||||
entryId: entry!.id,
|
||||
nickname: entry!.nickname,
|
||||
clientIp: entry!.clientIp,
|
||||
target: formatTeamSpeakTarget(entry!.target),
|
||||
...(entry!.accelerationRelay ? { relayName: entry!.accelerationRelay.name, relayTarget: entry!.accelerationRelay.target } : {}),
|
||||
}, "Web client connected to TeamSpeak");
|
||||
}
|
||||
session.transition("connected");
|
||||
sendJson({
|
||||
@@ -321,6 +373,7 @@ export class VoiceBridge {
|
||||
whisperTargetIds: [...entry!.whisperTargetIds],
|
||||
whisperActive: entry!.whisperActive,
|
||||
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
|
||||
accelerated: Boolean(entry!.acceleration),
|
||||
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
|
||||
});
|
||||
sendJson({ type: "channelList", channels: entry!.channelTree });
|
||||
@@ -347,7 +400,10 @@ export class VoiceBridge {
|
||||
try {
|
||||
if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed");
|
||||
} catch { /* teardown below remains authoritative */ }
|
||||
sendJson({ type: "reconnectFailed", code: normalized.code });
|
||||
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
|
||||
const failureDetail = publicFailureDetail(normalized);
|
||||
entry!.connectionFailureCode = failureCode;
|
||||
sendJson({ type: "reconnectFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
|
||||
void this.teardown(entryId, "teamSpeak-connect-failed");
|
||||
};
|
||||
|
||||
@@ -401,12 +457,27 @@ export class VoiceBridge {
|
||||
sendInitialState();
|
||||
} catch (error: unknown) {
|
||||
const normalized = normalizeTeamSpeakError(error);
|
||||
this.logger.error({ code: normalized.code, entryId, reconnect: isReconnect, attempt: reconnectAttempt }, "TS connect failed");
|
||||
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
|
||||
const failureDetail = publicFailureDetail(normalized);
|
||||
entry!.connectionFailureCode = failureCode;
|
||||
this.logger.warn({
|
||||
code: failureCode,
|
||||
normalizedCode: normalized.code,
|
||||
failureDetail: describeTeamSpeakError(normalized),
|
||||
...(Object.keys(normalized.diagnostics).length ? { failureDiagnostics: normalized.diagnostics } : {}),
|
||||
entryId,
|
||||
reconnect: isReconnect,
|
||||
attempt: reconnectAttempt,
|
||||
}, "TS connect failed");
|
||||
if (!isReconnect) {
|
||||
try {
|
||||
if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed");
|
||||
} catch { /* teardown below remains authoritative */ }
|
||||
if (ws.readyState === WebSocket.OPEN) ws.close(4003, normalized.code);
|
||||
// Send the structured failure before closing. Some browsers and
|
||||
// reverse proxies do not preserve a WebSocket close reason, which
|
||||
// would otherwise collapse every failure into a generic message.
|
||||
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
|
||||
if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode);
|
||||
void this.teardown(entryId, "teamSpeak-connect-failed");
|
||||
return;
|
||||
}
|
||||
@@ -545,10 +616,30 @@ export class VoiceBridge {
|
||||
addServerEvent("poke", `${event.invokerName || "用户"} 戳了你一下`);
|
||||
});
|
||||
|
||||
// 被踢/封禁对本会话是终态:把服务器给出的原因回放给浏览器并拆除会话,
|
||||
// 而不是像以前那样因原因被丢弃而反复重连、再次撞上同一踢出。
|
||||
// A kick or ban is terminal for this session: replay the reason the server
|
||||
// sent instead of reconnecting, which is what used to happen once the reason
|
||||
// message was dropped (the browser kept retrying straight into the kick).
|
||||
tsClient.on("kicked", (kick: WebSpeakError) => {
|
||||
if (!hasConnectedOnce || session.state !== "connected") return;
|
||||
pendingKickReason = kick;
|
||||
resetDirectoryForReconnect();
|
||||
const failureCode = clientConnectionFailureCode(kick, serverPassword);
|
||||
const failureDetail = publicFailureDetail(kick);
|
||||
entry!.connectionFailureCode = failureCode;
|
||||
this.logger.warn({ entryId, code: failureCode, normalizedCode: kick.code, failureDetail: describeTeamSpeakError(kick) }, "TeamSpeak session ended by kick/ban");
|
||||
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
|
||||
void this.teardown(entryId, "teamSpeak-kicked");
|
||||
});
|
||||
|
||||
tsClient.on("disconnected", (error?: Error) => {
|
||||
if (!hasConnectedOnce || session.state !== "connected") return;
|
||||
resetDirectoryForReconnect();
|
||||
const normalized = error ? normalizeTeamSpeakError(error) : null;
|
||||
// Prefer a kick reason over the generic transport error that follows it,
|
||||
// regardless of which of the two events arrives first.
|
||||
const normalized = pendingKickReason ?? (error ? normalizeTeamSpeakError(error) : null);
|
||||
pendingKickReason = null;
|
||||
sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) });
|
||||
scheduleReconnect(normalized);
|
||||
});
|
||||
@@ -580,6 +671,16 @@ export class VoiceBridge {
|
||||
entry!.audio.tsSendFirstAt ??= sentAt;
|
||||
entry!.audio.tsSendLastAt = sentAt;
|
||||
entry!.audio.tsSendFrames++;
|
||||
} else {
|
||||
// Opus 编码器不可用(初始化失败或销毁后仍有帧在途):显式告知浏览器
|
||||
// 而不是静默丢帧,5 秒限流避免高频告警刷屏。
|
||||
// The Opus encoder is unavailable (init failed or torn down while
|
||||
// frames are still in flight): say it instead of dropping silently.
|
||||
const warnedAt = entry!.opusEncoderWarnedAt;
|
||||
if (Date.now() - warnedAt > 5_000) {
|
||||
entry!.opusEncoderWarnedAt = Date.now();
|
||||
sendJson({ type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A frame arriving during shutdown is safe to discard.
|
||||
@@ -743,8 +844,11 @@ export class VoiceBridge {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
nickname: entry.nickname,
|
||||
clientIp: entry.clientIp,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
...(entry.accelerationRelay ? { relayName: entry.accelerationRelay.name, relayTarget: entry.accelerationRelay.target } : {}),
|
||||
reason,
|
||||
...(entry.connectionFailureCode ? { failureCode: entry.connectionFailureCode } : {}),
|
||||
durationSeconds: Math.max(0, Math.floor((Date.now() - entry.session.createdAt) / 1000)),
|
||||
audio: { ...entry.audio },
|
||||
}, "Client session torn down");
|
||||
@@ -777,6 +881,15 @@ export class VoiceBridge {
|
||||
return typeof configured === "function" ? configured() : configured;
|
||||
}
|
||||
|
||||
private getAccelerationOptions(relayId = ""): ConfiguredAccelerationRelay | undefined {
|
||||
const configured = this.options.acceleration;
|
||||
const relays = typeof configured === "function" ? configured() : configured;
|
||||
if (!relays?.length) return undefined;
|
||||
const selected = relayId ? relays.find((relay) => relay.id === relayId) : relays[0];
|
||||
if (!selected) return undefined;
|
||||
return selected;
|
||||
}
|
||||
|
||||
private async handleWebRtcOffer(
|
||||
entry: WebClientEntry,
|
||||
offer: WebRtcSessionDescription,
|
||||
@@ -847,6 +960,30 @@ function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveClientIp(request: IncomingMessage): string {
|
||||
const candidates = [
|
||||
firstHeader(request.headers["x-forwarded-for"])?.split(",", 1)[0],
|
||||
firstHeader(request.headers["x-real-ip"]),
|
||||
request.socket.remoteAddress,
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const normalized = normalizeClientIp(candidate);
|
||||
if (normalized) return normalized;
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function normalizeClientIp(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
let trimmed = value.trim();
|
||||
if (trimmed.startsWith("[") && trimmed.endsWith("]")) trimmed = trimmed.slice(1, -1);
|
||||
if (trimmed.toLowerCase().startsWith("::ffff:")) {
|
||||
const mapped = trimmed.slice("::ffff:".length);
|
||||
if (isIP(mapped) === 4) trimmed = mapped;
|
||||
}
|
||||
return isIP(trimmed) ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function firstHeader(value: string | string[] | undefined): string | undefined {
|
||||
return Array.isArray(value) ? value[0] : value;
|
||||
}
|
||||
@@ -966,8 +1103,24 @@ async function handleCommand(
|
||||
function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const normalized = text.toLocaleLowerCase();
|
||||
// A TeamSpeak server error id is authoritative when the SDK preserved it, so it
|
||||
// is consulted before the keyword rules: 781 (channel password), 2568
|
||||
// (permissions), 515/2817 (server or slot limit) and friends keep their exact
|
||||
// meaning instead of being guessed from prose.
|
||||
const serverCode =
|
||||
teamSpeakServerErrorCode(isRecord(error) ? (error.id ?? error.code) : undefined) ??
|
||||
teamSpeakServerErrorCode(/\bid[\s=:]*(\d{3,5})\b/.exec(normalized)?.[1]);
|
||||
if (serverCode) {
|
||||
if (serverCode === "identity_security_level_too_low") return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" };
|
||||
if (serverCode === "channel_password_required") return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" };
|
||||
if (serverCode === "server_full") return { code: "CHANNEL_FULL", message: "该频道已满" };
|
||||
if (serverCode === "client_version_outdated") return { code: "CLIENT_VERSION_OUTDATED", message: "客户端版本过旧,服务器拒绝了该操作" };
|
||||
if (serverCode === "flooding") return { code: "FLOOD_PROTECTION", message: "操作过于频繁,请稍后重试" };
|
||||
if (serverCode === "banned") return { code: "BANNED", message: "你已被该服务器封禁" };
|
||||
if (serverCode === "connection_initialisation_failed") return { code: "CONNECTION_INITIALISATION_FAILED", message: "TeamSpeak 服务器未能完成连接初始化,请稍后重试" };
|
||||
}
|
||||
if (/permission|not permitted|insufficient|i_permission|2568/.test(normalized)) return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" };
|
||||
if (/channel.*(password|password.*required)|invalid.*(channel|password)|i_channel_password|1794/.test(normalized)) return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" };
|
||||
if (/channel.*(password|password.*required)|invalid.*(channel|password)|i_channel_password|781/.test(normalized)) return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" };
|
||||
if (/already member/.test(normalized)) return { code: "ALREADY_IN_CHANNEL", message: "你已经在该频道中" };
|
||||
if (/full|maximum.*clients/.test(normalized)) return { code: "CHANNEL_FULL", message: "该频道已满" };
|
||||
if (/not found|unknown client|invalid client/.test(normalized)) return { code: "CLIENT_NOT_FOUND", message: "成员已离线" };
|
||||
|
||||
@@ -127,6 +127,7 @@ export class WebRtcAudioSession {
|
||||
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,
|
||||
@@ -153,6 +154,7 @@ export class WebRtcAudioSession {
|
||||
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" });
|
||||
|
||||
@@ -179,6 +181,13 @@ export class WebRtcAudioSession {
|
||||
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
|
||||
@@ -406,10 +415,7 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
|
||||
setMicrophoneMuted(muted: boolean): void {
|
||||
// The browser sends a mixed microphone/accompaniment track. The mute gain
|
||||
// is applied before RTP encoding, so a server-side mute flag must not drop
|
||||
// the whole packet and silence a still-playing accompaniment.
|
||||
void muted;
|
||||
this.microphoneMuted = muted;
|
||||
}
|
||||
|
||||
setAccompanimentActive(active: boolean): void {
|
||||
|
||||
@@ -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,244 +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",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
},
|
||||
});
|
||||
assert.equal(saved.body.ok, true);
|
||||
assert.equal(saved.body.settings.accessMode, "open");
|
||||
assert.equal(saved.body.settings.hasPassword, false);
|
||||
assert.equal(saved.body.settings.webRtcEnabled, true);
|
||||
assert.equal(saved.body.settings.webRtcUdpStart, 41000);
|
||||
assert.equal(saved.body.settings.webRtcUdpEnd, 41099);
|
||||
|
||||
const lockedPorts = await request(origin, "/api/admin/server", {
|
||||
method: "PUT",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: {
|
||||
target: "voice.example.com:9988",
|
||||
passwordAction: "keep",
|
||||
accessMode: "open",
|
||||
siteName: "Changed",
|
||||
welcomeText: "Open access",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 42000,
|
||||
webRtcUdpEnd: 42099,
|
||||
},
|
||||
});
|
||||
assert.equal(lockedPorts.response.status, 400);
|
||||
assert.equal(lockedPorts.body.code, "WEBRTC_PORT_LOCKED");
|
||||
|
||||
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, 4);
|
||||
assert.equal("target" in diagnostics.body.teamSpeak, true);
|
||||
assert.equal("protocol" in diagnostics.body.teamSpeak, false);
|
||||
|
||||
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("protocol" 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("protocol" in probe.body, false);
|
||||
const settings = await request(origin, "/api/admin/server", { cookie });
|
||||
assert.equal("detectedProtocol" in settings.body, false);
|
||||
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,37 +0,0 @@
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readConnectionHistory } from "../src/admin/admin-router.js";
|
||||
|
||||
test("admin log history groups a user's connection lifecycle", () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-log-history-"));
|
||||
const logFile = path.join(directory, "webspeak.log");
|
||||
const connectedAt = new Date(Date.now() - 8_000).toISOString();
|
||||
const disconnectedAt = new Date(Date.now() - 2_000).toISOString();
|
||||
const lines = [
|
||||
{ time: new Date(Date.now() - 9_000).toISOString(), msg: "WebClient connecting", entryId: "entry-a", nickname: "Alice", target: "voice.example.com:9987" },
|
||||
{ time: connectedAt, msg: "Web client connected to TeamSpeak", entryId: "entry-a", nickname: "Alice", target: "voice.example.com:9987" },
|
||||
{ time: disconnectedAt, msg: "Client session torn down", entryId: "entry-a", nickname: "Alice", target: "voice.example.com:9987", reason: "websocket-close", durationSeconds: 6 },
|
||||
{ time: new Date(Date.now() - 1_000).toISOString(), msg: "WebClient connecting", entryId: "entry-b", nickname: "Bob", target: "voice.example.com:9987" },
|
||||
{ time: new Date(Date.now() - 500).toISOString(), msg: "Web client connected to TeamSpeak", entryId: "entry-b", nickname: "Bob", target: "voice.example.com:9987" },
|
||||
{ time: new Date(Date.now() - 250).toISOString(), msg: "WebClient connecting", entryId: "entry-c", nickname: "Carol", target: "voice.example.com:9987" },
|
||||
{ time: new Date(Date.now() - 100).toISOString(), msg: "Client session torn down", entryId: "entry-c", nickname: "Carol", target: "voice.example.com:9987", reason: "teamSpeak-connect-failed", durationSeconds: 0 },
|
||||
].map((entry) => JSON.stringify(entry));
|
||||
writeFileSync(logFile, `${lines.join("\n")}\n`);
|
||||
|
||||
const history = readConnectionHistory(logFile, 10);
|
||||
assert.equal(history.length, 3);
|
||||
const alice = history.find((entry) => entry.id === "entry-a");
|
||||
const bob = history.find((entry) => entry.id === "entry-b");
|
||||
const carol = history.find((entry) => entry.id === "entry-c");
|
||||
assert.equal(alice?.status, "disconnected");
|
||||
assert.equal(alice?.durationSeconds, 6);
|
||||
assert.equal(alice?.disconnectedAt, disconnectedAt);
|
||||
assert.equal(bob?.status, "active");
|
||||
assert.equal(bob?.disconnectedAt, null);
|
||||
assert.ok((bob?.durationSeconds ?? 0) >= 0);
|
||||
assert.equal(carol?.status, "failed");
|
||||
assert.equal(carol?.durationSeconds, null);
|
||||
});
|
||||
@@ -1,128 +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",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
});
|
||||
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");
|
||||
assert.equal(service.getAdminSettings().webRtcEnabled, true);
|
||||
assert.equal(service.getAdminSettings().webRtcUdpStart, 41000);
|
||||
assert.equal(service.getAdminSettings().webRtcUdpEnd, 41099);
|
||||
assert.deepEqual(service.getWebRtcAudioOptions(), { enabled: true, udpPortRange: [41000, 41099] });
|
||||
assert.throws(() => service.updateSettings({
|
||||
target: "public.example.com:9987",
|
||||
accessMode: "open",
|
||||
siteName: "Open WebSpeak",
|
||||
welcomeText: "Public gateway",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 42000,
|
||||
webRtcUdpEnd: 42099,
|
||||
}), /Disable WebRTC/);
|
||||
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, 4);
|
||||
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 "@echosixhiya/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 { IdentityLeaseStore } from "../src/server/identity-lease.js";
|
||||
|
||||
test("an identity lease rejects a second live owner and ignores a release from another owner", () => {
|
||||
const store = new IdentityLeaseStore();
|
||||
assert.equal(store.acquire("target:identity", "first"), true);
|
||||
assert.equal(store.acquire("target:identity", "second"), false);
|
||||
store.release("target:identity", "second");
|
||||
assert.equal(store.acquire("target:identity", "second"), false);
|
||||
store.release("target:identity", "first");
|
||||
assert.equal(store.acquire("target:identity", "second"), true);
|
||||
});
|
||||
@@ -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 "@echosixhiya/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,84 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { collectTeamSpeakPings, pingTeamSpeakHost, pingTeamSpeakSession, summarizeTeamSpeakPings } from "../src/server/network-probe.js";
|
||||
|
||||
test("TeamSpeak latency probe uses the protocol command channel", async () => {
|
||||
let command = "";
|
||||
const result = await pingTeamSpeakSession(async (value) => {
|
||||
command = value;
|
||||
return [];
|
||||
});
|
||||
assert.equal(command, "version");
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.errorCode, undefined);
|
||||
assert.equal(typeof result.latencyMs, "number");
|
||||
});
|
||||
|
||||
test("TeamSpeak protocol probe classifies a timeout and aggregates packet loss", async () => {
|
||||
const timeout = await pingTeamSpeakSession(async () => {
|
||||
throw new Error("packet ack timeout");
|
||||
});
|
||||
assert.deepEqual(timeout, { ok: false, latencyMs: null, errorCode: "TIMEOUT" });
|
||||
|
||||
let calls = 0;
|
||||
const result = await collectTeamSpeakPings(async () => {
|
||||
calls += 1;
|
||||
return calls === 2
|
||||
? { ok: false, latencyMs: null, errorCode: "TIMEOUT" }
|
||||
: { ok: true, latencyMs: calls };
|
||||
}, { attempts: 4 });
|
||||
assert.equal(calls, 4);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.packetLossPercent, 25);
|
||||
assert.equal(result.successfulAttempts, 3);
|
||||
assert.deepEqual(result.samples, [1, 3, 4]);
|
||||
});
|
||||
|
||||
test("TeamSpeak ping summary reports complete loss without fake latency", () => {
|
||||
const result = summarizeTeamSpeakPings([
|
||||
{ ok: false, latencyMs: null, errorCode: "UNREACHABLE" },
|
||||
{ ok: false, latencyMs: null, errorCode: "UNREACHABLE" },
|
||||
]);
|
||||
assert.deepEqual(result, {
|
||||
ok: false,
|
||||
latencyMs: null,
|
||||
packetLossPercent: 100,
|
||||
attempts: 2,
|
||||
successfulAttempts: 0,
|
||||
samples: [],
|
||||
errorCode: "UNREACHABLE",
|
||||
});
|
||||
});
|
||||
|
||||
test("admin host ping measures the route without opening a TeamSpeak client", async () => {
|
||||
const calls: Array<[string, number]> = [];
|
||||
let attempt = 0;
|
||||
const result = await pingTeamSpeakHost("203.0.113.10", {
|
||||
attempts: 4,
|
||||
timeoutMs: 900,
|
||||
execute: async (host, timeoutMs) => {
|
||||
calls.push([host, timeoutMs]);
|
||||
attempt += 1;
|
||||
if (attempt === 3) throw new Error("ping timeout");
|
||||
return attempt * 2;
|
||||
},
|
||||
});
|
||||
assert.deepEqual(calls, [
|
||||
["203.0.113.10", 900],
|
||||
["203.0.113.10", 900],
|
||||
["203.0.113.10", 900],
|
||||
["203.0.113.10", 900],
|
||||
]);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.packetLossPercent, 25);
|
||||
assert.equal(result.latencyMs, 4);
|
||||
});
|
||||
|
||||
test("admin host ping reports a missing runtime ping tool separately from packet loss", async () => {
|
||||
const result = await pingTeamSpeakHost("203.0.113.20", {
|
||||
attempts: 1,
|
||||
execute: async () => { throw new Error("spawn ping ENOENT"); },
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCode, "PING_UNAVAILABLE");
|
||||
});
|
||||
@@ -1,87 +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",
|
||||
welcomeTextEn: "",
|
||||
accessMode: "open",
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
tsPasswordEncrypted: "v1:ciphertext",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
});
|
||||
assert.equal(database.hasAdmin(), true);
|
||||
assert.equal(database.getAdminCredential()?.hash, credential.hash);
|
||||
assert.deepEqual(database.getSettings(), {
|
||||
siteName: "Private Voice",
|
||||
welcomeText: "Welcome",
|
||||
welcomeTextEn: "",
|
||||
accessMode: "open",
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
tsPasswordEncrypted: "v1:ciphertext",
|
||||
detectedProtocol: null,
|
||||
lastTestAt: null,
|
||||
lastTestLatencyMs: null,
|
||||
lastTestError: null,
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
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 v4 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, 4);
|
||||
assert.equal(upgraded.getSettings().webRtcEnabled, false);
|
||||
assert.equal(upgraded.getSettings().webRtcUdpStart, 40000);
|
||||
assert.equal(upgraded.getSettings().webRtcUdpEnd, 40099);
|
||||
assert.equal(upgraded.getSettings().welcomeTextEn, "");
|
||||
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 "@echosixhiya/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,108 +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: "私语状态无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol accepts and validates the microphone mute state", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMicrophoneMuted", payload: { muted: true } })), {
|
||||
type: "setMicrophoneMuted",
|
||||
payload: { muted: true },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMicrophoneMuted", payload: { muted: "yes" } })), {
|
||||
error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol accepts and validates the accompaniment state", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAccompanimentActive", payload: { active: true } })), {
|
||||
type: "setAccompanimentActive",
|
||||
payload: { active: true },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAccompanimentActive", payload: { active: "yes" } })), {
|
||||
error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol accepts and validates per-member volume", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: 1.5 } })), {
|
||||
type: "setMemberVolume",
|
||||
payload: { clientId: 7, volume: 1.5 },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: 4.1 } })), {
|
||||
error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: Number.NaN } })), {
|
||||
error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" },
|
||||
});
|
||||
});
|
||||
Generated
+15
@@ -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"
|
||||
|
||||
@@ -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>
|
||||
@@ -42,7 +42,7 @@
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import Icon from "./Icon.vue";
|
||||
|
||||
type Language = "zh" | "en" | "de";
|
||||
type Language = "zh" | "en" | "de" | "ru" | "ja";
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: Language;
|
||||
@@ -60,6 +60,8 @@ const options: Array<{ value: Language; code: string; label: string; flag: strin
|
||||
{ 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);
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { reactive, ref } from "vue";
|
||||
import { RnnoiseWorkletNode, loadRnnoise } from "@sapphi-red/web-noise-suppressor";
|
||||
import rnnoiseSimdWasmUrl from "@sapphi-red/web-noise-suppressor/rnnoise_simd.wasm?url";
|
||||
import rnnoiseWasmUrl from "@sapphi-red/web-noise-suppressor/rnnoise.wasm?url";
|
||||
import rnnoiseWorkletUrl from "@sapphi-red/web-noise-suppressor/rnnoiseWorklet.js?url";
|
||||
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
|
||||
|
||||
const micCaptureWorkletUrl = "/mic-capture-worklet.js";
|
||||
@@ -12,6 +16,15 @@ export interface VoiceState {
|
||||
tsClientId: number;
|
||||
error: string;
|
||||
errorCode: string;
|
||||
/**
|
||||
* Non-fatal audio diagnostics. Unlike error/errorCode these never take over
|
||||
* the connect form: they explain a degraded microphone or playback path while
|
||||
* the voice room itself stays joined and usable.
|
||||
*/
|
||||
microphoneError: string;
|
||||
microphoneErrorCode: string;
|
||||
audioNotice: string;
|
||||
audioNoticeCode: string;
|
||||
channelSwitchedChannelId: string;
|
||||
}
|
||||
|
||||
@@ -41,6 +54,13 @@ export interface AudioOutputDevice {
|
||||
|
||||
export type AudioPermission = "unknown" | "granted" | "denied";
|
||||
|
||||
export interface MicrophoneProcessingSettings {
|
||||
echoCancellation: boolean | null;
|
||||
noiseSuppression: boolean | null;
|
||||
autoGainControl: boolean | null;
|
||||
rnnoise: boolean | null;
|
||||
}
|
||||
|
||||
type SinkAudioContext = AudioContext & {
|
||||
setSinkId?: (sinkId: string) => Promise<void>;
|
||||
};
|
||||
@@ -84,16 +104,141 @@ export interface LatencyProbeResult {
|
||||
teamSpeakErrorCode?: string;
|
||||
}
|
||||
|
||||
const MAX_VISIBLE_ERROR_CODE_LENGTH = 64;
|
||||
const CLIENT_ERROR_CODE_ALIASES: Record<string, string> = {
|
||||
PASSWORD_REQUIRED: "SERVER_PASSWORD_REQUIRED",
|
||||
INVALID_PASSWORD: "INVALID_SERVER_PASSWORD",
|
||||
AUTHENTICATION_FAILED: "INVALID_SERVER_PASSWORD",
|
||||
GATEWAY_FULL: "SERVER_REJECTED",
|
||||
TS_CONNECT_FAILED: "CONNECTION_FAILED",
|
||||
TEAM_SPEAK_CONNECT_FAILED: "CONNECTION_FAILED",
|
||||
};
|
||||
|
||||
/** Keep codes useful to the user without allowing an unbounded server value into the UI. */
|
||||
function safeClientErrorCode(value: unknown): string {
|
||||
const normalized = String(value ?? "")
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
.replace(/[^A-Z0-9_-]+/g, "_")
|
||||
.replace(/^_+|_+$/g, "");
|
||||
return normalized.slice(0, MAX_VISIBLE_ERROR_CODE_LENGTH);
|
||||
}
|
||||
|
||||
function normalizedClientErrorCode(value: unknown, fallback = "CONNECTION_FAILED"): string {
|
||||
const safe = safeClientErrorCode(value);
|
||||
return CLIENT_ERROR_CODE_ALIASES[safe] ?? (safe || fallback);
|
||||
}
|
||||
|
||||
function safeClientErrorDetail(value: unknown): string {
|
||||
return String(value ?? "")
|
||||
.replace(/[\u0000-\u001f\u007f]/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.slice(0, 160);
|
||||
}
|
||||
|
||||
// TeamSpeak 对非法昵称没有独立错误码:长度违规统一报 invalid parameter size
|
||||
// (服务器错误 id 1541),该特征串是网关能转发的唯一机器可读线索,因此把匹配器
|
||||
// 与解释文案放在一起,保证两者同步演进。
|
||||
/**
|
||||
* TeamSpeak has no dedicated error for a nickname it refuses: a nickname outside
|
||||
* its length rules is answered with "invalid parameter size" and server error id
|
||||
* 1541. That signature is the only machine-readable hint the gateway can forward,
|
||||
* so keep the matcher next to the message builder that explains it to the user.
|
||||
*/
|
||||
const NICKNAME_LENGTH_SIGNATURE = /invalid[\s_-]*parameter[\s_-]*size|\bid[\s=:]*1541\b|nickname.{0,30}(?:length|size)/i;
|
||||
|
||||
/** Shown whenever TeamSpeak refuses the nickname because of its length. */
|
||||
const NICKNAME_LENGTH_MESSAGE = "昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试";
|
||||
|
||||
/**
|
||||
* Browsers only hand out a DOMException name for getUserMedia failures (and an
|
||||
* often-English message that used to reach the UI verbatim). Map every name the
|
||||
* browsers actually raise to a sentence the user can act on, and keep the
|
||||
* DOMException name as the stable failure code.
|
||||
*/
|
||||
const MICROPHONE_FAILURE_REASONS: Record<string, string> = {
|
||||
NOTALLOWEDERROR: "浏览器未授予麦克风权限",
|
||||
PERMISSIONDENIEDERROR: "浏览器未授予麦克风权限",
|
||||
PERMISSION_DISMISSED: "浏览器未授予麦克风权限",
|
||||
SECURITYERROR: "浏览器阻止了麦克风访问",
|
||||
NOTFOUNDERROR: "未找到可用的麦克风",
|
||||
DEVICESNOTFOUNDERROR: "未找到可用的麦克风",
|
||||
OVERCONSTRAINEDERROR: "所选麦克风当前不可用",
|
||||
NOTREADABLEERROR: "麦克风可能正被其他程序占用",
|
||||
TRACKSTARTERROR: "麦克风可能正被其他程序占用",
|
||||
ABORTERROR: "麦克风启动被中断,请重试",
|
||||
INVALIDSTATEERROR: "麦克风启动被中断,请重试",
|
||||
TYPEFERROR: "麦克风访问参数被系统拒绝",
|
||||
};
|
||||
|
||||
const MICROPHONE_FAILURE_FALLBACK = "麦克风不可用,请检查浏览器权限与音频设备";
|
||||
|
||||
const MICROPHONE_FAILURE_CODE_PREFIX = "MIC_";
|
||||
|
||||
/** Turn a getUserMedia / DOMException failure into a stable code plus a readable sentence. */
|
||||
export function normalizeMicrophoneFailure(error: unknown): { code: string; message: string } {
|
||||
const rawName = error instanceof Error ? String(error.name || "") : "";
|
||||
const name = safeClientErrorCode(rawName).slice(0, 40);
|
||||
const reason = MICROPHONE_FAILURE_REASONS[name] ?? MICROPHONE_FAILURE_FALLBACK;
|
||||
return { code: `${MICROPHONE_FAILURE_CODE_PREFIX}${name || "UNAVAILABLE"}`, message: `麦克风访问失败:${reason}` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every code this client can render for a failed connection. A code is regarded
|
||||
* as "explainable" only when it appears here, which is also what keeps the
|
||||
* gateway close codes from being replaced by an unknown close reason.
|
||||
*/
|
||||
const CONNECTION_FAILURE_MESSAGES: Record<string, string> = {
|
||||
ORIGIN_REJECTED: "请求来源不受信任,请从正确的网站入口重新打开",
|
||||
NOT_INITIALIZED: "WebSpeak 尚未完成配置,请联系管理员",
|
||||
RATE_LIMITED: "请求过于频繁,请稍后重试",
|
||||
INVALID_TARGET: "TeamSpeak 服务器地址无效",
|
||||
INVALID_NICKNAME: NICKNAME_LENGTH_MESSAGE,
|
||||
HOST_NOT_FOUND: "找不到 TeamSpeak 服务器主机名,请检查地址",
|
||||
UNREACHABLE: "无法到达 TeamSpeak 服务器,请检查网络或地址",
|
||||
CONNECTION_REFUSED: "TeamSpeak 服务器拒绝了连接,请检查端口和服务状态",
|
||||
CONNECTION_RESET: "TeamSpeak 连接被服务器或网络重置,请稍后重试",
|
||||
TIMEOUT: "连接 TeamSpeak 超时,请检查网络或服务器状态",
|
||||
SERVER_PASSWORD_REQUIRED: "该服务器需要密码,请输入密码后重试",
|
||||
INVALID_SERVER_PASSWORD: "服务器密码错误,请重新输入",
|
||||
PROTOCOL_NEGOTIATION_FAILED: "TeamSpeak 协议协商失败",
|
||||
SERVER_REJECTED: "TeamSpeak 服务器拒绝了连接",
|
||||
CHANNEL_PASSWORD_REQUIRED: "该频道需要密码",
|
||||
NICKNAME_IN_USE: "该昵称已被服务器上的其他用户占用,请更换昵称",
|
||||
IDENTITY_SECURITY_LEVEL_TOO_LOW: "你的身份安全等级低于该服务器要求,请提升后重试",
|
||||
IDENTITY_LIMIT_REACHED: "该身份建立的连接数已达上限,请关闭其他连接后重试",
|
||||
CLIENT_VERSION_OUTDATED: "客户端版本过旧,服务器拒绝连接,请升级后重试",
|
||||
FLOOD_PROTECTION: "操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试",
|
||||
BANNED: "你已被该服务器封禁,无法连接",
|
||||
KICKED: "你已被服务器移出",
|
||||
SERVER_SHUTTING_DOWN: "TeamSpeak 服务器正在关闭,暂时无法连接",
|
||||
CONNECTION_INITIALISATION_FAILED: "TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试",
|
||||
SERVER_FULL: "服务器当前已满,请稍后重试",
|
||||
INVALID_PARAMETER: "TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规",
|
||||
IDENTITY_IN_USE: "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试",
|
||||
CONNECTION_FAILED: "TeamSpeak 连接失败,请检查地址、网络或服务器状态",
|
||||
// Gateway close codes: these replace the generic "connection failed" when the
|
||||
// gateway drops the socket itself (see GATEWAY_CLOSE_CODE_CODES).
|
||||
JOIN_TICKET_REQUIRED: "语音会话票据缺失或已过期,请返回列表重新进入语音空间",
|
||||
IDENTITY_INVALID: "语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入",
|
||||
IDENTITY_REJECTED: "语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入",
|
||||
ACCELERATION_UNAVAILABLE: "当前中继加速不可用,请关闭加速后重试或联系管理员",
|
||||
GATEWAY_NETWORK_LOST: "与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入",
|
||||
GATEWAY_SESSION_ENDED: "语音网关会话意外结束,请重新进入语音空间",
|
||||
TEAM_SPEAK_CLIENT_UNAVAILABLE: "语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试",
|
||||
};
|
||||
|
||||
export function useVoiceWebSocket() {
|
||||
const ws = ref<WebSocket | null>(null);
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", channelSwitchedChannelId: "" });
|
||||
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" });
|
||||
const members = reactive<ChannelMember[]>([]);
|
||||
const channels = reactive<ChannelInfo[]>([]);
|
||||
const chatMessages = reactive<ChatMessage[]>([]);
|
||||
const serverEvents = reactive<ServerEvent[]>([]);
|
||||
const pokeNotifications = reactive<{ id: string; invokerId: number; invokerUid: string; invokerName: string; message: string; timestamp: number }[]>([]);
|
||||
let connectionSequence = 0;
|
||||
let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean } | null = null;
|
||||
let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean; accelerated: boolean; accelerationRelayId: string } | null = null;
|
||||
let latencyProbeSequence = 0;
|
||||
const pendingLatencyProbes = new Map<string, { startedAt: number; resolve: (result: LatencyProbeResult | null) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
let webrtcPeer: RTCPeerConnection | null = null;
|
||||
@@ -116,9 +261,13 @@ export function useVoiceWebSocket() {
|
||||
let workletNode: AudioWorkletNode | null = null;
|
||||
let workletContext: AudioContext | null = null;
|
||||
let workletModulePromise: Promise<void> | null = null;
|
||||
let rnnoiseNode: RnnoiseWorkletNode | null = null;
|
||||
let rnnoiseWorkletModulePromise: Promise<void> | null = null;
|
||||
let rnnoiseWasmPromise: Promise<ArrayBuffer> | null = null;
|
||||
let micSource: MediaStreamAudioSourceNode | null = null;
|
||||
let micGain: GainNode | null = null;
|
||||
let silentGain: GainNode | null = null;
|
||||
let processedMicDestination: MediaStreamAudioDestinationNode | null = null;
|
||||
const accompanimentActive = ref(false);
|
||||
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
|
||||
const accompanimentErrorCode = ref<"" | "unsupported" | "needsWebRtc" | "noAudio" | "permission">("");
|
||||
@@ -137,6 +286,12 @@ export function useVoiceWebSocket() {
|
||||
const selectedOutputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:output-device") ?? "" : "");
|
||||
const outputDeviceSupported = ref(false);
|
||||
const audioPermission = ref<AudioPermission>("unknown");
|
||||
const microphoneProcessing = reactive<MicrophoneProcessingSettings>({
|
||||
echoCancellation: null,
|
||||
noiseSuppression: null,
|
||||
autoGainControl: null,
|
||||
rnnoise: null,
|
||||
});
|
||||
const audioContextState = ref<AudioContextState | "unknown">("unknown");
|
||||
const micLevel = ref(0);
|
||||
const microphoneTestActive = ref(false);
|
||||
@@ -144,6 +299,7 @@ export function useVoiceWebSocket() {
|
||||
let testRecorder: MediaRecorder | null = null;
|
||||
let testRecorderTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const microphoneMuted = ref(false);
|
||||
const noiseSuppressionEnabled = ref(true);
|
||||
const inputVolume = ref(1);
|
||||
const outputVolume = ref(1);
|
||||
const outputMuted = ref(false);
|
||||
@@ -188,6 +344,7 @@ export function useVoiceWebSocket() {
|
||||
preferredInputDeviceId: selectedInputDeviceId.value,
|
||||
inputDeviceId: selectedInputDeviceId.value,
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
noiseSuppressionEnabled: noiseSuppressionEnabled.value,
|
||||
voxThreshold: voxThreshold.value,
|
||||
inputGain: inputVolume.value,
|
||||
outputVolume: outputVolume.value,
|
||||
@@ -208,6 +365,7 @@ export function useVoiceWebSocket() {
|
||||
void loadLocalPreferences().then((preferences) => {
|
||||
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
|
||||
if (typeof preferences.microphoneMuted === "boolean") microphoneMuted.value = preferences.microphoneMuted;
|
||||
if (typeof preferences.noiseSuppressionEnabled === "boolean") noiseSuppressionEnabled.value = preferences.noiseSuppressionEnabled;
|
||||
if (typeof preferences.voxThreshold === "number") voxThreshold.value = clamp(preferences.voxThreshold, 0.001, 0.08);
|
||||
if (typeof preferences.inputGain === "number") inputVolume.value = Math.max(0, Math.min(1, preferences.inputGain));
|
||||
if (typeof preferences.outputVolume === "number") outputVolume.value = Math.max(0, Math.min(1, preferences.outputVolume));
|
||||
@@ -272,6 +430,51 @@ export function useVoiceWebSocket() {
|
||||
return Math.max(minimum, Math.min(maximum, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Microphone failures are a degraded state, not a connection failure: the room
|
||||
* stays joined, so they get their own slot instead of taking over `error`.
|
||||
*/
|
||||
function setMicrophoneError(error: unknown): string {
|
||||
const failure = normalizeMicrophoneFailure(error);
|
||||
state.microphoneErrorCode = failure.code;
|
||||
state.microphoneError = failure.message;
|
||||
return failure.message;
|
||||
}
|
||||
|
||||
function clearMicrophoneError(): void {
|
||||
state.microphoneError = "";
|
||||
state.microphoneErrorCode = "";
|
||||
}
|
||||
|
||||
/** Non-fatal audio notice (WebRTC fallback, blocked autoplay, device list failure...). */
|
||||
function setAudioNotice(code: string, message: string): void {
|
||||
state.audioNoticeCode = safeClientErrorCode(code) || "AUDIO_NOTICE";
|
||||
state.audioNotice = message;
|
||||
}
|
||||
|
||||
function clearAudioNotice(code?: string): void {
|
||||
if (code && state.audioNoticeCode !== safeClientErrorCode(code)) return;
|
||||
state.audioNotice = "";
|
||||
state.audioNoticeCode = "";
|
||||
}
|
||||
|
||||
/** A suspended AudioContext silently swallows capture: say so instead of pretending. */
|
||||
function syncAudioContextNotice(): void {
|
||||
if (audioCtx && audioCtx.state === "suspended") {
|
||||
setAudioNotice("AUDIO_CONTEXT_SUSPENDED", "浏览器的音频处理被暂停(需要一次页面交互),麦克风与扬声器可能无声:请点击页面任意位置后重试");
|
||||
} else {
|
||||
clearAudioNotice("AUDIO_CONTEXT_SUSPENDED");
|
||||
}
|
||||
}
|
||||
|
||||
function audioNoticeMessage(code: string, detail?: unknown): string {
|
||||
const detailText = safeClientErrorDetail(detail);
|
||||
if (code === "AUDIO_ENCODER_UNAVAILABLE") {
|
||||
return `麦克风声音未能发送:语音网关的音频编码器不可用(错误代码:${code})${detailText ? `:${detailText}` : ""},请联系管理员`;
|
||||
}
|
||||
return `音频链路异常(错误代码:${code})${detailText ? `:${detailText}` : ""},麦克风声音可能没有发送给其他成员`;
|
||||
}
|
||||
|
||||
async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise<void> {
|
||||
const mediaSinkSupported = typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
|
||||
if (!ctx.setSinkId && !mediaSinkSupported) {
|
||||
@@ -305,12 +508,19 @@ export function useVoiceWebSocket() {
|
||||
// route: a running-but-silent graph could leave the UI reporting a live
|
||||
// speaker while the actual remote audio element remained muted.
|
||||
output.muted = false;
|
||||
if (audioCtx && audioCtx.state === "suspended") {
|
||||
try { await audioCtx.resume(); } catch { /* a user gesture is still required */ }
|
||||
}
|
||||
try {
|
||||
await output.play();
|
||||
webrtcPlaybackRetryCleanup?.();
|
||||
clearAudioNotice("PLAYBACK_BLOCKED");
|
||||
syncAudioContextNotice();
|
||||
} catch {
|
||||
// Mobile and privacy-focused browsers can require a gesture even for a
|
||||
// MediaStream. Keep retrying after the next real interaction.
|
||||
// MediaStream. Keep retrying after the next real interaction, but tell the
|
||||
// user why the remote audio is missing instead of staying silent.
|
||||
setAudioNotice("PLAYBACK_BLOCKED", "浏览器阻止了音频自动播放,暂时听不到其他成员的声音:请点击页面任意位置,或在地址栏允许本站播放声音");
|
||||
installWebRtcPlaybackRetry();
|
||||
}
|
||||
}
|
||||
@@ -329,8 +539,10 @@ export function useVoiceWebSocket() {
|
||||
sampleRate: { ideal: 48000 },
|
||||
channelCount: { ideal: 1 },
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
noiseSuppression: noiseSuppressionEnabled.value,
|
||||
// Keep the microphone's natural dynamics. Browser AGC can make speech
|
||||
// pump in volume, especially while background noise changes.
|
||||
autoGainControl: false,
|
||||
};
|
||||
if (selectedInputDeviceId.value) constraints.deviceId = { exact: selectedInputDeviceId.value };
|
||||
return constraints;
|
||||
@@ -340,9 +552,21 @@ export function useVoiceWebSocket() {
|
||||
if (!navigator.mediaDevices?.enumerateDevices) {
|
||||
inputDevices.length = 0;
|
||||
outputDevices.length = 0;
|
||||
setAudioNotice("DEVICE_LIST_UNAVAILABLE", "无法读取音频设备列表,将使用浏览器默认音频设备:请在系统或浏览器隐私设置中允许读取设备信息");
|
||||
return;
|
||||
}
|
||||
let devices: MediaDeviceInfo[];
|
||||
try {
|
||||
devices = await navigator.mediaDevices.enumerateDevices();
|
||||
clearAudioNotice("DEVICE_LIST_UNAVAILABLE");
|
||||
} catch {
|
||||
// enumerateDevices rejects when the device list is blocked (for example in a
|
||||
// locked-down iframe). Use the browser defaults and explain the limitation.
|
||||
inputDevices.length = 0;
|
||||
outputDevices.length = 0;
|
||||
setAudioNotice("DEVICE_LIST_UNAVAILABLE", "无法读取音频设备列表,将使用浏览器默认音频设备:请在系统或浏览器隐私设置中允许读取设备信息");
|
||||
return;
|
||||
}
|
||||
const devices = await navigator.mediaDevices.enumerateDevices();
|
||||
const microphones = devices
|
||||
.filter((device) => device.kind === "audioinput")
|
||||
.map((device) => ({ deviceId: device.deviceId, label: device.label, groupId: device.groupId }));
|
||||
@@ -369,23 +593,72 @@ export function useVoiceWebSocket() {
|
||||
await refreshAudioDevices();
|
||||
}
|
||||
|
||||
async function createRnnoiseNode(ctx: AudioContext): Promise<RnnoiseWorkletNode | null> {
|
||||
if (typeof AudioWorkletNode === "undefined" || !ctx.audioWorklet) {
|
||||
microphoneProcessing.rnnoise = false;
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (!rnnoiseWasmPromise) {
|
||||
rnnoiseWasmPromise = loadRnnoise({ url: rnnoiseWasmUrl, simdUrl: rnnoiseSimdWasmUrl }).catch((error) => {
|
||||
rnnoiseWasmPromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
if (!rnnoiseWorkletModulePromise) {
|
||||
rnnoiseWorkletModulePromise = ctx.audioWorklet.addModule(rnnoiseWorkletUrl).catch((error) => {
|
||||
rnnoiseWorkletModulePromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
const [wasmBinary] = await Promise.all([rnnoiseWasmPromise, rnnoiseWorkletModulePromise]);
|
||||
const node = new RnnoiseWorkletNode(ctx, { maxChannels: 1, wasmBinary });
|
||||
microphoneProcessing.rnnoise = true;
|
||||
return node;
|
||||
} catch {
|
||||
// Native browser NS remains active as a fallback. RNNoise is an optional
|
||||
// enhancement and must never prevent a microphone from starting.
|
||||
microphoneProcessing.rnnoise = false;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function startMicrophone(): Promise<void> {
|
||||
const ctx = getAudioCtx();
|
||||
if (ctx.state === "suspended") await ctx.resume();
|
||||
if (ctx.state === "suspended") {
|
||||
try { await ctx.resume(); } catch { /* the audio context notice explains the silence */ }
|
||||
}
|
||||
// Acquire the replacement stream before tearing down the current graph so
|
||||
// changing devices does not interrupt an active microphone on failure.
|
||||
let nextStream: MediaStream;
|
||||
try {
|
||||
nextStream = await navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() });
|
||||
audioPermission.value = "granted";
|
||||
clearMicrophoneError();
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && ["NotAllowedError", "SecurityError"].includes(error.name)) audioPermission.value = "denied";
|
||||
// Never let the raw DOMException (usually an English message) reach the UI:
|
||||
// record a readable failure first, then let the caller decide how to show it.
|
||||
setMicrophoneError(error);
|
||||
throw error;
|
||||
}
|
||||
const microphoneTrack = nextStream.getAudioTracks()[0];
|
||||
const settings = microphoneTrack?.getSettings();
|
||||
microphoneProcessing.echoCancellation = typeof settings?.echoCancellation === "boolean" ? settings.echoCancellation : null;
|
||||
microphoneProcessing.noiseSuppression = typeof settings?.noiseSuppression === "boolean" ? settings.noiseSuppression : null;
|
||||
microphoneProcessing.autoGainControl = typeof settings?.autoGainControl === "boolean" ? settings.autoGainControl : null;
|
||||
stopMicrophone(false);
|
||||
micStream = nextStream;
|
||||
|
||||
micSource = ctx.createMediaStreamSource(micStream);
|
||||
rnnoiseNode = noiseSuppressionEnabled.value ? await createRnnoiseNode(ctx) : null;
|
||||
if (!noiseSuppressionEnabled.value) microphoneProcessing.rnnoise = false;
|
||||
const processedSource: AudioNode = rnnoiseNode ?? micSource;
|
||||
if (rnnoiseNode) micSource.connect(rnnoiseNode);
|
||||
processedMicDestination = ctx.createMediaStreamDestination();
|
||||
processedMicDestination.channelCount = 1;
|
||||
processedMicDestination.channelCountMode = "explicit";
|
||||
processedSource.connect(processedMicDestination);
|
||||
micGain = ctx.createGain();
|
||||
micGain.gain.value = inputVolume.value;
|
||||
silentGain = ctx.createGain();
|
||||
@@ -468,14 +741,16 @@ export function useVoiceWebSocket() {
|
||||
scriptNode.onaudioprocess = (event) => handleCaptureChunk(event.inputBuffer.getChannelData(0));
|
||||
}
|
||||
|
||||
micSource.connect(micGain);
|
||||
processedSource.connect(micGain);
|
||||
const captureNode = workletNode ?? scriptNode!;
|
||||
micGain.connect(captureNode);
|
||||
captureNode.connect(silentGain);
|
||||
silentGain.connect(ctx.destination);
|
||||
await refreshAudioDevices();
|
||||
syncAudioContextNotice();
|
||||
}
|
||||
|
||||
// 导出给 WebClient:开麦前先 await 此函数完成真实采集,避免出现“假成功”
|
||||
async function ensureMicrophone(): Promise<void> {
|
||||
if (micStream) return;
|
||||
if (!microphoneStartPromise) {
|
||||
@@ -528,7 +803,11 @@ export function useVoiceWebSocket() {
|
||||
const destination = ctx.createMediaStreamDestination();
|
||||
destination.channelCount = 1;
|
||||
destination.channelCountMode = "explicit";
|
||||
const microphoneSource = ctx.createMediaStreamSource(micStream);
|
||||
// Use the browser-native processed track plus the browser-side RNNoise
|
||||
// graph. Display/application audio is added separately below and never
|
||||
// passes through this microphone denoiser.
|
||||
const microphoneStream = processedMicDestination?.stream ?? micStream;
|
||||
const microphoneSource = ctx.createMediaStreamSource(microphoneStream);
|
||||
const microphoneGain = ctx.createGain();
|
||||
microphoneGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
|
||||
microphoneSource.connect(microphoneGain);
|
||||
@@ -690,7 +969,7 @@ export function useVoiceWebSocket() {
|
||||
};
|
||||
startWebRtcMicMonitor(getAudioCtx(), micStream, microphoneTrack);
|
||||
peer.onconnectionstatechange = () => {
|
||||
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket);
|
||||
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket, "WEBRTC_CONNECTION_FAILED");
|
||||
};
|
||||
|
||||
const negotiation = (async () => {
|
||||
@@ -707,14 +986,14 @@ export function useVoiceWebSocket() {
|
||||
accompanimentActive: accompanimentActive.value,
|
||||
} }));
|
||||
window.setTimeout(() => {
|
||||
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket);
|
||||
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket, "WEBRTC_ANSWER_TIMEOUT");
|
||||
}, 8_000);
|
||||
})();
|
||||
webrtcNegotiationPromise = negotiation;
|
||||
try {
|
||||
await negotiation;
|
||||
} catch (error) {
|
||||
if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket);
|
||||
if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket, "WEBRTC_NEGOTIATION_FAILED");
|
||||
throw error;
|
||||
} finally {
|
||||
if (webrtcNegotiationPromise === negotiation) webrtcNegotiationPromise = null;
|
||||
@@ -747,19 +1026,22 @@ export function useVoiceWebSocket() {
|
||||
webrtcActive.value = true;
|
||||
syncWebRtcMemberVolumes();
|
||||
} catch {
|
||||
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value);
|
||||
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value, "WEBRTC_ANSWER_REJECTED");
|
||||
}
|
||||
}
|
||||
|
||||
async function fallbackFromWebRtc(sequence: number, socket: WebSocket): Promise<void> {
|
||||
async function fallbackFromWebRtc(sequence: number, socket: WebSocket, reasonCode = "WEBRTC_UNAVAILABLE"): Promise<void> {
|
||||
if (sequence !== connectionSequence || webrtcFallbackStarted) return;
|
||||
webrtcFallbackStarted = true;
|
||||
webrtcActive.value = false;
|
||||
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: "webrtcStop" }));
|
||||
stopWebRtcTransport();
|
||||
if (socket.readyState === WebSocket.OPEN && state.connected) {
|
||||
// Degrading to the compatibility transport must be visible: the user is
|
||||
// still connected, but with different latency and audio quality.
|
||||
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reasonCode) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
|
||||
try { await startMicrophone(); } catch (error: unknown) {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
setMicrophoneError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -844,17 +1126,27 @@ export function useVoiceWebSocket() {
|
||||
workletNode?.port.close();
|
||||
workletNode?.disconnect();
|
||||
micGain?.disconnect();
|
||||
micSource?.disconnect();
|
||||
silentGain?.disconnect();
|
||||
scriptNode = null;
|
||||
workletNode = null;
|
||||
micGain = null;
|
||||
micSource = null;
|
||||
silentGain = null;
|
||||
}
|
||||
|
||||
function stopMicrophoneProcessingGraph(): void {
|
||||
rnnoiseNode?.destroy();
|
||||
rnnoiseNode?.disconnect();
|
||||
rnnoiseNode = null;
|
||||
micSource?.disconnect();
|
||||
processedMicDestination?.disconnect();
|
||||
processedMicDestination?.stream.getTracks().forEach((track) => track.stop());
|
||||
micSource = null;
|
||||
processedMicDestination = null;
|
||||
}
|
||||
|
||||
function stopMicrophone(closeContext = true): void {
|
||||
stopCaptureGraph();
|
||||
stopMicrophoneProcessingGraph();
|
||||
releaseAccompanimentStream();
|
||||
stopWebRtcMix();
|
||||
micStream?.getTracks().forEach((track) => track.stop());
|
||||
@@ -864,6 +1156,7 @@ export function useVoiceWebSocket() {
|
||||
audioCtx = null;
|
||||
workletContext = null;
|
||||
workletModulePromise = null;
|
||||
rnnoiseWorkletModulePromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1088,37 +1381,45 @@ export function useVoiceWebSocket() {
|
||||
clearRemotePlayback(clientId);
|
||||
}
|
||||
|
||||
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false, inviteToken = ""): void {
|
||||
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false, inviteToken = "", accelerated = false, accelerationRelayId = ""): void {
|
||||
disconnect(true);
|
||||
lastConnection = { target, channel, nickname, serverPassword, ...(identity ? { identity } : {}), rememberIdentity };
|
||||
lastConnection = { target, channel, nickname, serverPassword, ...(identity ? { identity } : {}), rememberIdentity, accelerated, accelerationRelayId };
|
||||
identityMaterial.value = identity;
|
||||
const sequence = ++connectionSequence;
|
||||
state.error = "";
|
||||
state.errorCode = "";
|
||||
// Audio diagnostics belong to the previous session, never to the new one.
|
||||
clearMicrophoneError();
|
||||
clearAudioNotice();
|
||||
state.connecting = true;
|
||||
state.reconnecting = false;
|
||||
state.reconnectAttempt = 0;
|
||||
state.reconnectFailed = false;
|
||||
void openTicketedConnection(sequence, target, channel, nickname, serverPassword, inviteToken);
|
||||
void openTicketedConnection(sequence, target, channel, nickname, serverPassword, inviteToken, accelerated);
|
||||
}
|
||||
|
||||
async function openTicketedConnection(sequence: number, target: string, channel: string, nickname: string, serverPassword: string, inviteToken: string): Promise<void> {
|
||||
async function openTicketedConnection(sequence: number, target: string, channel: string, nickname: string, serverPassword: string, inviteToken: string, accelerated: boolean): Promise<void> {
|
||||
try {
|
||||
const response = await fetch("/api/join-ticket", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", accept: "application/json" },
|
||||
body: JSON.stringify({ target, nickname, channel, serverPassword, ...(inviteToken ? { invite: inviteToken } : {}), ...(lastConnection?.rememberIdentity && lastConnection.identity ? { identity: lastConnection.identity } : {}), ...(lastConnection?.rememberIdentity ? { rememberIdentity: true } : {}) }),
|
||||
body: JSON.stringify({ target, nickname, channel, serverPassword, ...(inviteToken ? { invite: inviteToken } : {}), ...(accelerated ? { accelerated: true, ...(lastConnection?.accelerationRelayId ? { accelerationRelayId: lastConnection.accelerationRelayId } : {}) } : {}), ...(lastConnection?.rememberIdentity && lastConnection.identity ? { identity: lastConnection.identity } : {}), ...(lastConnection?.rememberIdentity ? { rememberIdentity: true } : {}) }),
|
||||
});
|
||||
const result = await response.json().catch(() => ({})) as { ticket?: unknown; code?: unknown };
|
||||
const result = await response.json().catch(() => ({})) as { ticket?: unknown; code?: unknown; detail?: unknown };
|
||||
if (!response.ok || typeof result.ticket !== "string") {
|
||||
throw new Error(joinTicketReason(typeof result.code === "string" ? result.code : ""));
|
||||
const failureCode = normalizedClientErrorCode(result.code);
|
||||
const failure = new Error(joinTicketReason(failureCode, result.detail));
|
||||
Object.assign(failure, { code: failureCode });
|
||||
throw failure;
|
||||
}
|
||||
if (sequence !== connectionSequence) return;
|
||||
openVoiceSocket(sequence, result.ticket);
|
||||
} catch (error: unknown) {
|
||||
if (sequence !== connectionSequence) return;
|
||||
state.connecting = false;
|
||||
state.error = error instanceof Error ? error.message : "连接服务器失败,请检查邀请链接或服务器状态";
|
||||
const errorRecord = error && typeof error === "object" ? error as { code?: unknown } : {};
|
||||
state.errorCode = normalizedClientErrorCode(errorRecord.code, "REQUEST_FAILED");
|
||||
state.error = error instanceof Error ? error.message : connectionFailureMessage(state.errorCode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1153,9 +1454,14 @@ export function useVoiceWebSocket() {
|
||||
// Prefer the close code over the generic WebSocket error event. The
|
||||
// gateway uses a dedicated code when a remembered identity is already
|
||||
// active in another browser page.
|
||||
if (event.code !== 1000 && !state.reconnectFailed) state.error = closeReason(event.code);
|
||||
if (event.code !== 1000 && !state.reconnectFailed && !state.errorCode) {
|
||||
state.errorCode = closeErrorCode(event.code, event.reason);
|
||||
state.error = closeReason(event.code, event.reason);
|
||||
}
|
||||
stopWebRtcTransport();
|
||||
stopMicrophone();
|
||||
clearMicrophoneError();
|
||||
clearAudioNotice();
|
||||
whisperTargetIds.clear();
|
||||
whisperActive.value = false;
|
||||
};
|
||||
@@ -1165,20 +1471,66 @@ export function useVoiceWebSocket() {
|
||||
};
|
||||
}
|
||||
|
||||
function joinTicketReason(code: string): string {
|
||||
if (code === "NOT_INITIALIZED") return "WebSpeak 尚未完成首次配置";
|
||||
if (code === "TARGET_NOT_ALLOWED") return "此 TeamSpeak 服务器地址不允许连接";
|
||||
if (code === "INVALID_NICKNAME") return "请输入有效的昵称";
|
||||
if (code === "INVITE_INVALID") return "邀请链接已失效或已被撤销";
|
||||
return "连接服务器失败,请检查邀请链接或服务器状态";
|
||||
function joinTicketReason(code: string, detail?: unknown): string {
|
||||
const messages: Record<string, string> = {
|
||||
ORIGIN_REJECTED: "请求来源不受信任,请从正确的网站入口重新打开",
|
||||
NOT_INITIALIZED: "WebSpeak 尚未完成配置,请联系管理员",
|
||||
RATE_LIMITED: "请求过于频繁,请稍后重试",
|
||||
TARGET_NOT_ALLOWED: "此 TeamSpeak 服务器地址不允许连接",
|
||||
ACCELERATION_UNAVAILABLE: "当前中继加速不可用,请关闭加速或联系管理员",
|
||||
INVALID_NICKNAME: "请输入有效的昵称",
|
||||
INVITE_INVALID: "邀请链接已失效或已被撤销",
|
||||
};
|
||||
const normalized = normalizedClientErrorCode(code);
|
||||
return messages[normalized] ?? connectionFailureMessage(normalized, detail);
|
||||
}
|
||||
|
||||
function closeReason(code: number): string {
|
||||
if (code === 4002) return "TeamSpeak 服务器地址无效";
|
||||
if (code === 4003) return "TeamSpeak 服务器连接失败";
|
||||
if (code === 4004) return "服务器当前已满,请稍后重试";
|
||||
if (code === 4005) return "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试";
|
||||
return "连接已断开";
|
||||
// 网关关闭码 → 前端可解释错误码的映射:4000-4003 是网关/会话级,4004/4005 是
|
||||
// TeamSpeak 拒绝与身份冲突,4006 是中继加速,1006/1011 是传输级掉线,绝不能
|
||||
// 被误当成 TeamSpeak 服务器拒绝。
|
||||
/**
|
||||
* Gateway close codes. 4000-4003 are gateway/session level, 4004/4005 are a
|
||||
* TeamSpeak rejection and an identity conflict, 4006 is the acceleration relay,
|
||||
* and 1006 is a transport-level drop that must not be blamed on TeamSpeak.
|
||||
*/
|
||||
const GATEWAY_CLOSE_CODE_CODES: Record<number, string> = {
|
||||
4000: "CONNECTION_FAILED",
|
||||
4001: "JOIN_TICKET_REQUIRED",
|
||||
4002: "INVALID_TARGET",
|
||||
4003: "IDENTITY_REJECTED",
|
||||
4004: "SERVER_REJECTED",
|
||||
4005: "IDENTITY_IN_USE",
|
||||
4006: "ACCELERATION_UNAVAILABLE",
|
||||
1006: "GATEWAY_NETWORK_LOST",
|
||||
1011: "GATEWAY_SESSION_ENDED",
|
||||
};
|
||||
|
||||
function closeErrorCode(code: number, reason = ""): string {
|
||||
const closeCode = normalizedClientErrorCode(reason, "");
|
||||
// The gateway repeats the failure code in the close reason. Trust it when the
|
||||
// browser can explain that code, otherwise fall back to the numeric close code
|
||||
// so even a silent close maps to an actionable message.
|
||||
if (closeCode && CONNECTION_FAILURE_MESSAGES[closeCode]) return closeCode;
|
||||
return GATEWAY_CLOSE_CODE_CODES[code] ?? "CONNECTION_FAILED";
|
||||
}
|
||||
|
||||
function connectionFailureMessage(code: string, detail?: unknown): string {
|
||||
const messages = CONNECTION_FAILURE_MESSAGES;
|
||||
const normalized = normalizedClientErrorCode(code);
|
||||
if (messages[normalized]) return messages[normalized];
|
||||
const safeCode = safeClientErrorCode(normalized);
|
||||
const safeDetail = safeClientErrorDetail(detail);
|
||||
// The gateway classifies a refused nickname before it reaches the browser,
|
||||
// but translate the raw TeamSpeak signature too: a nickname problem must
|
||||
// never end up as the generic "check your network" fallback.
|
||||
if (safeDetail && NICKNAME_LENGTH_SIGNATURE.test(safeDetail)) return NICKNAME_LENGTH_MESSAGE;
|
||||
return `TeamSpeak 连接失败(错误代码:${safeCode})${safeDetail ? `:${safeDetail}` : ""},请检查输入、网络或服务器状态`;
|
||||
}
|
||||
|
||||
function closeReason(code: number, reason = ""): string {
|
||||
const failureCode = closeErrorCode(code, reason);
|
||||
if (code === 4004 && failureCode === "SERVER_REJECTED") return "服务器当前已满或拒绝了连接,请稍后重试";
|
||||
return connectionFailureMessage(failureCode);
|
||||
}
|
||||
|
||||
function disconnect(preserveConnection = false): void {
|
||||
@@ -1187,6 +1539,8 @@ export function useVoiceWebSocket() {
|
||||
const keepRememberedIdentity = lastConnection?.rememberIdentity === true;
|
||||
if (!preserveConnection) lastConnection = null;
|
||||
stopMicrophone();
|
||||
clearMicrophoneError();
|
||||
clearAudioNotice();
|
||||
const socket = ws.value;
|
||||
ws.value = null;
|
||||
stopWebRtcTransport();
|
||||
@@ -1254,17 +1608,13 @@ export function useVoiceWebSocket() {
|
||||
const start = msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined"
|
||||
? (ws.value ? startWebRtcTransport(connectionSequence, ws.value) : Promise.resolve())
|
||||
: ensureMicrophone();
|
||||
start.catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
// A failed microphone must not look like a failed connection: record it
|
||||
// as an audio diagnostic so the room stays visible with a clear reason.
|
||||
start.catch((error: unknown) => { setMicrophoneError(error); });
|
||||
} else if (msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined" && ws.value) {
|
||||
void startWebRtcTransport(connectionSequence, ws.value).catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
void startWebRtcTransport(connectionSequence, ws.value).catch((error: unknown) => { setMicrophoneError(error); });
|
||||
} else {
|
||||
void ensureMicrophone().catch((error: unknown) => {
|
||||
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
|
||||
});
|
||||
void ensureMicrophone().catch((error: unknown) => { setMicrophoneError(error); });
|
||||
}
|
||||
break;
|
||||
case "memberEnter":
|
||||
@@ -1370,7 +1720,20 @@ export function useVoiceWebSocket() {
|
||||
state.connecting = false;
|
||||
state.reconnecting = false;
|
||||
state.reconnectFailed = true;
|
||||
state.error = "连接已中断,无法自动恢复";
|
||||
state.errorCode = normalizedClientErrorCode(msg.code);
|
||||
state.error = connectionFailureMessage(state.errorCode, msg.detail);
|
||||
whisperTargetIds.clear();
|
||||
whisperActive.value = false;
|
||||
break;
|
||||
case "connectionFailed":
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
state.reconnecting = false;
|
||||
// This is the first connection attempt, not a failed reconnect. Keep
|
||||
// the user on the welcome form instead of showing an empty voice room.
|
||||
state.reconnectFailed = false;
|
||||
state.errorCode = normalizedClientErrorCode(msg.code);
|
||||
state.error = connectionFailureMessage(state.errorCode, msg.detail);
|
||||
whisperTargetIds.clear();
|
||||
whisperActive.value = false;
|
||||
break;
|
||||
@@ -1381,8 +1744,15 @@ export function useVoiceWebSocket() {
|
||||
void applyWebRtcAnswer(msg.payload?.sdp);
|
||||
break;
|
||||
case "webrtcError":
|
||||
if (ws.value) void fallbackFromWebRtc(connectionSequence, ws.value);
|
||||
if (ws.value) void fallbackFromWebRtc(connectionSequence, ws.value, safeClientErrorCode(msg.code) || "WEBRTC_NEGOTIATION_FAILED");
|
||||
break;
|
||||
case "audioError": {
|
||||
// The gateway could not encode our microphone audio (for example its Opus
|
||||
// encoder is unavailable): say it instead of dropping frames silently.
|
||||
const audioCode = safeClientErrorCode(msg.code) || "AUDIO_ERROR";
|
||||
setAudioNotice(audioCode, audioNoticeMessage(audioCode, msg.detail));
|
||||
break;
|
||||
}
|
||||
case "voiceActivity":
|
||||
if (Array.isArray(msg.clientIds)) {
|
||||
for (const clientId of msg.clientIds) {
|
||||
@@ -1391,7 +1761,7 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
break;
|
||||
case "error":
|
||||
state.errorCode = String(msg.error?.code || "");
|
||||
state.errorCode = normalizedClientErrorCode(msg.error?.code, "OPERATION_FAILED");
|
||||
state.error = protocolErrorMessage(state.errorCode, String(msg.error?.message || msg.message || "操作失败"));
|
||||
break;
|
||||
}
|
||||
@@ -1498,7 +1868,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function reconnectNow(): void {
|
||||
if (!lastConnection || state.connecting) return;
|
||||
connect(lastConnection.target, lastConnection.channel, lastConnection.nickname, lastConnection.serverPassword, lastConnection.rememberIdentity ? identityMaterial.value || lastConnection.identity : "", lastConnection.rememberIdentity);
|
||||
connect(lastConnection.target, lastConnection.channel, lastConnection.nickname, lastConnection.serverPassword, lastConnection.rememberIdentity ? identityMaterial.value || lastConnection.identity : "", lastConnection.rememberIdentity, "", lastConnection.accelerated, lastConnection.accelerationRelayId);
|
||||
}
|
||||
|
||||
function setMicrophoneMuted(muted: boolean): void {
|
||||
@@ -1540,11 +1910,20 @@ export function useVoiceWebSocket() {
|
||||
CHANNEL_SWITCH_FAILED: "频道切换失败",
|
||||
CHANNEL_PASSWORD_REQUIRED: "该频道需要密码",
|
||||
CHANNEL_FULL: "该频道已满",
|
||||
NICKNAME_IN_USE: "该昵称已被占用,请更换昵称",
|
||||
CLIENT_VERSION_OUTDATED: "客户端版本过旧,服务器拒绝了该操作",
|
||||
FLOOD_PROTECTION: "操作过于频繁,请稍后重试",
|
||||
BANNED: "你已被该服务器封禁",
|
||||
KICKED: "你已被服务器移出",
|
||||
PERMISSION_DENIED: "你没有执行此操作的权限",
|
||||
CLIENT_NOT_FOUND: "成员已离线",
|
||||
OPERATION_FAILED: "操作失败",
|
||||
};
|
||||
return messages[code] || fallback;
|
||||
const normalized = normalizedClientErrorCode(code, "OPERATION_FAILED");
|
||||
if (messages[normalized]) return messages[normalized];
|
||||
const safeCode = safeClientErrorCode(normalized);
|
||||
const safeFallback = safeClientErrorDetail(fallback);
|
||||
return `操作失败(错误代码:${safeCode})${safeFallback ? `:${safeFallback}` : ""}`;
|
||||
}
|
||||
|
||||
function setVolume(clientId: number, volume: number): void {
|
||||
@@ -1576,6 +1955,21 @@ export function useVoiceWebSocket() {
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
async function setNoiseSuppressionEnabled(enabled: boolean): Promise<void> {
|
||||
if (noiseSuppressionEnabled.value === enabled) return;
|
||||
const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value);
|
||||
noiseSuppressionEnabled.value = enabled;
|
||||
void saveAudioPreferences();
|
||||
if (!micStream) return;
|
||||
try {
|
||||
if (shouldRestartWebRtc) stopWebRtcTransport();
|
||||
await startMicrophone();
|
||||
if (shouldRestartWebRtc && ws.value) await startWebRtcTransport(connectionSequence, ws.value);
|
||||
} catch (error) {
|
||||
setMicrophoneError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function setOutputVolume(volume: number): void {
|
||||
outputVolume.value = Math.max(0, Math.min(1, volume));
|
||||
applyOutputVolume();
|
||||
@@ -1606,6 +2000,7 @@ export function useVoiceWebSocket() {
|
||||
serverEvents,
|
||||
pokeNotifications,
|
||||
microphoneMuted,
|
||||
noiseSuppressionEnabled,
|
||||
inputVolume,
|
||||
outputVolume,
|
||||
outputMuted,
|
||||
@@ -1617,6 +2012,7 @@ export function useVoiceWebSocket() {
|
||||
selectedOutputDeviceId,
|
||||
outputDeviceSupported,
|
||||
audioPermission,
|
||||
microphoneProcessing,
|
||||
audioContextState,
|
||||
identityMaterial,
|
||||
micLevel,
|
||||
@@ -1631,6 +2027,7 @@ export function useVoiceWebSocket() {
|
||||
accompanimentErrorCode,
|
||||
setVolume,
|
||||
setInputVolume,
|
||||
setNoiseSuppressionEnabled,
|
||||
setOutputVolume,
|
||||
toggleOutputMute,
|
||||
setVoxThreshold,
|
||||
@@ -1654,6 +2051,7 @@ export function useVoiceWebSocket() {
|
||||
setWhisperTargets,
|
||||
setWhisperActive,
|
||||
setMicrophoneMuted,
|
||||
ensureMicrophone,
|
||||
startAccompaniment,
|
||||
stopAccompaniment,
|
||||
checkSupport,
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -34,8 +34,9 @@ export interface LocalPreferences {
|
||||
locale?: "auto" | "zh-CN" | "en";
|
||||
theme?: "system" | "light" | "dark";
|
||||
microphoneMuted?: boolean;
|
||||
noiseSuppressionEnabled?: boolean;
|
||||
voxThreshold?: number;
|
||||
language?: "zh" | "en" | "de";
|
||||
language?: "zh" | "en" | "de" | "ru" | "ja";
|
||||
preferredInputDeviceId?: string;
|
||||
preferredOutputDeviceId?: string;
|
||||
inputGain?: number;
|
||||
|
||||
+531
-30
@@ -34,9 +34,10 @@
|
||||
<section v-if="route.path === '/admin/server'" class="page-content server-page">
|
||||
<div class="page-heading"><div><h2>{{ tr('serverSettings') }}</h2><p>{{ tr('serverSettingsLead') }}</p></div><button class="primary-button" :disabled="submitting" @click="saveServerSettings">{{ submitting ? tr('saving') : tr('saveChanges') }}</button></div>
|
||||
<div class="settings-grid">
|
||||
<article class="settings-card"><h3>{{ tr('teamSpeakTarget') }}</h3><div class="target-fields"><label><span>{{ tr('serverAddress') }}</span><input v-model.trim="serverForm.address" :placeholder="tr('serverPlaceholder')" /></label><label><span>{{ tr('serverPort') }}</span><input v-model.trim="serverForm.port" inputmode="numeric" type="text" maxlength="5" :placeholder="tr('serverPortPlaceholder')" /></label></div><div class="password-row"><label><span>{{ tr('serverPassword') }}</span><input v-model="serverForm.serverPassword" type="password" autocomplete="off" :disabled="serverForm.passwordAction !== 'replace'" :placeholder="serverForm.hasPassword ? tr('passwordConfigured') : tr('optionalPassword')" /></label><div class="password-actions"><button type="button" :class="{ active: serverForm.passwordAction === 'replace' }" @click="serverForm.passwordAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasPassword" type="button" :class="{ danger: serverForm.passwordAction === 'remove' }" @click="serverForm.passwordAction = 'remove'">{{ tr('remove') }}</button></div></div><button class="secondary-button" type="button" :disabled="testing" @click="testServerConnection"><span v-if="testing" class="spinner small"></span><Icon v-else name="activity" :size="17" />{{ testing ? tr('testing') : tr('testConnection') }}</button><div v-if="testResult" :class="['test-result', testResult.ok ? 'success' : 'error']"><Icon :name="testResult.ok ? 'check' : 'close'" :size="18" /><div><strong>{{ testResult.ok ? tr('connectionReady') : tr('connectionFailed') }}</strong><small>{{ testResultText }}</small></div></div></article>
|
||||
<article class="settings-card"><h3>{{ tr('accessAndIdentity') }}</h3><fieldset><legend>{{ tr('accessMode') }}</legend><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="fixed" /><span><strong>{{ tr('fixedMode') }}</strong><small>{{ tr('fixedModeLead') }}</small></span></label><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="open" /><span><strong>{{ tr('openMode') }}</strong><small>{{ tr('openModeLead') }}</small></span></label></fieldset><label><span>{{ tr('siteName') }}</span><input v-model.trim="serverForm.siteName" maxlength="80" /></label><label><span>{{ tr('welcomeTextZh') }}</span><textarea v-model="serverForm.welcomeText" maxlength="500" rows="3"></textarea></label><label><span>{{ tr('welcomeTextEn') }}</span><textarea v-model="serverForm.welcomeTextEn" maxlength="500" rows="3"></textarea></label></article>
|
||||
<article class="settings-card"><h3>{{ tr('teamSpeakTarget') }}</h3><div class="target-fields"><label><span>{{ tr('serverAddress') }}</span><input v-model.trim="serverForm.address" :placeholder="tr('serverPlaceholder')" /></label><label><span>{{ tr('serverPort') }}</span><input v-model.trim="serverForm.port" inputmode="numeric" type="text" maxlength="5" :placeholder="tr('serverPortPlaceholder')" /></label></div><div class="password-row"><label><span>{{ tr('serverPassword') }}</span><input v-model="serverForm.serverPassword" type="password" autocomplete="off" :disabled="serverForm.passwordAction !== 'replace'" :placeholder="serverForm.hasPassword ? tr('passwordConfigured') : tr('optionalPassword')" /></label><div class="password-actions"><button type="button" :class="{ active: serverForm.passwordAction === 'replace' }" @click="serverForm.passwordAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasPassword" type="button" :class="{ danger: serverForm.passwordAction === 'remove' }" @click="serverForm.passwordAction = 'remove'">{{ tr('remove') }}</button></div></div><button class="secondary-button" type="button" :disabled="testing" @click="testServerConnection"><span v-if="testing" class="spinner small"></span><Icon v-else name="activity" :size="17" />{{ testing ? tr('testing') : tr('testConnection') }}</button><div v-if="testResult" :class="['test-result', testResult.ok ? 'success' : 'error']"><Icon :name="testResult.ok ? 'check' : 'close'" :size="18" /><div><strong>{{ testResultTitle }}</strong><small>{{ testResultText }}</small></div></div></article>
|
||||
<article class="settings-card"><h3>{{ tr('accessAndIdentity') }}</h3><fieldset><legend>{{ tr('accessMode') }}</legend><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="fixed" /><span><strong>{{ tr('fixedMode') }}</strong><small>{{ tr('fixedModeLead') }}</small></span></label><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="open" /><span><strong>{{ tr('openMode') }}</strong><small>{{ tr('openModeLead') }}</small></span></label></fieldset><label><span>{{ tr('siteName') }}</span><input v-model.trim="serverForm.siteName" maxlength="80" /></label><div class="welcome-editor"><div class="welcome-editor-heading"><label><span>{{ tr('welcomeLanguage') }}</span><select v-model="welcomeLanguage"><option v-for="option in welcomeLanguageOptions" :key="option.value" :value="option.value">{{ option.label }}</option></select></label><small>{{ tr('welcomeLanguageHint') }}</small></div><label><span>{{ tr('welcomeText') }} · {{ selectedWelcomeLanguageLabel }}</span><textarea v-model="selectedWelcomeText" maxlength="500" rows="4" :placeholder="selectedWelcomeDefault"></textarea></label><small class="field-help">{{ tr('welcomeFallbackHint') }}</small></div></article>
|
||||
<article class="settings-card advanced-card"><div><h3>{{ tr('advancedSettings') }}</h3><p class="card-help">{{ tr('advancedSettingsLead') }}</p></div><label class="choice toggle-choice"><input v-model="serverForm.webRtcEnabled" type="checkbox" @change="handleWebRtcToggle" /><span><strong>{{ tr('webrtcEnabled') }}</strong><small>{{ tr('webrtcEnabledLead') }}</small></span></label><div class="webrtc-port-fields"><div class="port-fields-heading"><strong>{{ tr('webrtcPortRange') }}</strong><small>{{ tr('webrtcPortRangeLead') }}</small></div><div class="port-inputs"><label><span>{{ tr('webrtcPortStart') }}</span><input v-model.number="serverForm.webRtcUdpStart" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label><label><span>{{ tr('webrtcPortEnd') }}</span><input v-model.number="serverForm.webRtcUdpEnd" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label></div></div><small class="field-help">{{ tr('webrtcApplyHint') }}</small></article>
|
||||
<article class="settings-card relay-card"><div><h3>{{ tr('relaySettings') }}</h3><p class="card-help">{{ tr('relaySettingsLead') }}</p></div><div v-if="!serverForm.relayNodes.length" class="relay-empty">{{ tr('relayNodeEmpty') }}</div><div class="relay-node-list"><div v-for="(relay, index) in serverForm.relayNodes" :key="relay.id" class="relay-node"><div class="relay-node-heading"><label class="relay-enabled"><input v-model="relay.enabled" type="checkbox" /><strong>{{ relay.name || tr('relayUnnamed') }}</strong></label><button class="text-danger" type="button" @click="removeRelayNode(index)">{{ tr('remove') }}</button></div><div class="relay-fields"><label><span>{{ tr('relayName') }}</span><input v-model.trim="relay.name" maxlength="80" :placeholder="tr('relayNamePlaceholder')" /></label><label><span>{{ tr('relayTarget') }}</span><input v-model.trim="relay.target" maxlength="300" :placeholder="tr('relayTargetPlaceholder')" /></label><div class="password-row"><label><span>{{ tr('relayToken') }}</span><input v-model="relay.token" type="password" autocomplete="off" :disabled="relay.tokenAction !== 'replace'" :placeholder="relay.hasToken ? tr('relayTokenConfigured') : tr('relayTokenPlaceholder')" /></label><div class="password-actions"><button type="button" :class="{ active: relay.tokenAction === 'replace' }" @click="relay.tokenAction = 'replace'">{{ tr('change') }}</button><button v-if="relay.hasToken" type="button" :class="{ danger: relay.tokenAction === 'remove' }" @click="relay.tokenAction = 'remove'">{{ tr('remove') }}</button></div></div></div></div></div><button class="secondary-button relay-add" type="button" @click="addRelayNode">{{ tr('relayAdd') }}</button><small class="field-help">{{ tr('relayManagedHint') }}</small></article>
|
||||
</div>
|
||||
<article class="readonly-card"><h3>{{ tr('runtimeFacts') }}</h3><dl><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(serverForm.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ serverForm.lastTestLatencyMs == null ? '—' : `${serverForm.lastTestLatencyMs} ms` }}</dd></div><div><dt>{{ tr('internalPort') }}</dt><dd>3040</dd></div></dl></article>
|
||||
</section>
|
||||
@@ -50,7 +51,7 @@
|
||||
</div>
|
||||
<div class="operations-grid lower-operations">
|
||||
<article class="operation-card diagnostics-card"><header><div><h3>{{ tr('diagnostics') }}</h3><p>{{ tr('diagnosticsLead') }}</p></div><a class="text-link" href="/api/admin/diagnostics/report">{{ tr('downloadReport') }}</a></header><dl class="diagnostic-list"><div><dt>{{ tr('version') }}</dt><dd>{{ operations.diagnostics.version || '—' }}</dd></div><div><dt>{{ tr('runtime') }}</dt><dd>{{ operations.diagnostics.node || '—' }}</dd></div><div><dt>{{ tr('platform') }}</dt><dd>{{ operations.diagnostics.platform || '—' }} / {{ operations.diagnostics.arch || '—' }}</dd></div><div><dt>{{ tr('databaseSchema') }}</dt><dd>v{{ operations.diagnostics.schemaVersion || '—' }}</dd></div><div><dt>{{ tr('createdSessions') }}</dt><dd>{{ operations.diagnostics.createdSessions }}</dd></div></dl><button class="secondary-button" type="button" @click="downloadBackup">{{ tr('exportBackup') }}</button></article>
|
||||
<article class="operation-card logs-card"><header><div><h3>{{ tr('logViewer') }}</h3><p>{{ tr('logViewerLead') }}</p></div><span v-if="!operations.logs.available" class="muted-label">{{ tr('logsUnavailable') }}</span></header><div v-if="operations.logs.sessions.length" class="connection-list"><div class="connection-history-heading"><strong>{{ tr('connectionHistory') }}</strong><small>{{ tr('connectionHistoryLead') }}</small></div><div v-for="record in operations.logs.sessions" :key="record.id" class="connection-row"><div class="connection-person"><strong>{{ record.nickname }}</strong><small>{{ record.target }}</small></div><div class="connection-detail"><span :class="['connection-status', record.status]">{{ connectionStatusLabel(record.status) }}</span><small>{{ record.connectedAt ? tr('connectedAt') : tr('connectionAttemptedAt') }}:{{ formatDate(record.connectedAt || record.startedAt) }}</small><small>{{ tr('duration') }}:{{ formatAge(record.durationSeconds) }}</small><small v-if="record.disconnectedAt">{{ tr('disconnectedAt') }}:{{ formatDate(record.disconnectedAt) }}</small></div></div></div><div v-if="operations.logs.entries.length" class="log-list"><div v-for="(entry, index) in operations.logs.entries" :key="`${entry.timestamp}-${index}`" class="log-row"><span :class="['log-level', entry.level.toLowerCase()]">{{ entry.level }}</span><div><strong>{{ entry.message || '—' }}</strong><small>{{ formatDate(entry.timestamp) }}<template v-if="Object.keys(entry.context).length"> · {{ formatContext(entry.context) }}</template></small></div></div></div><div v-if="!operations.logs.sessions.length && !operations.logs.entries.length" class="operation-empty"><Icon name="activity" :size="22" /><span>{{ tr('noLogs') }}</span></div></article>
|
||||
<article class="operation-card logs-card"><header><div><h3>{{ tr('logViewer') }}</h3><p>{{ tr('logViewerLead') }}</p></div><span v-if="!operations.logs.available" class="muted-label">{{ tr('logsUnavailable') }}</span></header><div v-if="operations.logs.sessions.length" class="connection-list"><div class="connection-history-heading"><strong>{{ tr('connectionHistory') }}</strong><small>{{ tr('connectionHistoryLead') }}</small></div><div v-for="record in operations.logs.sessions" :key="record.id" class="connection-row"><div class="connection-person"><strong>{{ record.nickname }}</strong><small>{{ record.target }}</small><small class="connection-route">{{ connectionRoute(record) }}</small></div><div class="connection-detail"><span :class="['connection-status', record.status]">{{ connectionStatusLabel(record.status) }}</span><small>{{ record.connectedAt ? tr('connectedAt') : tr('connectionAttemptedAt') }}:{{ formatDate(record.connectedAt || record.startedAt) }}</small><small>{{ tr('duration') }}:{{ formatAge(record.durationSeconds) }}</small><small v-if="record.disconnectedAt">{{ tr('disconnectedAt') }}:{{ formatDate(record.disconnectedAt) }}</small><small v-if="record.reason">{{ tr('failureReason') }}:{{ connectionFailureText(record.reason) }}</small><small v-if="record.failureDetail" class="failure-detail">{{ tr('failureDetail') }}:{{ record.failureDetail }}</small></div></div></div><div v-if="operations.logs.entries.length" class="log-list"><div v-for="(entry, index) in operations.logs.entries" :key="`${entry.timestamp}-${index}`" class="log-row"><span :class="['log-level', entry.level.toLowerCase()]">{{ entry.level }}</span><div><strong>{{ entry.message || '—' }}</strong><small>{{ formatDate(entry.timestamp) }}<template v-if="Object.keys(entry.context).length"> · {{ formatContext(entry.context) }}</template></small></div></div></div><div v-if="!operations.logs.sessions.length && !operations.logs.entries.length" class="operation-empty"><Icon name="activity" :size="22" /><span>{{ tr('noLogs') }}</span></div></article>
|
||||
<article class="operation-card audit-card"><header><div><h3>{{ tr('audit') }}</h3><p>{{ tr('auditLead') }}</p></div></header><ul class="event-list"><li v-for="event in operations.audit" :key="`${event.event}-${event.createdAt}`"><span><Icon name="check" :size="14" /></span><div><strong>{{ eventName(event.event) }}</strong><small>{{ formatDate(event.createdAt) }}</small></div></li><li v-if="!operations.audit.length" class="empty-event">{{ tr('auditEmpty') }}</li></ul></article>
|
||||
</div>
|
||||
</section>
|
||||
@@ -75,15 +76,26 @@ import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
|
||||
type Language = "zh" | "en" | "de";
|
||||
type Language = "zh" | "en" | "de" | "ru" | "ja";
|
||||
type Screen = "login" | "change-password" | "admin";
|
||||
type AccessMode = "fixed" | "open";
|
||||
interface ProbeState { ok: boolean; latencyMs?: number; serverName?: string | null; packetLossPercent?: number; attempts?: number; successfulAttempts?: number; code?: string; errorCode?: string }
|
||||
interface ProbeState { ok: boolean; checkType?: "network" | "protocol"; passwordVerified?: boolean; latencyMs?: number; serverName?: string | null; packetLossPercent?: number; attempts?: number; successfulAttempts?: number; code?: string; errorCode?: string }
|
||||
interface RelayNodeForm { id: string; name: string; enabled: boolean; target: string; token: string; tokenAction: "keep" | "replace" | "remove"; hasToken: boolean }
|
||||
type WelcomeLanguage = "zh" | "en" | "de" | "ru" | "ja";
|
||||
type WelcomeTextField = "welcomeText" | "welcomeTextEn" | "welcomeTextDe" | "welcomeTextRu" | "welcomeTextJa";
|
||||
|
||||
const DEFAULT_WELCOME_TEXTS: Record<WelcomeLanguage, 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 クライアントのインストールは不要です。ブラウザを開くだけで音声チャンネルに参加できます。低遅延で軽快な会話を楽しめます。",
|
||||
};
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const storedLanguage = localStorage.getItem("webspeak:language");
|
||||
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" ? storedLanguage : "zh");
|
||||
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" || storedLanguage === "ru" || storedLanguage === "ja" ? storedLanguage : typeof navigator !== "undefined" && navigator.language.toLowerCase().startsWith("ru") ? "ru" : typeof navigator !== "undefined" && navigator.language.toLowerCase().startsWith("ja") ? "ja" : "zh");
|
||||
const themeMode = ref<ThemeMode>(getStoredTheme());
|
||||
const themeIcon = computed(() => isDarkTheme(themeMode.value) ? "sun" : "moon");
|
||||
const themeLabel = computed(() => isDarkTheme(themeMode.value) ? tr("switchToLightTheme") : tr("switchToDarkTheme"));
|
||||
@@ -100,12 +112,13 @@ const newPassword = ref("");
|
||||
const confirmNewPassword = ref("");
|
||||
const testResult = ref<ProbeState | null>(null);
|
||||
|
||||
const serverForm = reactive({ address: "", port: "9987", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", welcomeTextEn: "", webRtcEnabled: false, webRtcUdpStart: 40000, webRtcUdpEnd: 40099, lastTestAt: null as string | null, lastTestLatencyMs: null as number | null });
|
||||
const serverForm = reactive({ address: "", port: "9987", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", welcomeTextEn: "", welcomeTextDe: "", welcomeTextRu: "", welcomeTextJa: "", welcomeDefaults: { ...DEFAULT_WELCOME_TEXTS }, webRtcEnabled: false, webRtcUdpStart: 40000, webRtcUdpEnd: 40099, relayConfigured: false, relayEnabled: false, relayName: "", relayTarget: "", relayToken: "", relayTokenAction: "keep" as "keep" | "replace" | "remove", hasRelayToken: false, relaySettingsTouched: false, relayNodes: [] as RelayNodeForm[], lastTestAt: null as string | null, lastTestLatencyMs: null as number | null });
|
||||
const welcomeLanguage = ref<WelcomeLanguage>("zh");
|
||||
const overview = reactive({ gateway: { version: "", uptimeSeconds: 0 }, teamSpeak: { target: "", status: "unknown", lastTestAt: null as string | null, latencyMs: null as number | null }, sessions: { active: 0, peak: 0, limit: 100 }, recentEvents: [] as Array<{ event: string; createdAt: string }>, legacyConfigImported: false });
|
||||
interface AdminSession { id: string; nickname: string; target: string; state: string; createdAt: string; ageSeconds: number; tsClientId: number | null; channelId: string | null; memberCount: number }
|
||||
interface ManagedInvite { id: string; target: string; channel: string; expiresAt: string; maxUses: number; useCount: number; createdAt: string; revokedAt: string | null; status: "active" | "expired" | "exhausted" | "revoked" }
|
||||
interface AdminLog { timestamp: string | null; level: string; message: string; context: Record<string, string | number | boolean> }
|
||||
interface AdminConnectionRecord { id: string; nickname: string; target: string; startedAt: string; connectedAt: string | null; disconnectedAt: string | null; durationSeconds: number; status: "active" | "connecting" | "disconnected" | "failed"; reason: string | null }
|
||||
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 }
|
||||
const operationsLoading = ref(false);
|
||||
const terminatingSession = ref("");
|
||||
const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 });
|
||||
@@ -164,7 +177,22 @@ const copy = {
|
||||
testing: "正在测试…",
|
||||
connectionReady: "连接成功",
|
||||
connectionFailed: "连接失败",
|
||||
packetLoss: "丢包率",
|
||||
packetLoss: "丢包率",
|
||||
networkReachable: "网络可达(未验证密码)",
|
||||
networkReachableHint: "Ping 成功;管理员测试不会创建额外 TeamSpeak 成员,因此未验证服务器密码。",
|
||||
failureReason: "原因",
|
||||
failureDetail: "诊断",
|
||||
hostNotFoundError: "找不到服务器",
|
||||
networkUnreachableError: "网络不可达",
|
||||
connectionRefusedError: "服务器拒绝连接",
|
||||
connectionResetError: "连接被服务器或网络重置",
|
||||
networkTimeoutError: "网络请求超时",
|
||||
serverPasswordRequiredError: "服务器需要密码",
|
||||
invalidServerPasswordError: "服务器密码错误",
|
||||
protocolFailureError: "TeamSpeak 协议协商失败",
|
||||
serverRejectedError: "服务器拒绝连接",
|
||||
invalidNicknameError: "昵称长度不符合服务器要求",
|
||||
pingUnavailableError: "无法执行网络探测",
|
||||
accessAndIdentity: "访问与站点信息",
|
||||
advancedSettings: "高级参数",
|
||||
advancedSettingsLead: "仅在需要时调整网关的高级传输参数。",
|
||||
@@ -179,15 +207,32 @@ const copy = {
|
||||
webrtcApplyHint: "端口范围仅可在 WebRTC 关闭时修改;开启后会锁定,保存后对新连接生效。",
|
||||
webrtcPortNoticeTitle: "请先放行 WebRTC 端口",
|
||||
webrtcPortNotice: "需要开启端口,范围是 {{range}}(UDP)。请先在主机防火墙、安全组和 Docker 端口映射中放行该范围。",
|
||||
relaySettings: "中继服务器",
|
||||
relaySettingsLead: "配置访客连接使用的中继节点;名称会显示在首页加速选项中。",
|
||||
relayEnabled: "启用中继加速",
|
||||
relayEnabledLead: "访客勾选加速后,通过此中继访问目标 TeamSpeak 服务器。",
|
||||
relayName: "中继显示名称",
|
||||
relayNamePlaceholder: "例如:大陆节点、香港节点",
|
||||
relayTarget: "中继服务器地址",
|
||||
relayTargetPlaceholder: "例如:relay.example.com#39087",
|
||||
relayToken: "中继令牌",
|
||||
relayTokenPlaceholder: "填写中继服务令牌",
|
||||
relayTokenConfigured: "已配置令牌(留空保持不变)",
|
||||
relayAdd: "添加中继节点",
|
||||
relayNodeEmpty: "尚未配置中继节点。",
|
||||
relayUnnamed: "未命名中继",
|
||||
relayManagedHint: "当前使用管理控制台保存的中继配置。令牌只保存为加密密文,不会返回到页面。",
|
||||
relayEnvironmentHint: "中继仅使用此页面保存的配置;关闭并保存后,访客页面不会显示中继选项。",
|
||||
accessMode: "访客访问模式",
|
||||
fixedMode: "仅限此 TeamSpeak 服务器",
|
||||
fixedModeLead: "访客只需填写昵称,目标和密码由 WebSpeak 管理。",
|
||||
openMode: "允许访客输入其他服务器",
|
||||
openModeLead: "访客可输入公网 TeamSpeak 地址;内网和保留地址会被阻止。",
|
||||
siteName: "站点显示名称",
|
||||
welcomeText: "公告",
|
||||
welcomeTextZh: "中文公告",
|
||||
welcomeTextEn: "英文公告",
|
||||
welcomeText: "欢迎词",
|
||||
welcomeLanguage: "欢迎词语言",
|
||||
welcomeLanguageHint: "切换语言编辑对应文本;留空时自动使用默认模板。",
|
||||
welcomeFallbackHint: "留空将回退到该语言的默认欢迎词。",
|
||||
runtimeFacts: "运行时信息",
|
||||
lastTest: "最近测试",
|
||||
latency: "延迟",
|
||||
@@ -268,6 +313,8 @@ const copy = {
|
||||
logViewerLead: "最近的网关日志及用户连接记录,不包含聊天内容。",
|
||||
connectionHistory: "用户连接记录",
|
||||
connectionHistoryLead: "按用户合并连接、断开与持续时间。",
|
||||
connectionFromTo: "来源 {{ip}} → 目标 {{target}}",
|
||||
connectionViaRelay: "中继 {{relay}}",
|
||||
connectionActive: "连接中",
|
||||
connectionConnecting: "准备连接",
|
||||
connectionDisconnected: "已断开",
|
||||
@@ -334,7 +381,22 @@ const copy = {
|
||||
testing: "Testing…",
|
||||
connectionReady: "Connection ready",
|
||||
connectionFailed: "Connection failed",
|
||||
packetLoss: "Packet loss",
|
||||
packetLoss: "Packet loss",
|
||||
networkReachable: "Network reachable (password not verified)",
|
||||
networkReachableHint: "Ping succeeded. The admin test does not create an extra TeamSpeak client, so the server password was not verified.",
|
||||
failureReason: "Reason",
|
||||
failureDetail: "Diagnostics",
|
||||
hostNotFoundError: "Server not found",
|
||||
networkUnreachableError: "Network unreachable",
|
||||
connectionRefusedError: "Connection refused",
|
||||
connectionResetError: "Connection reset",
|
||||
networkTimeoutError: "Network request timed out",
|
||||
serverPasswordRequiredError: "Server password required",
|
||||
invalidServerPasswordError: "Invalid server password",
|
||||
protocolFailureError: "TeamSpeak protocol negotiation failed",
|
||||
serverRejectedError: "Server rejected the connection",
|
||||
invalidNicknameError: "The nickname length does not meet the server requirements",
|
||||
pingUnavailableError: "Network probe unavailable",
|
||||
accessAndIdentity: "Access and site identity",
|
||||
advancedSettings: "Advanced settings",
|
||||
advancedSettingsLead: "Adjust gateway transport options only when needed.",
|
||||
@@ -349,15 +411,32 @@ const copy = {
|
||||
webrtcApplyHint: "The range can only be edited while WebRTC is off. It is locked while enabled and applies to new connections after saving.",
|
||||
webrtcPortNoticeTitle: "Allow WebRTC ports first",
|
||||
webrtcPortNotice: "Ports must be opened: {{range}} (UDP). Allow this range in the host firewall, security group, and Docker port mapping first.",
|
||||
relaySettings: "Relay server",
|
||||
relaySettingsLead: "Configure the relay used by accelerated guest connections; its name is shown on the welcome page.",
|
||||
relayEnabled: "Enable relay acceleration",
|
||||
relayEnabledLead: "Guests who select acceleration will reach their TeamSpeak target through this relay.",
|
||||
relayName: "Relay display name",
|
||||
relayNamePlaceholder: "For example: Mainland relay or Japan relay",
|
||||
relayTarget: "Relay server address",
|
||||
relayTargetPlaceholder: "For example: relay.example.com#39087",
|
||||
relayToken: "Relay token",
|
||||
relayTokenPlaceholder: "Enter the relay service token",
|
||||
relayTokenConfigured: "Token configured (leave blank to keep it)",
|
||||
relayAdd: "Add relay node",
|
||||
relayNodeEmpty: "No relay nodes are configured.",
|
||||
relayUnnamed: "Unnamed relay",
|
||||
relayManagedHint: "The relay is managed from the console. The token is stored encrypted and is never returned to the browser.",
|
||||
relayEnvironmentHint: "The relay uses only the settings saved here. After you disable and save it, visitors will no longer see the relay option.",
|
||||
accessMode: "Guest access mode",
|
||||
fixedMode: "Only this TeamSpeak server",
|
||||
fixedModeLead: "Guests enter only a nickname; WebSpeak manages the target and password.",
|
||||
openMode: "Allow other TeamSpeak servers",
|
||||
openModeLead: "Guests may enter public TeamSpeak addresses; private and reserved networks are blocked.",
|
||||
siteName: "Site display name",
|
||||
welcomeText: "Announcement",
|
||||
welcomeTextZh: "Chinese announcement",
|
||||
welcomeTextEn: "English announcement",
|
||||
welcomeText: "Welcome message",
|
||||
welcomeLanguage: "Welcome message language",
|
||||
welcomeLanguageHint: "Switch languages to edit each message. Leave it blank to use the built-in template.",
|
||||
welcomeFallbackHint: "An empty field falls back to the built-in template for this language.",
|
||||
runtimeFacts: "Runtime facts",
|
||||
lastTest: "Last test",
|
||||
latency: "Latency",
|
||||
@@ -438,6 +517,8 @@ const copy = {
|
||||
logViewerLead: "Recent gateway logs and user connection records; chat content is not recorded.",
|
||||
connectionHistory: "User connection records",
|
||||
connectionHistoryLead: "Connections, disconnects, and durations grouped by user.",
|
||||
connectionFromTo: "From {{ip}} To {{target}}",
|
||||
connectionViaRelay: "Via relay {{relay}}",
|
||||
connectionActive: "Connected",
|
||||
connectionConnecting: "Connecting",
|
||||
connectionDisconnected: "Disconnected",
|
||||
@@ -502,6 +583,21 @@ const germanCopy = {
|
||||
connectionReady: "Verbindung hergestellt",
|
||||
connectionFailed: "Verbindung fehlgeschlagen",
|
||||
packetLoss: "Paketverlust",
|
||||
networkReachable: "Netzwerk erreichbar (Passwort nicht geprüft)",
|
||||
networkReachableHint: "Ping erfolgreich. Der Admin-Test erstellt keinen zusätzlichen TeamSpeak-Client und prüft daher das Serverpasswort nicht.",
|
||||
failureReason: "Grund",
|
||||
failureDetail: "Diagnose",
|
||||
hostNotFoundError: "Server nicht gefunden",
|
||||
networkUnreachableError: "Netzwerk nicht erreichbar",
|
||||
connectionRefusedError: "Verbindung abgelehnt",
|
||||
connectionResetError: "Verbindung zurückgesetzt",
|
||||
networkTimeoutError: "Netzwerk-Zeitüberschreitung",
|
||||
serverPasswordRequiredError: "Serverpasswort erforderlich",
|
||||
invalidServerPasswordError: "Falsches Serverpasswort",
|
||||
protocolFailureError: "Aushandlung des TeamSpeak-Protokolls fehlgeschlagen",
|
||||
serverRejectedError: "Server hat die Verbindung abgelehnt",
|
||||
invalidNicknameError: "Die Länge des Spitznamens entspricht nicht den Serveranforderungen",
|
||||
pingUnavailableError: "Netzwerkprüfung nicht verfügbar",
|
||||
accessAndIdentity: "Zugriff und Website-Informationen",
|
||||
advancedSettings: "Erweiterte Einstellungen",
|
||||
advancedSettingsLead: "Erweiterte Gateway-Transportparameter nur bei Bedarf ändern.",
|
||||
@@ -510,13 +606,30 @@ const germanCopy = {
|
||||
webrtcPortRange: "WebRTC-UDP-Portbereich",
|
||||
webrtcPortStart: "Startport",
|
||||
webrtcPortEnd: "Endport",
|
||||
relaySettings: "Relay-Server",
|
||||
relaySettingsLead: "Konfiguriere den Relay-Knoten für beschleunigte Verbindungen; sein Name wird auf der Startseite angezeigt.",
|
||||
relayEnabled: "Relay-Beschleunigung aktivieren",
|
||||
relayEnabledLead: "Besucher mit aktivierter Beschleunigung erreichen ihr TeamSpeak-Ziel über diesen Relay.",
|
||||
relayName: "Anzeigename des Relays",
|
||||
relayNamePlaceholder: "Zum Beispiel: Festland-Relay oder Japan-Relay",
|
||||
relayTarget: "Relay-Serveradresse",
|
||||
relayTargetPlaceholder: "Zum Beispiel: relay.example.com#39087",
|
||||
relayToken: "Relay-Token",
|
||||
relayTokenPlaceholder: "Token des Relay-Dienstes eingeben",
|
||||
relayTokenConfigured: "Token konfiguriert (leer lassen zum Beibehalten)",
|
||||
relayAdd: "Relay-Knoten hinzufügen",
|
||||
relayNodeEmpty: "Keine Relay-Knoten konfiguriert.",
|
||||
relayUnnamed: "Unbenannter Relay",
|
||||
relayManagedHint: "Der Relay wird über die Konsole verwaltet. Das Token wird verschlüsselt gespeichert und nie an den Browser zurückgegeben.",
|
||||
relayEnvironmentHint: "Der Relay verwendet nur die hier gespeicherten Einstellungen. Nach dem Deaktivieren und Speichern wird die Option für Besucher ausgeblendet.",
|
||||
accessMode: "Gastzugriff",
|
||||
fixedMode: "Nur dieser TeamSpeak-Server",
|
||||
openMode: "Andere TeamSpeak-Server erlauben",
|
||||
siteName: "Anzeigename der Website",
|
||||
welcomeText: "Ankündigung",
|
||||
welcomeTextZh: "Chinesische Ankündigung",
|
||||
welcomeTextEn: "Englische Ankündigung",
|
||||
welcomeText: "Willkommenstext",
|
||||
welcomeLanguage: "Sprache des Willkommenstexts",
|
||||
welcomeLanguageHint: "Sprache auswählen und den jeweiligen Text bearbeiten. Leer lassen, um die Vorlage zu verwenden.",
|
||||
welcomeFallbackHint: "Ein leeres Feld verwendet automatisch die Vorlage dieser Sprache.",
|
||||
runtimeFacts: "Laufzeitinformationen",
|
||||
lastTest: "Letzter Test",
|
||||
latency: "Latenz",
|
||||
@@ -568,6 +681,8 @@ const germanCopy = {
|
||||
exportBackup: "Datenbanksicherung exportieren",
|
||||
logViewer: "Laufzeitprotokoll",
|
||||
connectionHistory: "Verbindungsaufzeichnungen",
|
||||
connectionFromTo: "Von {{ip}} zu {{target}}",
|
||||
connectionViaRelay: "Über Relay {{relay}}",
|
||||
connectionActive: "Verbunden",
|
||||
connectionConnecting: "Verbindung wird hergestellt",
|
||||
connectionDisconnected: "Getrennt",
|
||||
@@ -583,10 +698,291 @@ const germanCopy = {
|
||||
auditEmpty: "Keine Prüfereignisse.",
|
||||
} as const;
|
||||
|
||||
function tr(key: keyof typeof copy.zh, vars: Record<string, string | number> = {}): string { let value: string = language.value === "zh" ? copy.zh[key] : language.value === "de" ? germanCopy[key] ?? copy.en[key] ?? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; }
|
||||
const russianCopy = {
|
||||
...copy.en,
|
||||
loading: "Загрузка панели администратора…",
|
||||
adminConsole: "Панель администратора",
|
||||
changePasswordTitle: "Измените пароль по умолчанию",
|
||||
changePasswordLead: "Пароль по умолчанию используется только для первого входа. Задайте новый пароль длиной не менее 12 символов.",
|
||||
savePassword: "Сохранить новый пароль",
|
||||
languageMenu: "Язык",
|
||||
welcomeAdmin: "С возвращением",
|
||||
loginLead: "Войдите, чтобы управлять этим экземпляром WebSpeak.",
|
||||
adminPassword: "Пароль администратора",
|
||||
login: "Войти",
|
||||
backHome: "На главную",
|
||||
overview: "Обзор",
|
||||
server: "Сервер",
|
||||
operations: "Операции",
|
||||
openGuest: "Открыть страницу гостя",
|
||||
logout: "Выйти",
|
||||
gatewayRunning: "Шлюз работает",
|
||||
serverSettings: "Настройки сервера",
|
||||
serverSettingsLead: "Управляйте целью TeamSpeak, политикой доступа и содержимым для гостей.",
|
||||
saving: "Сохранение…",
|
||||
saveChanges: "Сохранить изменения",
|
||||
teamSpeakTarget: "Цель TeamSpeak по умолчанию",
|
||||
serverAddress: "Адрес сервера TeamSpeak",
|
||||
serverPlaceholder: "например, ts.example.com или 127.0.0.1",
|
||||
serverPort: "Голосовой порт",
|
||||
serverPassword: "Пароль сервера",
|
||||
optional: "необязательно",
|
||||
optionalPassword: "Оставьте пустым, если пароль не нужен",
|
||||
passwordConfigured: "Пароль настроен (оставьте пустым, чтобы сохранить)",
|
||||
change: "Изменить",
|
||||
remove: "Удалить",
|
||||
testConnection: "Проверить подключение",
|
||||
testing: "Проверка…",
|
||||
connectionReady: "Подключение установлено",
|
||||
connectionFailed: "Подключение не удалось",
|
||||
packetLoss: "Потери пакетов",
|
||||
accessAndIdentity: "Доступ и данные сайта",
|
||||
advancedSettings: "Расширенные настройки",
|
||||
advancedSettingsLead: "Изменяйте расширенные параметры передачи только при необходимости.",
|
||||
webrtcEnabled: "Включить WebRTC",
|
||||
relaySettings: "Сервер ретрансляции",
|
||||
relaySettingsLead: "Настройте узлы ретрансляции для ускоренных подключений.",
|
||||
relayEnabled: "Включить ретрансляцию",
|
||||
relayName: "Название ретранслятора",
|
||||
relayTarget: "Адрес ретранслятора",
|
||||
relayToken: "Токен ретранслятора",
|
||||
relayAdd: "Добавить узел ретрансляции",
|
||||
relayNodeEmpty: "Узлы ретрансляции не настроены.",
|
||||
relayUnnamed: "Ретранслятор без названия",
|
||||
accessMode: "Режим доступа гостей",
|
||||
fixedMode: "Только этот сервер TeamSpeak",
|
||||
openMode: "Разрешить другие серверы TeamSpeak",
|
||||
siteName: "Отображаемое имя сайта",
|
||||
welcomeText: "Приветственное сообщение",
|
||||
welcomeLanguage: "Язык приветственного сообщения",
|
||||
welcomeLanguageHint: "Переключайте язык, чтобы редактировать отдельное сообщение. Оставьте поле пустым для встроенного шаблона.",
|
||||
welcomeFallbackHint: "Пустое поле автоматически использует шаблон выбранного языка.",
|
||||
runtimeFacts: "Сведения о работе",
|
||||
lastTest: "Последняя проверка",
|
||||
latency: "Задержка",
|
||||
internalPort: "Внутренний порт",
|
||||
systemStatus: "СОСТОЯНИЕ СИСТЕМЫ",
|
||||
everythingRunning: "WebSpeak работает",
|
||||
running: "Работает",
|
||||
gateway: "Шлюз",
|
||||
activeSessions: "Активные сессии",
|
||||
targetHealth: "Состояние цели",
|
||||
status: "Состояние",
|
||||
recentEvents: "Последние события",
|
||||
noRecentEvents: "Нет последних событий",
|
||||
reachable: "Доступен",
|
||||
unreachable: "Недоступен",
|
||||
notTested: "Не проверен",
|
||||
requestFailed: "Запрос не выполнен. Проверьте поля и повторите попытку.",
|
||||
refresh: "Обновить",
|
||||
sessions: "Активные сессии",
|
||||
sessionEmpty: "Нет активных сессий.",
|
||||
nickname: "Имя",
|
||||
sessionState: "Состояние",
|
||||
age: "Длительность",
|
||||
memberCount: "Участники",
|
||||
endSession: "Отключить",
|
||||
terminating: "Отключение…",
|
||||
invites: "Управляемые приглашения",
|
||||
inviteChannel: "Целевой канал",
|
||||
expiresIn: "Срок действия (часы)",
|
||||
maxUses: "Максимум использований",
|
||||
createInvite: "Создать ссылку-приглашение",
|
||||
inviteCreated: "Ссылка-приглашение создана",
|
||||
copyLink: "Копировать ссылку",
|
||||
copiedLink: "Ссылка-приглашение скопирована.",
|
||||
revoke: "Отозвать",
|
||||
active: "Активно",
|
||||
expired: "Истекло",
|
||||
exhausted: "Лимит исчерпан",
|
||||
revoked: "Отозвано",
|
||||
diagnostics: "Диагностика",
|
||||
downloadReport: "Скачать отчёт диагностики",
|
||||
exportBackup: "Экспортировать резервную копию",
|
||||
logViewer: "Рабочие журналы",
|
||||
connectionHistory: "История подключений пользователей",
|
||||
connectionFromTo: "От {{ip}} к {{target}}",
|
||||
connectionViaRelay: "Через ретранслятор {{relay}}",
|
||||
connectionActive: "Подключён",
|
||||
connectionConnecting: "Подключение",
|
||||
connectionDisconnected: "Отключён",
|
||||
connectedAt: "Подключён",
|
||||
connectionAttemptedAt: "Попытка",
|
||||
disconnectedAt: "Отключён",
|
||||
duration: "Длительность",
|
||||
noLogs: "Нет доступных журналов.",
|
||||
operationFailed: "Операция не выполнена. Повторите позже.",
|
||||
version: "Версия",
|
||||
audit: "Журнал аудита",
|
||||
auditEmpty: "Нет событий аудита.",
|
||||
} as const;
|
||||
|
||||
const japaneseCopy = {
|
||||
...copy.en,
|
||||
loading: "管理コンソールを読み込み中…",
|
||||
adminConsole: "管理コンソール",
|
||||
changePasswordTitle: "初期パスワードを変更",
|
||||
changePasswordLead: "初期パスワードは初回ログイン専用です。12文字以上の新しい管理者パスワードを設定してください。",
|
||||
savePassword: "新しいパスワードを保存",
|
||||
languageMenu: "言語",
|
||||
welcomeAdmin: "おかえりなさい",
|
||||
loginLead: "ログインして WebSpeak を管理します。",
|
||||
adminPassword: "管理者パスワード",
|
||||
login: "ログイン",
|
||||
backHome: "ホームに戻る",
|
||||
overview: "概要",
|
||||
server: "サーバー",
|
||||
operations: "運用",
|
||||
openGuest: "ゲストページを開く",
|
||||
logout: "ログアウト",
|
||||
gatewayRunning: "ゲートウェイ稼働中",
|
||||
serverSettings: "サーバー設定",
|
||||
serverSettingsLead: "TeamSpeak 接続先、アクセス方針、ゲスト向け内容を管理します。",
|
||||
saving: "保存中…",
|
||||
saveChanges: "変更を保存",
|
||||
teamSpeakTarget: "デフォルト TeamSpeak 接続先",
|
||||
serverAddress: "TeamSpeak サーバーアドレス",
|
||||
serverPlaceholder: "例: ts.example.com または 127.0.0.1",
|
||||
serverPort: "音声ポート",
|
||||
serverPassword: "サーバーパスワード",
|
||||
optional: "任意",
|
||||
optionalPassword: "不要な場合は空欄",
|
||||
passwordConfigured: "パスワード設定済み(変更しない場合は空欄)",
|
||||
change: "変更",
|
||||
remove: "削除",
|
||||
testConnection: "接続をテスト",
|
||||
testing: "テスト中…",
|
||||
connectionReady: "接続準備完了",
|
||||
connectionFailed: "接続に失敗しました",
|
||||
packetLoss: "パケット損失",
|
||||
accessAndIdentity: "アクセスとサイト情報",
|
||||
advancedSettings: "詳細設定",
|
||||
advancedSettingsLead: "必要な場合だけゲートウェイの詳細な転送設定を変更します。",
|
||||
webrtcEnabled: "WebRTC を有効化",
|
||||
relaySettings: "中継サーバー",
|
||||
relaySettingsLead: "高速接続で使用する中継ノードを設定します。",
|
||||
relayEnabled: "中継を有効化",
|
||||
relayName: "中継名",
|
||||
relayTarget: "中継サーバーアドレス",
|
||||
relayToken: "中継トークン",
|
||||
relayAdd: "中継ノードを追加",
|
||||
relayNodeEmpty: "中継ノードは設定されていません。",
|
||||
relayUnnamed: "名前のない中継",
|
||||
accessMode: "ゲストアクセスモード",
|
||||
fixedMode: "この TeamSpeak サーバーのみ",
|
||||
openMode: "他の TeamSpeak サーバーを許可",
|
||||
siteName: "サイト表示名",
|
||||
welcomeText: "ウェルカムメッセージ",
|
||||
welcomeLanguage: "ウェルカムメッセージの言語",
|
||||
welcomeLanguageHint: "言語を切り替えて個別のメッセージを編集します。空欄の場合は組み込みテンプレートを使用します。",
|
||||
welcomeFallbackHint: "空欄にすると選択した言語のデフォルトテンプレートに戻ります。",
|
||||
runtimeFacts: "実行情報",
|
||||
lastTest: "最終テスト",
|
||||
latency: "遅延",
|
||||
internalPort: "内部ポート",
|
||||
systemStatus: "システム状態",
|
||||
everythingRunning: "WebSpeak は稼働中です",
|
||||
running: "稼働中",
|
||||
gateway: "ゲートウェイ",
|
||||
activeSessions: "アクティブセッション",
|
||||
targetHealth: "接続先の状態",
|
||||
status: "状態",
|
||||
recentEvents: "最近のイベント",
|
||||
noRecentEvents: "最近のイベントはありません",
|
||||
reachable: "接続可能",
|
||||
unreachable: "接続不可",
|
||||
notTested: "未テスト",
|
||||
requestFailed: "リクエストに失敗しました。入力を確認して再試行してください。",
|
||||
refresh: "更新",
|
||||
sessions: "アクティブセッション",
|
||||
sessionEmpty: "アクティブなセッションはありません。",
|
||||
nickname: "名前",
|
||||
sessionState: "状態",
|
||||
age: "経過時間",
|
||||
memberCount: "メンバー",
|
||||
endSession: "切断",
|
||||
terminating: "切断中…",
|
||||
invites: "管理済み招待",
|
||||
inviteChannel: "参加先チャンネル",
|
||||
expiresIn: "有効期間(時間)",
|
||||
maxUses: "最大使用回数",
|
||||
createInvite: "招待リンクを作成",
|
||||
inviteCreated: "招待リンクを作成しました",
|
||||
copyLink: "リンクをコピー",
|
||||
copiedLink: "招待リンクをコピーしました。",
|
||||
revoke: "取り消す",
|
||||
active: "有効",
|
||||
expired: "期限切れ",
|
||||
exhausted: "上限到達",
|
||||
revoked: "取り消し済み",
|
||||
diagnostics: "診断情報",
|
||||
downloadReport: "診断レポートをダウンロード",
|
||||
exportBackup: "データベースをバックアップ",
|
||||
logViewer: "実行ログ",
|
||||
connectionHistory: "ユーザー接続履歴",
|
||||
connectionFromTo: "{{ip}} から {{target}} へ",
|
||||
connectionViaRelay: "中継 {{relay}} 経由",
|
||||
connectionActive: "接続中",
|
||||
connectionConnecting: "接続準備中",
|
||||
connectionDisconnected: "切断済み",
|
||||
connectedAt: "接続",
|
||||
connectionAttemptedAt: "試行",
|
||||
disconnectedAt: "切断",
|
||||
duration: "時間",
|
||||
noLogs: "表示できるログはありません。",
|
||||
operationFailed: "操作に失敗しました。後でもう一度お試しください。",
|
||||
version: "バージョン",
|
||||
audit: "監査ログ",
|
||||
auditEmpty: "監査イベントはありません。",
|
||||
} as const;
|
||||
|
||||
const welcomeLanguageOptions: Array<{ value: WelcomeLanguage; label: string }> = [
|
||||
{ value: "zh", label: "中文" },
|
||||
{ value: "en", label: "English" },
|
||||
{ value: "de", label: "Deutsch" },
|
||||
{ value: "ru", label: "Русский" },
|
||||
{ value: "ja", label: "日本語" },
|
||||
];
|
||||
|
||||
const welcomeTextFieldByLanguage: Record<WelcomeLanguage, WelcomeTextField> = {
|
||||
zh: "welcomeText",
|
||||
en: "welcomeTextEn",
|
||||
de: "welcomeTextDe",
|
||||
ru: "welcomeTextRu",
|
||||
ja: "welcomeTextJa",
|
||||
};
|
||||
|
||||
const selectedWelcomeText = computed<string>({
|
||||
get: () => serverForm[welcomeTextFieldByLanguage[welcomeLanguage.value]],
|
||||
set: (value: string) => { serverForm[welcomeTextFieldByLanguage[welcomeLanguage.value]] = value; },
|
||||
});
|
||||
const selectedWelcomeLanguageLabel = computed(() => welcomeLanguageOptions.find((option) => option.value === welcomeLanguage.value)?.label ?? "");
|
||||
const selectedWelcomeDefault = computed(() => serverForm.welcomeDefaults[welcomeLanguage.value] || DEFAULT_WELCOME_TEXTS[welcomeLanguage.value]);
|
||||
|
||||
function tr(key: keyof typeof copy.zh, vars: Record<string, string | number> = {}): string { let value: string = language.value === "zh" ? copy.zh[key] : language.value === "de" ? germanCopy[key] ?? copy.en[key] ?? copy.zh[key] : language.value === "ru" ? russianCopy[key] ?? copy.en[key] ?? copy.zh[key] : language.value === "ja" ? japaneseCopy[key] ?? copy.en[key] ?? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; }
|
||||
const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.value.length * 5 + (/[\s\W]/.test(newPassword.value) ? 15 : 0))));
|
||||
const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : route.path === "/admin/operations" ? tr('operations') : tr('overview'));
|
||||
const testResultText = computed(() => { if (!testResult.value) return ""; const result = testResult.value; const toolUnavailable = result.errorCode === "PING_UNAVAILABLE"; const loss = toolUnavailable || result.packetLossPercent == null ? null : `${tr('packetLoss')} ${result.packetLossPercent}%`; if (!result.ok) return [errorText(result.code ?? result.errorCode), loss].filter(Boolean).join(" · "); return [result.serverName, result.latencyMs == null ? null : `${result.latencyMs} ms`, loss].filter(Boolean).join(" · "); });
|
||||
const testResultTitle = computed(() => {
|
||||
const result = testResult.value;
|
||||
if (!result) return "";
|
||||
if (result.ok) return result.checkType === "network" ? tr("networkReachable") : tr("connectionReady");
|
||||
const names: Record<string, keyof typeof copy.zh> = {
|
||||
INVALID_TARGET: "serverAddress",
|
||||
INVALID_NICKNAME: "invalidNicknameError",
|
||||
HOST_NOT_FOUND: "hostNotFoundError",
|
||||
UNREACHABLE: "networkUnreachableError",
|
||||
CONNECTION_REFUSED: "connectionRefusedError",
|
||||
CONNECTION_RESET: "connectionResetError",
|
||||
TIMEOUT: "networkTimeoutError",
|
||||
PASSWORD_REQUIRED: "serverPasswordRequiredError",
|
||||
INVALID_PASSWORD: "invalidServerPasswordError",
|
||||
PROTOCOL_NEGOTIATION_FAILED: "protocolFailureError",
|
||||
SERVER_REJECTED: "serverRejectedError",
|
||||
PING_UNAVAILABLE: "pingUnavailableError",
|
||||
};
|
||||
return tr(names[result.code ?? result.errorCode ?? ""] ?? "connectionFailed");
|
||||
});
|
||||
const testResultText = computed(() => { if (!testResult.value) return ""; const result = testResult.value; const toolUnavailable = result.errorCode === "PING_UNAVAILABLE"; const loss = toolUnavailable || result.packetLossPercent == null ? null : `${tr('packetLoss')} ${result.packetLossPercent}%`; if (!result.ok) return [connectionFailureText(result.code ?? result.errorCode), loss].filter(Boolean).join(" · "); if (result.checkType === "network") return [tr("networkReachableHint"), result.latencyMs == null ? null : `${result.latencyMs} ms`, loss].filter(Boolean).join(" · "); return [result.serverName, result.latencyMs == null ? null : `${result.latencyMs} ms`, loss].filter(Boolean).join(" · "); });
|
||||
const targetStatusText = computed(() => overview.teamSpeak.status === "reachable" ? tr('reachable') : overview.teamSpeak.status === "unreachable" ? tr('unreachable') : tr('notTested'));
|
||||
const webrtcPortRangeText = computed(() => `${serverForm.webRtcUdpStart}–${serverForm.webRtcUdpEnd}`);
|
||||
|
||||
@@ -599,7 +995,19 @@ async function login() { submitting.value = true; errorMessage.value = ""; try {
|
||||
async function changePassword() { errorMessage.value = ""; if (newPassword.value.length < 12) { errorMessage.value = tr('setupPasswordShort'); return; } if (newPassword.value !== confirmNewPassword.value) { errorMessage.value = tr('setupPasswordsMismatch'); return; } submitting.value = true; try { await sendJson("/api/admin/change-password", "POST", { newPassword: newPassword.value }); newPassword.value = ""; confirmNewPassword.value = ""; screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
async function logout() { try { await sendJson("/api/admin/logout", "POST", {}); } finally { csrfToken.value = ""; screen.value = "login"; await router.replace("/admin/login"); } }
|
||||
async function loadOverview() { Object.assign(overview, await getJson("/api/admin/overview")); }
|
||||
async function loadServerSettings() { const value = await getJson("/api/admin/server"); const target = splitTeamSpeakTarget(value.target); Object.assign(serverForm, value, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", webRtcEnabled: value.webRtcEnabled === true, webRtcUdpStart: Number(value.webRtcUdpStart || 40000), webRtcUdpEnd: Number(value.webRtcUdpEnd || 40099) }); }
|
||||
function mapRelayNodes(value: unknown): RelayNodeForm[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.flatMap((item) => {
|
||||
if (!item || typeof item !== "object") return [];
|
||||
const node = item as { id?: unknown; name?: unknown; enabled?: unknown; target?: unknown; hasToken?: unknown };
|
||||
if (typeof node.id !== "string" || typeof node.name !== "string" || typeof node.target !== "string") return [];
|
||||
return [{ id: node.id, name: node.name, enabled: node.enabled === true, target: node.target, token: "", tokenAction: "keep" as const, hasToken: node.hasToken === true }];
|
||||
});
|
||||
}
|
||||
function createRelayNode(): RelayNodeForm { return { id: `relay-new-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`, name: "", enabled: false, target: "", token: "", tokenAction: "replace", hasToken: false }; }
|
||||
function addRelayNode() { serverForm.relayNodes.push(createRelayNode()); serverForm.relaySettingsTouched = true; }
|
||||
function removeRelayNode(index: number) { serverForm.relayNodes.splice(index, 1); serverForm.relaySettingsTouched = true; }
|
||||
async function loadServerSettings() { const value = await getJson("/api/admin/server"); const target = splitTeamSpeakTarget(value.target); Object.assign(serverForm, value, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", welcomeTextDe: String(value.welcomeTextDe || ""), welcomeTextRu: String(value.welcomeTextRu || ""), welcomeTextJa: String(value.welcomeTextJa || ""), welcomeDefaults: { ...DEFAULT_WELCOME_TEXTS, ...(value.welcomeDefaults && typeof value.welcomeDefaults === "object" ? value.welcomeDefaults : {}) }, webRtcEnabled: value.webRtcEnabled === true, webRtcUdpStart: Number(value.webRtcUdpStart || 40000), webRtcUdpEnd: Number(value.webRtcUdpEnd || 40099), relayConfigured: value.relayConfigured === true, relayEnabled: value.relayEnabled === true, relayName: String(value.relayName || ""), relayTarget: String(value.relayTarget || ""), relayToken: "", relayTokenAction: "keep", hasRelayToken: value.hasRelayToken === true, relaySettingsTouched: false, relayNodes: mapRelayNodes(value.relayNodes) }); }
|
||||
async function loadOperations() { operationsLoading.value = true; try { const [sessions, invites, diagnostics, logs, audit] = await Promise.all([getJson("/api/admin/sessions"), getJson("/api/admin/invites"), getJson("/api/admin/diagnostics"), getJson("/api/admin/logs?limit=100"), getJson("/api/admin/audit?limit=50")]); operations.sessions = Array.isArray(sessions.sessions) ? sessions.sessions : []; operations.invites = Array.isArray(invites.invites) ? invites.invites : []; operations.diagnostics = { version: String(diagnostics.gateway?.version || ""), node: String(diagnostics.gateway?.node || ""), platform: String(diagnostics.gateway?.platform || ""), arch: String(diagnostics.gateway?.arch || ""), schemaVersion: Number(diagnostics.database?.schemaVersion || 0), createdSessions: Number(diagnostics.sessions?.created || 0) }; operations.logs = { available: Boolean(logs.available), entries: Array.isArray(logs.entries) ? logs.entries : [], sessions: Array.isArray(logs.sessions) ? logs.sessions : [] }; operations.audit = Array.isArray(audit.events) ? audit.events : []; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { operationsLoading.value = false; } }
|
||||
async function terminateSession(session: AdminSession) { if (!window.confirm(tr('confirmTerminate', { nickname: session.nickname }))) return; terminatingSession.value = session.id; errorMessage.value = ""; try { await sendJson(`/api/admin/sessions/${encodeURIComponent(session.id)}/terminate`, "POST", {}); await Promise.all([loadOperations(), loadOverview()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { terminatingSession.value = ""; } }
|
||||
async function createInvite() { submitting.value = true; errorMessage.value = ""; createdInvite.value = null; try { const result = await sendJson("/api/admin/invites", "POST", { channel: inviteForm.channel, expiresInHours: inviteForm.expiresInHours, maxUses: inviteForm.maxUses }); if (typeof result.token !== "string") throw new Error("INVITE_CREATE_FAILED"); createdInvite.value = { token: result.token, link: `${location.origin}/?invite=${encodeURIComponent(result.token)}` }; inviteForm.channel = ""; await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
@@ -607,23 +1015,88 @@ async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('con
|
||||
async function copyInviteLink() { if (!createdInvite.value) return; try { await navigator.clipboard.writeText(createdInvite.value.link); showOperationNotice(tr('copiedLink')); } catch { errorMessage.value = tr('operationFailed'); } }
|
||||
function showOperationNotice(message: string) { errorMessage.value = message; window.setTimeout(() => { if (errorMessage.value === message) errorMessage.value = ""; }, 2200); }
|
||||
async function downloadBackup() { try { const response = await fetch("/api/admin/backup", { headers: { accept: "application/octet-stream" } }); if (!response.ok) throw new Error("BACKUP_FAILED"); const blob = await response.blob(); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url; anchor.download = `webspeak-backup-${new Date().toISOString().slice(0, 10)}.db`; anchor.click(); URL.revokeObjectURL(url); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } }
|
||||
async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", webRtcEnabled: result.settings.webRtcEnabled === true, webRtcUdpStart: Number(result.settings.webRtcUdpStart || 40000), webRtcUdpEnd: Number(result.settings.webRtcUdpEnd || 40099) }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", welcomeTextDe: String(result.settings.welcomeTextDe || ""), welcomeTextRu: String(result.settings.welcomeTextRu || ""), welcomeTextJa: String(result.settings.welcomeTextJa || ""), welcomeDefaults: { ...DEFAULT_WELCOME_TEXTS, ...(result.settings.welcomeDefaults && typeof result.settings.welcomeDefaults === "object" ? result.settings.welcomeDefaults : {}) }, webRtcEnabled: result.settings.webRtcEnabled === true, webRtcUdpStart: Number(result.settings.webRtcUdpStart || 40000), webRtcUdpEnd: Number(result.settings.webRtcUdpEnd || 40099), relayConfigured: result.settings.relayConfigured === true, relayEnabled: result.settings.relayEnabled === true, relayName: String(result.settings.relayName || ""), relayTarget: String(result.settings.relayTarget || ""), relayToken: "", relayTokenAction: "keep", hasRelayToken: result.settings.hasRelayToken === true, relaySettingsTouched: false, relayNodes: mapRelayNodes(result.settings.relayNodes) }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
|
||||
function handleWebRtcToggle() { if (serverForm.webRtcEnabled) webrtcPortNoticeOpen.value = true; }
|
||||
async function testServerConnection() { await runTest("/api/admin/server/test", { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction }); if (testResult.value) { await loadOverview(); serverForm.lastTestAt = new Date().toISOString(); serverForm.lastTestLatencyMs = testResult.value.ok ? (testResult.value.latencyMs ?? null) : null; } }
|
||||
function serverPayload() { return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText, welcomeTextEn: serverForm.welcomeTextEn, webRtcEnabled: serverForm.webRtcEnabled, webRtcUdpStart: serverForm.webRtcUdpStart, webRtcUdpEnd: serverForm.webRtcUdpEnd }; }
|
||||
function touchRelaySettings() { serverForm.relaySettingsTouched = true; }
|
||||
function serverPayload() { return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText, welcomeTextEn: serverForm.welcomeTextEn, welcomeTextDe: serverForm.welcomeTextDe, welcomeTextRu: serverForm.welcomeTextRu, welcomeTextJa: serverForm.welcomeTextJa, webRtcEnabled: serverForm.webRtcEnabled, webRtcUdpStart: serverForm.webRtcUdpStart, webRtcUdpEnd: serverForm.webRtcUdpEnd, relayNodes: serverForm.relayNodes.map((node) => ({ id: node.id, name: node.name, target: node.target, enabled: node.enabled, tokenAction: node.tokenAction, ...(node.tokenAction === "replace" ? { token: node.token } : {}) })) }; }
|
||||
async function runTest(url: string, body: Record<string, unknown>) { testing.value = true; errorMessage.value = ""; testResult.value = null; try { testResult.value = await sendJson(url, "POST", body, url.includes("/server/test")); } catch (error) { testResult.value = { ok: false, code: (error as ApiError).code }; } finally { testing.value = false; } }
|
||||
async function dismissLegacyNotice() { await sendJson("/api/admin/legacy-import/dismiss", "POST", {}); overview.legacyConfigImported = false; }
|
||||
function persistLanguage() { localStorage.setItem("webspeak:language", language.value); }
|
||||
function cycleTheme() { themeMode.value = nextTheme(themeMode.value); saveTheme(themeMode.value); }
|
||||
function formatDate(value: string | null) { return value ? new Intl.DateTimeFormat(language.value === "zh" ? "zh-CN" : language.value === "de" ? "de-DE" : "en-US", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value)) : "—"; }
|
||||
function formatUptime(seconds: number) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); return language.value === "zh" ? `已运行 ${hours} 小时 ${minutes} 分钟` : language.value === "de" ? `${hours} Std. ${minutes} Min. aktiv` : `Up ${hours}h ${minutes}m`; }
|
||||
function formatAge(seconds: number | null) { if (seconds == null) return "—"; if (seconds < 60) return language.value === "zh" ? `${seconds} 秒` : language.value === "de" ? `${seconds} Sek.` : `${seconds}s`; const minutes = Math.floor(seconds / 60); if (minutes < 60) return language.value === "zh" ? `${minutes} 分钟` : language.value === "de" ? `${minutes} Min.` : `${minutes}m`; const hours = Math.floor(minutes / 60); return language.value === "zh" ? `${hours} 小时 ${minutes % 60} 分钟` : language.value === "de" ? `${hours} Std. ${minutes % 60} Min.` : `${hours}h ${minutes % 60}m`; }
|
||||
function formatDate(value: string | null) { return value ? new Intl.DateTimeFormat(language.value === "zh" ? "zh-CN" : language.value === "de" ? "de-DE" : language.value === "ru" ? "ru-RU" : language.value === "ja" ? "ja-JP" : "en-US", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value)) : "—"; }
|
||||
function formatUptime(seconds: number) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); if (language.value === "zh") return `已运行 ${hours} 小时 ${minutes} 分钟`; if (language.value === "de") return `${hours} Std. ${minutes} Min. aktiv`; if (language.value === "ru") return `Работает ${hours} ч ${minutes} мин`; if (language.value === "ja") return `${hours}時間 ${minutes}分 稼働`; return `Up ${hours}h ${minutes}m`; }
|
||||
function formatAge(seconds: number | null) { if (seconds == null) return "—"; if (seconds < 60) { if (language.value === "zh") return `${seconds} 秒`; if (language.value === "de") return `${seconds} Sek.`; if (language.value === "ru") return `${seconds} с`; if (language.value === "ja") return `${seconds}秒`; return `${seconds}s`; } const minutes = Math.floor(seconds / 60); if (minutes < 60) { if (language.value === "zh") return `${minutes} 分钟`; if (language.value === "de") return `${minutes} Min.`; if (language.value === "ru") return `${minutes} мин`; if (language.value === "ja") return `${minutes}分`; return `${minutes}m`; } const hours = Math.floor(minutes / 60); const rest = minutes % 60; if (language.value === "zh") return `${hours} 小时 ${rest} 分钟`; if (language.value === "de") return `${hours} Std. ${rest} Min.`; if (language.value === "ru") return `${hours} ч ${rest} мин`; if (language.value === "ja") return `${hours}時間 ${rest}分`; return `${hours}h ${rest}m`; }
|
||||
function connectionStatusLabel(status: AdminConnectionRecord["status"]) { const names: Record<AdminConnectionRecord["status"], keyof typeof copy.zh> = { active: "connectionActive", connecting: "connectionConnecting", disconnected: "connectionDisconnected", failed: "connectionFailed" }; return tr(names[status]); }
|
||||
function sessionStateLabel(state: string) { const names: Record<string, { zh: string; en: string; de: string }> = { connecting: { zh: "连接中", en: "Connecting", de: "Verbindung wird hergestellt" }, authenticating: { zh: "认证中", en: "Authenticating", de: "Authentifizierung" }, syncing: { zh: "同步中", en: "Syncing", de: "Synchronisierung" }, connected: { zh: "已连接", en: "Connected", de: "Verbunden" }, interrupted: { zh: "已中断", en: "Interrupted", de: "Unterbrochen" }, reconnecting: { zh: "重连中", en: "Reconnecting", de: "Wiederverbindung" }, disconnecting: { zh: "断开中", en: "Disconnecting", de: "Wird getrennt" }, failed: { zh: "失败", en: "Failed", de: "Fehlgeschlagen" }, idle: { zh: "空闲", en: "Idle", de: "Inaktiv" } }; return names[state]?.[language.value] ?? state; }
|
||||
function connectionRoute(record: AdminConnectionRecord) {
|
||||
const route = tr("connectionFromTo", { ip: record.clientIp || "—", target: record.target || "—" });
|
||||
if (!record.relayName && !record.relayTarget) return route;
|
||||
const relay = [record.relayName, record.relayTarget].filter(Boolean).join(" · ") || "—";
|
||||
return `${route} · ${tr("connectionViaRelay", { relay })}`;
|
||||
}
|
||||
function sessionStateLabel(state: string) { const names: Record<string, { zh: string; en: string; de: string }> = { connecting: { zh: "连接中", en: "Connecting", de: "Verbindung wird hergestellt" }, authenticating: { zh: "认证中", en: "Authenticating", de: "Authentifizierung" }, syncing: { zh: "同步中", en: "Syncing", de: "Synchronisierung" }, connected: { zh: "已连接", en: "Connected", de: "Verbunden" }, interrupted: { zh: "已中断", en: "Interrupted", de: "Unterbrochen" }, reconnecting: { zh: "重连中", en: "Reconnecting", de: "Wiederverbindung" }, disconnecting: { zh: "断开中", en: "Disconnecting", de: "Wird getrennt" }, failed: { zh: "失败", en: "Failed", de: "Fehlgeschlagen" }, idle: { zh: "空闲", en: "Idle", de: "Inaktiv" } }; const locale = language.value === "zh" ? "zh" : language.value === "de" ? "de" : "en"; return names[state]?.[locale] ?? state; }
|
||||
function inviteStatusLabel(status: ManagedInvite["status"]) { const names: Record<ManagedInvite["status"], keyof typeof copy.zh> = { active: "active", expired: "expired", exhausted: "exhausted", revoked: "revoked" }; return tr(names[status]); }
|
||||
function formatContext(context: Record<string, string | number | boolean>) { return Object.entries(context).map(([key, value]) => `${key}=${value}`).join(" · "); }
|
||||
function eventName(event: string) { if (event === "ADMIN_LOGIN_FAILED") return language.value === "zh" ? "管理员登录失败" : "Administrator login failed"; if (event === "CONNECTION_TEST_SUCCEEDED") return language.value === "zh" ? "连接测试成功" : "Connection test succeeded"; if (event === "CONNECTION_TEST_FAILED") return language.value === "zh" ? "连接测试失败" : "Connection test failed"; const names: Record<string, keyof typeof copy.zh> = { ADMIN_LOGIN_SUCCEEDED: "loginEvent", ADMIN_LOGOUT: "logoutEvent", SETTINGS_CHANGED: "settingsEvent", ADMIN_INITIALIZED: "initializedEvent", LEGACY_CONFIG_IMPORTED: "importedEvent", CONNECTION_TEST: "testEvent" }; return names[event] ? tr(names[event]) : language.value === "zh" ? "系统事件" : event.replaceAll("_", " "); }
|
||||
function errorText(code?: string) { if (code === "INVALID_PASSWORD") return tr('invalidPassword'); if (code === "INVALID_ADMIN_PASSWORD") return tr('setupPasswordShort'); if (code === "PASSWORD_CHANGE_REQUIRED") return tr('changePasswordLead'); if (code === "RATE_LIMITED") return tr('rateLimited'); if (code === "INVALID_WEBRTC_PORT_RANGE") return language.value === "zh" ? "WebRTC UDP 端口范围无效,请填写 1024–65535 且起始端口不能大于结束端口。" : language.value === "de" ? "Der WebRTC-UDP-Portbereich ist ungültig. Verwende 1024–65535; der Startport darf nicht größer als der Endport sein." : "The WebRTC UDP port range is invalid. Use 1024–65535 with the start no greater than the end."; if (code === "WEBRTC_PORT_LOCKED") return language.value === "zh" ? "WebRTC 已开启,请先关闭并保存后再修改端口范围。" : language.value === "de" ? "WebRTC ist aktiviert. Deaktiviere es und speichere zuerst, bevor du den Portbereich änderst." : "WebRTC is enabled. Turn it off and save before changing the port range."; const probe: Record<string, { zh: string; en: string; de: string }> = { INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid.", de: "Die TeamSpeak-Serveradresse ist ungültig." }, PING_UNAVAILABLE: { zh: "当前运行环境没有可用的 ICMP Ping 工具。", en: "The runtime does not provide an ICMP ping tool.", de: "In der Laufzeitumgebung ist kein ICMP-Ping-Tool verfügbar." }, HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved.", de: "Der Servername konnte nicht aufgelöst werden." }, UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable.", de: "Der TeamSpeak-Server ist nicht erreichbar." }, TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out.", de: "Die Verbindung zu TeamSpeak ist abgelaufen." }, PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed.", de: "Die Aushandlung des TeamSpeak-Protokolls ist fehlgeschlagen." }, SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection.", de: "Der TeamSpeak-Server hat die Verbindung abgelehnt." }, TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode.", de: "Dieses Ziel ist im offenen Modus nicht erlaubt." } }; return probe[code || ""]?.[language.value] ?? tr('requestFailed'); }
|
||||
function eventName(event: string) { if (event === "ADMIN_LOGIN_FAILED") return language.value === "zh" ? "管理员登录失败" : language.value === "ru" ? "Ошибка входа администратора" : language.value === "ja" ? "管理者ログイン失敗" : language.value === "de" ? "Administrator-Anmeldung fehlgeschlagen" : "Administrator login failed"; if (event === "CONNECTION_TEST_SUCCEEDED") return language.value === "zh" ? "连接测试成功" : language.value === "ru" ? "Проверка подключения успешна" : language.value === "ja" ? "接続テスト成功" : language.value === "de" ? "Verbindungstest erfolgreich" : "Connection test succeeded"; if (event === "CONNECTION_TEST_FAILED") return language.value === "zh" ? "连接测试失败" : language.value === "ru" ? "Проверка подключения не удалась" : language.value === "ja" ? "接続テスト失敗" : language.value === "de" ? "Verbindungstest fehlgeschlagen" : "Connection test failed"; const names: Record<string, keyof typeof copy.zh> = { ADMIN_LOGIN_SUCCEEDED: "loginEvent", ADMIN_LOGOUT: "logoutEvent", SETTINGS_CHANGED: "settingsEvent", ADMIN_INITIALIZED: "initializedEvent", LEGACY_CONFIG_IMPORTED: "importedEvent", CONNECTION_TEST: "testEvent" }; return names[event] ? tr(names[event]) : language.value === "zh" ? "系统事件" : event.replaceAll("_", " "); }
|
||||
function errorText(code?: string) {
|
||||
if (code === "INVALID_PASSWORD") return tr('invalidPassword');
|
||||
if (code === "INVALID_ADMIN_PASSWORD") return tr('setupPasswordShort');
|
||||
if (code === "PASSWORD_CHANGE_REQUIRED") return tr('changePasswordLead');
|
||||
if (code === "RATE_LIMITED") return tr('rateLimited');
|
||||
if (code === "INVALID_WEBRTC_PORT_RANGE") {
|
||||
if (language.value === "zh") return "WebRTC UDP 端口范围无效,请填写 1024–65535 且起始端口不能大于结束端口。";
|
||||
if (language.value === "de") return "Der WebRTC-UDP-Portbereich ist ungültig. Verwende 1024–65535; der Startport darf nicht größer als der Endport sein.";
|
||||
if (language.value === "ru") return "Диапазон UDP-портов WebRTC некорректен. Используйте 1024–65535; начальный порт не может быть больше конечного.";
|
||||
if (language.value === "ja") return "WebRTC UDP ポート範囲が正しくありません。1024–65535 の範囲で、開始ポートを終了ポート以下にしてください。";
|
||||
return "The WebRTC UDP port range is invalid. Use 1024–65535 with the start no greater than the end.";
|
||||
}
|
||||
if (code === "WEBRTC_PORT_LOCKED") {
|
||||
if (language.value === "zh") return "WebRTC 已开启,请先关闭并保存后再修改端口范围。";
|
||||
if (language.value === "de") return "WebRTC ist aktiviert. Deaktiviere es und speichere zuerst, bevor du den Portbereich änderst.";
|
||||
if (language.value === "ru") return "WebRTC включён. Сначала отключите его и сохраните настройки, затем изменяйте диапазон портов.";
|
||||
if (language.value === "ja") return "WebRTC が有効です。ポート範囲を変更する前に無効にして保存してください。";
|
||||
return "WebRTC is enabled. Turn it off and save before changing the port range.";
|
||||
}
|
||||
const locale = language.value === "zh" ? "zh" : language.value === "de" ? "de" : "en";
|
||||
const relayErrors: Record<string, { zh: string; en: string; de: string }> = {
|
||||
INVALID_RELAY_NAME: { zh: "中继名称无效或为空。", en: "The relay name is invalid or empty.", de: "Der Relay-Name ist ungültig oder leer." },
|
||||
INVALID_RELAY_TARGET: { zh: "中继服务器地址无效。", en: "The relay server address is invalid.", de: "Die Relay-Serveradresse ist ungültig." },
|
||||
INVALID_RELAY_TOKEN: { zh: "启用中继时必须填写令牌。", en: "A relay token is required when the relay is enabled.", de: "Beim Aktivieren des Relays ist ein Token erforderlich." },
|
||||
};
|
||||
if (relayErrors[code || ""]) return relayErrors[code || ""][locale];
|
||||
const probe: Record<string, { zh: string; en: string; de: string }> = {
|
||||
INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid.", de: "Die TeamSpeak-Serveradresse ist ungültig." },
|
||||
PING_UNAVAILABLE: { zh: "当前运行环境没有可用的 ICMP Ping 工具。", en: "The runtime does not provide an ICMP ping tool.", de: "In der Laufzeitumgebung ist kein ICMP-Ping-Tool verfügbar." },
|
||||
HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved.", de: "Der Servername konnte nicht aufgelöst werden." },
|
||||
UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable.", de: "Der TeamSpeak-Server ist nicht erreichbar." },
|
||||
TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out.", de: "Die Verbindung zu TeamSpeak ist abgelaufen." },
|
||||
PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed.", de: "Die Aushandlung des TeamSpeak-Protokolls ist fehlgeschlagen." },
|
||||
SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection.", de: "Der TeamSpeak-Server hat die Verbindung abgelehnt." },
|
||||
TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode.", de: "Dieses Ziel ist im offenen Modus nicht erlaubt." },
|
||||
};
|
||||
return probe[code || ""]?.[locale] ?? tr('requestFailed');
|
||||
}
|
||||
|
||||
function connectionFailureText(code?: string) {
|
||||
const names: Record<string, keyof typeof copy.zh> = {
|
||||
PASSWORD_REQUIRED: "serverPasswordRequiredError",
|
||||
SERVER_PASSWORD_REQUIRED: "serverPasswordRequiredError",
|
||||
INVALID_PASSWORD: "invalidServerPasswordError",
|
||||
INVALID_SERVER_PASSWORD: "invalidServerPasswordError",
|
||||
INVALID_TARGET: "serverAddress",
|
||||
INVALID_NICKNAME: "invalidNicknameError",
|
||||
HOST_NOT_FOUND: "hostNotFoundError",
|
||||
UNREACHABLE: "networkUnreachableError",
|
||||
CONNECTION_REFUSED: "connectionRefusedError",
|
||||
CONNECTION_RESET: "connectionResetError",
|
||||
TIMEOUT: "networkTimeoutError",
|
||||
PROTOCOL_NEGOTIATION_FAILED: "protocolFailureError",
|
||||
SERVER_REJECTED: "serverRejectedError",
|
||||
PING_UNAVAILABLE: "pingUnavailableError",
|
||||
CONNECTION_FAILED: "connectionFailed",
|
||||
};
|
||||
return names[code || ""] ? tr(names[code || ""]) : errorText(code);
|
||||
}
|
||||
|
||||
interface ApiError extends Error { code?: string }
|
||||
async function getJson(url: string): Promise<any> { const response = await fetch(url, { headers: { accept: "application/json" } }); return parseResponse(response); }
|
||||
@@ -758,6 +1231,27 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
.advanced-card{grid-column:1 / -1}
|
||||
.advanced-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}
|
||||
.advanced-card .toggle-choice{margin:0}
|
||||
.relay-card{grid-column:1 / -1}
|
||||
.relay-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}
|
||||
.relay-card .toggle-choice{margin:0}
|
||||
.relay-node-list{display:grid;gap:10px}
|
||||
.relay-node{display:grid;gap:10px;padding:12px;background:#f6f9f8;border:1px solid #e4efeb;border-radius:10px}
|
||||
.relay-node-heading{display:flex;align-items:center;justify-content:space-between;gap:10px}
|
||||
.relay-enabled{display:flex;align-items:center;gap:8px;margin:0;cursor:pointer}
|
||||
.relay-enabled input{width:16px;height:16px;margin:0;accent-color:#087d74}
|
||||
.relay-enabled strong{font-size:12px}
|
||||
.relay-empty{padding:10px 12px;color:#82908c;background:#f6f9f8;border:1px dashed #cfe3de;border-radius:9px;font-size:11px}
|
||||
.relay-add{justify-self:start;min-height:34px;padding-inline:13px}
|
||||
.relay-fields{display:grid;grid-template-columns:1fr 1fr;gap:12px}
|
||||
.relay-fields .password-row{grid-column:1 / -1}
|
||||
.relay-card .field-help{line-height:1.55}
|
||||
.welcome-editor{display:grid;gap:10px;padding:12px;background:#f6f9f8;border:1px solid #e4efeb;border-radius:10px}
|
||||
.welcome-editor-heading{display:grid;grid-template-columns:minmax(0,1fr) minmax(180px,1fr);align-items:end;gap:12px}
|
||||
.welcome-editor-heading label{min-width:0}
|
||||
.welcome-editor-heading>small{margin:0;color:#899792;font-size:10px;line-height:1.5}
|
||||
.welcome-editor select{width:100%;height:40px;padding:0 10px;color:#22332f;background:#fbfdfc;border:1px solid #dbe7e3;border-radius:9px;font:inherit;font-size:12px;outline:none}
|
||||
.welcome-editor select:focus{border-color:#54bdb2;box-shadow:0 0 0 3px rgba(84,189,178,.13)}
|
||||
.welcome-editor textarea{background:#fff}
|
||||
.webrtc-port-fields{display:grid;gap:10px;padding:14px;background:#f6f9f8;border:1px solid #e4efeb;border-radius:10px}
|
||||
.port-fields-heading strong,.port-fields-heading small{display:block}
|
||||
.port-fields-heading strong{font-size:11px}
|
||||
@@ -767,15 +1261,21 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
.port-inputs input:disabled{color:#70817b;background:#e9f1ee;border-color:#d7e5e1;cursor:not-allowed;opacity:1}
|
||||
.modal-backdrop{position:fixed;z-index:20;inset:0;display:grid;place-items:center;padding:22px;background:rgba(5,41,38,.38);backdrop-filter:blur(3px)}
|
||||
.modal-card{width:min(410px,100%);padding:26px;background:#fff;border:1px solid #d9e9e4;border-radius:16px;box-shadow:0 20px 60px rgba(14,62,55,.2)}
|
||||
:global(html[data-theme="dark"] .relay-node),:global(html[data-theme="dark"] .relay-empty){color:#e8f3f0;background:#202f2c;border-color:#30413d}
|
||||
.modal-icon{display:grid;place-items:center;width:38px;height:38px;color:#087d74;background:#e3f5f0;border-radius:11px}
|
||||
.modal-card h2{margin:16px 0 8px;font-size:20px}
|
||||
.modal-card p{margin:0 0 20px;color:#71817c;font-size:12px;line-height:1.7}
|
||||
:global(html[data-theme="dark"] .webrtc-port-fields){background:#202f2c;border-color:#30413d}
|
||||
:global(html[data-theme="dark"] .port-fields-heading small){color:#9bb0aa}
|
||||
:global(html[data-theme="dark"] .port-inputs input:disabled){color:#9bb0aa;background:#263a35;border-color:#3a514b}
|
||||
:global(html[data-theme="dark"] .welcome-editor){background:#202f2c;border-color:#30413d}
|
||||
:global(html[data-theme="dark"] .welcome-editor select),:global(html[data-theme="dark"] .welcome-editor textarea){color:#e8f3f0;background:#172321;border-color:#30413d}
|
||||
:global(html[data-theme="dark"] .welcome-editor-heading>small){color:#9bb0aa}
|
||||
:global(html[data-theme="dark"] .modal-card){color:#e8f3f0;background:#172321;border-color:#30413d}
|
||||
:global(html[data-theme="dark"] .modal-card p){color:#9bb0aa}
|
||||
@media(max-width:850px){.relay-card{grid-column:auto}.relay-fields{grid-template-columns:1fr}.relay-fields .password-row{grid-column:auto}}
|
||||
@media(max-width:520px){.advanced-card{grid-column:auto}.port-inputs{grid-template-columns:1fr}}
|
||||
@media(max-width:520px){.welcome-editor-heading{grid-template-columns:1fr;gap:6px}}
|
||||
|
||||
/* Server settings are a short form, not a set of independent data feeds.
|
||||
Let each card keep its natural height so a few extra pixels do not create
|
||||
@@ -843,6 +1343,7 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
.connection-person strong,.connection-person small,.connection-detail small{display:block;overflow-wrap:anywhere;word-break:break-word}
|
||||
.connection-person strong{font-size:10px}
|
||||
.connection-person small{margin-top:3px;color:#899792;font-size:8px}
|
||||
.connection-person .connection-route{color:#5f9189;font-weight:600}
|
||||
.connection-detail{display:grid;flex:0 1 58%;justify-items:end;gap:2px;text-align:right}
|
||||
.connection-detail small{color:#899792;font-size:8px}
|
||||
.connection-status{display:inline-flex;padding:3px 6px;border-radius:999px;color:#236c63;background:#e3f3ef;font-size:8px;font-weight:800}
|
||||
|
||||
@@ -36,12 +36,12 @@ import { computed, ref } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
|
||||
type Language = "zh" | "en" | "de";
|
||||
interface DemoMessage { id: number; author: string; time: string; text: string; zhText?: string; enText?: string; mine: boolean }
|
||||
type Language = "zh" | "en" | "de" | "ru" | "ja";
|
||||
interface DemoMessage { id: number; author: string; time: string; text: string; zhText?: string; enText?: string; ruText?: string; jaText?: string; mine: boolean }
|
||||
type Tab = "channel" | "server";
|
||||
const storedLanguage = localStorage.getItem("webspeak:language");
|
||||
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" ? storedLanguage : "zh");
|
||||
const copy = computed(() => language.value === "zh" ? zh : language.value === "de" ? de : en);
|
||||
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" || storedLanguage === "ru" || storedLanguage === "ja" ? storedLanguage : "zh");
|
||||
const copy = computed(() => language.value === "zh" ? zh : language.value === "de" ? de : language.value === "ru" ? ru : language.value === "ja" ? ja : en);
|
||||
const selectedChannelId = ref("quiet");
|
||||
const activeTab = ref<Tab>("channel");
|
||||
const speakingId = ref("illusia");
|
||||
@@ -61,6 +61,8 @@ const messages = ref<DemoMessage[]>([
|
||||
const zh = { languageMenu: "语言", browserClient: "浏览器语音工作台", demoBadge: "演示 — 模拟数据", languageSwitch: "English", back: "返回主页", reconnecting: "连接中断,正在恢复…", restore: "恢复连接", channels: "频道", channel: "频道", simulated: "演示状态", heroLead: "这里展示 WebSpeak 的频道、语音和聊天交互。", online: "人在线", voiceActivity: "语音活动", speakingNow: "正在语音中", speaking: "正在说话…", connected: "已连接", textChannel: "文字频道", chat: "聊天", server: "服务器", emptyChat: "暂无消息", placeholder: "发送一条消息…", voice: "语音", simulationControls: "模拟控制", stopSpeaking: "停止说话", simulateSpeaking: "模拟发言", poke: "戳一戳", simulateReconnect: "模拟重连", demoNote: "此页面不会连接真实 TeamSpeak 服务器。", you: "你", ready: "已就绪", pokedYou: "戳了你一下" };
|
||||
const en = { languageMenu: "Language", browserClient: "Browser voice workspace", demoBadge: "Demo — simulated data", languageSwitch: "中文", back: "Back home", reconnecting: "Connection interrupted, recovering…", restore: "Restore", channels: "Channels", channel: "Channel", simulated: "Simulation", heroLead: "A preview of WebSpeak channels, voice, and chat interactions.", online: "online", voiceActivity: "VOICE ACTIVITY", speakingNow: "Speaking now", speaking: "Speaking…", connected: "Connected", textChannel: "TEXT CHANNEL", chat: "chat", server: "Server", emptyChat: "No messages yet", placeholder: "Send a message…", voice: "Voice", simulationControls: "Simulation controls", stopSpeaking: "Stop speaking", simulateSpeaking: "Simulate speaking", poke: "Poke", simulateReconnect: "Simulate reconnect", demoNote: "This page never connects to a real TeamSpeak server.", you: "You", ready: "Ready", pokedYou: "poked you" };
|
||||
const de = { languageMenu: "Sprache", browserClient: "Sprachbereich im Browser", demoBadge: "Demo — simulierte Daten", languageSwitch: "中文", back: "Zur Startseite", reconnecting: "Verbindung unterbrochen, Wiederherstellung…", restore: "Wiederherstellen", channels: "Kanäle", channel: "Kanal", simulated: "Simulation", heroLead: "Eine Vorschau auf Kanäle, Sprache und Chat von WebSpeak.", online: "online", voiceActivity: "SPRACHAKTIVITÄT", speakingNow: "Spricht gerade", speaking: "Spricht…", connected: "Verbunden", textChannel: "TEXTKANAL", chat: "Chat", server: "Server", emptyChat: "Noch keine Nachrichten", placeholder: "Nachricht senden…", voice: "Sprache", simulationControls: "Simulation steuern", stopSpeaking: "Sprechen stoppen", simulateSpeaking: "Sprechen simulieren", poke: "Anstupsen", simulateReconnect: "Verbindung simulieren", demoNote: "Diese Seite verbindet sich nie mit einem echten TeamSpeak-Server.", you: "Du", ready: "Bereit", pokedYou: "hat dich angestupst" };
|
||||
const ru = { languageMenu: "Язык", browserClient: "Голосовое пространство в браузере", demoBadge: "Демо — симуляция", languageSwitch: "中文", back: "На главную", reconnecting: "Соединение прервано, восстановление…", restore: "Восстановить", channels: "Каналы", channel: "Канал", simulated: "Симуляция", heroLead: "Предпросмотр каналов, голоса и чата WebSpeak.", online: "онлайн", voiceActivity: "ГОЛОСОВАЯ АКТИВНОСТЬ", speakingNow: "Сейчас говорят", speaking: "Говорит…", connected: "Подключён", textChannel: "ТЕКСТОВЫЙ КАНАЛ", chat: "чат", server: "Сервер", emptyChat: "Сообщений пока нет", placeholder: "Написать сообщение…", voice: "Голос", simulationControls: "Управление симуляцией", stopSpeaking: "Остановить речь", simulateSpeaking: "Симулировать речь", poke: "Толкнуть", simulateReconnect: "Симулировать переподключение", demoNote: "Эта страница не подключается к реальному серверу TeamSpeak.", you: "Вы", ready: "Готово", pokedYou: "толкнул вас" };
|
||||
const ja = { languageMenu: "言語", browserClient: "ブラウザ音声ワークスペース", demoBadge: "デモ — シミュレーション", languageSwitch: "中文", back: "ホームに戻る", reconnecting: "接続が中断されました。復旧中…", restore: "復旧", channels: "チャンネル", channel: "チャンネル", simulated: "シミュレーション", heroLead: "WebSpeak のチャンネル、音声、チャットのプレビューです。", online: "人がオンライン", voiceActivity: "音声アクティビティ", speakingNow: "発話中", speaking: "発話中…", connected: "接続済み", textChannel: "テキストチャンネル", chat: "チャット", server: "サーバー", emptyChat: "メッセージはありません", placeholder: "メッセージを送信…", voice: "音声", simulationControls: "シミュレーション操作", stopSpeaking: "発話を停止", simulateSpeaking: "発話をシミュレート", poke: "つつく", simulateReconnect: "再接続をシミュレート", demoNote: "このページは実際の TeamSpeak サーバーには接続しません。", you: "あなた", ready: "準備完了", pokedYou: "あなたをつつきました" };
|
||||
const tabs = computed(() => [{ id: "channel" as const, label: copy.value.channel }, { id: "server" as const, label: copy.value.server }]);
|
||||
const selectedChannel = computed(() => channels.find((channel) => channel.id === selectedChannelId.value) ?? channels[0]);
|
||||
const visibleMessages = computed(() => activeTab.value === "channel" ? messages.value : []);
|
||||
@@ -68,7 +70,7 @@ const visibleMessages = computed(() => activeTab.value === "channel" ? messages.
|
||||
function persistLanguage() { localStorage.setItem("webspeak:language", language.value); }
|
||||
function selectChannel(id: string) { selectedChannelId.value = id; activeTab.value = "channel"; }
|
||||
function toggleSpeaking() { speakingId.value = speakingId.value ? "" : selectedChannel.value.members[0]?.id ?? ""; }
|
||||
function messageText(message: DemoMessage): string { return language.value === "zh" ? message.zhText ?? message.text : message.enText ?? message.text; }
|
||||
function messageText(message: DemoMessage): string { return language.value === "zh" ? message.zhText ?? message.text : language.value === "ru" ? message.ruText ?? message.enText ?? message.text : language.value === "ja" ? message.jaText ?? message.enText ?? message.text : message.enText ?? message.text; }
|
||||
function sendMessage() { const text = draft.value.trim(); if (!text) return; messages.value.push({ id: Date.now(), author: "illusia", time: "now", text, mine: true }); draft.value = ""; }
|
||||
function avatarStyle(name: string) { let hash = 0; for (const char of name) hash = char.charCodeAt(0) + ((hash << 5) - hash); const colors = ["#168f83", "#7b9ed0", "#b99070", "#8b78b9"]; return { background: colors[Math.abs(hash) % colors.length] }; }
|
||||
</script>
|
||||
|
||||
+597
-28
@@ -30,7 +30,7 @@
|
||||
<h2>{{ t('welcomeBack') }}</h2>
|
||||
<p class="card-lead">{{ t('joinLead') }}</p>
|
||||
|
||||
<div v-if="voiceState.error" class="notice error-notice"><span class="notice-symbol">!</span><span>{{ localizedMessage(voiceState.error) }}</span></div>
|
||||
<div v-if="voiceState.error" class="notice error-notice"><span class="notice-symbol">!</span><span class="notice-content"><span>{{ localizedMessage(voiceState.error) }}</span><code v-if="voiceState.errorCode">{{ t('errorCode') }}: {{ visibleErrorCode(voiceState.errorCode) }}</code></span></div>
|
||||
<div v-if="browserError" class="notice warning-notice"><span class="notice-symbol">i</span><span>{{ localizedMessage(browserError) }}</span></div>
|
||||
<div v-if="!serverConfigLoading && !initialized" class="notice warning-notice"><span class="notice-symbol">i</span><span>{{ t('notConfigured') }} <a href="/admin">{{ t('configureNow') }}</a></span></div>
|
||||
<div v-if="!localPersistenceAvailable" class="notice warning-notice"><span class="notice-symbol">i</span><span>{{ t('localPersistenceUnavailable') }}</span></div>
|
||||
@@ -41,6 +41,7 @@
|
||||
<label class="field-label" for="server-port"><span>{{ t('serverPort') }}</span><div class="field-wrap"><Icon name="hash" :size="17" /><input id="server-port" v-model="serverPort" inputmode="numeric" type="text" maxlength="5" :placeholder="t('serverPortPlaceholder')" /></div></label>
|
||||
</div>
|
||||
<p v-if="accessMode === 'open'" class="field-hint">{{ t('serverAddressHint') }}</p>
|
||||
<div v-if="accelerationAvailable" class="acceleration-choice"><div class="acceleration-copy"><strong>{{ t('relayAcceleration') }}</strong><small>{{ t('relayAccelerationHint') }}</small></div><select v-model="accelerationRelayId" :aria-label="t('relayAcceleration')"><option value="">{{ t('directConnection') }}</option><option v-for="relay in accelerationRelays" :key="relay.id" :value="relay.id">{{ relay.name }}</option></select></div>
|
||||
<div v-if="accessMode === 'open' && (favoriteServers.length || recentServers.length)" class="local-servers">
|
||||
<div v-if="favoriteServers.length" class="local-server-group"><span>{{ t('favoriteServers') }}</span><button v-for="favorite in favoriteServers" :key="favorite.id" type="button" @click="selectLocalServer(favorite.address, favorite.nickname)">{{ favorite.label }}</button></div>
|
||||
<div v-if="recentServers.length" class="local-server-group"><span>{{ t('recentServers') }}</span><button v-for="recent in recentServers" :key="recent.id" type="button" @click="selectLocalServer(recent.address, recent.nickname)">{{ recent.address }}</button></div>
|
||||
@@ -121,6 +122,7 @@
|
||||
<div class="reconnect-copy"><strong>{{ voiceState.reconnectFailed ? t('reconnectFailed') : t('connectionInterrupted') }}</strong><span v-if="voiceState.reconnecting">{{ t('reconnectingAttempt', { attempt: voiceState.reconnectAttempt }) }}</span><span v-else>{{ localizedMessage(voiceState.error) }}</span></div>
|
||||
<div class="reconnect-actions"><button v-if="voiceState.reconnectFailed" type="button" class="secondary-button" @click="reconnectNow">{{ t('reconnectNow') }}</button><button type="button" class="text-button" @click="doDisconnect">{{ t('back') }}</button></div>
|
||||
</div>
|
||||
<div v-if="voiceState.audioNotice" class="reconnect-banner degraded" role="status"><div class="reconnect-copy"><strong>{{ t('audioStatus') }}</strong><span>{{ localizedAudioNotice(voiceState.audioNoticeCode, voiceState.audioNotice) }}</span></div></div>
|
||||
<div v-for="poke in visiblePokes" :key="poke.id" class="poke-banner" role="status"><Icon name="bell" :size="17" /><span><strong>{{ poke.invokerName }}</strong> {{ t('pokedYou') }}<small v-if="poke.message">:{{ poke.message }}</small></span><button type="button" @click="dismissPoke(poke.id)"><Icon name="close" :size="15" /></button></div>
|
||||
|
||||
<div class="workspace-scroll">
|
||||
@@ -213,12 +215,23 @@
|
||||
</div>
|
||||
<div v-if="!filteredMemberChannels.length" class="member-empty">{{ t('noMatchingMembers') }}</div>
|
||||
<div v-if="!isMobileViewport" class="desktop-audio-dock" role="toolbar" :aria-label="t('desktopAudioControls')">
|
||||
<div class="desktop-audio-dock-copy"><strong>{{ t('desktopAudioControls') }}</strong><span>{{ accompanimentActive ? t('accompanimentActive') : t('volumeTip') }}</span></div>
|
||||
<div class="desktop-audio-dock-copy"><strong>{{ t('desktopAudioControls') }}</strong><span>{{ accompanimentActive ? t('accompanimentActive') : t('desktopAudioHint') }}</span></div>
|
||||
<div class="desktop-audio-dock-actions">
|
||||
<button type="button" class="dock-audio-button microphone-header-toggle" :class="{ muted: microphoneMuted }" :title="microphoneMuted ? t('unmuteMic') : t('muteMic')" :aria-label="microphoneMuted ? t('microphoneMuted') : t('microphoneActive')" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /></button>
|
||||
<div class="dock-output-control">
|
||||
<button type="button" class="dock-audio-button" :class="{ muted: outputMuted }" :title="outputMuted ? t('unmuteOutput') : t('muteOutput')" :aria-label="outputMuted ? t('unmuteOutput') : t('muteOutput')" :aria-pressed="!outputMuted" @click="toggleOutputMute"><Icon :name="outputMuted ? 'volume-off' : 'volume'" :size="18" /></button>
|
||||
<input class="dock-output-slider" type="range" min="0" max="100" :value="outputVolume * 100" :style="rangeStyle(outputVolume, 1)" :aria-label="t('overallVolume')" @input="onOutputVolume" />
|
||||
<div class="dock-hover-control">
|
||||
<button type="button" class="dock-audio-button microphone-header-toggle" :class="{ muted: microphoneMuted }" :title="microphoneMuted ? t('unmuteMic') : t('muteMic')" :aria-label="microphoneMuted ? t('microphoneMuted') : t('microphoneActive')" :aria-pressed="!microphoneMuted" aria-haspopup="dialog" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /></button>
|
||||
<div class="dock-hover-panel dock-microphone-panel" role="dialog" :aria-label="t('microphone')">
|
||||
<div class="dock-slider-heading"><span>{{ t('inputVolume') }}</span><strong>{{ Math.round(inputVolume * 100) }}%</strong></div>
|
||||
<input class="dock-slider" type="range" min="0" max="100" :value="inputVolume * 100" :style="rangeStyle(inputVolume, 1)" :aria-label="t('inputVolume')" @input="onInputVolume" />
|
||||
<div class="dock-panel-divider"></div>
|
||||
<label class="dock-switch-row"><span><strong>{{ t('noiseSuppression') }}</strong></span><input type="checkbox" :checked="noiseSuppressionEnabled" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionToggle" /></label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dock-hover-control">
|
||||
<button type="button" class="dock-audio-button" :class="{ muted: outputMuted }" :title="outputMuted ? t('unmuteOutput') : t('muteOutput')" :aria-label="outputMuted ? t('unmuteOutput') : t('muteOutput')" :aria-pressed="!outputMuted" aria-haspopup="dialog" @click="toggleOutputMute"><Icon :name="outputMuted ? 'volume-off' : 'volume'" :size="18" /></button>
|
||||
<div class="dock-hover-panel dock-output-panel" role="dialog" :aria-label="t('overallVolume')">
|
||||
<div class="dock-slider-heading"><span>{{ t('overallVolume') }}</span><strong>{{ Math.round(outputVolume * 100) }}%</strong></div>
|
||||
<input class="dock-slider" type="range" min="0" max="100" :value="outputVolume * 100" :style="rangeStyle(outputVolume, 1)" :aria-label="t('overallVolume')" @input="onOutputVolume" />
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="dock-audio-button" :title="t('audioSettings')" :aria-label="t('audioSettings')" @click="settingsOpen = true"><Icon name="settings" :size="18" /></button>
|
||||
<button type="button" class="dock-audio-button accompaniment-toggle" :class="{ active: accompanimentActive }" :title="accompanimentActive ? t('stopAccompaniment') : t('startAccompaniment')" :aria-label="accompanimentActive ? t('stopAccompaniment') : t('startAccompaniment')" :aria-pressed="accompanimentActive" @click="toggleAccompaniment"><Icon name="music" :size="18" /></button>
|
||||
@@ -271,12 +284,28 @@
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- TeamSpeak server password modal -->
|
||||
<div v-if="serverPasswordDialog.open" class="modal-backdrop channel-password-backdrop" @click.self="cancelServerPassword">
|
||||
<section class="channel-password-modal server-password-modal" role="dialog" aria-modal="true" :aria-labelledby="'server-password-title'" @click.stop>
|
||||
<button type="button" class="qq-modal-close" :aria-label="t('close')" :title="t('close')" @click="cancelServerPassword"><Icon name="close" :size="19" /></button>
|
||||
<div class="channel-password-icon"><Icon name="lock" :size="22" /></div>
|
||||
<span class="card-kicker">{{ t('serverPasswordPrompt') }}</span>
|
||||
<h2 id="server-password-title">{{ t('serverPasswordTitle') }}</h2>
|
||||
<p>{{ serverPasswordDialog.errorCode === 'INVALID_SERVER_PASSWORD' ? t('serverPasswordInvalidLead') : t('serverPasswordRequiredLead') }}</p>
|
||||
<form class="channel-password-form" @submit.prevent="submitServerPassword">
|
||||
<label class="field-label" for="retry-server-password-input">{{ t('serverPasswordPrompt') }}</label>
|
||||
<div class="field-wrap"><Icon name="lock" :size="17" /><input id="retry-server-password-input" v-model="serverPasswordDialog.password" type="password" autocomplete="current-password" :placeholder="t('serverPasswordRetryPlaceholder')" autofocus /></div>
|
||||
<div class="channel-password-actions"><button type="button" class="text-button" @click="cancelServerPassword">{{ t('channelPasswordCancel') }}</button><button type="submit" class="primary-button channel-password-submit" :disabled="!serverPasswordDialog.password"><span>{{ t('serverPasswordRetry') }}</span><Icon name="chevron-right" :size="17" /></button></div>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- Audio settings modal -->
|
||||
<div v-if="settingsOpen" class="modal-backdrop" @click.self="settingsOpen = false">
|
||||
<section class="settings-modal" role="dialog" aria-modal="true" :aria-labelledby="'settings-title'">
|
||||
<div class="settings-main"><header class="settings-header"><h2 id="settings-title">{{ t('audioConfiguration') }}</h2><button class="round-icon" :title="t('close')" @click="settingsOpen = false"><Icon name="close" :size="19" /></button></header><div class="settings-content">
|
||||
<section class="settings-section"><h3><Icon name="mic" :size="20" /> {{ t('inputDevice') }}</h3><label class="settings-label" for="input-device">{{ t('microphone') }}</label><select id="input-device" class="settings-select" :value="selectedInputDeviceId" :disabled="!inputDevices.length" @change="onInputDeviceChange"><option value="">{{ t('defaultMicrophone') }}</option><option v-for="(device, index) in inputDevices" :key="device.deviceId || `microphone-${index}`" :value="device.deviceId">{{ device.label || t('microphoneNumber', { index: index + 1 }) }}</option></select><p v-if="audioSettingsError" class="settings-error">{{ localizedMessage(audioSettingsError) }}</p><p class="audio-diagnostic"><span>{{ t('permission') }}</span><strong :class="`permission-${audioPermission}`">{{ audioPermission === 'granted' ? t('permissionGranted') : audioPermission === 'denied' ? t('permissionDenied') : t('permissionUnknown') }}</strong></p><div class="microphone-control"><div><label class="settings-label">{{ t('microphoneState') }}</label><p class="settings-hint">{{ microphoneMuted ? t('microphoneMutedHint') : t('microphoneActiveHint') }}</p></div><button type="button" class="microphone-toggle" :class="{ muted: microphoneMuted }" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="16" /> {{ microphoneMuted ? t('unmuteMic') : t('muteMic') }}</button></div><div class="settings-range-row"><label class="settings-label">{{ t('inputVolume') }}</label><strong>{{ Math.round(inputVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="inputVolume * 100" :style="rangeStyle(inputVolume, 1)" :aria-label="t('inputVolume')" @input="onInputVolume" /><div class="settings-range-row"><label class="settings-label">{{ t('voxThreshold') }}</label><strong>{{ (voxThreshold * 100).toFixed(1) }}%</strong></div><input class="settings-range" type="range" min="1" max="80" :value="voxThreshold * 1000" :style="rangeStyle(voxThreshold, 0.08)" :aria-label="t('voxThreshold')" @input="onVoxThreshold" /><div class="audio-level-row"><span>{{ t('micLevel') }}</span><strong>{{ Math.round(micLevel * 100) }}%</strong></div><div class="audio-level-track"><i :style="{ width: `${Math.round(micLevel * 100)}%` }"></i></div><div class="mic-test"><div class="mic-test-header"><strong>{{ t('microphoneTest') }}</strong><button type="button" @click="toggleMicTest">{{ microphoneTestActive ? t('stopTest') : t('startTest') }}</button></div><div class="meter"><i v-for="index in 24" :key="index" :class="{ active: microphoneTestActive && index <= micMeterBars }" :style="{ height: `${meterBarHeight(index) }px` }"></i></div><div class="meter-labels"><span>{{ t('silence') }}</span><span>{{ t('optimal') }}</span><span>{{ t('loud') }}</span></div><p class="settings-hint">{{ t('localMicTestHint') }}</p><audio v-if="testAudioUrl" class="test-audio" :src="testAudioUrl" controls :aria-label="t('microphoneTest')"></audio></div></section>
|
||||
<div class="settings-separator"></div><section class="settings-section"><h3><Icon name="volume" :size="20" /> {{ t('outputVolume') }}</h3><label v-if="outputDeviceSupported" class="settings-label" for="output-device">{{ t('outputDevice') }}</label><select v-if="outputDeviceSupported" id="output-device" class="settings-select" :value="selectedOutputDeviceId" :disabled="!outputDevices.length" @change="onOutputDeviceChange"><option value="">{{ t('defaultOutput') }}</option><option v-for="(device, index) in outputDevices" :key="device.deviceId || `speaker-${index}`" :value="device.deviceId">{{ device.label || t('speakerNumber', { index: index + 1 }) }}</option></select><p v-else class="mode-note"><Icon name="info" :size="16" /><span>{{ t('outputDeviceUnsupported') }}</span></p><div class="settings-range-row"><label class="settings-label">{{ t('speakers') }}</label><strong>{{ Math.round(outputVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="outputVolume * 100" :style="rangeStyle(outputVolume, 1)" :aria-label="t('outputVolume')" @input="onOutputVolume" /><div class="settings-range-row"><label class="settings-label">{{ t('notificationVolume') }}</label><strong>{{ Math.round(notificationVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="notificationVolume * 100" :style="rangeStyle(notificationVolume, 1)" :aria-label="t('notificationVolume')" @input="onNotificationVolume" /><div class="audio-diagnostic"><span>{{ t('audioStatus') }}</span><strong>{{ audioContextState === 'running' ? t('audioReady') : audioContextState === 'suspended' ? t('audioSuspended') : t('audioUnknown') }}</strong></div><div class="mode-note"><Icon name="shield" :size="16" /><span>{{ t('audioPrivacy') }}</span></div></section>
|
||||
<section class="settings-section"><h3><Icon name="mic" :size="20" /> {{ t('inputDevice') }}</h3><label class="settings-label" for="input-device">{{ t('microphone') }}</label><select id="input-device" class="settings-select" :value="selectedInputDeviceId" :disabled="!inputDevices.length" @change="onInputDeviceChange"><option value="">{{ t('defaultMicrophone') }}</option><option v-for="(device, index) in inputDevices" :key="device.deviceId || `microphone-${index}`" :value="device.deviceId">{{ device.label || t('microphoneNumber', { index: index + 1 }) }}</option></select><p v-if="audioSettingsError" class="settings-error">{{ localizedMessage(audioSettingsError) }}</p><p class="audio-diagnostic"><span>{{ t('permission') }}</span><strong :class="`permission-${audioPermission}`">{{ audioPermission === 'granted' ? t('permissionGranted') : audioPermission === 'denied' ? t('permissionDenied') : t('permissionUnknown') }}</strong></p><div class="microphone-control"><div><label class="settings-label">{{ t('microphoneState') }}</label><p class="settings-hint">{{ microphoneMuted ? t('microphoneMutedHint') : t('microphoneActiveHint') }}</p></div><button type="button" class="microphone-toggle" :class="{ muted: microphoneMuted }" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="16" /> {{ microphoneMuted ? t('unmuteMic') : t('muteMic') }}</button></div><label v-if="isMobileViewport" class="mobile-noise-toggle"><span><strong>{{ t('noiseSuppression') }}</strong><small>{{ t('noiseSuppressionHint') }}</small></span><input type="checkbox" :checked="noiseSuppressionEnabled" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionToggle" /></label><template v-if="isMobileViewport"><div class="settings-range-row"><label class="settings-label">{{ t('inputVolume') }}</label><strong>{{ Math.round(inputVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="inputVolume * 100" :style="rangeStyle(inputVolume, 1)" :aria-label="t('inputVolume')" @input="onInputVolume" /></template><div class="settings-range-row"><label class="settings-label">{{ t('voxThreshold') }}</label><strong>{{ (voxThreshold * 100).toFixed(1) }}%</strong></div><input class="settings-range" type="range" min="1" max="80" :value="voxThreshold * 1000" :style="rangeStyle(voxThreshold, 0.08)" :aria-label="t('voxThreshold')" @input="onVoxThreshold" /><div class="audio-level-row"><span>{{ t('micLevel') }}</span><strong>{{ Math.round(micLevel * 100) }}%</strong></div><div class="audio-level-track"><i :style="{ width: `${Math.round(micLevel * 100)}%` }"></i></div><div class="mic-test"><div class="mic-test-header"><strong>{{ t('microphoneTest') }}</strong><button type="button" @click="toggleMicTest">{{ microphoneTestActive ? t('stopTest') : t('startTest') }}</button></div><div class="meter"><i v-for="index in 24" :key="index" :class="{ active: microphoneTestActive && index <= micMeterBars }" :style="{ height: `${meterBarHeight(index) }px` }"></i></div><div class="meter-labels"><span>{{ t('silence') }}</span><span>{{ t('optimal') }}</span><span>{{ t('loud') }}</span></div><p class="settings-hint">{{ t('localMicTestHint') }}</p><audio v-if="testAudioUrl" class="test-audio" :src="testAudioUrl" controls :aria-label="t('microphoneTest')"></audio></div></section>
|
||||
<div class="settings-separator"></div><section class="settings-section"><h3><Icon name="volume" :size="20" /> {{ t('outputVolume') }}</h3><label v-if="outputDeviceSupported" class="settings-label" for="output-device">{{ t('outputDevice') }}</label><select v-if="outputDeviceSupported" id="output-device" class="settings-select" :value="selectedOutputDeviceId" :disabled="!outputDevices.length" @change="onOutputDeviceChange"><option value="">{{ t('defaultOutput') }}</option><option v-for="(device, index) in outputDevices" :key="device.deviceId || `speaker-${index}`" :value="device.deviceId">{{ device.label || t('speakerNumber', { index: index + 1 }) }}</option></select><p v-else class="mode-note"><Icon name="info" :size="16" /><span>{{ t('outputDeviceUnsupported') }}</span></p><template v-if="isMobileViewport"><div class="settings-range-row"><label class="settings-label">{{ t('speakers') }}</label><strong>{{ Math.round(outputVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="outputVolume * 100" :style="rangeStyle(outputVolume, 1)" :aria-label="t('outputVolume')" @input="onOutputVolume" /></template><div class="settings-range-row"><label class="settings-label">{{ t('notificationVolume') }}</label><strong>{{ Math.round(notificationVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="notificationVolume * 100" :style="rangeStyle(notificationVolume, 1)" :aria-label="t('notificationVolume')" @input="onNotificationVolume" /><div class="audio-diagnostic"><span>{{ t('audioStatus') }}</span><strong>{{ audioContextState === 'running' ? (voiceState.microphoneError ? t('audioUnavailable') : t('audioReady')) : audioContextState === 'suspended' ? t('audioSuspended') : t('audioUnknown') }}</strong></div><p v-if="voiceState.microphoneError" class="settings-error">{{ localizedMessage(voiceState.microphoneError) }}</p><div class="mode-note"><Icon name="shield" :size="16" /><span>{{ t('audioPrivacy') }}</span></div></section>
|
||||
</div><footer class="settings-footer"><button class="primary-button save-button" @click="settingsOpen = false">{{ t('done') }}</button></footer></div>
|
||||
</section>
|
||||
</div>
|
||||
@@ -307,6 +336,7 @@ const {
|
||||
serverEvents,
|
||||
pokeNotifications,
|
||||
microphoneMuted,
|
||||
noiseSuppressionEnabled,
|
||||
inputVolume,
|
||||
outputVolume,
|
||||
outputMuted,
|
||||
@@ -329,6 +359,7 @@ const {
|
||||
whisperActive,
|
||||
setVolume,
|
||||
setInputVolume,
|
||||
setNoiseSuppressionEnabled,
|
||||
setOutputVolume,
|
||||
toggleOutputMute,
|
||||
setVoxThreshold,
|
||||
@@ -378,7 +409,13 @@ const initialized = ref(false);
|
||||
const siteName = ref("WebSpeak");
|
||||
const welcomeTextZh = ref("");
|
||||
const welcomeTextEn = ref("");
|
||||
const appVersion = ref("0.1.2");
|
||||
const welcomeTextDe = ref("");
|
||||
const welcomeTextRu = ref("");
|
||||
const welcomeTextJa = ref("");
|
||||
const appVersion = ref("0.2.2");
|
||||
const accelerationRelays = ref<Array<{ id: string; name: string }>>([]);
|
||||
const accelerationRelayId = ref("");
|
||||
const accelerationAvailable = computed(() => accelerationRelays.value.length > 0);
|
||||
const browserError = ref("");
|
||||
const serverConfigLoading = ref(true);
|
||||
const memberQuery = ref("");
|
||||
@@ -386,6 +423,7 @@ const messageDraft = ref("");
|
||||
const selectedChannelId = ref("");
|
||||
const settingsOpen = ref(false);
|
||||
const channelPasswordDialog = reactive({ open: false, channelId: "", password: "", error: "", submitting: false });
|
||||
const serverPasswordDialog = reactive({ open: false, password: "", errorCode: "" });
|
||||
const qqModalOpen = ref(false);
|
||||
const qqJoinUrl = "http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475";
|
||||
const audioSettingsError = ref("");
|
||||
@@ -412,12 +450,21 @@ let performanceTimer: number | null = null;
|
||||
let performanceMonitorGeneration = 0;
|
||||
let toastTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
type Language = "zh" | "en" | "de";
|
||||
type Language = "zh" | "en" | "de" | "ru" | "ja";
|
||||
const language = ref<Language>(getInitialLanguage());
|
||||
const themeMode = ref<ThemeMode>(getStoredTheme());
|
||||
const themeIcon = computed(() => isDarkTheme(themeMode.value) ? "sun" : "moon");
|
||||
const themeLabel = computed(() => isDarkTheme(themeMode.value) ? t("switchToLightTheme") : t("switchToDarkTheme"));
|
||||
const localizedWelcomeText = computed(() => (language.value === "en" ? welcomeTextEn.value : welcomeTextZh.value) || t("joinDescription"));
|
||||
const localizedWelcomeText = computed(() => {
|
||||
const customText = {
|
||||
zh: welcomeTextZh.value,
|
||||
en: welcomeTextEn.value,
|
||||
de: welcomeTextDe.value,
|
||||
ru: welcomeTextRu.value,
|
||||
ja: welcomeTextJa.value,
|
||||
}[language.value];
|
||||
return customText || t("joinDescription");
|
||||
});
|
||||
applyTheme(themeMode.value);
|
||||
const translations: Record<string, Record<string, string>> = {
|
||||
zh: {
|
||||
@@ -430,6 +477,7 @@ const translations: Record<string, Record<string, string>> = {
|
||||
secureGateway: "安全语音网关",
|
||||
adminConsole: "管理控制台",
|
||||
currentVersion: "当前版本",
|
||||
errorCode: "错误代码",
|
||||
viewChangelog: "查看更新日志",
|
||||
notConfigured: "WebSpeak 尚未配置 TeamSpeak 目标。",
|
||||
configureNow: "打开管理控制台",
|
||||
@@ -454,6 +502,9 @@ const translations: Record<string, Record<string, string>> = {
|
||||
serverPort: "语音端口",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "这是网关服务器连接的 TeamSpeak 地址和端口,不是浏览器直接连接地址。",
|
||||
relayAcceleration: "连接中继",
|
||||
directConnection: "直连 TeamSpeak",
|
||||
relayAccelerationHint: "选择一个已配置的中继节点,适合直连不稳定或被拒绝的服务器。",
|
||||
nickname: "你的昵称",
|
||||
nicknamePlaceholder: "例如:Alex Rivera",
|
||||
targetChannel: "目标频道",
|
||||
@@ -498,6 +549,7 @@ const translations: Record<string, Record<string, string>> = {
|
||||
muteOutput: "临时静音",
|
||||
unmuteOutput: "恢复声音",
|
||||
desktopAudioControls: "音频控制",
|
||||
desktopAudioHint: "悬停图标调整音量",
|
||||
startAccompaniment: "共享伴奏",
|
||||
stopAccompaniment: "停止伴奏",
|
||||
accompanimentStarted: "伴奏共享已开始",
|
||||
@@ -509,6 +561,12 @@ const translations: Record<string, Record<string, string>> = {
|
||||
accompanimentUnsupported: "当前浏览器不支持伴奏共享",
|
||||
serverPassword: "服务器密码",
|
||||
optionalPassword: "没有密码可留空",
|
||||
serverPasswordTitle: "服务器需要密码",
|
||||
serverPasswordPrompt: "输入服务器密码",
|
||||
serverPasswordRequiredLead: "该服务器需要密码,输入密码后重试。",
|
||||
serverPasswordInvalidLead: "服务器密码不正确,请重新输入后重试。",
|
||||
serverPasswordRetry: "输入密码并重试",
|
||||
serverPasswordRetryPlaceholder: "请输入服务器密码",
|
||||
switchChannel: "切换频道",
|
||||
searchChannels: "搜索频道",
|
||||
voiceChannels: "语音频道",
|
||||
@@ -643,6 +701,16 @@ const translations: Record<string, Record<string, string>> = {
|
||||
notificationVolume: "通知音量",
|
||||
audioStatus: "音频状态",
|
||||
audioReady: "音频已就绪",
|
||||
noiseSuppression: "浏览器降噪",
|
||||
noiseSuppressionHint: "在浏览器采集端处理",
|
||||
rnnoise: "RNNoise 降噪",
|
||||
echoCancellation: "回声消除",
|
||||
autoGainControl: "自动增益",
|
||||
processingEnabled: "已启用",
|
||||
processingDisabled: "已关闭",
|
||||
processingUnknown: "浏览器未报告",
|
||||
audioUnavailable: "音频不可用(麦克风故障)",
|
||||
microphoneUnavailable: "麦克风不可用,你暂时无法说话",
|
||||
audioSuspended: "音频被浏览器暂停",
|
||||
audioUnknown: "尚未初始化",
|
||||
audioPrivacy: "WebSpeak 会在浏览器安全上下文中处理音频,不会保存录音。",
|
||||
@@ -687,6 +755,7 @@ const translations: Record<string, Record<string, string>> = {
|
||||
secureGateway: "Secure voice gateway",
|
||||
adminConsole: "Admin console",
|
||||
currentVersion: "Current version",
|
||||
errorCode: "Error code",
|
||||
viewChangelog: "View changelog",
|
||||
notConfigured: "The WebSpeak TeamSpeak target has not been configured.",
|
||||
configureNow: "Open admin console",
|
||||
@@ -711,6 +780,9 @@ const translations: Record<string, Record<string, string>> = {
|
||||
serverPort: "Voice port",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "This is the TeamSpeak address and port reached by the gateway, not a direct browser connection.",
|
||||
relayAcceleration: "Connection relay",
|
||||
directConnection: "Direct TeamSpeak connection",
|
||||
relayAccelerationHint: "Choose a configured relay when the direct path is unstable or blocked.",
|
||||
nickname: "Your nickname",
|
||||
nicknamePlaceholder: "e.g. Alex Rivera",
|
||||
targetChannel: "Target channel",
|
||||
@@ -755,6 +827,7 @@ const translations: Record<string, Record<string, string>> = {
|
||||
muteOutput: "Mute all audio",
|
||||
unmuteOutput: "Restore audio",
|
||||
desktopAudioControls: "Audio controls",
|
||||
desktopAudioHint: "Hover an icon to adjust volume",
|
||||
startAccompaniment: "Share accompaniment",
|
||||
stopAccompaniment: "Stop accompaniment",
|
||||
accompanimentStarted: "Accompaniment sharing started",
|
||||
@@ -766,6 +839,12 @@ const translations: Record<string, Record<string, string>> = {
|
||||
accompanimentUnsupported: "This browser does not support accompaniment sharing",
|
||||
serverPassword: "Server password",
|
||||
optionalPassword: "Leave blank if not required",
|
||||
serverPasswordTitle: "Server password required",
|
||||
serverPasswordPrompt: "Enter server password",
|
||||
serverPasswordRequiredLead: "This TeamSpeak server requires a password. Enter it and try again.",
|
||||
serverPasswordInvalidLead: "The server password was rejected. Enter it again and retry.",
|
||||
serverPasswordRetry: "Enter password and retry",
|
||||
serverPasswordRetryPlaceholder: "Enter the server password",
|
||||
switchChannel: "Switch channel",
|
||||
searchChannels: "Search channels",
|
||||
voiceChannels: "Voice channels",
|
||||
@@ -900,6 +979,16 @@ const translations: Record<string, Record<string, string>> = {
|
||||
notificationVolume: "Notification volume",
|
||||
audioStatus: "Audio status",
|
||||
audioReady: "Audio ready",
|
||||
noiseSuppression: "Browser noise suppression",
|
||||
noiseSuppressionHint: "Process audio in the browser",
|
||||
rnnoise: "RNNoise suppression",
|
||||
echoCancellation: "Echo cancellation",
|
||||
autoGainControl: "Automatic gain control",
|
||||
processingEnabled: "Enabled",
|
||||
processingDisabled: "Disabled",
|
||||
processingUnknown: "Not reported by browser",
|
||||
audioUnavailable: "Audio unavailable (microphone failure)",
|
||||
microphoneUnavailable: "Microphone unavailable — others cannot hear you",
|
||||
audioSuspended: "Audio paused by the browser",
|
||||
audioUnknown: "Not initialized",
|
||||
audioPrivacy: "WebSpeak processes audio in the browser's secure context and does not save recordings.",
|
||||
@@ -947,6 +1036,7 @@ translations.de = {
|
||||
secureGateway: "Sicheres Sprach-Gateway",
|
||||
adminConsole: "Administrationskonsole",
|
||||
currentVersion: "Aktuelle Version",
|
||||
errorCode: "Fehlercode",
|
||||
viewChangelog: "Änderungsprotokoll ansehen",
|
||||
notConfigured: "Das TeamSpeak-Ziel von WebSpeak wurde noch nicht konfiguriert.",
|
||||
configureNow: "Administrationskonsole öffnen",
|
||||
@@ -971,6 +1061,9 @@ translations.de = {
|
||||
serverPort: "Sprachport",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "Dies ist die TeamSpeak-Adresse und der Port, die vom Gateway erreicht werden – keine direkte Browseradresse.",
|
||||
relayAcceleration: "Verbindungs-Relay",
|
||||
directConnection: "Direkte TeamSpeak-Verbindung",
|
||||
relayAccelerationHint: "Wähle einen konfigurierten Relay, wenn die direkte Verbindung instabil ist oder abgelehnt wird.",
|
||||
nickname: "Dein Name",
|
||||
nicknamePlaceholder: "z. B. Alex Rivera",
|
||||
targetChannel: "Zielkanal",
|
||||
@@ -1015,6 +1108,7 @@ translations.de = {
|
||||
muteOutput: "Alle Töne stummschalten",
|
||||
unmuteOutput: "Ton wiederherstellen",
|
||||
desktopAudioControls: "Audiosteuerung",
|
||||
desktopAudioHint: "Bewege den Zeiger über ein Symbol, um die Lautstärke anzupassen",
|
||||
startAccompaniment: "Begleitung teilen",
|
||||
stopAccompaniment: "Begleitung stoppen",
|
||||
accompanimentStarted: "Begleitung wird geteilt",
|
||||
@@ -1026,6 +1120,12 @@ translations.de = {
|
||||
accompanimentUnsupported: "Dieser Browser unterstützt das Teilen von Begleitung nicht.",
|
||||
serverPassword: "Serverpasswort",
|
||||
optionalPassword: "Leer lassen, wenn kein Passwort erforderlich ist",
|
||||
serverPasswordTitle: "Serverpasswort erforderlich",
|
||||
serverPasswordPrompt: "Serverpasswort eingeben",
|
||||
serverPasswordRequiredLead: "Dieser TeamSpeak-Server benötigt ein Passwort. Gib es ein und versuche es erneut.",
|
||||
serverPasswordInvalidLead: "Das Serverpasswort wurde abgelehnt. Gib es erneut ein und versuche es noch einmal.",
|
||||
serverPasswordRetry: "Passwort eingeben und erneut versuchen",
|
||||
serverPasswordRetryPlaceholder: "Serverpasswort eingeben",
|
||||
switchChannel: "Kanal wechseln",
|
||||
searchChannels: "Kanäle suchen",
|
||||
voiceChannels: "Sprachkanäle",
|
||||
@@ -1160,6 +1260,16 @@ translations.de = {
|
||||
notificationVolume: "Benachrichtigungslautstärke",
|
||||
audioStatus: "Audiostatus",
|
||||
audioReady: "Audio bereit",
|
||||
noiseSuppression: "Browser-Geräuschunterdrückung",
|
||||
noiseSuppressionHint: "Verarbeitung bei der Aufnahme im Browser",
|
||||
rnnoise: "RNNoise-Geräuschunterdrückung",
|
||||
echoCancellation: "Echounterdrückung",
|
||||
autoGainControl: "Automatische Verstärkungsregelung",
|
||||
processingEnabled: "Aktiviert",
|
||||
processingDisabled: "Deaktiviert",
|
||||
processingUnknown: "Vom Browser nicht gemeldet",
|
||||
audioUnavailable: "Audio nicht verfügbar (Mikrofonfehler)",
|
||||
microphoneUnavailable: "Mikrofon nicht verfügbar – andere können dich nicht hören",
|
||||
audioSuspended: "Audio wurde vom Browser pausiert",
|
||||
audioUnknown: "Nicht initialisiert",
|
||||
audioPrivacy: "WebSpeak verarbeitet Audio im sicheren Browserkontext und speichert keine Aufnahmen.",
|
||||
@@ -1192,7 +1302,151 @@ translations.de = {
|
||||
measureComplete: "Laufende Messung (alle 3 Sekunden)",
|
||||
measureNow: "Jetzt messen",
|
||||
measureUnavailable: "Nach der Verbindung verfügbar",
|
||||
langSwitch: "中文",
|
||||
langSwitch: "中文",
|
||||
};
|
||||
|
||||
translations.ru = {
|
||||
...translations.en,
|
||||
themeSystem: "Системная тема",
|
||||
themeLight: "Светлая тема",
|
||||
themeDark: "Тёмная тема",
|
||||
switchToLightTheme: "Включить светлую тему",
|
||||
switchToDarkTheme: "Включить тёмную тему",
|
||||
browserWorkspace: "Голосовое пространство в браузере",
|
||||
secureGateway: "Безопасный голосовой шлюз",
|
||||
adminConsole: "Панель администратора",
|
||||
currentVersion: "Текущая версия",
|
||||
errorCode: "Код ошибки",
|
||||
viewChangelog: "Открыть журнал изменений",
|
||||
notConfigured: "Цель TeamSpeak ещё не настроена в WebSpeak.",
|
||||
configureNow: "Открыть панель администратора",
|
||||
privateAudio: "Приватное голосовое сообщество",
|
||||
joinLine1: "Подключитесь к серверу,",
|
||||
joinLine2: "и начните общение.",
|
||||
joinDescription: "Клиент TeamSpeak устанавливать не нужно. Откройте браузер и присоединитесь к голосовому каналу с низкой задержкой.",
|
||||
overallVolume: "Общая громкость",
|
||||
inputVolume: "Громкость микрофона",
|
||||
desktopAudioControls: "Управление звуком",
|
||||
desktopAudioHint: "Наведите на значок, чтобы изменить громкость",
|
||||
noiseSuppression: "Шумоподавление",
|
||||
noiseSuppressionHint: "Обработка звука при захвате в браузере",
|
||||
highQuality: "Качественный звук",
|
||||
opusAudio: "Передача Opus с низкой задержкой",
|
||||
secureJoin: "Безопасное подключение",
|
||||
inviteProtected: "Сервер защищён ссылкой-приглашением",
|
||||
realtime: "Синхронизация в реальном времени",
|
||||
membersSync: "Участники каналов всегда синхронизированы",
|
||||
privateServer: "Приватный голосовой сервер",
|
||||
joinServer: "Войти на сервер",
|
||||
welcomeBack: "С возвращением",
|
||||
joinLead: "Выберите имя и канал для входа.",
|
||||
serverAddress: "Адрес сервера TeamSpeak",
|
||||
serverAddressPlaceholder: "например, ts.example.com или 127.0.0.1",
|
||||
serverPort: "Голосовой порт",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "Это адрес и порт TeamSpeak, к которым обращается шлюз, а не прямое подключение браузера.",
|
||||
relayAcceleration: "Подключение через ретранслятор",
|
||||
directConnection: "Прямое подключение к TeamSpeak",
|
||||
relayAccelerationHint: "Выберите настроенный ретранслятор, если прямой маршрут нестабилен или заблокирован.",
|
||||
nickname: "Ваше имя",
|
||||
nicknamePlaceholder: "например, Alex Rivera",
|
||||
targetChannel: "Целевой канал",
|
||||
optional: "необязательно",
|
||||
emptyDefault: "Оставьте пустым для канала по умолчанию",
|
||||
rememberIdentity: "Запомнить личность TeamSpeak на этом устройстве",
|
||||
rememberIdentityHint: "Хранится только на этом устройстве и используется при следующем подключении.",
|
||||
rememberIdentityConcurrentWarning: "Одна личность может использоваться только одним подключением в этом браузере. Для второго подключения отключите эту опцию или используйте другой браузер.",
|
||||
deviceIdentityOptions: "Настройки личности устройства",
|
||||
enterVoiceSpace: "Войти в голосовое пространство",
|
||||
connectionDetailsPrivate: "Данные подключения используются только для этой голосовой сессии",
|
||||
recentServers: "Недавние серверы",
|
||||
saveFavorite: "Сохранить в избранное",
|
||||
savedFavoriteToast: "Сервер сохранён в избранное",
|
||||
removedFavoriteToast: "Сервер удалён из избранного",
|
||||
clearLocalData: "Очистить локальные данные",
|
||||
clearLocalDataConfirm: "Удалить сохранённое имя, настройки и личность с этого устройства?",
|
||||
localDataCleared: "Локальные данные очищены",
|
||||
languageMenu: "Язык",
|
||||
networkPerformance: "Сетевая производительность",
|
||||
networkPerformanceHint: "Непрерывные измерения от браузера через WebSpeak к TeamSpeak",
|
||||
packetLoss: "Потери пакетов",
|
||||
measuring: "Измерение…",
|
||||
measureComplete: "Мониторинг продолжается (обновление каждые 3 секунды)",
|
||||
measureNow: "Измерить сейчас",
|
||||
measureUnavailable: "Доступно после подключения",
|
||||
langSwitch: "中文",
|
||||
};
|
||||
|
||||
translations.ja = {
|
||||
...translations.en,
|
||||
themeSystem: "システム設定",
|
||||
themeLight: "ライトテーマ",
|
||||
themeDark: "ダークテーマ",
|
||||
switchToLightTheme: "ライトテーマに切り替え",
|
||||
switchToDarkTheme: "ダークテーマに切り替え",
|
||||
browserWorkspace: "ブラウザ音声ワークスペース",
|
||||
secureGateway: "安全な音声ゲートウェイ",
|
||||
adminConsole: "管理コンソール",
|
||||
currentVersion: "現在のバージョン",
|
||||
errorCode: "エラーコード",
|
||||
viewChangelog: "更新履歴を見る",
|
||||
notConfigured: "WebSpeak の TeamSpeak 接続先がまだ設定されていません。",
|
||||
configureNow: "管理コンソールを開く",
|
||||
privateAudio: "プライベートコミュニティ音声",
|
||||
joinLine1: "サーバーに接続して、",
|
||||
joinLine2: "すぐに会話を始めよう。",
|
||||
joinDescription: "TeamSpeak クライアントのインストールは不要です。ブラウザから低遅延の音声チャンネルに参加できます。",
|
||||
overallVolume: "全体音量",
|
||||
inputVolume: "マイク音量",
|
||||
desktopAudioControls: "音声コントロール",
|
||||
desktopAudioHint: "アイコンにカーソルを合わせて音量を調整",
|
||||
noiseSuppression: "ノイズ抑制",
|
||||
noiseSuppressionHint: "ブラウザ側で音声を処理",
|
||||
highQuality: "高品質な音声",
|
||||
opusAudio: "低遅延 Opus 転送",
|
||||
secureJoin: "安全に参加",
|
||||
inviteProtected: "招待リンクでサーバーを保護",
|
||||
realtime: "リアルタイムの同期",
|
||||
membersSync: "チャンネルメンバーを常に同期",
|
||||
privateServer: "プライベート音声サーバー",
|
||||
joinServer: "サーバーに参加",
|
||||
welcomeBack: "おかえりなさい",
|
||||
joinLead: "名前と参加するチャンネルを選択してください。",
|
||||
serverAddress: "TeamSpeak サーバーアドレス",
|
||||
serverAddressPlaceholder: "例: ts.example.com または 127.0.0.1",
|
||||
serverPort: "音声ポート",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "ゲートウェイが接続する TeamSpeak のアドレスとポートです。ブラウザからの直接接続先ではありません。",
|
||||
relayAcceleration: "中継接続",
|
||||
directConnection: "TeamSpeak へ直接接続",
|
||||
relayAccelerationHint: "直接接続が不安定またはブロックされている場合は、設定済みの中継を選択してください。",
|
||||
nickname: "ニックネーム",
|
||||
nicknamePlaceholder: "例: Alex Rivera",
|
||||
targetChannel: "参加先チャンネル",
|
||||
optional: "任意",
|
||||
emptyDefault: "空欄にするとデフォルトチャンネルを使用します",
|
||||
rememberIdentity: "この端末に TeamSpeak ID を保存",
|
||||
rememberIdentityHint: "この端末だけに保存し、次回の接続で再利用します。",
|
||||
rememberIdentityConcurrentWarning: "同じブラウザでは、この ID を同時に1接続だけ使用できます。2つ目の接続では無効にするか、別のブラウザを使ってください。",
|
||||
deviceIdentityOptions: "端末 ID の設定",
|
||||
enterVoiceSpace: "音声スペースに参加",
|
||||
connectionDetailsPrivate: "接続情報は今回の音声セッションでのみ使用されます",
|
||||
recentServers: "最近のサーバー",
|
||||
saveFavorite: "お気に入りに保存",
|
||||
savedFavoriteToast: "サーバーをお気に入りに保存しました",
|
||||
removedFavoriteToast: "お気に入りから削除しました",
|
||||
clearLocalData: "ローカルデータを消去",
|
||||
clearLocalDataConfirm: "この端末に保存された名前、設定、IDを削除しますか?",
|
||||
localDataCleared: "ローカルデータを消去しました",
|
||||
languageMenu: "言語",
|
||||
networkPerformance: "ネットワーク性能",
|
||||
networkPerformanceHint: "ブラウザから WebSpeak を経由して TeamSpeak まで継続測定",
|
||||
packetLoss: "パケット損失",
|
||||
measuring: "測定中…",
|
||||
measureComplete: "継続監視中(3秒ごとに更新)",
|
||||
measureNow: "今すぐ測定",
|
||||
measureUnavailable: "接続後に利用できます",
|
||||
langSwitch: "中文",
|
||||
};
|
||||
|
||||
function initialServerTarget() {
|
||||
@@ -1205,9 +1459,11 @@ function initialServerTarget() {
|
||||
|
||||
function getInitialLanguage(): Language {
|
||||
const stored = localStorage.getItem("webspeak:language");
|
||||
if (stored === "zh" || stored === "en" || stored === "de") return stored;
|
||||
if (stored === "zh" || stored === "en" || stored === "de" || stored === "ru" || stored === "ja") return stored;
|
||||
if (typeof navigator !== "undefined" && navigator.language.toLowerCase().startsWith("zh")) return "zh";
|
||||
if (typeof navigator !== "undefined" && navigator.language.toLowerCase().startsWith("de")) return "de";
|
||||
if (typeof navigator !== "undefined" && navigator.language.toLowerCase().startsWith("ru")) return "ru";
|
||||
if (typeof navigator !== "undefined" && navigator.language.toLowerCase().startsWith("ja")) return "ja";
|
||||
return "en";
|
||||
}
|
||||
|
||||
@@ -1219,6 +1475,36 @@ function t(key: string, variables: Record<string, string | number> = {}) {
|
||||
|
||||
function localizedMessage(message: string) {
|
||||
if (language.value === "zh") return message;
|
||||
const localizedExact: Record<string, string> = language.value === "ru" ? {
|
||||
"该服务器需要密码,请输入密码后重试": "Для этого сервера требуется пароль. Введите его и повторите попытку",
|
||||
"服务器密码错误,请重新输入": "Неверный пароль сервера. Введите его ещё раз",
|
||||
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "Длина имени не соответствует требованиям TeamSpeak (не менее 3 символов). Измените имя и повторите попытку",
|
||||
"TeamSpeak 服务器地址无效": "Неверный адрес сервера TeamSpeak",
|
||||
"找不到 TeamSpeak 服务器主机名,请检查地址": "Не удалось найти сервер TeamSpeak. Проверьте адрес",
|
||||
"无法到达 TeamSpeak 服务器,请检查网络或地址": "Сервер TeamSpeak недоступен. Проверьте сеть или адрес",
|
||||
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "Сервер TeamSpeak отклонил подключение. Проверьте порт и состояние службы",
|
||||
"连接 TeamSpeak 超时,请检查网络或服务器状态": "Истекло время подключения к TeamSpeak. Проверьте сеть и состояние сервера",
|
||||
} : {
|
||||
"该服务器需要密码,请输入密码后重试": "このサーバーにはパスワードが必要です。入力して再試行してください",
|
||||
"服务器密码错误,请重新输入": "サーバーパスワードが正しくありません。もう一度入力してください",
|
||||
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "ニックネームの長さが TeamSpeak の要件を満たしていません(3文字以上)。変更して再試行してください",
|
||||
"TeamSpeak 服务器地址无效": "TeamSpeak サーバーアドレスが正しくありません",
|
||||
"找不到 TeamSpeak 服务器主机名,请检查地址": "TeamSpeak サーバーが見つかりません。アドレスを確認してください",
|
||||
"无法到达 TeamSpeak 服务器,请检查网络或地址": "TeamSpeak サーバーに到達できません。ネットワークまたはアドレスを確認してください",
|
||||
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "TeamSpeak サーバーが接続を拒否しました。ポートとサービスの状態を確認してください",
|
||||
"连接 TeamSpeak 超时,请检查网络或服务器状态": "TeamSpeak への接続がタイムアウトしました。ネットワークとサーバーの状態を確認してください",
|
||||
};
|
||||
if (localizedExact[message]) return localizedExact[message];
|
||||
const errorCodeMatch = message.match(/错误代码:([A-Z0-9_-]{1,64}))(?::([^,。]+))?/);
|
||||
if (errorCodeMatch) {
|
||||
const code = errorCodeMatch[1];
|
||||
const detail = errorCodeMatch[2] ? `: ${errorCodeMatch[2]}` : "";
|
||||
const operation = message.startsWith("操作失败");
|
||||
if (language.value === "de") return `${operation ? "Vorgang" : "TeamSpeak-Verbindung"} fehlgeschlagen (Fehlercode: ${code})${detail}. Prüfe Eingaben, Netzwerk und Serverstatus`;
|
||||
if (language.value === "ru") return `${operation ? "Операция" : "Подключение TeamSpeak"} не выполнена (код ошибки: ${code})${detail}. Проверьте ввод, сеть и состояние сервера`;
|
||||
if (language.value === "ja") return `${operation ? "操作" : "TeamSpeak 接続"}に失敗しました(エラーコード: ${code})${detail}。入力、ネットワーク、サーバーの状態を確認してください`;
|
||||
return `${operation ? "Operation" : "TeamSpeak connection"} failed (error code: ${code})${detail}. Check your input, network, and server status`;
|
||||
}
|
||||
const exact: Record<string, string> = {
|
||||
"语音功能需要 HTTPS 安全连接": "Voice requires a secure HTTPS connection",
|
||||
"当前浏览器不支持麦克风访问": "This browser does not support microphone access",
|
||||
@@ -1227,12 +1513,29 @@ function localizedMessage(message: string) {
|
||||
"当前浏览器不支持扬声器设备选择,将使用默认输出设备": "Output device selection is not supported by this browser. Using the default output device",
|
||||
"所选扬声器当前不可用": "The selected speaker is not available",
|
||||
"连接服务器失败,请检查邀请链接或服务器状态": "Could not connect. Check the invite link or server status",
|
||||
"请求来源不受信任,请从正确的网站入口重新打开": "The request origin is not trusted. Reopen the official WebSpeak page",
|
||||
"WebSpeak 尚未完成配置,请联系管理员": "WebSpeak has not been configured yet. Contact the administrator",
|
||||
"请求过于频繁,请稍后重试": "Too many requests. Try again shortly",
|
||||
"当前中继加速不可用,请关闭加速或联系管理员": "The selected relay is unavailable. Turn off relay mode or contact the administrator",
|
||||
"邀请链接已失效或已被撤销": "The invite link is invalid, expired, or revoked",
|
||||
"TeamSpeak 连接已断开": "The TeamSpeak connection was closed",
|
||||
"连接已断开": "The connection was closed",
|
||||
"此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "This TeamSpeak identity is already used by another browser page. Close that connection or clear ‘Remember identity’ and try again",
|
||||
"TeamSpeak 服务器地址无效": "The TeamSpeak server address is invalid",
|
||||
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "The nickname length does not meet the TeamSpeak server requirements (at least 3 characters). Change it and try again",
|
||||
"TeamSpeak 服务器连接失败": "Could not connect to the TeamSpeak server",
|
||||
"找不到 TeamSpeak 服务器主机名,请检查地址": "The TeamSpeak server hostname could not be resolved. Check the address",
|
||||
"无法到达 TeamSpeak 服务器,请检查网络或地址": "The TeamSpeak server is unreachable. Check the network or address",
|
||||
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "The TeamSpeak server refused the connection. Check the port and server status",
|
||||
"TeamSpeak 连接被服务器或网络重置,请稍后重试": "The TeamSpeak connection was reset by the server or network. Try again shortly",
|
||||
"连接 TeamSpeak 超时,请检查网络或服务器状态": "The TeamSpeak connection timed out. Check the network or server status",
|
||||
"该服务器需要密码,请输入密码后重试": "This server requires a password. Enter it and try again",
|
||||
"服务器密码错误,请重新输入": "The server password is incorrect. Enter it again",
|
||||
"TeamSpeak 协议协商失败": "TeamSpeak protocol negotiation failed",
|
||||
"TeamSpeak 服务器拒绝了连接": "The TeamSpeak server rejected the connection",
|
||||
"TeamSpeak 连接失败,请检查地址、网络或服务器状态": "TeamSpeak connection failed. Check the address, network, or server status",
|
||||
"服务器当前已满,请稍后重试": "The server is full. Try again shortly",
|
||||
"服务器当前已满或拒绝了连接,请稍后重试": "The server is full or rejected the connection. Try again shortly",
|
||||
"WebSpeak 尚未配置 TeamSpeak 目标。": "The WebSpeak TeamSpeak target has not been configured",
|
||||
"此 TeamSpeak 服务器地址不允许连接": "This TeamSpeak server address is not allowed",
|
||||
"请输入有效的昵称": "Enter a valid nickname",
|
||||
@@ -1258,11 +1561,170 @@ function localizedMessage(message: string) {
|
||||
"你没有执行此操作的权限": "You do not have permission to perform this action",
|
||||
"成员已离线": "This member is offline",
|
||||
"操作失败": "The operation failed",
|
||||
"语音会话票据缺失或已过期,请返回列表重新进入语音空间": "The voice session token is missing or expired. Return to the list and enter the voice space again",
|
||||
"语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入": "The voice gateway rejected the connection because the identity is invalid. Clear ‘Remember identity’ and try again",
|
||||
"语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入": "The voice gateway rejected the connection because the identity is invalid or unavailable on this page. Clear ‘Remember identity’ and try again",
|
||||
"当前中继加速不可用,请关闭加速后重试或联系管理员": "The selected relay is unavailable. Turn off relay mode and try again, or contact the administrator",
|
||||
"与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入": "The voice gateway connection was interrupted (offline or proxy disconnected); the TeamSpeak server did not reject it. Check your network and enter again",
|
||||
"语音网关会话意外结束,请重新进入语音空间": "The voice gateway session ended unexpectedly. Enter the voice space again",
|
||||
"语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试": "The voice gateway could not create a TeamSpeak client. The server may be offline or unreachable; check the address and try again",
|
||||
"该昵称已被服务器上的其他用户占用,请更换昵称": "This nickname is already in use on the server. Choose another one",
|
||||
"该昵称已被占用,请更换昵称": "This nickname is already in use. Choose another one",
|
||||
"你的身份安全等级低于该服务器要求,请提升后重试": "Your identity security level is below what this server requires. Raise it and try again",
|
||||
"该身份建立的连接数已达上限,请关闭其他连接后重试": "This identity reached its connection limit. Close the other connections and try again",
|
||||
"客户端版本过旧,服务器拒绝连接,请升级后重试": "Your client version is outdated and the server rejected the connection. Update and try again",
|
||||
"客户端版本过旧,服务器拒绝了该操作": "Your client version is outdated, so the server rejected this action",
|
||||
"操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试": "Too many requests: the server flood protection rejected you temporarily. Try again shortly",
|
||||
"操作过于频繁,请稍后重试": "Too many requests. Try again shortly",
|
||||
"你已被该服务器封禁,无法连接": "You are banned from this server, so the connection is refused",
|
||||
"你已被该服务器封禁": "You are banned from this server",
|
||||
"你已被服务器移出": "You were removed from the server",
|
||||
"TeamSpeak 服务器正在关闭,暂时无法连接": "The TeamSpeak server is shutting down and is unreachable right now",
|
||||
"TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试": "The TeamSpeak server could not finish initialising the connection. Check the address and port, or try again shortly",
|
||||
"TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规": "The TeamSpeak server rejected the parameters, usually because the nickname length or format is invalid",
|
||||
};
|
||||
if (exact[message]) return exact[message];
|
||||
if (message.startsWith("麦克风访问失败:")) return `Microphone access failed: ${message.slice(8)}`;
|
||||
if (message.startsWith("切换失败:")) return `Channel switch failed: ${message.slice(5)}`;
|
||||
return message;
|
||||
if (language.value === "en" && exact[message]) return exact[message];
|
||||
if (message.startsWith("麦克风访问失败:")) {
|
||||
const detail = message.slice(8);
|
||||
if (language.value === "ru") return `Не удалось получить доступ к микрофону: ${detail}`;
|
||||
if (language.value === "ja") return `マイクへのアクセスに失敗しました: ${detail}`;
|
||||
return language.value === "de" ? `Mikrofonzugriff fehlgeschlagen: ${detail}` : `Microphone access failed: ${detail}`;
|
||||
}
|
||||
if (message.startsWith("切换失败:")) {
|
||||
const detail = message.slice(5);
|
||||
if (language.value === "ru") return `Не удалось переключить канал: ${detail}`;
|
||||
if (language.value === "ja") return `チャンネルの切り替えに失敗しました: ${detail}`;
|
||||
return language.value === "de" ? `Kanalwechsel fehlgeschlagen: ${detail}` : `Channel switch failed: ${detail}`;
|
||||
}
|
||||
if (language.value === "de") {
|
||||
const german: Record<string, string> = {
|
||||
"语音功能需要 HTTPS 安全连接": "Für Sprachfunktionen ist eine sichere HTTPS-Verbindung erforderlich",
|
||||
"当前浏览器不支持麦克风访问": "Dieser Browser unterstützt keinen Mikrofonzugriff",
|
||||
"当前浏览器不支持 Web Audio 音频处理": "Dieser Browser unterstützt keine Web-Audio-Verarbeitung",
|
||||
"连接服务器失败,请检查邀请链接或服务器状态": "Verbindung fehlgeschlagen. Prüfe den Einladungslink oder den Serverstatus",
|
||||
"请求来源不受信任,请从正确的网站入口重新打开": "Die Anfragequelle ist nicht vertrauenswürdig. Öffne die offizielle WebSpeak-Seite erneut",
|
||||
"WebSpeak 尚未完成配置,请联系管理员": "WebSpeak wurde noch nicht konfiguriert. Wende dich an den Administrator",
|
||||
"请求过于频繁,请稍后重试": "Zu viele Anfragen. Versuche es gleich erneut",
|
||||
"当前中继加速不可用,请关闭加速或联系管理员": "Das ausgewählte Relay ist nicht verfügbar. Deaktiviere den Relay-Modus oder wende dich an den Administrator",
|
||||
"邀请链接已失效或已被撤销": "Der Einladungslink ist ungültig, abgelaufen oder widerrufen",
|
||||
"TeamSpeak 连接已断开": "Die TeamSpeak-Verbindung wurde getrennt",
|
||||
"连接已断开": "Die Verbindung wurde getrennt",
|
||||
"TeamSpeak 服务器地址无效": "Die TeamSpeak-Serveradresse ist ungültig",
|
||||
"昵称长度不符合 TeamSpeak 服务器要求,至少 3 个字符,请修改后重试": "Die Länge des Spitznamens entspricht nicht den Anforderungen des TeamSpeak-Servers (mindestens 3 Zeichen). Ändere ihn und versuche es erneut",
|
||||
"请输入有效的昵称": "Gib einen gültigen Nicknamen ein",
|
||||
"找不到 TeamSpeak 服务器主机名,请检查地址": "Der TeamSpeak-Servername konnte nicht aufgelöst werden. Prüfe die Adresse",
|
||||
"无法到达 TeamSpeak 服务器,请检查网络或地址": "Der TeamSpeak-Server ist nicht erreichbar. Prüfe Netzwerk und Adresse",
|
||||
"TeamSpeak 服务器拒绝了连接,请检查端口和服务状态": "Der TeamSpeak-Server hat die Verbindung abgelehnt. Prüfe Port und Serverstatus",
|
||||
"TeamSpeak 连接被服务器或网络重置,请稍后重试": "Die TeamSpeak-Verbindung wurde vom Server oder Netzwerk zurückgesetzt. Versuche es später erneut",
|
||||
"连接 TeamSpeak 超时,请检查网络或服务器状态": "Die TeamSpeak-Verbindung hat das Zeitlimit überschritten. Prüfe Netzwerk und Serverstatus",
|
||||
"该服务器需要密码,请输入密码后重试": "Dieser Server benötigt ein Passwort. Gib es ein und versuche es erneut",
|
||||
"服务器密码错误,请重新输入": "Das Serverpasswort ist falsch. Gib es erneut ein",
|
||||
"TeamSpeak 协议协商失败": "Die Aushandlung des TeamSpeak-Protokolls ist fehlgeschlagen",
|
||||
"TeamSpeak 服务器拒绝了连接": "Der TeamSpeak-Server hat die Verbindung abgelehnt",
|
||||
"TeamSpeak 连接失败,请检查地址、网络或服务器状态": "Die TeamSpeak-Verbindung ist fehlgeschlagen. Prüfe Adresse, Netzwerk und Serverstatus",
|
||||
"服务器当前已满或拒绝了连接,请稍后重试": "Der Server ist voll oder hat die Verbindung abgelehnt. Versuche es später erneut",
|
||||
"服务器当前已满,请稍后重试": "Der Server ist derzeit voll. Versuche es später erneut",
|
||||
"该昵称已被服务器上的其他用户占用,请更换昵称": "Dieser Spitzname wird auf dem Server bereits verwendet. Wähle einen anderen",
|
||||
"该昵称已被占用,请更换昵称": "Dieser Spitzname wird bereits verwendet. Wähle einen anderen",
|
||||
"你的身份安全等级低于该服务器要求,请提升后重试": "Deine Sicherheitsstufe liegt unter der Anforderung dieses Servers. Erhöhe sie und versuche es erneut",
|
||||
"该身份建立的连接数已达上限,请关闭其他连接后重试": "Diese Identität hat ihr Verbindungslimit erreicht. Schließe die anderen Verbindungen und versuche es erneut",
|
||||
"客户端版本过旧,服务器拒绝连接,请升级后重试": "Deine Client-Version ist veraltet und der Server hat die Verbindung abgelehnt. Aktualisiere und versuche es erneut",
|
||||
"客户端版本过旧,服务器拒绝了该操作": "Deine Client-Version ist veraltet, daher hat der Server diese Aktion abgelehnt",
|
||||
"操作过于频繁,已被服务器洪水防护暂时拒绝,请稍后重试": "Zu viele Anfragen: Der Flood-Schutz des Servers hat dich vorübergehend abgewiesen. Versuche es gleich erneut",
|
||||
"操作过于频繁,请稍后重试": "Zu viele Anfragen. Versuche es gleich erneut",
|
||||
"你已被该服务器封禁,无法连接": "Du wurdest von diesem Server gebannt und kannst nicht verbinden",
|
||||
"你已被该服务器封禁": "Du wurdest von diesem Server gebannt",
|
||||
"你已被服务器移出": "Du wurdest vom Server entfernt",
|
||||
"TeamSpeak 服务器正在关闭,暂时无法连接": "Der TeamSpeak-Server wird heruntergefahren und ist derzeit nicht erreichbar",
|
||||
"TeamSpeak 服务器未能完成连接初始化,请检查地址、端口或稍后重试": "Der TeamSpeak-Server konnte die Verbindungsinitialisierung nicht abschließen. Prüfe Adresse und Port oder versuche es später erneut",
|
||||
"TeamSpeak 服务器拒绝了参数,通常是昵称长度或格式不合规": "Der TeamSpeak-Server hat die Parameter abgelehnt, meist wegen ungültiger Länge oder ungültigen Formats des Spitznamens",
|
||||
"此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "Diese TeamSpeak-Identität wird bereits in einem anderen Browser-Tab verwendet. Schließe die andere Verbindung oder deaktiviere „Identität merken“ und versuche es erneut",
|
||||
"语音会话票据缺失或已过期,请返回列表重新进入语音空间": "Der Sprachsitzungs-Token fehlt oder ist abgelaufen. Kehre zur Liste zurück und tritt dem Sprachraum erneut bei",
|
||||
"语音网关拒绝了本次连接:身份无效,请取消“保持身份”后重新进入": "Das Sprach-Gateway hat die Verbindung abgelehnt: Die Identität ist ungültig. Deaktiviere „Identität merken“ und tritt erneut bei",
|
||||
"语音网关拒绝了本次连接:身份无效或无法在此页面使用,请取消“保持身份”后重新进入": "Das Sprach-Gateway hat die Verbindung abgelehnt: Die Identität ist ungültig oder kann auf dieser Seite nicht verwendet werden. Deaktiviere „Identität merken“ und tritt erneut bei",
|
||||
"当前中继加速不可用,请关闭加速后重试或联系管理员": "Der beschleunigte Relay-Modus ist nicht verfügbar. Deaktiviere ihn und versuche es erneut oder wende dich an den Administrator",
|
||||
"与语音网关的网络连接异常中断(掉线或代理断开),并非 TeamSpeak 服务器拒绝连接,请检查网络后重新进入": "Die Verbindung zum Sprach-Gateway wurde unerwartet unterbrochen (Offline oder Proxy getrennt) – der TeamSpeak-Server hat die Verbindung nicht abgelehnt. Prüfe deine Netzwerkverbindung und tritt erneut bei",
|
||||
"语音网关会话意外结束,请重新进入语音空间": "Die Sprach-Gateway-Sitzung wurde unerwartet beendet. Tritt dem Sprachraum erneut bei",
|
||||
"语音网关未能创建 TeamSpeak 客户端(服务器可能已关闭或地址不可达),请确认服务器地址或稍后重试": "Das Sprach-Gateway konnte keinen TeamSpeak-Client erstellen (der Server ist möglicherweise aus oder nicht erreichbar). Prüfe die Serveradresse oder versuche es später erneut",
|
||||
"消息格式无效": "Ungültiges Nachrichtenformat",
|
||||
"请求标识无效": "Ungültige Anforderungs-ID",
|
||||
"不支持的操作": "Nicht unterstützte Operation",
|
||||
"操作参数无效": "Ungültige Operationsparameter",
|
||||
"频道标识无效": "Ungültige Kanal-ID",
|
||||
"频道密码无效": "Ungültiges Kanalpasswort",
|
||||
"成员标识无效": "Ungültige Mitglieds-ID",
|
||||
"文字消息无效": "Ungültige Textnachricht",
|
||||
"戳一戳消息无效": "Ungültige Poke-Nachricht",
|
||||
"离开状态无效": "Ungültiger Abwesenheitsstatus",
|
||||
"音频帧格式无效": "Ungültiges Audio-Frame-Format",
|
||||
"成员音量无效": "Ungültige Mitgliedslautstärke",
|
||||
"私语目标无效": "Ungültige Flüsterziele",
|
||||
"私语状态无效": "Ungültiger Flüsterstatus",
|
||||
"请先选择私语目标": "Wähle zuerst ein Flüsterziel",
|
||||
"TeamSpeak 会话尚未就绪": "Die TeamSpeak-Sitzung ist noch nicht bereit",
|
||||
"频道切换失败": "Kanalwechsel fehlgeschlagen",
|
||||
"该频道需要密码": "Dieser Kanal erfordert ein Passwort",
|
||||
"该频道已满": "Dieser Kanal ist voll",
|
||||
"你没有执行此操作的权限": "Du hast keine Berechtigung für diese Aktion",
|
||||
"成员已离线": "Das Mitglied ist offline",
|
||||
"操作失败": "Operation fehlgeschlagen",
|
||||
};
|
||||
if (german[message]) return german[message];
|
||||
if (message.startsWith("麦克风访问失败:")) return `Mikrofonzugriff fehlgeschlagen: ${message.slice(8)}`;
|
||||
if (message.startsWith("麦克风声音未能发送:")) return `Mikrofon-Audio konnte nicht gesendet werden: ${message.slice(10)}`;
|
||||
if (message.startsWith("音频链路异常")) return message.replace("音频链路异常", "Audioverbindung fehlerhaft");
|
||||
}
|
||||
if (language.value === "ru") return exact[message] ?? "Не удалось выполнить операцию. Проверьте ввод, сеть и состояние сервера";
|
||||
if (language.value === "ja") return exact[message] ?? "操作に失敗しました。入力、ネットワーク、サーバーの状態を確認してください";
|
||||
return exact[message] ?? message;
|
||||
}
|
||||
|
||||
function localizedAudioNotice(code: string, message: string) {
|
||||
if (language.value === "zh") return message;
|
||||
const normalizedCode = visibleErrorCode(code || "AUDIO_NOTICE");
|
||||
const messages: Record<string, { en: string; de: string; ru: string; ja: string }> = {
|
||||
WEBRTC_FALLBACK: {
|
||||
en: `WebRTC realtime voice is unavailable (error code: ${normalizedCode}). Compatibility transport is active; latency and audio quality may be lower`,
|
||||
de: `Echtzeitstimme über WebRTC ist nicht verfügbar (Fehlercode: ${normalizedCode}). Der Kompatibilitätstransport ist aktiv; Latenz und Audioqualität können schlechter sein`,
|
||||
ru: `Голосовая связь WebRTC недоступна (код ошибки: ${normalizedCode}). Используется совместимый транспорт; задержка и качество звука могут быть ниже`,
|
||||
ja: `WebRTC のリアルタイム音声は利用できません(エラーコード: ${normalizedCode})。互換トランスポートを使用するため、遅延や音質が低下する場合があります`,
|
||||
},
|
||||
PLAYBACK_BLOCKED: {
|
||||
en: "The browser blocked automatic audio playback. Click the page or allow audio playback for this site",
|
||||
de: "Der Browser hat die automatische Audiowiedergabe blockiert. Klicke auf die Seite oder erlaube die Audiowiedergabe für diese Website",
|
||||
ru: "Браузер заблокировал автоматическое воспроизведение. Нажмите на страницу или разрешите воспроизведение для этого сайта",
|
||||
ja: "ブラウザが自動再生をブロックしました。ページをクリックするか、このサイトの再生を許可してください",
|
||||
},
|
||||
DEVICE_LIST_UNAVAILABLE: {
|
||||
en: "Audio devices could not be listed. The browser default devices will be used",
|
||||
de: "Audiogeräte konnten nicht aufgelistet werden. Die Standardgeräte des Browsers werden verwendet",
|
||||
ru: "Не удалось получить список аудиоустройств. Будут использованы устройства браузера по умолчанию",
|
||||
ja: "オーディオデバイスを一覧表示できません。ブラウザのデフォルトデバイスを使用します",
|
||||
},
|
||||
AUDIO_CONTEXT_SUSPENDED: {
|
||||
en: "Browser audio processing is paused. Click the page once to resume microphone and speaker audio",
|
||||
de: "Die Audioverarbeitung des Browsers ist pausiert. Klicke einmal auf die Seite, um Mikrofon und Lautsprecher fortzusetzen",
|
||||
ru: "Обработка звука браузером приостановлена. Нажмите на страницу, чтобы возобновить работу микрофона и динамиков",
|
||||
ja: "ブラウザの音声処理が一時停止しています。ページを一度クリックしてマイクとスピーカーを再開してください",
|
||||
},
|
||||
AUDIO_ENCODER_UNAVAILABLE: {
|
||||
en: `Microphone audio could not be encoded (error code: ${normalizedCode}). Other members may not hear you`,
|
||||
de: `Mikrofon-Audio konnte nicht kodiert werden (Fehlercode: ${normalizedCode}). Andere Mitglieder hören dich möglicherweise nicht`,
|
||||
ru: `Не удалось кодировать звук микрофона (код ошибки: ${normalizedCode}). Другие участники могут вас не слышать`,
|
||||
ja: `マイク音声をエンコードできませんでした(エラーコード: ${normalizedCode})。他のメンバーに音声が届かない可能性があります`,
|
||||
},
|
||||
};
|
||||
const locale = language.value === "de" ? "de" : language.value === "ru" ? "ru" : language.value === "ja" ? "ja" : "en";
|
||||
return messages[code]?.[locale] ?? localizedMessage(message);
|
||||
}
|
||||
|
||||
function visibleErrorCode(code: string): string {
|
||||
const normalized = String(code || "CONNECTION_FAILED")
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
.replace(/[^A-Z0-9_-]+/g, "_")
|
||||
.replace(/^_+|_+$/g, "");
|
||||
return (normalized || "CONNECTION_FAILED").slice(0, 64);
|
||||
}
|
||||
|
||||
function persistLanguage() {
|
||||
@@ -1392,6 +1854,14 @@ watch(() => voiceState.errorCode, (code) => {
|
||||
clearError();
|
||||
void nextTick(() => document.getElementById("channel-password-input")?.focus());
|
||||
});
|
||||
watch(() => voiceState.errorCode, (code) => {
|
||||
if (code !== "SERVER_PASSWORD_REQUIRED" && code !== "INVALID_SERVER_PASSWORD") return;
|
||||
serverPasswordDialog.open = true;
|
||||
serverPasswordDialog.password = "";
|
||||
serverPasswordDialog.errorCode = code;
|
||||
clearError();
|
||||
void nextTick(() => document.getElementById("retry-server-password-input")?.focus());
|
||||
});
|
||||
watch(() => voiceState.channelSwitchedChannelId, (channelId) => {
|
||||
if (!channelPasswordDialog.open || !channelId || channelId !== channelPasswordDialog.channelId) return;
|
||||
channelPasswordDialog.open = false;
|
||||
@@ -1514,7 +1984,7 @@ onMounted(() => {
|
||||
browserError.value = checkSupport() ?? "";
|
||||
void loadPublicConfig();
|
||||
void loadLocalPreferences().then((preferences) => {
|
||||
if (!localStorage.getItem("webspeak:language") && (preferences.language === "zh" || preferences.language === "en" || preferences.language === "de")) language.value = preferences.language;
|
||||
if (!localStorage.getItem("webspeak:language") && (preferences.language === "zh" || preferences.language === "en" || preferences.language === "de" || preferences.language === "ru" || preferences.language === "ja")) language.value = preferences.language;
|
||||
if (!localStorage.getItem("webspeak:theme") && (preferences.theme === "system" || preferences.theme === "light" || preferences.theme === "dark")) {
|
||||
themeMode.value = preferences.theme;
|
||||
applyTheme(themeMode.value);
|
||||
@@ -1560,7 +2030,10 @@ function doConnect() {
|
||||
serverPort.value = serverPort.value.trim();
|
||||
}
|
||||
selectedChannelId.value = "";
|
||||
connect(currentServerTarget(), channel.value.trim(), nickname.value, accessMode.value === "open" ? serverPassword.value : "", rememberIdentity.value ? identityMaterial.value : "", rememberIdentity.value, inviteToken);
|
||||
// Keep the password field available for a retry even when the target is
|
||||
// administrator-managed. The gateway still controls the target in fixed
|
||||
// mode and only accepts a non-empty retry password for that target.
|
||||
connect(currentServerTarget(), channel.value.trim(), nickname.value, serverPassword.value, rememberIdentity.value ? identityMaterial.value : "", rememberIdentity.value, inviteToken, Boolean(accelerationRelayId.value), accelerationRelayId.value);
|
||||
}
|
||||
|
||||
function doDisconnect() {
|
||||
@@ -1569,6 +2042,22 @@ function doDisconnect() {
|
||||
showToast(t("leftToast"));
|
||||
}
|
||||
|
||||
function submitServerPassword() {
|
||||
if (!serverPasswordDialog.open || !serverPasswordDialog.password) return;
|
||||
serverPassword.value = serverPasswordDialog.password;
|
||||
serverPasswordDialog.open = false;
|
||||
serverPasswordDialog.password = "";
|
||||
serverPasswordDialog.errorCode = "";
|
||||
doConnect();
|
||||
}
|
||||
|
||||
function cancelServerPassword() {
|
||||
serverPasswordDialog.open = false;
|
||||
serverPasswordDialog.password = "";
|
||||
serverPasswordDialog.errorCode = "";
|
||||
clearError();
|
||||
}
|
||||
|
||||
function selectChannel(item: TreeChannel) {
|
||||
selectedChannelId.value = item.id;
|
||||
channel.value = item.name;
|
||||
@@ -1671,13 +2160,31 @@ async function loadPublicConfig() {
|
||||
try {
|
||||
const response = await fetch("/api/public-config", { headers: { accept: "application/json" } });
|
||||
if (!response.ok) return;
|
||||
const config = await response.json() as { version?: unknown; initialized?: unknown; siteName?: unknown; welcomeText?: unknown; welcomeTextEn?: unknown; accessMode?: unknown; target?: unknown };
|
||||
const config = await response.json() as { version?: unknown; initialized?: unknown; siteName?: unknown; welcomeText?: unknown; welcomeTextEn?: unknown; welcomeTexts?: unknown; accessMode?: unknown; target?: unknown; accelerationAvailable?: unknown; accelerationRelays?: unknown };
|
||||
if (typeof config.version === "string" && config.version.trim()) appVersion.value = config.version.trim();
|
||||
initialized.value = config.initialized === true;
|
||||
if (typeof config.siteName === "string" && config.siteName.trim()) siteName.value = config.siteName.trim();
|
||||
if (typeof config.welcomeText === "string") welcomeTextZh.value = config.welcomeText;
|
||||
if (typeof config.welcomeTextEn === "string") welcomeTextEn.value = config.welcomeTextEn;
|
||||
if (config.welcomeTexts && typeof config.welcomeTexts === "object" && !Array.isArray(config.welcomeTexts)) {
|
||||
const welcomeTexts = config.welcomeTexts as Record<string, unknown>;
|
||||
if (typeof welcomeTexts.zh === "string") welcomeTextZh.value = welcomeTexts.zh;
|
||||
if (typeof welcomeTexts.en === "string") welcomeTextEn.value = welcomeTexts.en;
|
||||
if (typeof welcomeTexts.de === "string") welcomeTextDe.value = welcomeTexts.de;
|
||||
if (typeof welcomeTexts.ru === "string") welcomeTextRu.value = welcomeTexts.ru;
|
||||
if (typeof welcomeTexts.ja === "string") welcomeTextJa.value = welcomeTexts.ja;
|
||||
}
|
||||
accessMode.value = config.accessMode === "open" ? "open" : "fixed";
|
||||
accelerationRelays.value = Array.isArray(config.accelerationRelays)
|
||||
? config.accelerationRelays.flatMap((value) => {
|
||||
if (!value || typeof value !== "object") return [];
|
||||
const relay = value as { id?: unknown; name?: unknown };
|
||||
return typeof relay.id === "string" && typeof relay.name === "string" && relay.id && relay.name
|
||||
? [{ id: relay.id, name: relay.name }]
|
||||
: [];
|
||||
})
|
||||
: [];
|
||||
if (!accelerationAvailable.value || !accelerationRelays.value.some((relay) => relay.id === accelerationRelayId.value)) accelerationRelayId.value = "";
|
||||
const hasInviteTarget = query.has("server") || query.has("target") || query.has("tsHost") || query.has("tsPort");
|
||||
if (!hasInviteTarget && typeof config.target === "string" && config.target.trim()) {
|
||||
const target = splitTeamSpeakTarget(config.target);
|
||||
@@ -1785,7 +2292,7 @@ function memberDisplayName(member: ChannelMember): string {
|
||||
}
|
||||
|
||||
function formatTime(timestamp: number) {
|
||||
const locale = language.value === "zh" ? "zh-CN" : language.value === "de" ? "de-DE" : "en-US";
|
||||
const locale = language.value === "zh" ? "zh-CN" : language.value === "de" ? "de-DE" : language.value === "ru" ? "ru-RU" : language.value === "ja" ? "ja-JP" : "en-US";
|
||||
return new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit" }).format(timestamp);
|
||||
}
|
||||
|
||||
@@ -1802,6 +2309,10 @@ function onInputVolume(event: Event) {
|
||||
setInputVolume(Number((event.target as HTMLInputElement).value) / 100);
|
||||
}
|
||||
|
||||
function onNoiseSuppressionToggle(event: Event) {
|
||||
void setNoiseSuppressionEnabled((event.target as HTMLInputElement).checked);
|
||||
}
|
||||
|
||||
function onOutputVolume(event: Event) {
|
||||
setOutputVolume(Number((event.target as HTMLInputElement).value) / 100);
|
||||
}
|
||||
@@ -1959,7 +2470,9 @@ function stopWhisperTalk(): void {
|
||||
.card-kicker, .section-kicker { color: #79918c; font-size: 10px; font-weight: 700; letter-spacing: .16em; }
|
||||
.join-card h2 { margin: 10px 0 7px; color: #1b2825; font-size: 27px; letter-spacing: -.045em; }
|
||||
.card-lead { margin: 0 0 18px; color: #7b8885; font-size: 13px; }
|
||||
.notice { display: flex; align-items: flex-start; gap: 10px; margin: 0 0 10px; padding: 9px 10px; border-radius: 10px; font-size: 12px; line-height: 1.45; }
|
||||
.notice { display: flex; align-items: flex-start; gap: 10px; min-width: 0; margin: 0 0 10px; padding: 9px 10px; border-radius: 10px; font-size: 12px; line-height: 1.45; }
|
||||
.notice-content { min-width: 0; overflow-wrap: anywhere; }
|
||||
.notice-content code { display: block; max-width: 100%; margin-top: 3px; overflow: hidden; color: currentColor; font-family: ui-monospace,SFMono-Regular,Consolas,monospace; font-size: 10px; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; opacity: .78; }
|
||||
.error-notice { color: #a53c38; background: #fff0ef; border: 1px solid #f7d4d1; }
|
||||
.warning-notice { color: #8a6537; background: #fff8e9; border: 1px solid #f2dfb3; }
|
||||
.notice-symbol { display: grid; place-items: center; width: 16px; height: 16px; flex: 0 0 auto; border-radius: 50%; color: #fff; background: currentColor; color: #fff; font-size: 10px; font-weight: 800; }
|
||||
@@ -2104,17 +2617,27 @@ function stopWhisperTalk(): void {
|
||||
.settings-footer { justify-content: flex-end; }
|
||||
.reconnect-banner { display: flex; align-items: center; justify-content: space-between; gap: 18px; margin: 14px auto 0; width: min(950px, calc(100% - 64px)); padding: 12px 16px; color: #6c5a2c; border: 1px solid #f0dfae; border-radius: 10px; background: #fff9e8; }
|
||||
.reconnect-banner.failed { color: #8f4540; border-color: #f2d1cd; background: #fff2f1; }
|
||||
.reconnect-banner.degraded { color: #7a4d1d; border-color: #f3d9a9; background: #fff7ec; } /* 降级/告警级提示(如音频链路降级) */
|
||||
.reconnect-copy { display: flex; align-items: baseline; gap: 10px; min-width: 0; }
|
||||
.reconnect-copy strong { font-size: 13px; }
|
||||
.reconnect-copy span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px; }
|
||||
.reconnect-actions { display: flex; align-items: center; gap: 12px; flex: 0 0 auto; }
|
||||
.reconnect-actions .secondary-button { min-height: 34px; padding-inline: 13px; }
|
||||
.remember-identity { display: flex; align-items: flex-start; gap: 9px; margin-top: 8px; color: #465650; cursor: pointer; }
|
||||
.acceleration-choice { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 8px 0 2px; padding: 10px 11px; color: #245f58; background: #edf9f5; border: 1px solid #c4e9df; border-radius: 10px; }
|
||||
.acceleration-choice select { min-width: 150px; max-width: 48%; padding: 8px 28px 8px 10px; color: #245f58; background: #fff; border: 1px solid #b9ded5; border-radius: 8px; font: inherit; font-size: 11px; font-weight: 700; }
|
||||
.acceleration-copy { min-width: 0; }
|
||||
.acceleration-choice strong, .acceleration-choice small { display: block; }
|
||||
.acceleration-choice strong { font-size: 11px; font-weight: 800; }
|
||||
.acceleration-choice small { margin-top: 3px; color: #6b8c85; font-size: 10px; line-height: 1.45; }
|
||||
.remember-identity input { width: 16px; height: 16px; flex: 0 0 auto; margin: 1px 0 0; accent-color: #087d74; }
|
||||
.remember-identity strong, .remember-identity small { display: block; }
|
||||
.remember-identity strong { font-size: 11px; font-weight: 700; }
|
||||
.remember-identity small { margin-top: 3px; color: #8b9994; font-size: 10px; line-height: 1.4; }
|
||||
.identity-warning { margin: 8px 0 0; color: #9a6a32; font-size: 10px; line-height: 1.45; }
|
||||
:global(html[data-theme="dark"] .acceleration-choice) { color: #b8eee3; background: #183530; border-color: #2b645b; }
|
||||
:global(html[data-theme="dark"] .acceleration-choice small) { color: #91b9b0; }
|
||||
:global(html[data-theme="dark"] .acceleration-choice select) { color: #d9f8f1; background: #203f39; border-color: #3b766d; }
|
||||
.local-servers { display: grid; gap: 8px; margin: 1px 0 5px; }
|
||||
.local-server-group { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }
|
||||
.local-server-group > span { width: 100%; color: #87958f; font-size: 10px; font-weight: 700; }
|
||||
@@ -2225,12 +2748,6 @@ function stopWhisperTalk(): void {
|
||||
.desktop-audio-dock-copy strong { overflow: hidden; color: var(--text-primary); font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.desktop-audio-dock-copy span { overflow: hidden; font-size: 10px; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.desktop-audio-dock-actions { display: flex; align-items: center; gap: 4px; flex: 0 0 auto; }
|
||||
.dock-output-control { display: flex; align-items: center; gap: 5px; width: 34px; overflow: hidden; transition: width .18s ease; }
|
||||
.dock-output-control:hover, .dock-output-control:focus-within { width: 115px; }
|
||||
.dock-output-slider { width: 0; min-width: 0; height: 5px; opacity: 0; appearance: none; border-radius: 999px; outline: none; pointer-events: none; cursor: pointer; transition: width .18s ease, opacity .14s ease; }
|
||||
.dock-output-control:hover .dock-output-slider, .dock-output-control:focus-within .dock-output-slider { width: 76px; opacity: 1; pointer-events: auto; }
|
||||
.dock-output-slider::-webkit-slider-thumb { width: 14px; height: 14px; appearance: none; border: 2px solid #81d8d0; border-radius: 50%; background: var(--surface-1); cursor: pointer; }
|
||||
.dock-output-slider::-moz-range-thumb { width: 14px; height: 14px; border: 2px solid #81d8d0; border-radius: 50%; background: var(--surface-1); cursor: pointer; }
|
||||
.dock-audio-button { display: grid; place-items: center; width: 34px; height: 34px; padding: 0; color: var(--text-muted); background: transparent; border: 1px solid transparent; border-radius: 9px; cursor: pointer; transition: color .16s, background .16s, border-color .16s, transform .16s; }
|
||||
.dock-audio-button:hover, .dock-audio-button:focus-visible { color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, var(--surface-1)); border-color: color-mix(in srgb, var(--accent) 32%, var(--border)); transform: translateY(-1px); }
|
||||
.dock-audio-button.microphone-header-toggle.muted { color: var(--danger); background: color-mix(in srgb, var(--danger) 12%, var(--surface-1)); }
|
||||
@@ -2744,4 +3261,56 @@ function stopWhisperTalk(): void {
|
||||
.performance-route { gap: 3px; }
|
||||
.performance-route span { padding-inline: 4px; font-size: 8px; }
|
||||
}
|
||||
|
||||
/* Desktop audio popovers: keep the rail compact and reveal each control's
|
||||
adjustment surface only while the pointer or keyboard focus is on it. */
|
||||
@media (min-width: 741px) {
|
||||
.app-shell .member-panel { overflow: visible; }
|
||||
.desktop-audio-dock { position: relative; z-index: 6; }
|
||||
}
|
||||
|
||||
.dock-hover-control { position: relative; flex: 0 0 34px; }
|
||||
.dock-hover-panel {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
right: 50%;
|
||||
bottom: calc(100% + 10px);
|
||||
width: min(224px, calc(100vw - 32px));
|
||||
padding: 13px 14px;
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-1);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 15px 34px color-mix(in srgb, var(--text-primary) 18%, transparent);
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
transform: translate(50%, 6px);
|
||||
transition: opacity .16s ease, transform .16s ease, visibility .16s ease;
|
||||
}
|
||||
.dock-hover-panel::after { content: ""; position: absolute; right: auto; bottom: -6px; left: 50%; width: 10px; height: 10px; background: var(--surface-1); border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); transform: translateX(-50%) rotate(45deg); }
|
||||
.dock-hover-control:hover .dock-hover-panel,
|
||||
.dock-hover-control:focus-within .dock-hover-panel { opacity: 1; visibility: visible; pointer-events: auto; transform: translate(50%, 0); }
|
||||
.dock-microphone-panel { width: min(246px, calc(100vw - 32px)); }
|
||||
.dock-slider-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.dock-slider-heading span { min-width: 0; overflow: hidden; color: var(--text-muted); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.dock-slider-heading strong { flex: 0 0 auto; color: var(--accent); font-size: 11px; }
|
||||
.dock-slider { width: 100%; height: 5px; margin: 11px 0 1px; appearance: none; border-radius: 999px; outline: none; cursor: pointer; }
|
||||
.dock-slider::-webkit-slider-thumb { width: 14px; height: 14px; appearance: none; border: 2px solid #81d8d0; border-radius: 50%; background: var(--surface-1); box-shadow: 0 2px 4px color-mix(in srgb, var(--text-primary) 14%, transparent); cursor: pointer; }
|
||||
.dock-slider::-moz-range-thumb { width: 14px; height: 14px; border: 2px solid #81d8d0; border-radius: 50%; background: var(--surface-1); box-shadow: 0 2px 4px color-mix(in srgb, var(--text-primary) 14%, transparent); cursor: pointer; }
|
||||
.dock-panel-divider { height: 1px; margin: 12px 0; background: var(--border); }
|
||||
.dock-switch-row, .mobile-noise-toggle { display: flex; align-items: center; justify-content: space-between; gap: 12px; cursor: pointer; }
|
||||
.dock-switch-row > span, .mobile-noise-toggle > span { min-width: 0; }
|
||||
.dock-switch-row strong, .mobile-noise-toggle strong { display: block; color: var(--text-primary); font-size: 11px; }
|
||||
.mobile-noise-toggle { margin-bottom: 18px; padding: 12px; background: var(--surface-2); border: 1px solid var(--border); border-radius: 11px; }
|
||||
.mobile-noise-toggle small { display: block; margin-top: 3px; color: var(--text-muted); font-size: 10px; line-height: 1.4; }
|
||||
.dock-switch-row input, .mobile-noise-toggle input { position: relative; width: 34px; height: 20px; flex: 0 0 34px; margin: 0; padding: 0; appearance: none; border: 2px solid var(--border); border-radius: 999px; outline: none; background: var(--surface-2); cursor: pointer; transition: background .16s ease, border-color .16s ease; }
|
||||
.dock-switch-row input::before, .mobile-noise-toggle input::before { content: ""; position: absolute; top: 2px; left: 2px; width: 12px; height: 12px; border-radius: 50%; background: var(--text-muted); transition: transform .16s ease, background .16s ease; }
|
||||
.dock-switch-row input:checked, .mobile-noise-toggle input:checked { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 72%, var(--surface-2)); }
|
||||
.dock-switch-row input:checked::before, .mobile-noise-toggle input:checked::before { background: var(--surface-1); transform: translateX(14px); }
|
||||
.dock-switch-row input:focus-visible, .mobile-noise-toggle input:focus-visible { outline: 3px solid color-mix(in srgb, var(--accent) 45%, transparent); outline-offset: 2px; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.dock-hover-panel, .dock-switch-row input, .mobile-noise-toggle input { transition-duration: .01ms; }
|
||||
}
|
||||
</style>
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
Reference in new issue
Block a user