Compare commits

..
90 Commits
Author SHA1 Message Date
illusia 5ce73d2c84 docs: finalize v0.2.0 release notes 2026-09-10 20:42:17 +08:00
illusia 2d1d202981 fix: use valid Docker healthcheck syntax 2026-09-10 20:20:09 +08:00
illusia 73313f9e2d feat: add relay deployment mode and multiple relays 2026-09-10 20:16:50 +08:00
illusia 097c72bc5d release: prepare v0.2.0 2026-09-10 17:47:34 +08:00
illusia 71f219b7ca merge: promote 0.2.0 preview features 2026-09-10 17:29:35 +08:00
illusia bacc9fe07e merge: integrate connection error fixes 2026-09-10 17:28:41 +08:00
illusia a9c360fb9c docs: describe 0.2.0 connection fixes 2026-09-10 17:27:44 +08:00
illusia 04926c8491 docs: record admin log improvements 2026-09-10 17:25:28 +08:00
illusia fa1d1ad01b docs: add advanced feature guides 2026-09-10 17:22:13 +08:00
illusia c0fc18c344 docs: add advanced feature guides 2026-09-10 17:20:13 +08:00
illusia 69d69f0a5a fix: show generic reason for untraceable history 2026-09-10 17:03:22 +08:00
illusia 6d7976e5d8 fix: hide disabled relay and report password errors 2026-09-10 16:32:18 +08:00
illusia aef1f68875 fix: explain TeamSpeak connection failures 2026-09-10 16:11:18 +08:00
illusia 06e5cc6d8b fix: allow explicit private targets on relay service 2026-09-10 15:35:57 +08:00
illusia 7782e9b327 feat: expose acceleration relay settings in admin console 2026-09-10 15:25:47 +08:00
illusia b82c4fe0af feat: add mainland acceleration preview 2026-09-10 14:27:33 +08:00
illusia 45584810a2 test: add IPv6 acceleration smoke 2026-09-10 11:54:31 +08:00
illusia bfefd053a0 feat: add acceleration tunnel proof of concept 2026-09-10 11:29:18 +08:00
illusia 324213de14 chore: remove repository test sources 2026-09-10 10:54:18 +08:00
illusia a041ba90bb fix: support IPv6 TeamSpeak targets safely 2026-09-10 10:39:02 +08:00
illusia 0dc623eb69 docs: simplify Docker deployment instructions 2026-09-08 13:38:23 +08:00
illusia 3e6876dbe7 release: prepare v0.1.8 2026-09-08 11:25:50 +08:00
illusia a60abffd3b fix: make performance probe handlers browser-safe 2026-09-08 11:09:51 +08:00
illusia 2b43952c01 fix: harden local targets and monitor network continuously 2026-09-08 11:01:28 +08:00
Object ILLUSIA 12f440ab8b Update README to remove image width attribute
Removed width attribute from project icon image.
2026-09-07 13:39:11 +08:00
Object ILLUSIA 7221af78bf Change project icon image in README
Updated the image source in the README file.
2026-09-07 13:38:39 +08:00
Object ILLUSIA a88b0616f5 upload banner
banner
2026-09-07 13:38:14 +08:00
illusia ea4d5b2a70 docs: expand localized interface screenshots 2026-09-06 15:36:46 +08:00
illusia a439100ad6 docs: add localized interface screenshots 2026-09-06 15:28:37 +08:00
illusia 620d24f796 fix: compact latin locale typography 2026-09-06 15:24:51 +08:00
illusia fc3bbd0c59 fix: install ping for admin diagnostics 2026-09-06 15:08:19 +08:00
illusia 3b5ce9b446 fix: restore dark welcome contrast 2026-09-06 14:51:51 +08:00
illusia 37de6067d0 fix: widen language menu options 2026-09-06 14:40:51 +08:00
illusia 45410fcc7d fix: keep quiet WebRTC audio frames 2026-09-06 14:33:15 +08:00
illusia 166cb543a1 fix: make admin diagnostics clientless 2026-09-06 14:18:41 +08:00
illusia a295ff4b27 fix: measure TeamSpeak latency over its protocol 2026-09-06 14:04:41 +08:00
illusia dcc52c4530 release: refresh v0.1.7 diagnostics 2026-09-06 13:47:37 +08:00
illusia dc3ad6a598 release: prepare v0.1.7 2026-09-06 10:48:16 +08:00
illusia ef59e51e32 fix: reveal master volume slider on hover 2026-09-06 10:38:54 +08:00
illusia 9bbc22de25 feat: add master output volume control 2026-09-06 10:25:18 +08:00
illusia 335d93a8b8 fix: preserve accompaniment levels and channel password retry 2026-09-06 09:54:01 +08:00
illusia 52ff0560d1 feat: add German language option and Telegram community link 2026-09-06 09:10:58 +08:00
illusia a5e5dd6592 fix: align connection diagnostics and localize announcement 2026-09-06 08:53:39 +08:00
illusia 62e41dbc51 docs: show demo URL directly 2026-09-06 00:59:00 +08:00
illusia d8b2fd9e1b docs: reorganize bilingual README 2026-09-06 00:49:56 +08:00
illusia 8ca3249832 feat: use penguin icon for QQ entry 2026-09-05 23:35:42 +08:00
illusia 92574fddb1 feat: add QQ community entry to homepage 2026-09-05 21:59:15 +08:00
illusia 596114e6a3 fix: repair admin theme and merge connection history 2026-09-05 21:45:54 +08:00
illusia 2868f7a478 feat: animate welcome page text 2026-09-05 20:08:29 +08:00
illusia 63ef6b673d docs: remove private server address from README 2026-09-05 19:52:04 +08:00
illusia 5a56e1706f fix: remove welcome artwork 2026-09-05 18:09:37 +08:00
illusia 986814441d fix: keep welcome artwork and text readable 2026-09-05 18:09:06 +08:00
illusia 0ab6fb6f3f fix: remove welcome background overlay 2026-09-05 17:43:06 +08:00
illusia a966be4db6 feat: refresh welcome page visuals 2026-09-05 17:35:49 +08:00
illusia 556084233d fix: do not drop WebRTC volume updates 2026-09-04 19:39:45 +08:00
illusia c38239ec35 fix: apply member volume in WebRTC playback 2026-09-04 19:31:50 +08:00
illusia 21041346e3 docs: update README version badge 2026-09-04 16:59:55 +08:00
illusia 7320aa3bb5 release: prepare v0.1.6 2026-09-04 16:31:59 +08:00
illusia d9b8ea625a feat: add repository and site branding 2026-09-04 16:08:43 +08:00
illusia 2323e22fef fix: keep identity concurrency warning visible 2026-09-04 16:03:13 +08:00
illusia b5f8f01301 fix: guard concurrent remembered identities 2026-09-04 15:53:15 +08:00
illusia e964ff460e fix: bypass mixer for single accompaniment stream 2026-09-04 15:41:58 +08:00
illusia 21d8d9c3bc fix: preserve accompaniment audio levels 2026-09-04 14:30:51 +08:00
illusia 169cf88306 fix: preserve accompaniment frames in WebRTC mixer 2026-09-04 12:46:07 +08:00
illusia 059435f4cb fix: preserve WebRTC playback diagnostics 2026-09-04 11:59:53 +08:00
illusia 4d4d4cdeb1 fix: pace WebRTC downlink audio 2026-09-04 11:50:26 +08:00
illusia d42e7a033c fix: handle canceled accompaniment sharing 2026-09-04 10:37:38 +08:00
illusia 0986c65551 feat: add desktop accompaniment controls 2026-09-04 10:24:10 +08:00
illusia 694f864d36 fix: include ca certificates in docker build 2026-09-04 08:38:06 +08:00
illusia 512854ab9f fix: pin sdk lockfile for reproducible installs 2026-09-04 08:31:48 +08:00
illusia b298496911 fix: make sdk release preparation deterministic 2026-09-04 08:27:28 +08:00
illusia b6367e2645 release: prepare v0.1.5 2026-09-04 08:18:56 +08:00
illusia b0fa4bf5d0 fix: make theme toggle respond on first click 2026-09-04 08:05:19 +08:00
illusia cb3dbe4ca4 fix: preserve remembered browser identity on exit 2026-09-03 23:40:38 +08:00
illusia 96ba467d52 release: prepare v0.1.4 2026-09-03 17:07:35 +08:00
illusia 20fdcc7b1d fix: fit welcome header actions on narrow screens 2026-09-03 16:59:28 +08:00
illusia feea39a81c feat: add bilibili profile link 2026-09-03 16:57:35 +08:00
illusia 69d1653f99 feat: add home link to admin login 2026-09-03 16:53:39 +08:00
illusia a18a5b4920 fix: wrap long admin logs on desktop 2026-09-03 16:46:40 +08:00
illusia 343dd84132 fix: wrap long mobile admin logs 2026-09-03 16:44:52 +08:00
illusia a037962cc1 fix: let mobile admin pages scroll naturally 2026-09-03 16:40:22 +08:00
illusia 680ce246fd fix: compact server settings layout 2026-09-03 16:36:52 +08:00
illusia baa09ad38c feat: customize and lock WebRTC media ports 2026-09-03 16:28:49 +08:00
illusia 767bdea018 fix: show channel broadcast messages 2026-09-03 16:08:51 +08:00
illusia 83a8fd0d5a fix: enforce WebRTC microphone mute at gateway 2026-09-03 15:25:34 +08:00
illusia e14ddc9465 fix: filter silent WebRTC uplink frames 2026-09-03 15:16:20 +08:00
illusia 7feb97d77d fix: keep WebRTC playback on native media output 2026-09-03 14:52:59 +08:00
illusia 434360cda9 fix: recover WebRTC playback and speaker state 2026-09-03 14:45:44 +08:00
illusia d0a2e9edc0 fix: make WebRTC playback reliable 2026-09-03 14:28:47 +08:00
illusia 61f66ab319 docs: simplify user-facing README 2026-09-03 12:54:11 +08:00
81 changed files with 5599 additions and 1796 deletions

No files matched your search

+1
View File
@@ -8,6 +8,7 @@ web/dist
data
certs
release-artifacts
scripts/acceleration-poc
*.tar.gz
*.tar.xz
claude.pem
+8 -2
View File
@@ -34,7 +34,11 @@ jobs:
run: |
$ErrorActionPreference = "Stop"
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
npm ci --no-audit --no-fund
npm ci --ignore-scripts --no-audit --no-fund
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
npm run prepare:sdk
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
npm --prefix web ci --no-audit --no-fund
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
@@ -130,7 +134,9 @@ jobs:
run: |
set -euo pipefail
release_version="${RELEASE_REF#v}"
npm ci --no-audit --no-fund
npm ci --ignore-scripts --no-audit --no-fund
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
npm --prefix web ci --no-audit --no-fund
current_version="$(node -p "require('./package.json').version")"
if [ "$current_version" != "$release_version" ]; then
+4 -3
View File
@@ -22,11 +22,12 @@ jobs:
web/package-lock.json
- name: Install dependencies
run: |
npm ci --no-audit --no-fund
npm ci --ignore-scripts --no-audit --no-fund
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
npm --prefix web ci --no-audit --no-fund
- name: Test and build
- name: Build application
run: |
npm test
npm run build
npm --prefix web run build
+138
View File
@@ -1,7 +1,145 @@
# Changelog
## [0.2.0] — 2026-09-10
### 中文
- 新增 README“高级功能”章节,补充 WebRTC 与中继服务器的配置和使用步骤。
- 明确 WebRTC 的 UDP 端口、安全组与防火墙要求,以及中继令牌和管理员控制台配置方式。
- 标注中继服务为 WebSpeak 自带实现;同时注明 WebRTC 使用 MIT 许可的 `werift` 依赖,TeamSpeak 连接使用项目维护的 SDK fork。
- 细分 TeamSpeak 连接失败原因,服务器需要密码时提示用户输入密码并重试。
- 优化管理员历史连接日志:能够追溯时显示具体原因,无法追溯时使用通用失败提示,不猜测历史原因。
- 新增正式中继部署模式:中继实例不提供前台和管理员后台,只接受带令牌的网关转发会话。
- 管理员可配置多个中继节点,访客可在欢迎页为当前连接选择直连或指定中继。
- 修复用户正常断开后被管理员运维日志误显示为“请求失败”的问题。
### English
- Added an “Advanced features” section to the README with WebRTC and relay configuration and usage steps.
- Documented WebRTC UDP, security-group, and firewall requirements, plus relay-token and administration-console setup.
- Clarified that the relay is built into WebSpeak, while WebRTC uses the MIT-licensed `werift` dependency and TeamSpeak connectivity uses the project-maintained SDK fork.
- Classified TeamSpeak connection failures and prompt users for a server password with a retry when authentication requires one.
- Improved administrator connection history: show a specific reason when available and use a generic failure message when older records cannot be traced, without guessing.
- Added a formal relay deployment mode: relay instances expose no visitor or admin UI and accept only token-authenticated gateway sessions.
- Administrators can configure multiple relay nodes, and visitors can choose direct access or a specific relay for each connection.
- Fixed normal user disconnects being shown as “request failed” in administrator connection history.
### Deutsch
- Einen Abschnitt „Erweiterte Funktionen“ mit Anleitungen für WebRTC und Relay-Server zur README hinzugefügt.
- UDP-, Sicherheitsgruppen- und Firewall-Anforderungen für WebRTC sowie Relay-Token und Administrationskonfiguration dokumentiert.
- Klargestellt, dass das Relay Bestandteil von WebSpeak ist; WebRTC verwendet die MIT-lizenzierte Abhängigkeit `werift`, die TeamSpeak-Verbindung den projektgepflegten SDK-Fork.
- TeamSpeak-Verbindungsfehler genauer klassifiziert und bei erforderlichem Serverpasswort eine Eingabe mit Wiederholung angeboten.
- Den Verlauf der Administrator-Verbindungen verbessert: verfügbare Ursachen werden angezeigt, ältere nicht nachvollziehbare Einträge erhalten eine allgemeine Fehlermeldung statt einer Vermutung.
- Einen dedizierten Relay-Bereitstellungsmodus ergänzt: Relay-Instanzen stellen keine Besucher- oder Admin-Oberfläche bereit und akzeptieren nur Gateway-Sitzungen mit Token.
- Administratoren können mehrere Relay-Knoten konfigurieren; Besucher wählen pro Verbindung Direktzugriff oder ein bestimmtes Relay.
- Behoben, dass normale Benutzertrennungen im Administrationsverlauf als „Anfrage fehlgeschlagen“ erschienen.
## [0.1.8] — 2026-09-08
### 中文
- Docker 默认使用 host 网络,支持网关访问同机 TeamSpeak 并直接暴露 WebRTC UDP 端口。
- 开放模式统一校验用户提交的目标地址,包括管理员默认目标,修复本机与内网目标绕过限制的问题。
- TeamSpeak SDK 连接握手增加 15 秒超时,失败连接会及时清理。
- 网络性能面板改为持续监测,打开后每 3 秒更新一次延迟与丢包率。
### English
- Docker now uses host networking by default, allowing the gateway to reach a local TeamSpeak server and expose the WebRTC UDP range directly.
- Open access now validates every submitted target, including the administrator default, closing loopback and private-network bypasses.
- Added a 15-second TeamSpeak SDK handshake timeout with prompt cleanup after failed connections.
- The network performance panel now measures continuously and refreshes latency and packet loss every 3 seconds while open.
### Deutsch
- Docker verwendet standardmäßig das Host-Netzwerk, damit das Gateway einen lokalen TeamSpeak-Server erreicht und den WebRTC-UDP-Bereich direkt bereitstellt.
- Der offene Zugriffsmodus prüft nun jedes Ziel einschließlich des Administrator-Standards und schließt Umgehungen für Loopback- und private Netze.
- Für den TeamSpeak-SDK-Handshake gilt jetzt ein Timeout von 15 Sekunden; fehlgeschlagene Verbindungen werden zeitnah bereinigt.
- Das Netzwerkleistungsfeld misst bei geöffneter Ansicht fortlaufend und aktualisiert Latenz und Paketverlust alle 3 Sekunden.
## [0.1.7] — 2026-09-06
### 中文
- 增加 Deutsch 界面支持和 Telegram 群组入口。
- 增加桌面端整体音量滑块,默认收起并在悬停时展开。
- 修复伴奏音量忽大忽小的问题。
- 增加可展开的网络性能面板,显示浏览器、WebSpeak 与 TeamSpeak 之间的延迟和丢包率。
- 管理员连接测试改用服务端多次主机 Ping 并显示丢包率,不再创建临时 TeamSpeak 客户端。
- 统一中文、English、Deutsch 的旗帜代码语言菜单。
- 修复 TeamSpeak 使用 TCP 探测导致的误报丢包,并修正语言菜单异常留白。
- 移除 WebRTC 桥接中的 RMS 静音帧过滤,安静帧仅用于发言状态指示,不再丢弃。
- 修复 Docker 运行环境缺少 ICMP Ping 工具导致管理员测试误报 100% 丢包。
### English
- Added German UI support and a Telegram community link.
- Added a compact desktop master-volume slider that expands on hover.
- Fixed accompaniment volume fluctuations.
- Added an expandable network performance panel with latency and packet loss across the browser, WebSpeak, and TeamSpeak path.
- Updated the administrator connection test to use repeated host pings, report packet loss, and avoid creating temporary TeamSpeak clients.
- Unified the Chinese, English, and German flag/code language menu.
- Fixed false packet-loss reports caused by probing the TeamSpeak UDP service with TCP, and corrected excess space in the language menu.
- Removed RMS-based silence filtering from the WebRTC bridge; quiet frames are now retained for the codec timeline.
- Fixed Docker admin diagnostics falsely reporting 100% packet loss when the runtime lacked the ICMP ping tool.
### Deutsch
- Deutsche Benutzeroberfläche und Telegram-Community-Link hinzugefügt.
- Kompakten Gesamtlautstärkeregler für den Desktop ergänzt, der sich beim Überfahren öffnet.
- Schwankende Lautstärke bei der Begleittonfreigabe behoben.
- Aufklappbares Netzwerkleistungsfeld mit Latenz und Paketverlust zwischen Browser, WebSpeak und TeamSpeak ergänzt.
- Verbindungstest in der Administration auf wiederholte Host-Pings mit Paketverlustanzeige umgestellt, ohne temporäre TeamSpeak-Clients zu erzeugen.
- Einheitliches Sprachmenü mit Flaggen und Sprachcodes für Chinesisch, Englisch und Deutsch ergänzt.
- Falsche Paketverlustmeldungen durch TCP-Prüfung des UDP-Dienstes behoben und übermäßigen Leerraum im Sprachmenü korrigiert.
- RMS-basierte Stillefilterung aus der WebRTC-Brücke entfernt; leise Frames bleiben nun im Codec-Zeitverlauf erhalten.
- Falsche 100-%-Paketverlustmeldungen behoben, wenn dem Docker-Laufzeitimage das ICMP-Ping-Tool fehlte.
## [0.1.6] — 2026-09-04
### 中文
- 新增保持身份并发连接提醒,避免同一浏览器复用身份造成连接卡住。
- 新增桌面端伴奏共享功能。
- 新增网站 favicon,并更新仓库 README 主视觉。
### English
- Added a warning for concurrent remembered-identity connections in the same browser.
- Added desktop accompaniment sharing.
- Added a site favicon and refreshed the repository README branding.
## [0.1.5] — 2026-09-04
### 中文
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
- 修复浏览器身份保存与退出后的保持逻辑。
### English
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
- Fixed browser identity persistence across exit and return.
All notable changes to WebSpeak are documented here. Versions follow SemVer.
## [0.1.4] — 2026-09-03
### 中文
- 修复 WebRTC 语音收发与发言状态同步。
- 修复频道文字消息在 WebSpeak 客户端之间无法互收。
- 优化管理员页面、运行日志换行和移动端顶部布局。
- 首页新增 Bilibili 入口,管理员登录页新增返回首页。
### English
- Fixed WebRTC voice transport and speaking-state synchronization.
- Fixed channel text messages between WebSpeak clients.
- Refined admin pages, log wrapping, and narrow-screen header layout.
- Added the Bilibili profile link and the admin-login home link.
## [0.1.3] — 2026-09-03
### Added
+8 -5
View File
@@ -2,12 +2,15 @@ FROM node:22-bookworm-slim AS build
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends git python3 make g++ \
&& apt-get install -y --no-install-recommends ca-certificates git python3 make g++ \
&& rm -rf /var/lib/apt/lists/*
COPY package.json package-lock.json ./
COPY web/package.json web/package-lock.json ./web/
RUN npm ci
RUN npm ci --ignore-scripts --no-audit --no-fund
COPY scripts/prepare-sdk.mjs ./scripts/prepare-sdk.mjs
RUN npm run prepare:sdk
RUN npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
RUN npm --prefix web ci
COPY . .
@@ -20,7 +23,7 @@ FROM node:22-bookworm-slim AS runtime
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 \
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 iputils-ping \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /data \
&& chown node:node /data
@@ -35,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"]
+600 -453
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -3,9 +3,9 @@ services:
image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest}
pull_policy: missing
restart: unless-stopped
ports:
- "${WEBSPEAK_PORT:-3040}:3040"
- "40000-40099:40000-40099/udp"
# WebSpeak needs to reach a TeamSpeak server running on the same host.
# Host networking also exposes the configured WebRTC UDP range directly.
network_mode: host
volumes:
- webspeak-data:/data
Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+4 -4
View File
@@ -1,16 +1,16 @@
{
"name": "webspeak-webclient",
"version": "0.1.3",
"version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.1.3",
"version": "0.2.0",
"license": "AGPL-3.0-only",
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6",
"@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#f38dee6cd83c0fd4f6e00fc9c1ff4ec79dcbfd55",
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338c7a83044dee0951c412ad91292b570215",
"license": "MIT",
"dependencies": {
"@noble/curves": "^2.0.1"
+8 -4
View File
@@ -1,6 +1,6 @@
{
"name": "webspeak-webclient",
"version": "0.1.3",
"version": "0.2.0",
"private": true,
"license": "AGPL-3.0-only",
"type": "module",
@@ -11,14 +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"
"web:build": "cd web && npx vite build",
"prepare:sdk": "node scripts/prepare-sdk.mjs",
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
"acceleration:relay": "node dist/relay.js"
},
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#a145338",
"express": "^5.2.1",
"pino": "^10.3.1",
"werift": "0.24.4",
+52
View File
@@ -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、断线重连和目标地址安全策略。
+116
View File
@@ -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");
+106
View File
@@ -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);
}
+180
View File
@@ -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}`);
}
+50
View File
@@ -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();
}
+60
View File
@@ -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;
});
+100
View File
@@ -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;
});
+48
View File
@@ -0,0 +1,48 @@
import { cpSync, existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import process from "node:process";
const root = process.cwd();
const sdkPackage = "@echosixhiya/teamspeak-client";
const packageJson = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
const dependency = packageJson.dependencies?.[sdkPackage];
const match = typeof dependency === "string" ? /^git\+(.+?)#(.+)$/.exec(dependency) : null;
if (!match) {
throw new Error(`${sdkPackage} must be pinned to a Git repository commit`);
}
const [, repository, commit] = match;
const temporaryRoot = mkdtempSync(join(tmpdir(), "webspeak-sdk-build-"));
const destination = join(root, "node_modules", "@echosixhiya", "teamspeak-client", "dist");
try {
execFileSync("git", ["clone", "--no-checkout", repository, temporaryRoot], { stdio: "inherit" });
execFileSync("git", ["checkout", "--detach", commit], { cwd: temporaryRoot, stdio: "inherit" });
const npmOptions = { cwd: temporaryRoot, stdio: "inherit" };
const runNpm = (args) => {
if (process.platform === "win32") {
execFileSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `npm.cmd ${args.join(" ")}`], npmOptions);
} else {
execFileSync("npm", args, npmOptions);
}
};
runNpm(["install", "--ignore-scripts", "--no-audit", "--no-fund"]);
runNpm(["run", "build"]);
const source = join(temporaryRoot, "dist");
if (!existsSync(join(source, "index.mjs"))) {
throw new Error(`SDK build did not produce ${join(source, "index.mjs")}`);
}
mkdirSync(dirname(destination), { recursive: true });
mkdirSync(destination, { recursive: true });
for (const entry of readdirSync(source)) {
cpSync(join(source, entry), join(destination, entry), { recursive: true, force: true });
}
console.log(`Prepared ${sdkPackage} from ${commit}`);
} finally {
rmSync(temporaryRoot, { recursive: true, force: true });
}
+171 -2
View File
@@ -1,12 +1,24 @@
import { Router, type NextFunction, type Request, type Response } from "express";
import { existsSync, readFileSync } from "node:fs";
import type { Logger } from "../logger.js";
import { AdminInputError, AdminService, type AdminSettingsInput } from "./admin-service.js";
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput } from "./admin-service.js";
import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
import type { AdminSessionSummary } from "../server/voice-bridge.js";
export interface AdminConnectionRecord {
id: string;
nickname: string;
target: string;
startedAt: string;
connectedAt: string | null;
disconnectedAt: string | null;
durationSeconds: number | null;
status: "active" | "connecting" | "disconnected" | "failed";
reason: string | null;
}
export interface AdminRouterOptions {
service: AdminService;
sessions: AdminSessionStore;
@@ -155,7 +167,12 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
});
router.get("/logs", (request, response) => {
response.json({ available: Boolean(options.logFile && existsSync(options.logFile)), entries: readRecentLogs(options.logFile, readLimit(request.query.limit, 100)) });
const limit = readLimit(request.query.limit, 100);
response.json({
available: Boolean(options.logFile && existsSync(options.logFile)),
entries: readRecentLogs(options.logFile, limit),
sessions: readConnectionHistory(options.logFile, limit),
});
});
router.get("/diagnostics", (_request, response) => {
@@ -325,6 +342,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,
@@ -332,10 +362,24 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
accessMode: body.accessMode === "open" ? "open" : body.accessMode === "fixed" ? "fixed" : body.accessMode as never,
siteName: readString(body, "siteName", 80),
welcomeText: readOptionalString(body, "welcomeText", 500),
welcomeTextEn: typeof body.welcomeTextEn === "string" ? body.welcomeTextEn.slice(0, 500) : undefined,
webRtcEnabled: body.webRtcEnabled === true,
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
relayEnabled: body.relayEnabled === true,
relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined,
relayTarget: typeof body.relayTarget === "string" ? body.relayTarget.slice(0, 300) : undefined,
relayToken: typeof body.relayToken === "string" ? body.relayToken.slice(0, 512) : undefined,
relayTokenAction: readPasswordAction(body.relayTokenAction),
relayNodes,
};
}
function readRelaySettingsAction(value: unknown): "keep" | "replace" | "remove" {
return value === "replace" || value === "remove" ? value : "keep";
}
function readPasswordAction(value: unknown): "keep" | "replace" | "remove" {
return value === "replace" || value === "remove" ? value : "keep";
}
@@ -350,6 +394,14 @@ function readString(body: Record<string, unknown>, key: string, max: number): st
return body[key];
}
function readOptionalInteger(body: Record<string, unknown>, key: string): number | undefined {
if (body[key] === undefined) return undefined;
if (typeof body[key] !== "number" || !Number.isSafeInteger(body[key])) {
throw new AdminInputError("INVALID_REQUEST", `${key} is invalid`);
}
return body[key];
}
function readOptionalString(body: Record<string, unknown>, key: string, max: number): string {
return typeof body[key] === "string" ? body[key].slice(0, max) : "";
}
@@ -397,6 +449,123 @@ function readRecentLogs(logFile: string | undefined, limit: number): AdminLogEnt
}
}
interface StructuredLogEntry {
timestamp: string | null;
message: string;
raw: Record<string, unknown>;
}
export function readConnectionHistory(logFile: string | undefined, limit: number): AdminConnectionRecord[] {
if (!logFile) return [];
const records = new Map<string, {
id: string;
nickname: string;
target: string;
startedAt: string | null;
connectedAt: string | null;
disconnectedAt: string | null;
durationSeconds: number | null;
status: AdminConnectionRecord["status"];
reason: string | null;
}>();
for (const log of readStructuredLogs(logFile)) {
const entryId = typeof log.raw.entryId === "string" ? log.raw.entryId : "";
if (!entryId || !log.timestamp) continue;
const current = records.get(entryId) ?? {
id: entryId,
nickname: "",
target: "",
startedAt: null,
connectedAt: null,
disconnectedAt: null,
durationSeconds: null,
status: "connecting" as const,
reason: null,
};
const nickname = typeof log.raw.nickname === "string" ? log.raw.nickname : "";
const target = typeof log.raw.target === "string" ? log.raw.target : "";
if (nickname) current.nickname = nickname;
if (target) current.target = target;
if (log.message === "WebClient connecting") {
current.startedAt ??= log.timestamp;
current.status = "connecting";
} else if (log.message === "Web client connected to TeamSpeak") {
current.startedAt ??= log.timestamp;
current.connectedAt = log.timestamp;
current.status = "active";
} else if (log.message === "Client session torn down") {
current.startedAt ??= log.timestamp;
current.disconnectedAt = log.timestamp;
current.durationSeconds = current.connectedAt && typeof log.raw.durationSeconds === "number"
? Math.max(0, Math.floor(log.raw.durationSeconds))
: current.connectedAt
? Math.max(0, Math.floor((Date.parse(log.timestamp) - Date.parse(current.connectedAt)) / 1000))
: null;
current.status = current.connectedAt ? "disconnected" : "failed";
// `reason` is also used for ordinary lifecycle teardown (for example
// websocket-close when a user clicks Leave). Only preserve an explicit
// TeamSpeak failure code here; otherwise a normal disconnect would be
// rendered by the admin UI as the generic request-failed message.
current.reason = typeof log.raw.failureCode === "string" && log.raw.failureCode
? log.raw.failureCode
: null;
}
records.set(entryId, current);
}
const now = Date.now();
return [...records.values()]
.filter((record): record is typeof record & { startedAt: string } => Boolean(record.startedAt))
.map((record) => {
const start = record.connectedAt ?? record.startedAt;
const end = record.disconnectedAt ? Date.parse(record.disconnectedAt) : now;
return {
id: record.id,
nickname: record.nickname || "—",
target: record.target || "—",
startedAt: record.startedAt,
connectedAt: record.connectedAt,
disconnectedAt: record.disconnectedAt,
durationSeconds: record.durationSeconds ?? (record.status === "active" || record.status === "connecting"
? Math.max(0, Math.floor((end - Date.parse(start)) / 1000))
: null),
status: record.status,
// Older sessions may only contain a teardown record without a
// structured failure code. Keep normal disconnects quiet, but make
// an untraceable failed connection explicitly visible as the generic
// request-failed message instead of implying a guessed cause.
reason: record.reason ?? (record.status === "failed" ? "CONNECTION_FAILED" : null),
};
})
.sort((left, right) => Date.parse(right.disconnectedAt ?? right.startedAt) - Date.parse(left.disconnectedAt ?? left.startedAt))
.slice(0, limit);
}
function readStructuredLogs(logFile: string): StructuredLogEntry[] {
const paths = [logFile, `${logFile}.1`, `${logFile}.2`, `${logFile}.3`].filter((value, index, all) => value && all.indexOf(value) === index);
const entries: StructuredLogEntry[] = [];
for (const path of paths) {
if (!existsSync(path)) continue;
try {
for (const line of readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean)) {
try {
const raw = JSON.parse(line) as Record<string, unknown>;
entries.push({
timestamp: typeof raw.time === "string" ? raw.time : null,
message: typeof raw.msg === "string" ? raw.msg : "",
raw,
});
} catch {
// Non-JSON lines are still shown by the normal log viewer, but cannot
// be associated with a user session safely.
}
}
} catch {
// A rotated file can disappear between existsSync and readFileSync.
}
}
return entries.sort((left, right) => Date.parse(left.timestamp ?? "") - Date.parse(right.timestamp ?? ""));
}
interface AdminOverview {
gateway: { uptimeSeconds: number };
teamSpeak: {
+266 -7
View File
@@ -3,11 +3,14 @@ import { existsSync } from "node:fs";
import type { Logger } from "../logger.js";
import { loadConfig } from "../config.js";
import { formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
import { type AccessMode, type ManagedInviteRecord, type PersistedRelayNode, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
import { probeTeamSpeak, TeamSpeakProbeError, type TeamSpeakProbeResult } from "../server/teamspeak-probe.js";
import { probeTeamSpeak, TeamSpeakProbeError } from "../server/teamspeak-probe.js";
import { pingTeamSpeakHost } from "../server/network-probe.js";
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
export interface AdminSettingsInput {
target: string;
@@ -16,7 +19,26 @@ export interface AdminSettingsInput {
accessMode: AccessMode;
siteName: string;
welcomeText: string;
welcomeTextEn?: 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,6 +116,7 @@ export class AdminService {
initialized: this.isInitialized(),
siteName: settings.siteName,
welcomeText: settings.welcomeText,
welcomeTextEn: settings.welcomeTextEn,
accessMode: settings.accessMode,
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
};
@@ -107,10 +130,19 @@ export class AdminService {
accessMode: settings.accessMode,
siteName: settings.siteName,
welcomeText: settings.welcomeText,
welcomeTextEn: settings.welcomeTextEn,
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,
};
@@ -118,14 +150,41 @@ export class AdminService {
getWebRtcAudioOptions(): WebRtcAudioOptions {
const settings = this.database.getSettings();
return { enabled: settings.webRtcEnabled };
return {
enabled: settings.webRtcEnabled,
udpPortRange: [settings.webRtcUdpStart, settings.webRtcUdpEnd],
};
}
getAccelerationRelayOptions(): ConfiguredAccelerationRelay[] {
const relays: ConfiguredAccelerationRelay[] = [];
for (const node of this.database.listRelayNodes()) {
if (!node.enabled || !node.host || !node.tokenEncrypted) continue;
try {
const token = decryptSecret(node.tokenEncrypted, this.masterSecret);
relays.push({ id: node.id, name: node.name, relayHost: node.host, relayPort: node.port, token });
} catch (error: unknown) {
this.logger.error({ err: error instanceof Error ? error.message : String(error), relayId: node.id }, "Stored acceleration relay token could not be decrypted");
}
}
return relays;
}
getAccelerationRelayName(): string | undefined {
return this.getAccelerationRelayOptions()[0]?.name;
}
updateSettings(input: AdminSettingsInput): void {
const current = this.database.getSettings();
const settings = this.normalizeSettings(input, current);
const relayNodes = input.relayNodes === undefined ? undefined : this.normalizeRelayNodes(input.relayNodes);
const settings = this.normalizeSettings(input, current, relayNodes);
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort;
this.database.updateSettings(settings);
if (relayNodes !== undefined) {
this.database.replaceRelayNodes(relayNodes);
} else if (input.relaySettingsAction && input.relaySettingsAction !== "keep") {
this.database.replaceRelayNodes(this.legacyRelayNodesFromSettings(settings));
}
if (targetChanged) this.database.clearConnectionTest();
}
@@ -144,7 +203,7 @@ export class AdminService {
};
}
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<Omit<TeamSpeakProbeResult, "protocol">> {
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);
@@ -152,13 +211,41 @@ export class AdminService {
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
}
try {
// The admin connection test must not create a temporary TeamSpeak
// client: that client becomes visible in the target channel. Use the
// WebSpeak host's ICMP route measurement instead. The injected probe is
// retained for unit tests and explicit protocol-probe callers.
if (this.probe === probeTeamSpeak) {
const result = await pingTeamSpeakHost(target.host, { attempts: 4 });
const publicResult = {
ok: result.ok,
checkType: "network" as const,
passwordVerified: false,
latencyMs: result.latencyMs ?? 0,
serverName: null,
requiresPassword: false,
packetLossPercent: result.packetLossPercent,
attempts: result.attempts,
successfulAttempts: result.successfulAttempts,
...(result.errorCode ? { errorCode: result.errorCode } : {}),
};
if (persistResult) {
this.database.recordConnectionTest({ protocol: null, latencyMs: result.latencyMs, error: result.ok ? null : (result.errorCode ?? "UNREACHABLE") });
this.database.addAudit(result.ok ? "CONNECTION_TEST_SUCCEEDED" : "CONNECTION_TEST_FAILED", {
latencyMs: result.latencyMs,
packetLossPercent: result.packetLossPercent,
...(result.errorCode ? { code: result.errorCode } : {}),
});
}
return publicResult;
}
const result = await this.probe(target, password, this.logger);
if (persistResult) {
this.database.recordConnectionTest({ protocol: result.protocol, latencyMs: result.latencyMs, error: null });
this.database.addAudit("CONNECTION_TEST_SUCCEEDED", { protocol: result.protocol, latencyMs: result.latencyMs });
}
const { protocol: _protocol, ...publicResult } = result;
return publicResult;
return { ...publicResult, checkType: "protocol", passwordVerified: true };
} catch (error: unknown) {
const probeError = error instanceof TeamSpeakProbeError
? error
@@ -246,7 +333,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);
@@ -255,30 +342,180 @@ export class AdminService {
}
const siteName = input.siteName.trim();
const welcomeText = input.welcomeText.trim();
const welcomeTextEn = typeof input.welcomeTextEn === "string" ? input.welcomeTextEn.trim() : current.welcomeTextEn;
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 (input.accessMode !== "fixed" && input.accessMode !== "open") {
throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid");
}
if (typeof input.webRtcEnabled !== "boolean") {
throw new AdminInputError("INVALID_WEBRTC_ENABLED", "WebRTC enabled value is invalid");
}
const webRtcUdpStart = input.webRtcUdpStart ?? current.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0];
const webRtcUdpEnd = input.webRtcUdpEnd ?? current.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1];
if (!Number.isInteger(webRtcUdpStart) || webRtcUdpStart < WEBRTC_UDP_PORT_MIN || webRtcUdpStart > WEBRTC_UDP_PORT_MAX) {
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP start port must be between 1024 and 65535");
}
if (!Number.isInteger(webRtcUdpEnd) || webRtcUdpEnd < WEBRTC_UDP_PORT_MIN || webRtcUdpEnd > WEBRTC_UDP_PORT_MAX) {
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP end port must be between 1024 and 65535");
}
if (webRtcUdpStart > webRtcUdpEnd) {
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP start port must not exceed the end port");
}
if (current.webRtcEnabled && (webRtcUdpStart !== current.webRtcUdpStart || webRtcUdpEnd !== current.webRtcUdpEnd)) {
throw new AdminInputError("WEBRTC_PORT_LOCKED", "Disable WebRTC and save before changing its UDP port range");
}
let encryptedPassword = current.tsPasswordEncrypted;
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
if (action === "remove") encryptedPassword = null;
if (action === "replace") encryptedPassword = input.serverPassword ? encryptSecret(input.serverPassword, this.masterSecret) : null;
let relayConfigured = current.relayConfigured;
let relayEnabled = current.relayEnabled;
let relayName = current.relayName;
let relayHost = current.relayHost;
let relayPort = current.relayPort || DEFAULT_ACCELERATION_RELAY_PORT;
let relayTokenEncrypted = current.relayTokenEncrypted;
const relaySettingsAction = input.relaySettingsAction ?? "keep";
if (relaySettingsAction === "remove") {
relayConfigured = true;
relayEnabled = false;
relayName = "";
relayHost = "";
relayPort = DEFAULT_ACCELERATION_RELAY_PORT;
relayTokenEncrypted = null;
} else if (relaySettingsAction === "replace") {
const relayTarget = (input.relayTarget ?? "").trim();
relayEnabled = input.relayEnabled === true;
relayName = (input.relayName ?? "").trim();
if (relayName.length > 80) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name must contain 80 characters or fewer");
if (relayEnabled && !relayName) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name is required when the relay is enabled");
if (relayEnabled && !relayTarget) throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is required when the relay is enabled");
if (relayTarget) {
try {
const relay = parseTeamSpeakTarget(relayTarget, DEFAULT_ACCELERATION_RELAY_PORT);
relayHost = relay.host;
relayPort = relay.port;
} catch {
throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid");
}
} else {
relayHost = "";
relayPort = DEFAULT_ACCELERATION_RELAY_PORT;
}
const relayTokenAction = input.relayTokenAction ?? (input.relayToken === undefined ? "keep" : "replace");
if (relayTokenAction === "remove") relayTokenEncrypted = null;
if (relayTokenAction === "replace") relayTokenEncrypted = input.relayToken ? encryptSecret(input.relayToken, this.masterSecret) : null;
if (relayEnabled && !relayTokenEncrypted) throw new AdminInputError("INVALID_RELAY_TOKEN", "Relay token is required when the relay is enabled");
relayConfigured = true;
}
if (relayNodes) {
const primary = relayNodes.find((node) => node.enabled) ?? relayNodes[0];
relayConfigured = relayNodes.length > 0;
relayEnabled = primary?.enabled === true;
relayName = primary?.name ?? "";
relayHost = primary?.host ?? "";
relayPort = primary?.port ?? DEFAULT_ACCELERATION_RELAY_PORT;
relayTokenEncrypted = primary?.tokenEncrypted ?? null;
}
return {
siteName,
welcomeText,
welcomeTextEn,
accessMode: input.accessMode,
tsHost: target.host,
tsPort: target.port,
tsPasswordEncrypted: encryptedPassword,
webRtcEnabled: input.webRtcEnabled,
webRtcUdpStart,
webRtcUdpEnd,
relayConfigured,
relayEnabled,
relayName,
relayHost,
relayPort,
relayTokenEncrypted,
};
}
private normalizeRelayNodes(inputs: RelayNodeInput[]): PersistedRelayNode[] {
if (!Array.isArray(inputs) || inputs.length > 16) throw new AdminInputError("INVALID_RELAY_NODES", "At most 16 relay nodes may be configured");
const current = new Map(this.database.listRelayNodes().map((node) => [node.id, node]));
const seen = new Set<string>();
const now = new Date().toISOString();
return inputs.map((input) => {
const name = typeof input.name === "string" ? input.name.trim() : "";
const targetText = typeof input.target === "string" ? input.target.trim() : "";
if (!name || name.length > 80) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name must contain 1 to 80 characters");
if (!targetText || targetText.length > 300) throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid");
let target: TeamSpeakTarget;
try { target = parseTeamSpeakTarget(targetText, DEFAULT_ACCELERATION_RELAY_PORT); }
catch { throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid"); }
const id = typeof input.id === "string" && /^relay-[a-z0-9-]{1,100}$/i.test(input.id)
? input.id
: `relay-${randomBytes(8).toString("hex")}`;
if (seen.has(id)) throw new AdminInputError("INVALID_RELAY_ID", "Relay id must be unique");
seen.add(id);
const previous = current.get(id);
const tokenAction = input.tokenAction ?? (input.token === undefined ? "keep" : "replace");
let tokenEncrypted = previous?.tokenEncrypted ?? null;
if (tokenAction === "remove") tokenEncrypted = null;
if (tokenAction === "replace") {
const token = typeof input.token === "string" ? input.token.trim() : "";
tokenEncrypted = token ? encryptSecret(token, this.masterSecret) : null;
}
if (input.enabled === true && (!tokenEncrypted || !this.canDecryptToken(tokenEncrypted))) {
throw new AdminInputError("INVALID_RELAY_TOKEN", "A relay token of at least 16 characters is required when the relay is enabled");
}
return {
id,
name,
enabled: input.enabled === true,
host: target.host,
port: target.port,
tokenEncrypted,
createdAt: previous?.createdAt ?? now,
updatedAt: now,
};
});
}
private canDecryptToken(encrypted: string): boolean {
try {
return decryptSecret(encrypted, this.masterSecret).length >= 16;
} catch {
return false;
}
}
private getRelayNodeViews(): Array<{ id: string; name: string; enabled: boolean; target: string; hasToken: boolean }> {
return this.database.listRelayNodes().map((node) => ({
id: node.id,
name: node.name,
enabled: node.enabled,
target: formatRelayTarget(node.host, node.port),
hasToken: Boolean(node.tokenEncrypted),
}));
}
private legacyRelayNodesFromSettings(settings: SettingsUpdate): PersistedRelayNode[] {
if (!settings.relayConfigured || !settings.relayHost || !settings.relayTokenEncrypted) return [];
const previous = this.database.listRelayNodes()[0];
const now = new Date().toISOString();
return [{
id: previous?.id ?? "relay-default",
name: settings.relayName || "中继加速",
enabled: settings.relayEnabled,
host: settings.relayHost,
port: settings.relayPort || DEFAULT_ACCELERATION_RELAY_PORT,
tokenEncrypted: settings.relayTokenEncrypted,
createdAt: previous?.createdAt ?? now,
updatedAt: now,
}];
}
private toInviteView(record: ManagedInviteRecord): ManagedInviteView {
const now = Date.now();
const expired = Date.parse(record.expiresAt) <= now;
@@ -300,11 +537,20 @@ export class AdminService {
return {
siteName: settings.siteName,
welcomeText: settings.welcomeText,
welcomeTextEn: settings.welcomeTextEn,
accessMode: settings.accessMode,
tsHost: settings.tsHost,
tsPort: settings.tsPort,
tsPasswordEncrypted: settings.tsPasswordEncrypted,
webRtcEnabled: settings.webRtcEnabled,
webRtcUdpStart: settings.webRtcUdpStart,
webRtcUdpEnd: settings.webRtcUdpEnd,
relayConfigured: settings.relayConfigured,
relayEnabled: settings.relayEnabled,
relayName: settings.relayName,
relayHost: settings.relayHost,
relayPort: settings.relayPort,
relayTokenEncrypted: settings.relayTokenEncrypted,
};
}
@@ -316,11 +562,20 @@ export class AdminService {
this.database.updateSettings({
siteName: current.siteName,
welcomeText: current.welcomeText,
welcomeTextEn: current.welcomeTextEn,
accessMode: current.accessMode,
tsHost: legacy.tsHost,
tsPort: legacy.tsPort,
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
webRtcEnabled: current.webRtcEnabled,
webRtcUdpStart: current.webRtcUdpStart,
webRtcUdpEnd: current.webRtcUdpEnd,
relayConfigured: current.relayConfigured,
relayEnabled: current.relayEnabled,
relayName: current.relayName,
relayHost: current.relayHost,
relayPort: current.relayPort,
relayTokenEncrypted: current.relayTokenEncrypted,
}, "LEGACY_CONFIG_IMPORTED");
this.database.setMeta("legacy_config_imported", "1");
this.database.setMeta("legacy_import_notice_pending", "1");
@@ -334,6 +589,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);
+30 -2
View File
@@ -7,6 +7,16 @@ export type WebSpeakErrorCode =
| "server_full"
| "unknown";
export type ClientConnectionFailureCode =
| "INVALID_TARGET"
| "UNREACHABLE"
| "TIMEOUT"
| "SERVER_PASSWORD_REQUIRED"
| "INVALID_SERVER_PASSWORD"
| "PROTOCOL_NEGOTIATION_FAILED"
| "SERVER_REJECTED"
| "CONNECTION_FAILED";
export class WebSpeakError extends Error {
readonly code: WebSpeakErrorCode;
readonly retryable: boolean;
@@ -24,10 +34,12 @@ export class WebSpeakError extends Error {
export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
if (error instanceof WebSpeakError) return error;
const candidate = error as { code?: unknown; message?: unknown } | null;
const candidate = error as { code?: unknown; id?: unknown; serverMessage?: unknown; message?: unknown } | null;
const code = typeof candidate?.code === "string" ? candidate.code : "";
const id = typeof candidate?.id === "string" || typeof candidate?.id === "number" ? String(candidate.id) : "";
const serverMessage = typeof candidate?.serverMessage === "string" ? candidate.serverMessage : "";
const message = typeof candidate?.message === "string" ? candidate.message : String(error);
const text = `${code} ${message}`.toLocaleLowerCase();
const text = `${code} ${id} ${serverMessage} ${message}`.toLocaleLowerCase();
if (/password|authenticate|authentication|not authorized|invalid.*(credential|password)/.test(text)) {
return new WebSpeakError("authentication_failed", "TeamSpeak authentication failed", false, error);
@@ -43,3 +55,19 @@ export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
}
return new WebSpeakError("unknown", "TeamSpeak connection failed", false, error);
}
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",
unreachable: "UNREACHABLE",
timeout: "TIMEOUT",
authentication_failed: "SERVER_PASSWORD_REQUIRED",
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
server_full: "SERVER_REJECTED",
unknown: "CONNECTION_FAILED",
};
return mapping[error.code];
}
+46 -7
View File
@@ -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 -6
View File
@@ -4,13 +4,15 @@ import { dirname } from "node:path";
import { DatabaseSync } from "node:sqlite";
import type { AdminCredential } from "../security/admin-password.js";
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
export const DATABASE_SCHEMA_VERSION = 3;
export const DATABASE_SCHEMA_VERSION = 6;
export type AccessMode = "fixed" | "open";
export interface PersistedSettings {
siteName: string;
welcomeText: string;
welcomeTextEn: string;
accessMode: AccessMode;
tsHost: string;
tsPort: number;
@@ -20,17 +22,45 @@ export interface PersistedSettings {
lastTestLatencyMs: number | null;
lastTestError: string | null;
webRtcEnabled: boolean;
webRtcUdpStart: number;
webRtcUdpEnd: number;
relayConfigured: boolean;
relayEnabled: boolean;
relayName: string;
relayHost: string;
relayPort: number;
relayTokenEncrypted: string | null;
updatedAt: string;
}
export interface SettingsUpdate {
siteName: string;
welcomeText: string;
welcomeTextEn?: string;
accessMode: AccessMode;
tsHost: string;
tsPort: number;
tsPasswordEncrypted: string | null;
webRtcEnabled: boolean;
webRtcUdpStart?: number;
webRtcUdpEnd?: number;
relayConfigured: boolean;
relayEnabled: boolean;
relayName: string;
relayHost: string;
relayPort: number;
relayTokenEncrypted: string | null;
}
export interface PersistedRelayNode {
id: string;
name: string;
enabled: boolean;
host: string;
port: number;
tokenEncrypted: string | null;
createdAt: string;
updatedAt: string;
}
export interface ManagedInviteRecord {
@@ -64,6 +94,7 @@ interface ManagedInviteRow extends Record<string, unknown> {
interface SettingsRow extends Record<string, unknown> {
site_name: string;
welcome_text: string;
welcome_text_en: string;
access_mode: string;
ts_host: string;
ts_port: number;
@@ -76,6 +107,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;
}
@@ -138,6 +186,7 @@ export class WebSpeakDatabase {
return {
siteName: row.site_name,
welcomeText: row.welcome_text,
welcomeTextEn: row.welcome_text_en,
accessMode: row.access_mode === "open" ? "open" : "fixed",
tsHost: row.ts_host,
tsPort: row.ts_port,
@@ -147,10 +196,57 @@ export class WebSpeakDatabase {
lastTestLatencyMs: row.last_test_latency_ms,
lastTestError: row.last_test_error,
webRtcEnabled: row.webrtc_enabled === 1,
webRtcUdpStart: row.webrtc_udp_start,
webRtcUdpEnd: row.webrtc_udp_end,
relayConfigured: row.relay_configured === 1,
relayEnabled: row.relay_enabled === 1,
relayName: row.relay_name,
relayHost: row.relay_host,
relayPort: row.relay_port,
relayTokenEncrypted: row.relay_token_encrypted,
updatedAt: row.updated_at,
};
}
listRelayNodes(): PersistedRelayNode[] {
const rows = this.database.prepare(
"SELECT * FROM relay_nodes ORDER BY created_at ASC, id ASC",
).all() as RelayNodeRow[];
return rows.map((row) => ({
id: row.id,
name: row.name,
enabled: row.enabled === 1,
host: row.host,
port: row.port,
tokenEncrypted: row.token_encrypted,
createdAt: row.created_at,
updatedAt: row.updated_at,
}));
}
replaceRelayNodes(nodes: Array<Omit<PersistedRelayNode, "createdAt" | "updatedAt"> & { createdAt?: string; updatedAt?: string }>): void {
const now = new Date().toISOString();
this.transaction(() => {
this.database.exec("DELETE FROM relay_nodes");
const insert = this.database.prepare(
`INSERT INTO relay_nodes (id, name, enabled, host, port, token_encrypted, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
);
for (const node of nodes) {
insert.run(
node.id,
node.name,
node.enabled ? 1 : 0,
node.host,
node.port,
node.tokenEncrypted,
node.createdAt ?? now,
node.updatedAt ?? now,
);
}
});
}
updateSettings(settings: SettingsUpdate, auditEvent = "SETTINGS_CHANGED"): void {
const now = new Date().toISOString();
this.transaction(() => {
@@ -361,9 +457,8 @@ export class WebSpeakDatabase {
if (version === 2) {
this.transaction(() => {
this.database.exec(`
-- The host and range columns are retained for v3 database compatibility.
-- WebSpeak no longer reads or exposes them; WebRTC now owns its media
-- endpoint and derives the public host from each browser connection.
-- WebRTC media ports are stored with the administrator settings so the
-- same range is used by the gateway and shown in the admin console.
ALTER TABLE settings ADD COLUMN webrtc_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_enabled IN (0, 1));
ALTER TABLE settings ADD COLUMN webrtc_public_host TEXT NOT NULL DEFAULT '';
ALTER TABLE settings ADD COLUMN webrtc_udp_start INTEGER NOT NULL DEFAULT 40000 CHECK (webrtc_udp_start BETWEEN 1 AND 65535);
@@ -371,23 +466,102 @@ export class WebSpeakDatabase {
`);
this.database.exec("PRAGMA user_version = 3");
});
version = 3;
}
if (version === 3) {
this.transaction(() => {
this.database.exec(`
ALTER TABLE settings ADD COLUMN welcome_text_en TEXT NOT NULL DEFAULT '';
`);
this.database.exec("PRAGMA user_version = 4");
});
version = 4;
}
if (version === 4) {
this.transaction(() => {
this.database.exec(`
ALTER TABLE settings ADD COLUMN relay_configured INTEGER NOT NULL DEFAULT 0 CHECK (relay_configured IN (0, 1));
ALTER TABLE settings ADD COLUMN relay_enabled INTEGER NOT NULL DEFAULT 0 CHECK (relay_enabled IN (0, 1));
ALTER TABLE settings ADD COLUMN relay_name TEXT NOT NULL DEFAULT '';
ALTER TABLE settings ADD COLUMN relay_host TEXT NOT NULL DEFAULT '';
ALTER TABLE settings ADD COLUMN relay_port INTEGER NOT NULL DEFAULT 39087 CHECK (relay_port BETWEEN 1 AND 65535);
ALTER TABLE settings ADD COLUMN relay_token_encrypted TEXT;
`);
this.database.exec("PRAGMA user_version = 5");
});
version = 5;
}
if (version === 5) {
this.transaction(() => {
this.database.exec(`
CREATE TABLE relay_nodes (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 0 CHECK (enabled IN (0, 1)),
host TEXT NOT NULL,
port INTEGER NOT NULL CHECK (port BETWEEN 1 AND 65535),
token_encrypted TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX relay_nodes_enabled_idx ON relay_nodes(enabled);
`);
const legacy = this.database.prepare(
`SELECT relay_configured, relay_enabled, relay_name, relay_host, relay_port, relay_token_encrypted
FROM settings WHERE id = 1`,
).get() as {
relay_configured?: number;
relay_enabled?: number;
relay_name?: string;
relay_host?: string;
relay_port?: number;
relay_token_encrypted?: string | null;
} | undefined;
if (legacy?.relay_configured === 1 && legacy.relay_host && legacy.relay_token_encrypted) {
const now = new Date().toISOString();
this.database.prepare(
`INSERT INTO relay_nodes (id, name, enabled, host, port, token_encrypted, created_at, updated_at)
VALUES ('relay-default', ?, ?, ?, ?, ?, ?, ?)`,
).run(
legacy.relay_name || "中继加速",
legacy.relay_enabled === 1 ? 1 : 0,
legacy.relay_host,
legacy.relay_port || 39087,
legacy.relay_token_encrypted,
now,
now,
);
}
this.database.exec("PRAGMA user_version = 6");
});
}
}
private writeSettings(settings: SettingsUpdate, now: string): void {
this.database.prepare(
`UPDATE settings SET
site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?,
ts_password_encrypted = ?, webrtc_enabled = ?, updated_at = ?
site_name = ?, welcome_text = ?, welcome_text_en = ?, access_mode = ?, ts_host = ?, ts_port = ?,
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_udp_start = ?,
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
WHERE id = 1`,
).run(
settings.siteName,
settings.welcomeText,
settings.welcomeTextEn ?? "",
settings.accessMode,
settings.tsHost,
settings.tsPort,
settings.tsPasswordEncrypted,
settings.webRtcEnabled ? 1 : 0,
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
settings.relayConfigured ? 1 : 0,
settings.relayEnabled ? 1 : 0,
settings.relayName,
settings.relayHost,
settings.relayPort,
settings.relayTokenEncrypted,
now,
);
}
+30
View File
@@ -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";
}
+366
View File
@@ -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)); }
+18
View File
@@ -0,0 +1,18 @@
/**
* Prevents one persisted TeamSpeak identity from being used by two live
* browser sessions at the same target at the same time.
*/
export class IdentityLeaseStore {
private readonly owners = new Map<string, string>();
acquire(key: string, owner: string): boolean {
const currentOwner = this.owners.get(key);
if (currentOwner && currentOwner !== owner) return false;
this.owners.set(key, owner);
return true;
}
release(key: string, owner: string): void {
if (this.owners.get(key) === owner) this.owners.delete(key);
}
}
+2
View File
@@ -8,6 +8,8 @@ export interface JoinTicketPayload {
channel?: string;
identity?: string;
rememberIdentity?: boolean;
accelerated?: boolean;
accelerationRelayId?: string;
}
interface StoredTicket {
+185
View File
@@ -0,0 +1,185 @@
import { spawn } from "node:child_process";
export type TeamSpeakPingErrorCode =
| "HOST_NOT_FOUND"
| "UNREACHABLE"
| "TIMEOUT"
| "PING_UNAVAILABLE"
| "INVALID_PASSWORD"
| "PROTOCOL_NEGOTIATION_FAILED"
| "SERVER_REJECTED"
| "INTERNAL_ERROR";
export interface TeamSpeakPingAttempt {
ok: boolean;
latencyMs: number | null;
errorCode?: TeamSpeakPingErrorCode;
}
export interface TeamSpeakPingResult {
ok: boolean;
latencyMs: number | null;
packetLossPercent: number;
attempts: number;
successfulAttempts: number;
samples: number[];
errorCode?: TeamSpeakPingErrorCode;
}
export type TeamSpeakCommandExecutor = (command: string, timeoutMs?: number) => Promise<unknown>;
export type HostPingExecutor = (host: string, timeoutMs: number) => Promise<number>;
/**
* Measure an already connected TeamSpeak session using the protocol's own
* command channel. TeamSpeak voice/query traffic is UDP; a TCP connect to
* port 9987 is therefore not a valid reachability test and reports false
* packet loss even while voice works normally.
*/
export async function pingTeamSpeakSession(
execute: TeamSpeakCommandExecutor,
timeoutMs = 1_500,
): Promise<TeamSpeakPingAttempt> {
const startedAt = Date.now();
try {
// `version` is read-only and is handled by both TS3 and TS6.
await execute("version", timeoutMs);
return { ok: true, latencyMs: Math.max(0, Date.now() - startedAt) };
} catch (error: unknown) {
return {
ok: false,
latencyMs: null,
errorCode: classifyProbeError(error),
};
}
}
export async function collectTeamSpeakPings(
probe: () => Promise<TeamSpeakPingAttempt>,
options: { attempts?: number } = {},
): Promise<TeamSpeakPingResult> {
const attempts = Math.max(1, Math.min(8, Math.floor(options.attempts ?? 4)));
const results: TeamSpeakPingAttempt[] = [];
// Keep attempts sequential. This measures the real protocol path without
// opening several temporary TeamSpeak sessions at the same time.
for (let index = 0; index < attempts; index += 1) {
results.push(await probe());
}
return summarizeTeamSpeakPings(results, attempts);
}
/**
* Ping the TeamSpeak host from the WebSpeak machine without creating a
* TeamSpeak client. This is intentionally a host/network diagnostic: the
* TeamSpeak voice port is UDP, so a TCP socket probe is not meaningful and a
* client-protocol probe would create an extra visible member.
*/
export async function pingTeamSpeakHost(
host: string,
options: { attempts?: number; timeoutMs?: number; execute?: HostPingExecutor } = {},
): Promise<TeamSpeakPingResult> {
const timeoutMs = Math.max(250, Math.min(5_000, Math.floor(options.timeoutMs ?? 1_000)));
const execute = options.execute ?? pingHostOnce;
return collectTeamSpeakPings(async () => {
try {
return { ok: true, latencyMs: await execute(host, timeoutMs) };
} catch (error: unknown) {
return { ok: false, latencyMs: null, errorCode: classifyProbeError(error) };
}
}, { attempts: options.attempts ?? 4 });
}
export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempts = results.length): TeamSpeakPingResult {
const normalizedAttempts = Math.max(1, attempts);
const samples = results
.filter((result): result is TeamSpeakPingAttempt & { latencyMs: number } => result.ok && result.latencyMs !== null)
.map((result) => result.latencyMs)
.sort((left, right) => left - right);
const errorCode = results.find((result) => result.errorCode)?.errorCode;
return {
ok: samples.length > 0,
latencyMs: samples.length ? samples[Math.floor(samples.length / 2)] : null,
packetLossPercent: Math.round(((normalizedAttempts - samples.length) / normalizedAttempts) * 100),
attempts: normalizedAttempts,
successfulAttempts: samples.length,
samples,
...(errorCode ? { errorCode } : {}),
};
}
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
const text = error instanceof Error ? error.message : String(error);
const lower = text.toLocaleLowerCase();
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
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";
return "UNREACHABLE";
}
function pingHostOnce(host: string, timeoutMs: number): Promise<number> {
return new Promise((resolve, reject) => {
const windows = process.platform === "win32";
const command = windows ? "ping.exe" : "ping";
const args = windows
? ["-n", "1", "-w", String(timeoutMs), host]
: ["-c", "1", "-W", String(Math.max(1, Math.ceil(timeoutMs / 1_000))), host];
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
let output = "";
let settled = false;
const finish = (callback: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timer);
callback();
};
const timer = setTimeout(() => finish(() => {
child.kill();
reject(new Error("ping timeout"));
}), timeoutMs + 250);
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk: string) => { output += chunk; });
child.stderr.on("data", (chunk: string) => { output += chunk; });
child.once("error", (error) => finish(() => reject(error)));
child.once("close", (code) => finish(() => {
const match = output.match(/(?:time|时间)\s*[=<]\s*([\d.,]+)\s*(?:ms|毫秒)?/i);
if (code === 0 && match) {
const latencyMs = Number.parseFloat(match[1].replace(",", "."));
if (Number.isFinite(latencyMs)) {
resolve(Math.max(0, latencyMs));
return;
}
}
reject(new Error(output.trim() || `ping exited with code ${code ?? "unknown"}`));
}));
});
}
/**
* Keep a small compatibility helper for callers that only need one protocol
* attempt. It deliberately has no host/port argument because the connected
* TeamSpeak session owns the actual resolved endpoint.
*/
export function pingTeamSpeakPort(
execute: TeamSpeakCommandExecutor,
timeoutMs = 1_500,
): Promise<TeamSpeakPingAttempt> {
return pingTeamSpeakSession(execute, timeoutMs);
}
/*
* This function used to open a raw TCP socket to the TeamSpeak voice port.
* That transport is not TeamSpeak's client protocol and must not be used for
* reachability measurements. Keep the aggregation logic above independent of
* the connection setup so admin tests can supply a real protocol probe.
*/
export async function pingTeamSpeak(
probe: () => Promise<TeamSpeakPingAttempt>,
options: { attempts?: number } = {},
): Promise<TeamSpeakPingResult> {
return collectTeamSpeakPings(probe, options);
}
+39 -5
View File
@@ -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,15 +110,34 @@ export function createWebServer(options: WebServerOptions): WebServer {
let target = managedInvite?.target ?? policy.defaultTarget;
let serverPassword = managedInvite?.serverPassword ?? policy.serverPassword;
const channel = requestedChannel || managedInvite?.channel || "";
const requestedRelayId = typeof body.accelerationRelayId === "string" ? body.accelerationRelayId.trim().slice(0, 110) : "";
const accelerationRequested = body.accelerated === true || Boolean(requestedRelayId);
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
if (accelerationRequested && acceleration.length === 0) {
response.status(400).json({ ok: false, code: "ACCELERATION_UNAVAILABLE" });
return;
}
if (requestedRelayId && !acceleration.some((relay) => relay.id === requestedRelayId)) {
response.status(400).json({ ok: false, code: "ACCELERATION_UNAVAILABLE" });
return;
}
if (!managedInvite) {
try {
if (policy.accessMode === "open" && typeof body.target === "string" && body.target.trim()) {
target = parseTeamSpeakTarget(body.target);
const isDefault = teamSpeakTargetKey(target) === teamSpeakTargetKey(policy.defaultTarget);
if (!isDefault) {
target = await resolveSafeOpenTarget(target);
serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
}
// Open mode must protect the gateway even when a user submits the
// same address configured as the administrator's default target.
// The default target only controls which server is prefilled; it is
// not a trust boundary and must not bypass SSRF protection.
target = await resolveSafeOpenTarget(target);
if (!isDefault) serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
else if (typeof body.serverPassword === "string" && body.serverPassword.trim()) serverPassword = body.serverPassword.slice(0, 512);
} else if (policy.accessMode === "fixed" && typeof body.serverPassword === "string" && body.serverPassword.trim()) {
// The fixed target remains administrator-controlled, but a user may
// retry its server password after the gateway reports that one is
// required. The target itself is never taken from this request.
serverPassword = body.serverPassword.slice(0, 512);
}
} catch {
response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" });
@@ -126,6 +151,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
nickname,
...(channel ? { channel } : {}),
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
...(accelerationRequested ? { accelerated: true, ...(requestedRelayId ? { accelerationRelayId: requestedRelayId } : {}) } : {}),
});
response.status(201).json({ ok: true, ticket });
});
@@ -173,6 +199,14 @@ export function createWebServer(options: WebServerOptions): WebServer {
};
}
function resolveAccelerationOptions(
configured: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]) | undefined,
): ConfiguredAccelerationRelay[] {
const value = typeof configured === "function" ? configured() : configured;
if (!value) return [];
return Array.isArray(value) ? value : [value];
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
+4 -1
View File
@@ -57,6 +57,8 @@ export class EndpointProtocolCache {
export const endpointProtocolCache = new EndpointProtocolCache();
const TEAM_SPEAK_CONNECT_TIMEOUT_MS = 15_000;
export interface TeamSpeakAdapterOptions {
target: TeamSpeakTarget;
nickname: string;
@@ -109,8 +111,9 @@ export class TeamSpeakAdapter {
this.logger.info({ target: formatTeamSpeakTarget(this.target), cachedProtocol }, "Connecting through TeamSpeak adapter");
try {
await this.client.connect();
await this.client.waitConnected();
await this.client.waitConnected(AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS));
} catch (error: unknown) {
await this.client.disconnect().catch(() => undefined);
throw normalizeTeamSpeakError(error);
}
+25 -11
View File
@@ -1,12 +1,14 @@
import type { Logger } from "../logger.js";
import { normalizeTeamSpeakError, type WebSpeakErrorCode } from "../errors.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
import { TSClient } from "./ts-client.js";
import type { TeamSpeakProtocol } from "./teamspeak-adapter.js";
export type ProbeErrorCode =
| "HOST_NOT_FOUND"
| "UNREACHABLE"
| "TIMEOUT"
| "PASSWORD_REQUIRED"
| "INVALID_PASSWORD"
| "PROTOCOL_NEGOTIATION_FAILED"
| "SERVER_REJECTED"
@@ -30,8 +32,10 @@ export class TeamSpeakProbeError extends Error {
interface ProbeAdapter {
connect(): Promise<void>;
disconnect(): Promise<void>;
readonly protocol: TeamSpeakProtocol | null;
readonly client: {
readonly protocol?: TeamSpeakProtocol | null;
getProtocol?(): TeamSpeakProtocol | null;
execCommandWithResponse?(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
readonly client?: {
execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
};
}
@@ -47,7 +51,15 @@ export async function probeTeamSpeak(
password: string,
logger: Logger,
factory: ProbeAdapterFactory = ({ target: probeTarget, password: probePassword, logger: probeLogger }) =>
new TeamSpeakAdapter({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger),
(() => {
const client = new TSClient({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger);
return {
connect: () => client.connect(),
disconnect: () => client.disconnect(),
getProtocol: () => client.getProtocol(),
execCommandWithResponse: (command: string, timeoutMs?: number) => client.execCommandWithResponse(command, timeoutMs),
};
})(),
): Promise<TeamSpeakProbeResult> {
const startedAt = Date.now();
const adapter = factory({ target, password, logger: logger.child({ component: "teamspeak-probe" }) });
@@ -55,7 +67,9 @@ export async function probeTeamSpeak(
await adapter.connect();
let serverName: string | null = null;
try {
const rows = await adapter.client.execCommandWithResponse("serverinfo", 3000);
const execute = adapter.execCommandWithResponse?.bind(adapter) ?? adapter.client?.execCommandWithResponse.bind(adapter.client);
if (!execute) throw new Error("Probe adapter does not support commands");
const rows = await execute("serverinfo", 3000);
const first = rows[0] ?? {};
serverName = first.virtualserver_name ?? first.server_name ?? first.name ?? null;
} catch {
@@ -63,13 +77,13 @@ export async function probeTeamSpeak(
}
return {
ok: true,
protocol: adapter.protocol,
protocol: adapter.protocol ?? adapter.getProtocol?.() ?? null,
latencyMs: Math.max(0, Date.now() - startedAt),
serverName,
requiresPassword: Boolean(password),
};
} catch (error: unknown) {
throw toProbeError(error);
throw toProbeError(error, password);
} finally {
try {
await adapter.disconnect();
@@ -79,7 +93,7 @@ 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();
@@ -90,7 +104,7 @@ export function toProbeError(error: unknown): TeamSpeakProbeError {
invalid_target: "INTERNAL_ERROR",
unreachable: "UNREACHABLE",
timeout: "TIMEOUT",
authentication_failed: "INVALID_PASSWORD",
authentication_failed: password.trim() ? "INVALID_PASSWORD" : "PASSWORD_REQUIRED",
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
server_full: "SERVER_REJECTED",
unknown: "SERVER_REJECTED",
@@ -100,6 +114,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 : ""}`;
}
+27 -5
View File
@@ -16,6 +16,7 @@ import {
import type { Logger } from "../logger.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 +25,7 @@ export interface TSClientOptions {
defaultChannel?: string;
channelPassword?: string;
identity?: Identity;
acceleration?: AccelerationRelayOptions;
}
export interface TSVoiceData {
@@ -70,6 +72,7 @@ export class TSClient extends EventEmitter {
private clientId = 0;
private connected = false;
private preferredChannelId = 0n;
private accelerationClient: AccelerationRelayClient | null = null;
constructor(private options: TSClientOptions, logger: Logger) {
super();
@@ -79,8 +82,17 @@ export class TSClient extends EventEmitter {
async connect(): Promise<void> {
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,
@@ -247,6 +259,11 @@ export class TSClient extends EventEmitter {
return this.adapter?.protocol ?? null;
}
async execCommandWithResponse(command: string, timeoutMs = 3000): Promise<Record<string, string>[]> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
return this.client.execCommandWithResponse(command, timeoutMs);
}
getIdentityString(): string {
return this.identity.toString();
}
@@ -263,10 +280,15 @@ 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;
try {
if (this.adapter) await this.adapter.disconnect();
} finally {
this.accelerationClient?.close();
this.accelerationClient = null;
this.adapter = null;
this.client = null;
this.clientId = 0;
}
}
}
+168 -19
View File
@@ -5,13 +5,16 @@ 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 { formatTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { clientConnectionFailureCode, normalizeTeamSpeakError } 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";
import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js";
import { parseClientCommand, type ClientCommand } from "./voice-protocol.js";
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js";
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcSessionDescription } from "./webrtc-audio.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 {
@@ -31,6 +34,8 @@ const MAX_SERVER_AUDIO_BUFFERED_BYTES = 4_096;
export interface VoiceBridgeOptions {
joinTickets: JoinTicketStore;
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]);
accelerationName?: string | (() => string | undefined);
}
export interface AdminSessionSummary {
@@ -72,6 +77,24 @@ export interface AudioFlowStats {
egressSentMaxGapMs: number;
egressPeakBufferedBytes: number;
egressFramesByClient: Record<string, number>;
webrtcIngressRtpFrames: number;
webrtcIngressRtpFirstAt: number | null;
webrtcIngressRtpLastAt: number | null;
webrtcIngressRtpMaxGapMs: number;
webrtcEgressRtpFrames: number;
webrtcEgressRtpFirstAt: number | null;
webrtcEgressRtpLastAt: number | null;
webrtcEgressRtpMaxGapMs: number;
webrtcQueuePeakFrames: number;
webrtcQueueDroppedFrames: number;
webrtcQueueUnderrunTicks: number;
webrtcPacerLateTicks: number;
webrtcQueueCurrentFrames: number;
webrtcIngressQuietFrames: number;
webrtcIngressDecodeErrors: number;
webrtcDownlinkDecodedFrames: number;
webrtcDownlinkDecodeErrors: number;
webrtcDownlinkShortFrames: number;
}
interface ChannelMember {
@@ -100,6 +123,8 @@ interface WebClientEntry {
nickname: string;
rememberIdentity: boolean;
target: TeamSpeakTarget;
acceleration?: AccelerationRelayOptions;
identityLeaseKey?: string;
webrtcPublicHost?: string;
channelTree: unknown[];
members: Map<number, ChannelMember>;
@@ -111,11 +136,14 @@ interface WebClientEntry {
reconnectTimer: ReturnType<typeof setTimeout> | null;
audio: AudioFlowStats;
webrtc: WebRtcAudioSession | null;
lastLatencyProbeAt: number;
connectionFailureCode?: string;
}
export class VoiceBridge {
private readonly sessionManager = new SessionManager();
private readonly entries = new Map<string, WebClientEntry>();
private readonly identityLeases = new IdentityLeaseStore();
private wss: WebSocketServer | null = null;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
private logger: LoggerType;
@@ -141,6 +169,11 @@ 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 webrtcPublicHost = resolveWebRtcPublicHost(req);
let identity;
try {
@@ -160,11 +193,22 @@ export class VoiceBridge {
return;
}
const identityLeaseKey = identity
? `${teamSpeakTargetKey(target)}:${identity.toString()}`
: "";
if (identityLeaseKey && !this.identityLeases.acquire(identityLeaseKey, entryId)) {
this.logger.warn({ entryId, nickname, target: formatTeamSpeakTarget(target) }, "TeamSpeak identity already in use");
void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed");
ws.close(4005, "IDENTITY_IN_USE");
return;
}
this.logger.info({ entryId, nickname, channel: channelName, target: formatTeamSpeakTarget(target) }, "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");
@@ -178,6 +222,8 @@ export class VoiceBridge {
nickname,
rememberIdentity: connection.rememberIdentity === true,
target,
...(acceleration ? { acceleration } : {}),
...(identityLeaseKey ? { identityLeaseKey } : {}),
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
channelTree: [],
members: new Map(),
@@ -189,6 +235,7 @@ export class VoiceBridge {
reconnectTimer: null,
audio: createAudioFlowStats(),
webrtc: null,
lastLatencyProbeAt: 0,
};
this.entries.set(entryId, entry!);
try {
@@ -274,6 +321,7 @@ export class VoiceBridge {
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");
}
session.transition("connected");
sendJson({
@@ -284,6 +332,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 });
@@ -310,7 +359,9 @@ 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);
entry!.connectionFailureCode = failureCode;
sendJson({ type: "reconnectFailed", code: failureCode });
void this.teardown(entryId, "teamSpeak-connect-failed");
};
@@ -364,12 +415,14 @@ 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);
entry!.connectionFailureCode = failureCode;
this.logger.error({ code: failureCode, normalizedCode: normalized.code, 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);
if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode);
void this.teardown(entryId, "teamSpeak-connect-failed");
return;
}
@@ -416,6 +469,7 @@ export class VoiceBridge {
tsClient.on("clientLeave", (info) => {
const wasKnown = entry!.members.has(info.id);
const leavingMember = entry!.members.get(info.id);
entry!.webrtc?.setMemberVolume(info.id, 1);
directory.applyClientLeave(info.id);
refreshDirectory();
if (tsReady && initialStateSent && wasKnown) {
@@ -484,12 +538,16 @@ export class VoiceBridge {
tsClient.on("textMessage", (message) => {
const scope = message.targetMode === 1 ? "private" : message.targetMode === 3 ? "server" : message.targetMode === 2 ? "channel" : "server";
const targetId = message.targetId ?? 0n;
// TeamSpeak channel notifications omit `target`; the SDK represents
// that as 0. Bind the broadcast to this session's current channel so
// it remains visible now but cannot leak into another channel after a
// later channel switch.
const effectiveTargetId = scope === "channel" && targetId === 0n ? tsClient.getChannelId() : targetId;
sendJson({
type: "chatMessage",
scope,
// Keep event handling total: malformed/legacy SDK events must not
// throw from this callback and tear down the browser session.
targetId: String(message.targetId ?? 0n),
...(effectiveTargetId !== 0n ? { targetId: String(effectiveTargetId) } : {}),
senderUid: message.invokerUid,
timestamp: Date.now(),
invokerName: message.invokerName,
@@ -563,7 +621,11 @@ export class VoiceBridge {
if (isWebRtcStopMessage(rawMessage)) {
const webRtc = entry!.webrtc;
entry!.webrtc = null;
if (webRtc) void webRtc.close();
if (webRtc) {
void webRtc.close()
.then(() => Object.assign(entry!.audio, webRtc.getStats()))
.catch(() => undefined);
}
return;
}
const command = parseClientCommand(rawMessage);
@@ -654,7 +716,7 @@ export class VoiceBridge {
tsClientId,
channelId,
memberCount: entry.members.size,
audio: { ...entry.audio },
audio: snapshotAudioStats(entry),
};
});
}
@@ -680,6 +742,7 @@ export class VoiceBridge {
entry.webrtc = null;
if (webRtc) {
try { await webRtc.close(); } catch { /* peer teardown is idempotent */ }
Object.assign(entry.audio, webRtc.getStats());
}
entry.whisperTargetIds.clear();
entry.whisperActive = false;
@@ -692,7 +755,16 @@ export class VoiceBridge {
if (reason === "heartbeat-timeout" || reason === "gateway-shutdown") entry.ws.terminate();
else entry.ws.close(reason === "protocol-error" ? 1008 : 1000, reason);
}
this.logger.info({ entryId: entry.id, reason, audio: { ...entry.audio } }, "Client session torn down");
if (entry.identityLeaseKey) this.identityLeases.release(entry.identityLeaseKey, entry.id);
this.logger.info({
entryId: entry.id,
nickname: entry.nickname,
target: formatTeamSpeakTarget(entry.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");
}
private startHeartbeat(): void {
@@ -722,13 +794,24 @@ export class VoiceBridge {
return typeof configured === "function" ? configured() : configured;
}
private getAccelerationOptions(relayId = ""): AccelerationRelayOptions | 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 { relayHost: selected.relayHost, relayPort: selected.relayPort, token: selected.token };
}
private async handleWebRtcOffer(
entry: WebClientEntry,
offer: WebRtcSessionDescription,
sendJson: (message: Record<string, unknown>) => void,
): Promise<void> {
if (entry.webrtc) {
try { await entry.webrtc.close(); } catch { /* replace a retried offer */ }
const previousWebRtc = entry.webrtc;
try { await previousWebRtc.close(); } catch { /* replace a retried offer */ }
Object.assign(entry.audio, previousWebRtc.getStats());
entry.webrtc = null;
}
const config = this.getWebRtcOptions();
@@ -736,17 +819,26 @@ export class VoiceBridge {
const peer = new WebRtcAudioSession({
connectionId: entry.id,
...(entry.webrtcPublicHost ? { publicHost: entry.webrtcPublicHost } : {}),
udpPortRange: config.udpPortRange,
logger: this.logger,
onVoiceFrame: (data) => {
microphoneMuted: offer.muted === true,
accompanimentActive: offer.accompanimentActive === true,
onVoiceFrame: (data, codec) => {
const now = Date.now();
if (entry.audio.ingressLastAt !== null) entry.audio.ingressMaxGapMs = Math.max(entry.audio.ingressMaxGapMs, now - entry.audio.ingressLastAt);
entry.audio.ingressFirstAt ??= now;
entry.audio.ingressLastAt = now;
entry.audio.ingressFrames++;
try {
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], 4);
else entry.tsClient.sendVoice(data, 4);
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], codec);
else entry.tsClient.sendVoice(data, codec);
const sentAt = Date.now();
if (entry.audio.tsSendLastAt !== null) entry.audio.tsSendMaxGapMs = Math.max(entry.audio.tsSendMaxGapMs, sentAt - entry.audio.tsSendLastAt);
entry.audio.tsSendFirstAt ??= sentAt;
entry.audio.tsSendLastAt = sentAt;
entry.audio.tsSendFrames++;
} catch {
entry.audio.tsSendErrors++;
// A packet arriving while the TeamSpeak session is being replaced
// is discarded; the WebRTC peer remains independently closable.
}
@@ -757,7 +849,7 @@ export class VoiceBridge {
});
entry.webrtc = peer;
try {
const answer = await peer.createAnswer(offer);
const answer = await peer.createAnswer({ type: offer.type, sdp: offer.sdp });
if (entry.webrtc !== peer || entry.ws.readyState !== WebSocket.OPEN) return;
sendJson({ type: "webrtcAnswer", payload: { sdp: answer } });
this.logger.info({ entryId: entry.id }, "WebRTC audio negotiation completed");
@@ -802,6 +894,24 @@ async function handleCommand(
command: ClientCommand,
sendJson: (message: Record<string, unknown>) => void,
): Promise<void> {
if (command.type === "latencyProbe") {
const sequence = command.payload.sequence as string;
const now = Date.now();
if (now - entry.lastLatencyProbeAt < 150) return;
entry.lastLatencyProbeAt = now;
const result = await pingTeamSpeakSession(
(request, timeoutMs) => entry.tsClient.execCommandWithResponse(request, timeoutMs),
);
sendJson({
type: "latencyPong",
sequence,
teamSpeakLatencyMs: result.latencyMs,
teamSpeakReachable: result.ok,
teamSpeakErrorCode: result.errorCode ?? null,
});
return;
}
if (command.type === "switchChannel") {
const rawId = command.payload.channelId as string;
const channelPassword = typeof command.payload.password === "string" ? command.payload.password : "";
@@ -864,6 +974,13 @@ async function handleCommand(
}
entry.whisperActive = active;
sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive });
} else if (command.type === "setMicrophoneMuted") {
entry.webrtc?.setMicrophoneMuted(command.payload.muted as boolean);
} else if (command.type === "setAccompanimentActive") {
entry.webrtc?.setAccompanimentActive(command.payload.active as boolean);
} else if (command.type === "setMemberVolume") {
const clientId = command.payload.clientId as number;
entry.webrtc?.setMemberVolume(clientId, command.payload.volume as number);
}
if (command.requestId) sendJson({ type: "commandCompleted", requestId: command.requestId });
} catch (error: unknown) {
@@ -893,7 +1010,14 @@ function parseWebRtcOffer(raw: string): WebRtcSessionDescription | null {
if (!isRecord(value) || value.type !== "webrtcOffer" || !isRecord(value.payload) || !isRecord(value.payload.sdp)) return null;
const description = value.payload.sdp;
if (description.type !== "offer" || typeof description.sdp !== "string" || description.sdp.length > 256 * 1024) return null;
return { type: "offer", sdp: description.sdp };
if (value.payload.muted !== undefined && typeof value.payload.muted !== "boolean") return null;
if (value.payload.accompanimentActive !== undefined && typeof value.payload.accompanimentActive !== "boolean") return null;
return {
type: "offer",
sdp: description.sdp,
muted: value.payload.muted === true,
accompanimentActive: value.payload.accompanimentActive === true,
};
}
function isWebRtcStopMessage(raw: string): boolean {
@@ -940,9 +1064,34 @@ function createAudioFlowStats(): AudioFlowStats {
egressSentMaxGapMs: 0,
egressPeakBufferedBytes: 0,
egressFramesByClient: {},
webrtcIngressRtpFrames: 0,
webrtcIngressRtpFirstAt: null,
webrtcIngressRtpLastAt: null,
webrtcIngressRtpMaxGapMs: 0,
webrtcEgressRtpFrames: 0,
webrtcEgressRtpFirstAt: null,
webrtcEgressRtpLastAt: null,
webrtcEgressRtpMaxGapMs: 0,
webrtcQueuePeakFrames: 0,
webrtcQueueDroppedFrames: 0,
webrtcQueueUnderrunTicks: 0,
webrtcPacerLateTicks: 0,
webrtcQueueCurrentFrames: 0,
webrtcIngressQuietFrames: 0,
webrtcIngressDecodeErrors: 0,
webrtcDownlinkDecodedFrames: 0,
webrtcDownlinkDecodeErrors: 0,
webrtcDownlinkShortFrames: 0,
};
}
function snapshotAudioStats(entry: WebClientEntry): AudioFlowStats {
const stats = { ...entry.audio };
const webRtcStats: WebRtcAudioStats | undefined = entry.webrtc?.getStats();
if (webRtcStats) Object.assign(stats, webRtcStats);
return stats;
}
function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
return snapshot.channels.map((channel) => ({
id: String(channel.id),
+14 -2
View File
@@ -1,5 +1,5 @@
export interface ClientCommand {
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive";
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe";
requestId?: string;
payload: Record<string, unknown>;
}
@@ -19,7 +19,7 @@ export function parseClientCommand(raw: string): ClientCommandResult {
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
}
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive"]);
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
if (!supportedTypes.has(value.type)) {
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
}
@@ -56,6 +56,18 @@ export function parseClientCommand(raw: string): ClientCommandResult {
if (value.type === "setWhisperActive" && typeof value.payload.active !== "boolean") {
return { error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" } };
}
if (value.type === "setMicrophoneMuted" && typeof value.payload.muted !== "boolean") {
return { error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" } };
}
if (value.type === "setAccompanimentActive" && typeof value.payload.active !== "boolean") {
return { error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" } };
}
if (value.type === "setMemberVolume" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535 || typeof value.payload.volume !== "number" || !Number.isFinite(value.payload.volume) || value.payload.volume < 0 || value.payload.volume > 4)) {
return { error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" } };
}
if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } };
}
return {
type: value.type as ClientCommand["type"],
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
+280 -42
View File
@@ -8,6 +8,9 @@ import {
} from "werift";
import type { Logger as LoggerType } from "../logger.js";
import type { TSVoiceData } from "./ts-client.js";
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
@@ -23,49 +26,96 @@ const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
const AUDIO_CLOCK_INTERVAL_MS = 20;
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
const MAX_MIXER_QUEUE_FRAMES = 4;
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
const MIXER_UNDERRUN_WINDOW_MS = 200;
// This threshold is used only for the speaking indicator. It must never decide
// whether a media packet is forwarded or queued: quiet/comfort-noise Opus
// packets are still valid media and dropping them can break decoder continuity.
const SPEAKER_ACTIVITY_RMS = 160;
// WebRTC is served by the WebSpeak process itself. Docker publishes this
// fixed range so the administrator only needs to enable the transport; the
// advertised host is derived from the browser's current WebSpeak address.
export const WEBRTC_UDP_PORT_RANGE: [number, number] = [40000, 40099];
// WebRTC is served by the WebSpeak process itself. The default range is also
// published by the bundled Docker Compose file; advanced administrators can
// change it in the admin console before enabling WebRTC.
export interface WebRtcAudioOptions {
enabled: boolean;
udpPortRange?: [number, number];
}
export interface WebRtcSessionDescription {
type: "offer" | "answer";
sdp: string;
muted?: boolean;
accompanimentActive?: boolean;
}
export interface WebRtcAudioSessionOptions {
connectionId: string;
publicHost?: string;
udpPortRange?: [number, number];
logger: LoggerType;
onVoiceFrame: (data: Buffer) => void;
microphoneMuted?: boolean;
accompanimentActive?: boolean;
onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
onVoiceActivity: (clientIds: number[]) => void;
}
export interface WebRtcAudioStats {
webrtcIngressRtpFrames: number;
webrtcIngressRtpFirstAt: number | null;
webrtcIngressRtpLastAt: number | null;
webrtcIngressRtpMaxGapMs: number;
webrtcEgressRtpFrames: number;
webrtcEgressRtpFirstAt: number | null;
webrtcEgressRtpLastAt: number | null;
webrtcEgressRtpMaxGapMs: number;
webrtcQueuePeakFrames: number;
webrtcQueueDroppedFrames: number;
webrtcQueueUnderrunTicks: number;
webrtcPacerLateTicks: number;
webrtcQueueCurrentFrames: number;
webrtcIngressQuietFrames: number;
webrtcIngressDecodeErrors: number;
webrtcDownlinkDecodedFrames: number;
webrtcDownlinkDecodeErrors: number;
webrtcDownlinkShortFrames: number;
}
interface PendingAudioFrame {
pcm: Buffer;
receivedAt: number;
/** Preserve a native 20 ms Opus frame when no mix is required. */
opus?: Buffer;
}
interface SelectedAudioFrame extends PendingAudioFrame {
clientId: number;
volume: number;
}
/**
* One low-latency WebRTC audio session for one browser connection.
*
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
* audio track in this first transport, so this class mixes only the newest
* 20 ms frame from each active speaker and packetizes the result as RTP. The
* map is deliberately bounded to one frame per speaker; an old frame is
* replaced instead of becoming a playback queue.
* audio track in this first transport, so this class mixes one 20 ms frame
* from each active speaker and packetizes the result as RTP. Each speaker has
* a very small bounded queue so bursts from the TeamSpeak adapter can be
* smoothed without turning into an ever-growing playback delay.
*/
export class WebRtcAudioSession {
readonly peer: RTCPeerConnection;
private readonly logger: LoggerType;
private readonly onVoiceFrame: (data: Buffer) => void;
private readonly onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
private readonly onVoiceActivity: (clientIds: number[]) => void;
private readonly outgoingTrack: MediaStreamTrack;
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
private readonly pendingFrames = new Map<number, Buffer>();
private readonly partialPcmByClient = new Map<number, Buffer>();
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
private readonly memberVolumes = new Map<number, number>();
private readonly activeSpeakerIds = new Set<number>();
private readonly opusPayloadTypes = new Set<number>();
private readonly audioTimer: ReturnType<typeof setInterval>;
private audioTimer: ReturnType<typeof setTimeout> | null = null;
private readonly activityTimer: ReturnType<typeof setInterval>;
private encoder: { encode(data: Buffer): Buffer } | null;
private sequenceNumber = randomInt(0, 65_536);
@@ -73,28 +123,67 @@ export class WebRtcAudioSession {
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
private closed = false;
private nextAudioDeadline = 0;
private lastIngressRtpAt: number | null = null;
private lastEgressRtpAt: number | null = null;
private lastQueueEnqueuedAt: number | null = null;
private accompanimentActive: boolean;
private readonly stats: WebRtcAudioStats = {
webrtcIngressRtpFrames: 0,
webrtcIngressRtpFirstAt: null,
webrtcIngressRtpLastAt: null,
webrtcIngressRtpMaxGapMs: 0,
webrtcEgressRtpFrames: 0,
webrtcEgressRtpFirstAt: null,
webrtcEgressRtpLastAt: null,
webrtcEgressRtpMaxGapMs: 0,
webrtcQueuePeakFrames: 0,
webrtcQueueDroppedFrames: 0,
webrtcQueueUnderrunTicks: 0,
webrtcPacerLateTicks: 0,
webrtcQueueCurrentFrames: 0,
webrtcIngressQuietFrames: 0,
webrtcIngressDecodeErrors: 0,
webrtcDownlinkDecodedFrames: 0,
webrtcDownlinkDecodeErrors: 0,
webrtcDownlinkShortFrames: 0,
};
constructor(options: WebRtcAudioSessionOptions) {
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
this.onVoiceFrame = options.onVoiceFrame;
this.onVoiceActivity = options.onVoiceActivity;
this.accompanimentActive = options.accompanimentActive === true;
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
this.peer = new RTCPeerConnection({
iceServers: [],
iceUseIpv4: true,
iceUseIpv6: false,
iceUseTcp: false,
icePortRange: [...WEBRTC_UDP_PORT_RANGE] as [number, number],
icePortRange: [...udpPortRange] as [number, number],
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
});
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
audio.onTrack.subscribe((track) => {
track.onReceiveRtp.subscribe((rtp) => {
if (this.closed || !this.opusPayloadTypes.has(rtp.header.payloadType)) return;
this.onVoiceFrame(Buffer.from(rtp.payload));
if (this.closed) return;
const receivedAt = performance.now();
if (this.lastIngressRtpAt !== null) this.stats.webrtcIngressRtpMaxGapMs = Math.max(this.stats.webrtcIngressRtpMaxGapMs, Math.round(receivedAt - this.lastIngressRtpAt));
this.lastIngressRtpAt = receivedAt;
this.stats.webrtcIngressRtpFirstAt ??= Date.now();
this.stats.webrtcIngressRtpLastAt = Date.now();
this.stats.webrtcIngressRtpFrames++;
if (!this.opusPayloadTypes.has(rtp.header.payloadType)) return;
const payload = Buffer.from(rtp.payload);
// Forward every valid negotiated Opus payload unchanged. Do not
// decode it for RMS analysis or pass it through a speech/silence gate:
// quiet frames are still part of the codec timeline and dropping them
// can cause downstream gaps, clicks, or decoder recovery artifacts.
this.onVoiceFrame(payload, this.accompanimentActive ? 5 : 4);
});
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track");
@@ -112,11 +201,11 @@ export class WebRtcAudioSession {
}
if (!this.encoder) {
this.outgoingTrack.stop();
throw new Error("WebRTC mixer encoder is unavailable");
throw new Error("WebRTC Opus codec is unavailable");
}
this.audioTimer = setInterval(() => this.flushAudio(), AUDIO_CLOCK_INTERVAL_MS);
this.audioTimer.unref?.();
this.nextAudioDeadline = performance.now();
this.scheduleAudioTick();
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
this.activityTimer.unref?.();
this.peer.onconnectionstatechange = () => {
@@ -124,6 +213,10 @@ export class WebRtcAudioSession {
};
}
getStats(): WebRtcAudioStats {
return { ...this.stats, webrtcQueueCurrentFrames: this.getQueueFrameCount() };
}
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
if (this.closed) throw new Error("WebRTC session is closed");
this.setOpusPayloadTypes(offer.sdp);
@@ -139,8 +232,7 @@ export class WebRtcAudioSession {
}
pushTeamSpeakVoice(data: TSVoiceData): void {
if (this.closed || data.codec !== 4) return;
this.activeSpeakerIds.add(data.clientId);
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
let decoder = this.decoderByClient.get(data.clientId);
if (!decoder) {
try {
@@ -155,8 +247,51 @@ export class WebRtcAudioSession {
}
try {
const pcm = decoder.decode(data.data);
if (pcm.length >= AUDIO_FRAME_BYTES) this.pendingFrames.set(data.clientId, pcm.subarray(0, AUDIO_FRAME_BYTES));
this.stats.webrtcDownlinkDecodedFrames++;
if (pcm.length < 2) {
this.stats.webrtcDownlinkShortFrames++;
return;
}
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
// decoded frame per speaker and split every decoded buffer into the
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
// anything after the first 20 ms.
const pendingPcm = this.partialPcmByClient.get(data.clientId);
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
const rms = this.calculateRms(pcm);
// RMS is used only for the UI speaking indicator. Every decoded frame,
// including quiet/comfort-noise frames, continues into the queue so the
// receiver keeps an uninterrupted codec timeline.
if (rms >= SPEAKER_ACTIVITY_RMS) this.activeSpeakerIds.add(data.clientId);
const canForwardOpus = !pendingPcm && pcm.length === AUDIO_FRAME_BYTES;
let offset = 0;
let enqueued = false;
let queue = this.pendingFrames.get(data.clientId);
while (offset + AUDIO_FRAME_BYTES <= combined.length) {
if (!queue) {
queue = [];
this.pendingFrames.set(data.clientId, queue);
}
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
queue.push({
pcm: Buffer.from(combined.subarray(offset, offset + AUDIO_FRAME_BYTES)),
receivedAt: performance.now(),
...(canForwardOpus && offset === 0 ? { opus: Buffer.from(data.data) } : {}),
});
enqueued = true;
offset += AUDIO_FRAME_BYTES;
}
if (offset < combined.length) this.partialPcmByClient.set(data.clientId, Buffer.from(combined.subarray(offset)));
else this.partialPcmByClient.delete(data.clientId);
if (enqueued) {
this.lastQueueEnqueuedAt = performance.now();
this.stats.webrtcQueuePeakFrames = Math.max(this.stats.webrtcQueuePeakFrames, this.getQueueFrameCount());
}
} catch {
this.stats.webrtcDownlinkDecodeErrors++;
// A malformed or codec-transition packet is discarded without touching
// the peer connection. The next valid Opus frame can recover the stream.
}
@@ -165,9 +300,12 @@ export class WebRtcAudioSession {
async close(): Promise<void> {
if (this.closed) return;
this.closed = true;
clearInterval(this.audioTimer);
if (this.audioTimer) clearTimeout(this.audioTimer);
this.audioTimer = null;
clearInterval(this.activityTimer);
this.pendingFrames.clear();
this.memberVolumes.clear();
this.partialPcmByClient.clear();
this.activeSpeakerIds.clear();
this.decoderByClient.clear();
this.encoder = null;
@@ -175,41 +313,91 @@ export class WebRtcAudioSession {
await this.peer.close();
}
private scheduleAudioTick(): void {
if (this.closed) return;
const delay = Math.max(0, this.nextAudioDeadline - performance.now());
this.audioTimer = setTimeout(() => this.flushAudio(), delay);
this.audioTimer.unref?.();
}
private flushAudio(): void {
if (this.closed || !this.encoder || !this.pendingFrames.size) return;
if (this.closed) return;
const now = performance.now();
if (now > this.nextAudioDeadline + MAX_MIXER_PACER_LAG_MS) {
this.stats.webrtcPacerLateTicks++;
this.nextAudioDeadline = now;
this.trimQueuesAfterLateTick();
}
this.nextAudioDeadline += AUDIO_CLOCK_INTERVAL_MS;
this.audioTimer = null;
this.mixAndSendAudio();
this.scheduleAudioTick();
}
private mixAndSendAudio(): void {
if (!this.encoder) {
return;
}
if (!this.pendingFrames.size) {
if (this.lastQueueEnqueuedAt !== null && performance.now() - this.lastQueueEnqueuedAt <= MIXER_UNDERRUN_WINDOW_MS) {
this.stats.webrtcQueueUnderrunTicks++;
}
}
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
let sourceCount = 0;
for (const pcm of this.pendingFrames.values()) {
sourceCount++;
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) mixed[index] += pcm.readInt16LE(index * 2);
const selectedFrames: SelectedAudioFrame[] = [];
for (const [clientId, queue] of this.pendingFrames) {
const frame = queue.shift();
if (queue.length === 0) this.pendingFrames.delete(clientId);
if (!frame) continue;
const volume = this.memberVolumes.get(clientId) ?? 1;
selectedFrames.push({ ...frame, clientId, volume });
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
}
}
if (selectedFrames.length === 1 && selectedFrames[0]?.opus && selectedFrames[0].volume === 1) {
this.sendRtpAudio(selectedFrames[0].opus);
return;
}
this.pendingFrames.clear();
if (!sourceCount) return;
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
const scale = 1 / Math.sqrt(sourceCount);
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
const sample = Math.max(-32_768, Math.min(32_767, Math.round(mixed[index]! * scale)));
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
// the waveform's apparent loudness as the source level changes, which
// is especially noticeable on music. Only clip actual overflow caused
// by simultaneous speakers; never normalize by the active speaker count.
const sample = Math.max(-32_768, Math.min(32_767, mixed[index]!));
pcm.writeInt16LE(sample, index * 2);
}
try {
const encoded = this.encoder.encode(pcm);
const packet = new RtpPacket(new RtpHeader({
payloadType: this.outgoingPayloadType,
sequenceNumber: this.sequenceNumber,
timestamp: this.timestamp,
ssrc: this.ssrc,
marker: true,
}), encoded);
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
this.outgoingTrack.writeRtp(packet);
this.sendRtpAudio(encoded);
} catch {
// A peer closing concurrently may reject a packet; teardown owns the
// session lifecycle and no per-frame error needs to reach the logs.
}
}
private sendRtpAudio(encoded: Buffer): void {
const packet = new RtpPacket(new RtpHeader({
payloadType: this.outgoingPayloadType,
sequenceNumber: this.sequenceNumber,
timestamp: this.timestamp,
ssrc: this.ssrc,
marker: true,
}), encoded);
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
this.outgoingTrack.writeRtp(packet);
const sentAt = performance.now();
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
this.lastEgressRtpAt = sentAt;
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
this.stats.webrtcEgressRtpLastAt = Date.now();
this.stats.webrtcEgressRtpFrames++;
}
private flushSpeakerActivity(): void {
if (this.closed || !this.activeSpeakerIds.size) return;
const ids = [...this.activeSpeakerIds];
@@ -217,6 +405,56 @@ export class WebRtcAudioSession {
this.onVoiceActivity(ids);
}
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;
}
setAccompanimentActive(active: boolean): void {
this.accompanimentActive = active;
}
setMemberVolume(clientId: number, volume: number): void {
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535 || !Number.isFinite(volume)) return;
const normalized = Math.max(0, Math.min(4, volume));
if (normalized === 1) this.memberVolumes.delete(clientId);
else this.memberVolumes.set(clientId, normalized);
}
private calculateRms(pcm: Buffer): number {
let sum = 0;
let samples = 0;
for (let index = 0; index + 1 < pcm.length; index += 2) {
const sample = pcm.readInt16LE(index);
sum += sample * sample;
samples++;
}
return samples ? Math.sqrt(sum / samples) : 0;
}
private trimQueuesAfterLateTick(): void {
const now = performance.now();
for (const [clientId, queue] of this.pendingFrames) {
while (queue.length > 1) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
if (queue.length === 0) this.pendingFrames.delete(clientId);
}
}
private getQueueFrameCount(): number {
let count = 0;
for (const queue of this.pendingFrames.values()) count += queue.length;
return count;
}
private setOpusPayloadTypes(sdp: string): void {
this.opusPayloadTypes.clear();
for (const match of sdp.matchAll(/^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?/gim)) {
+7
View File
@@ -0,0 +1,7 @@
/** Default WebRTC media port range used by WebSpeak and its Docker image. */
export const DEFAULT_WEBRTC_UDP_PORT_RANGE: [number, number] = [40000, 40099];
// Kept as a public alias for callers that used the original fixed-range name.
export const WEBRTC_UDP_PORT_RANGE = DEFAULT_WEBRTC_UDP_PORT_RANGE;
export const WEBRTC_UDP_PORT_MIN = 1024;
export const WEBRTC_UDP_PORT_MAX = 65535;
-222
View File
@@ -1,222 +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,
},
});
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);
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, 3);
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()) };
}
-115
View File
@@ -1,115 +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,
});
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.deepEqual(service.getWebRtcAudioOptions(), { enabled: true });
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, 3);
assert.equal(reopened.listManagedInvites().length, 3);
reopened.close();
});
-71
View File
@@ -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 });
}
});
});
-46
View File
@@ -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]);
});
-16
View File
@@ -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");
});
});
-9
View File
@@ -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,
};
-13
View File
@@ -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);
});
-24
View File
@@ -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);
});
-12
View File
@@ -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);
});
});
-20
View File
@@ -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);
});
-18
View File
@@ -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 }));
});
-81
View File
@@ -1,81 +0,0 @@
import assert from "node:assert/strict";
import { existsSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import test from "node:test";
import { WebSpeakDatabase, DATABASE_SCHEMA_VERSION } from "../src/persistence/database.js";
import { hashAdminPassword } from "../src/security/admin-password.js";
test("SQLite persistence initializes schema and stores the single admin/settings model", async () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-"));
const dbPath = path.join(directory, "webspeak.db");
const database = new WebSpeakDatabase(dbPath);
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
assert.equal(database.hasAdmin(), false);
assert.equal(database.getSettings().accessMode, "fixed");
const credential = await hashAdminPassword("database-admin-password");
database.initializeAdmin(credential, {
siteName: "Private Voice",
welcomeText: "Welcome",
accessMode: "open",
tsHost: "voice.example.com",
tsPort: 9988,
tsPasswordEncrypted: "v1:ciphertext",
webRtcEnabled: true,
});
assert.equal(database.hasAdmin(), true);
assert.equal(database.getAdminCredential()?.hash, credential.hash);
assert.deepEqual(database.getSettings(), {
siteName: "Private Voice",
welcomeText: "Welcome",
accessMode: "open",
tsHost: "voice.example.com",
tsPort: 9988,
tsPasswordEncrypted: "v1:ciphertext",
detectedProtocol: null,
lastTestAt: null,
lastTestLatencyMs: null,
lastTestError: null,
webRtcEnabled: true,
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 v3 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, 3);
assert.equal(upgraded.getSettings().webRtcEnabled, false);
assert.equal("webRtcPublicHost" in upgraded.getSettings(), false);
assert.equal("webRtcUdpStart" in upgraded.getSettings(), false);
assert.equal("webRtcUdpEnd" in upgraded.getSettings(), false);
assert.equal(upgraded.listManagedInvites().length, 0);
assert.equal(existsSync(`${dbPath}.schema-1.bak`), true);
upgraded.close();
});
-49
View File
@@ -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");
});
-28
View File
@@ -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);
});
});
-19
View File
@@ -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);
});
-38
View File
@@ -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);
});
-59
View File
@@ -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);
});
-45
View File
@@ -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");
});
});
-28
View File
@@ -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");
});
-75
View File
@@ -1,75 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { parseClientCommand } from "../src/server/voice-protocol.js";
test("voice protocol accepts the versioned command payload", () => {
const command = parseClientCommand(JSON.stringify({
type: "switchChannel",
requestId: "switch-1",
payload: { channelId: "42" },
}));
assert.deepEqual(command, {
type: "switchChannel",
requestId: "switch-1",
payload: { channelId: "42" },
});
});
test("voice protocol rejects malformed and unsupported commands", () => {
assert.deepEqual(parseClientCommand("not-json"), {
error: { code: "INVALID_JSON", message: "消息不是有效的 JSON" },
});
assert.equal("error" in parseClientCommand(JSON.stringify({ type: "unknown", payload: {} })), true);
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage" })), {
error: { code: "INVALID_PAYLOAD", message: "消息参数无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage", payload: { message: "x".repeat(501) } })), {
error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" },
});
});
test("voice protocol keeps chat scopes and status actions explicit", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendPrivateMessage", requestId: "pm-1", payload: { clientId: 7, message: "hello" } })), {
type: "sendPrivateMessage",
requestId: "pm-1",
payload: { clientId: 7, message: "hello" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: true, message: "back soon" } })), {
type: "setAway",
payload: { away: true, message: "back soon" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "secret" } })), {
type: "switchChannel",
payload: { channelId: "42", password: "secret" },
});
});
test("voice protocol rejects unsafe client and away payloads", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "poke", payload: { clientId: 0, message: "hi" } })), {
error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: "yes" } })), {
error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "x".repeat(513) } })), {
error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" },
});
});
test("voice protocol validates whisper targets and its independent push state", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperTargets", requestId: "whisper-1", payload: { targetIds: [7, 9] } })), {
type: "setWhisperTargets",
requestId: "whisper-1",
payload: { targetIds: [7, 9] },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperActive", payload: { active: true } })), {
type: "setWhisperActive",
payload: { active: true },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperTargets", payload: { targetIds: [7, 7] } })), {
error: { code: "INVALID_WHISPER_TARGETS", message: "私语目标无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperActive", payload: { active: "yes" } })), {
error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" },
});
});
+1
View File
@@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#006a64" />
<meta name="description" content="WebSpeak — TeamSpeak browser voice workspace" />
<link rel="icon" type="image/jpeg" href="/网站图标.jpg" />
<title>WebSpeak · TeamSpeak Web Client</title>
</head>
<body>
Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

+21 -1
View File
@@ -31,7 +31,12 @@
</template>
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 0 1-1z" />
<template v-else-if="name === 'music'">
<path d="M9 18V5l10-2v13" />
<circle cx="6" cy="18" r="3" />
<circle cx="16" cy="16" r="3" />
</template>
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 1-1-1z" />
<path v-else-if="name === 'volume'" d="M4 10v4h3l4 3V7l-4 3zm10.5-2.5a6 6 0 0 1 0 9m2-11a9 9 0 0 1 0 13" />
<path v-else-if="name === 'volume-off'" d="m4 4 16 16M4 10v4h3l4 3V7l-4 3z" />
<template v-else-if="name === 'search'">
@@ -68,8 +73,23 @@
<path v-else-if="name === 'door'" d="M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5m5 14 5-5-5-5m5 5H9" />
<path v-else-if="name === 'waveform'" d="M3 12h2l2-6 3 12 3-9 2 6h6" />
<path v-else-if="name === 'shield'" d="M12 21s8-3.5 8-10V5l-8-3-8 3v6c0 6.5 8 10 8 10Z" />
<template v-else-if="name === 'sun'">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42" />
</template>
<path v-else-if="name === 'moon'" d="M20.4 15.2A8.5 8.5 0 0 1 8.8 3.6 8.5 8.5 0 1 0 20.4 15.2Z" />
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
<path v-else-if="name === 'github'" fill="currentColor" stroke="none" d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.53-1.33-1.28-1.68-1.28-1.68-1.04-.71.08-.7.08-.7 1.15.08 1.75 1.18 1.75 1.18 1.02 1.75 2.68 1.24 3.33.95.1-.74.4-1.24.73-1.52-2.55-.29-5.23-1.28-5.23-5.68 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.45.11-3.03 0 0 .96-.31 3.15 1.17.91-.25 1.88-.38 2.85-.38.97 0 1.94.13 2.85.38 2.19-1.48 3.15-1.17 3.15-1.17.62 1.58.23 2.74.11 3.03.73.8 1.18 1.82 1.18 3.07 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.04.78 2.1 0 1.52-.01 2.75-.01 3.12 0 .3.21.67.8.56C20.71 21.39 24 17.08 24 12 24 5.65 18.35.5 12 .5Z" />
<template v-else-if="name === 'qq'">
<ellipse cx="12" cy="12.3" rx="7.25" ry="8.85" fill="#202a2a" stroke="none" />
<ellipse cx="12" cy="14.8" rx="4.1" ry="5.55" fill="#fff" stroke="none" />
<circle cx="9.45" cy="9.55" r="1.35" fill="#fff" stroke="none" />
<circle cx="14.55" cy="9.55" r="1.35" fill="#fff" stroke="none" />
<circle cx="9.45" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
<circle cx="14.55" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
<path d="m10 11.15 2-1.05 2 1.05-2 1.45z" fill="#f2a53d" stroke="none" />
<path d="m5.8 18.55-2.1 2.1 3.75-.45m10.75-1.65 2.1 2.1-3.75-.45" fill="#f2a53d" stroke="#f2a53d" stroke-width="1.5" />
</template>
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
<circle v-else cx="12" cy="12" r="8" />
</svg>
+290
View File
@@ -0,0 +1,290 @@
<template>
<div ref="root" class="language-switcher" :class="{ open }" @keydown.esc="close">
<button
type="button"
class="language-trigger"
:aria-label="menuLabel"
aria-haspopup="listbox"
:aria-expanded="open"
:aria-controls="menuId"
@click.stop="toggle"
>
<span class="language-current-flag" aria-hidden="true">{{ currentLanguage.flag }}</span>
<span class="language-current-code">{{ currentLanguage.code }}</span>
<Icon name="chevron-down" :size="13" />
</button>
<div v-if="open" :id="menuId" class="language-dropdown" role="listbox" :aria-label="menuLabel" @click.stop>
<button
v-for="option in options"
:key="option.value"
type="button"
class="language-option"
:class="{ selected: modelValue === option.value }"
role="option"
:aria-selected="modelValue === option.value"
@pointerdown.stop.prevent="select(option.value)"
@keydown.enter.prevent="select(option.value)"
@keydown.space.prevent="select(option.value)"
>
<span class="language-option-flag" aria-hidden="true">{{ option.flag }}</span>
<span class="language-option-copy">
<strong>{{ option.label }}</strong>
<small>{{ option.code }}</small>
</span>
<Icon v-if="modelValue === option.value" name="check" :size="14" />
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import Icon from "./Icon.vue";
type Language = "zh" | "en" | "de";
const props = withDefaults(defineProps<{
modelValue: Language;
menuLabel?: string;
}>(), {
menuLabel: "Language",
});
const emit = defineEmits<{
"update:modelValue": [value: Language];
change: [value: Language];
}>();
const options: Array<{ value: Language; code: string; label: string; flag: string }> = [
{ value: "zh", code: "ZH", label: "中文", flag: "🇨🇳" },
{ value: "en", code: "EN", label: "English", flag: "🇬🇧" },
{ value: "de", code: "DE", label: "Deutsch", flag: "🇩🇪" },
];
const root = ref<HTMLElement | null>(null);
const open = ref(false);
const menuId = `language-menu-${Math.random().toString(36).slice(2, 9)}`;
const currentLanguage = computed(() => options.find((option) => option.value === props.modelValue) ?? options[0]);
function toggle() {
open.value = !open.value;
}
function close() {
open.value = false;
}
function select(value: Language) {
emit("update:modelValue", value);
emit("change", value);
close();
}
function onDocumentPointerDown(event: PointerEvent) {
if (root.value && !root.value.contains(event.target as Node)) close();
}
onMounted(() => document.addEventListener("pointerdown", onDocumentPointerDown));
onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerDown));
</script>
<style scoped>
.language-switcher {
position: relative;
z-index: 20;
flex: 0 0 auto;
color: #006a64;
font-family: inherit;
}
.language-trigger {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 70px;
min-height: 32px;
padding: 0 9px;
color: #006a64;
background: #e2f2ef;
border: 1px solid #c8e6e1;
border-radius: 8px;
font: inherit;
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
}
.language-trigger:hover,
.language-switcher.open .language-trigger {
color: #fff;
background: #006a64;
border-color: #006a64;
box-shadow: 0 7px 16px rgba(0, 106, 100, .16);
}
.language-trigger .ui-icon {
margin-left: auto;
transition: transform .16s;
}
.language-switcher.open .language-trigger .ui-icon {
transform: rotate(180deg);
}
.language-current-flag,
.language-option-flag {
font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
line-height: 1;
}
.language-current-flag {
font-size: 15px;
}
.language-current-code {
letter-spacing: .02em;
}
.language-dropdown {
position: absolute;
top: calc(100% + 8px);
right: 0;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-auto-rows: minmax(38px, max-content);
align-items: start;
align-content: start;
gap: 3px;
width: min(360px, calc(100vw - 16px));
height: auto;
max-height: none;
padding: 7px;
overflow: visible;
background: #fff;
border: 1px solid #dce9e5;
border-radius: 13px;
box-shadow: 0 16px 36px rgba(23, 60, 54, .18), 0 3px 8px rgba(23, 60, 54, .06);
animation: language-menu-in .14s ease-out;
}
.language-option {
display: flex;
align-items: center;
align-self: start;
min-width: 0;
gap: 8px;
min-height: 38px;
padding: 6px 8px;
color: #344540;
background: transparent;
border: 1px solid transparent;
border-radius: 8px;
font: inherit;
text-align: left;
cursor: pointer;
transition: color .14s, background .14s, border-color .14s;
}
.language-option:hover,
.language-option:focus-visible,
.language-option.selected {
color: #006a64;
background: #edf8f5;
border-color: #d4eee8;
}
.language-option-flag {
flex: 0 0 auto;
font-size: 17px;
}
.language-option-copy {
display: flex;
align-items: baseline;
justify-content: space-between;
min-width: 0;
flex: 1;
gap: 8px;
}
.language-option strong,
.language-option small {
overflow: visible;
text-overflow: clip;
white-space: nowrap;
}
.language-option strong {
flex: 0 0 auto;
font-size: 12px;
}
.language-option small {
flex: 0 0 auto;
color: #91a19c;
font-size: 10px;
font-weight: 700;
}
.language-option > .ui-icon {
flex: 0 0 auto;
}
@keyframes language-menu-in {
from { opacity: 0; transform: translateY(-4px) scale(.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
:global(html[data-theme="dark"]) .language-trigger,
:global(:root[data-theme="dark"]) .language-trigger {
color: #a9d9d1;
background: #203531;
border-color: #38564f;
}
:global(html[data-theme="dark"]) .language-trigger:hover,
:global(html[data-theme="dark"]) .language-switcher.open .language-trigger,
:global(:root[data-theme="dark"]) .language-trigger:hover,
:global(:root[data-theme="dark"]) .language-switcher.open .language-trigger {
color: #10201d;
background: #69d2c7;
border-color: #69d2c7;
}
:global(html[data-theme="dark"]) .language-dropdown,
:global(:root[data-theme="dark"]) .language-dropdown {
background: #172321;
border-color: #30413d;
box-shadow: 0 16px 36px rgba(0, 0, 0, .32);
}
:global(html[data-theme="dark"]) .language-option,
:global(:root[data-theme="dark"]) .language-option {
color: #d7e7e3;
}
:global(html[data-theme="dark"]) .language-option:hover,
:global(html[data-theme="dark"]) .language-option:focus-visible,
:global(html[data-theme="dark"]) .language-option.selected,
:global(:root[data-theme="dark"]) .language-option:hover,
:global(:root[data-theme="dark"]) .language-option:focus-visible,
:global(:root[data-theme="dark"]) .language-option.selected {
color: #69d2c7;
background: #203531;
border-color: #38564f;
}
@media (max-width: 520px) {
.language-trigger {
min-width: 62px;
min-height: 30px;
padding-inline: 7px;
}
.language-dropdown {
width: min(360px, calc(100vw - 16px));
}
}
</style>
+447 -107
View File
@@ -12,6 +12,7 @@ export interface VoiceState {
tsClientId: number;
error: string;
errorCode: string;
channelSwitchedChannelId: string;
}
export interface ChannelMember {
@@ -44,6 +45,10 @@ type SinkAudioContext = AudioContext & {
setSinkId?: (sinkId: string) => Promise<void>;
};
type SinkAudioElement = HTMLAudioElement & {
setSinkId?: (sinkId: string) => Promise<void>;
};
export interface ChannelInfo {
id: string;
parentID: string;
@@ -72,19 +77,29 @@ export interface ServerEvent {
timestamp: number;
}
export interface LatencyProbeResult {
browserRttMs: number;
teamSpeakLatencyMs: number | null;
teamSpeakReachable: boolean;
teamSpeakErrorCode?: string;
}
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: "" });
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", 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;
let webrtcOutputSource: MediaStreamAudioSourceNode | null = null;
let webrtcOutputGain: GainNode | null = null;
let webrtcOutputElement: SinkAudioElement | null = null;
let webrtcPlaybackStream: MediaStream | null = null;
let webrtcPlaybackRetryCleanup: (() => void) | null = null;
let webrtcNegotiationPromise: Promise<void> | null = null;
let webrtcFallbackStarted = false;
const webrtcActive = ref(false);
@@ -104,6 +119,18 @@ export function useVoiceWebSocket() {
let micSource: MediaStreamAudioSourceNode | null = null;
let micGain: GainNode | null = null;
let silentGain: GainNode | null = null;
const accompanimentActive = ref(false);
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
const accompanimentErrorCode = ref<"" | "unsupported" | "needsWebRtc" | "noAudio" | "permission">("");
let accompanimentStream: MediaStream | null = null;
let webrtcMixDestination: MediaStreamAudioDestinationNode | null = null;
let webrtcMixMicSource: MediaStreamAudioSourceNode | null = null;
let webrtcMixMicGain: GainNode | null = null;
let webrtcMixAccompanimentSource: MediaStreamAudioSourceNode | null = null;
let webrtcMicMonitorSource: MediaStreamAudioSourceNode | null = null;
let webrtcMicMonitorAnalyser: AnalyserNode | null = null;
let webrtcMicMonitorGain: GainNode | null = null;
let webrtcMicMonitorTimer: ReturnType<typeof setInterval> | null = null;
const inputDevices = reactive<AudioInputDevice[]>([]);
const outputDevices = reactive<AudioOutputDevice[]>([]);
const selectedInputDeviceId = ref(typeof localStorage !== "undefined" ? localStorage.getItem("webspeak:input-device") ?? "" : "");
@@ -119,6 +146,7 @@ export function useVoiceWebSocket() {
const microphoneMuted = ref(false);
const inputVolume = ref(1);
const outputVolume = ref(1);
const outputMuted = ref(false);
const notificationVolume = ref(0.5);
const voxThreshold = ref(0.008);
let voxAttack = 0;
@@ -153,40 +181,6 @@ export function useVoiceWebSocket() {
// for jitter; stale audio is discarded instead of being played late.
const MAX_REMOTE_PLAY_AHEAD_SECONDS = 0.08;
const MAX_REMOTE_DECODE_QUEUE_FRAMES = 3;
const audioDebugEnabled = typeof location !== "undefined"
&& new URLSearchParams(location.search).get("audioDebug") === "1";
const audioDiagnostics = reactive({
uplinkFrames: 0,
uplinkDroppedFrames: 0,
downlinkFrames: 0,
decoderOutputFrames: 0,
playbackStarts: 0,
playbackResets: 0,
peakBufferedBytes: 0,
peakPlayAheadMs: 0,
peakDecodeQueueFrames: 0,
downlinkFirstAt: null as number | null,
lastDownlinkAt: null as number | null,
downlinkMaxGapMs: 0,
lastDecodeOutputAt: null as number | null,
lastPlaybackStartAt: null as number | null,
lastPlayAheadMs: 0,
});
const audioCounters = { ...audioDiagnostics };
let nextAudioDiagnosticsPublishAt = 0;
function publishAudioDiagnostics(force = false): void {
const now = Date.now();
if (!force && now < nextAudioDiagnosticsPublishAt) return;
nextAudioDiagnosticsPublishAt = now + 1_000;
Object.assign(audioDiagnostics, audioCounters);
if (audioDebugEnabled) {
console.info("[WebSpeak audio checkpoint]", JSON.stringify({
at: new Date(now).toISOString(),
...audioDiagnostics,
}));
}
}
async function saveAudioPreferences(): Promise<void> {
await saveLocalPreferences({
@@ -248,6 +242,16 @@ export function useVoiceWebSocket() {
speakingIds.clear();
}
function effectiveOutputVolume(): number {
return outputMuted.value ? 0 : outputVolume.value;
}
function applyOutputVolume(): void {
const level = effectiveOutputVolume();
for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * level;
if (webrtcOutputElement) webrtcOutputElement.volume = level;
}
function getAudioCtx(): SinkAudioContext {
if (!audioCtx) {
audioCtx = new AudioContext({ sampleRate: 48000 }) as SinkAudioContext;
@@ -255,7 +259,8 @@ export function useVoiceWebSocket() {
audioCtx.addEventListener("statechange", () => {
if (audioCtx) audioContextState.value = audioCtx.state;
});
outputDeviceSupported.value = typeof audioCtx.setSinkId === "function";
outputDeviceSupported.value = typeof audioCtx.setSinkId === "function"
|| typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
if (selectedOutputDeviceId.value && outputDeviceSupported.value) {
void setAudioSink(audioCtx, selectedOutputDeviceId.value).catch(() => undefined);
}
@@ -268,13 +273,46 @@ export function useVoiceWebSocket() {
}
async function setAudioSink(ctx: SinkAudioContext, deviceId: string): Promise<void> {
if (!ctx.setSinkId) {
const mediaSinkSupported = typeof (HTMLMediaElement.prototype as SinkAudioElement).setSinkId === "function";
if (!ctx.setSinkId && !mediaSinkSupported) {
outputDeviceSupported.value = false;
if (deviceId) throw new Error("当前浏览器不支持扬声器设备选择,将使用默认输出设备");
return;
}
outputDeviceSupported.value = true;
await ctx.setSinkId(deviceId || "default");
if (ctx.setSinkId) await ctx.setSinkId(deviceId || "default");
if (webrtcOutputElement?.setSinkId) await webrtcOutputElement.setSinkId(deviceId || "default");
}
function installWebRtcPlaybackRetry(): void {
if (webrtcPlaybackRetryCleanup) return;
const retry = () => { void syncWebRtcPlayback(); };
const events: (keyof WindowEventMap)[] = ["pointerdown", "touchstart", "keydown"];
for (const event of events) window.addEventListener(event, retry, { passive: true });
document.addEventListener("visibilitychange", retry, { passive: true });
webrtcPlaybackRetryCleanup = () => {
for (const event of events) window.removeEventListener(event, retry);
document.removeEventListener("visibilitychange", retry);
webrtcPlaybackRetryCleanup = null;
};
}
async function syncWebRtcPlayback(): Promise<void> {
const output = webrtcOutputElement;
if (!output || !webrtcPlaybackStream) return;
// Keep WebRTC on the browser's native MediaStream playback path. The
// capture AudioContext is intentionally not used as a second output
// 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;
try {
await output.play();
webrtcPlaybackRetryCleanup?.();
} catch {
// Mobile and privacy-focused browsers can require a gesture even for a
// MediaStream. Keep retrying after the next real interaction.
installWebRtcPlaybackRetry();
}
}
function checkSupport(): string | null {
@@ -375,11 +413,8 @@ export function useVoiceWebSocket() {
return;
}
const bufferedBytes = socket.bufferedAmount;
audioCounters.peakBufferedBytes = Math.max(audioCounters.peakBufferedBytes, bufferedBytes);
if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) {
accumLen = 0;
audioCounters.uplinkDroppedFrames++;
publishAudioDiagnostics();
return;
}
@@ -398,8 +433,6 @@ export function useVoiceWebSocket() {
while (offset + AUDIO_FRAME_SAMPLES <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) {
socket.send(accumBuf.slice(offset, offset + AUDIO_FRAME_SAMPLES).buffer);
offset += AUDIO_FRAME_SAMPLES;
audioCounters.uplinkFrames++;
publishAudioDiagnostics();
}
if (offset > 0) markSpeaking(state.tsClientId);
accumLen -= offset;
@@ -471,31 +504,191 @@ export function useVoiceWebSocket() {
return false;
}
function stopWebRtcMix(): void {
webrtcMixAccompanimentSource?.disconnect();
webrtcMixMicSource?.disconnect();
webrtcMixMicGain?.disconnect();
webrtcMixDestination?.disconnect();
webrtcMixAccompanimentSource = null;
webrtcMixMicSource = null;
webrtcMixMicGain = null;
webrtcMixDestination = null;
}
function releaseAccompanimentStream(): void {
accompanimentStream?.getTracks().forEach((track) => track.stop());
accompanimentStream = null;
accompanimentActive.value = false;
}
function createWebRtcMixStream(): MediaStream {
if (!micStream) throw new Error("没有可用的麦克风音轨");
const ctx = getAudioCtx();
stopWebRtcMix();
const destination = ctx.createMediaStreamDestination();
destination.channelCount = 1;
destination.channelCountMode = "explicit";
const microphoneSource = ctx.createMediaStreamSource(micStream);
const microphoneGain = ctx.createGain();
microphoneGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
microphoneSource.connect(microphoneGain);
microphoneGain.connect(destination);
webrtcMixDestination = destination;
webrtcMixMicSource = microphoneSource;
webrtcMixMicGain = microphoneGain;
const accompanimentTrack = accompanimentStream?.getAudioTracks()[0];
if (accompanimentTrack) {
const accompanimentSource = ctx.createMediaStreamSource(accompanimentStream!);
// Keep the captured application audio at its source level. Do not add
// a fixed attenuation/gain node: it makes music sound quieter than the
// source and encourages later "compensation" steps to pump its volume.
accompanimentSource.connect(destination);
webrtcMixAccompanimentSource = accompanimentSource;
}
return destination.stream;
}
async function replaceWebRtcAudioTrack(): Promise<void> {
if (!webrtcPeer || !micStream) return;
const sender = webrtcPeer.getSenders().find((candidate) => candidate.track?.kind === "audio");
if (!sender) throw new Error("WebRTC 音频轨道尚未就绪");
const mixedStream = createWebRtcMixStream();
const mixedTrack = mixedStream.getAudioTracks()[0];
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
await sender.replaceTrack(mixedTrack);
}
async function startAccompaniment(): Promise<void> {
accompanimentErrorCode.value = "";
if (!accompanimentSupported.value) {
accompanimentErrorCode.value = "unsupported";
throw new Error("伴奏共享不可用");
}
if (!webrtcActive.value || !webrtcPeer || !micStream) {
accompanimentErrorCode.value = "needsWebRtc";
throw new Error("伴奏功能需要启用 WebRTC");
}
const captureProcessingConstraints: MediaTrackConstraints = {
// Display/application audio must not pass through browser voice
// processing. Those processors are designed for speech and can change
// music level from frame to frame (AGC), suppress quiet passages, or
// cancel sustained tones.
autoGainControl: false,
echoCancellation: false,
noiseSuppression: false,
};
const audioConstraints = { ...captureProcessingConstraints } as MediaTrackConstraints & { restrictOwnAudio?: boolean };
const supportedConstraints = navigator.mediaDevices.getSupportedConstraints?.() as Record<string, boolean> | undefined;
if (supportedConstraints?.restrictOwnAudio) audioConstraints.restrictOwnAudio = true;
const options = {
video: { displaySurface: "browser" },
audio: audioConstraints,
selfBrowserSurface: "exclude",
systemAudio: "include",
windowAudio: "window",
} as unknown as DisplayMediaStreamOptions;
let nextStream: MediaStream;
try {
nextStream = await navigator.mediaDevices.getDisplayMedia(options);
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") return;
accompanimentErrorCode.value = "permission";
throw error;
}
const audioTrack = nextStream.getAudioTracks()[0];
nextStream.getVideoTracks().forEach((track) => track.stop());
if (!audioTrack) {
nextStream.getTracks().forEach((track) => track.stop());
accompanimentErrorCode.value = "noAudio";
throw new Error("所选来源没有可共享音频");
}
try {
// Do not pass the Chromium-only restrictOwnAudio hint to
// applyConstraints: rejecting an unknown key could otherwise cause the
// browser to discard all three standard processing-off constraints.
await audioTrack.applyConstraints(captureProcessingConstraints);
} catch {
// Some browsers expose display audio but reject one or more optional
// processing constraints. The capture can still proceed without
// introducing a WebSpeak-side gain stage.
}
if ("contentHint" in audioTrack) audioTrack.contentHint = "music";
accompanimentStream?.getTracks().forEach((track) => track.stop());
accompanimentStream = nextStream;
accompanimentActive.value = true;
sendCmd("setAccompanimentActive", { active: true });
audioTrack.addEventListener("ended", () => { void stopAccompaniment(); }, { once: true });
try {
await replaceWebRtcAudioTrack();
} catch (error) {
releaseAccompanimentStream();
sendCmd("setAccompanimentActive", { active: false });
stopWebRtcMix();
accompanimentErrorCode.value = "permission";
throw error;
}
}
async function stopAccompaniment(): Promise<void> {
accompanimentErrorCode.value = "";
releaseAccompanimentStream();
if (webrtcActive.value) sendCmd("setAccompanimentActive", { active: false });
if (webrtcActive.value && webrtcPeer && micStream) await replaceWebRtcAudioTrack();
else stopWebRtcMix();
}
async function startWebRtcTransport(sequence: number, socket: WebSocket): Promise<void> {
if (typeof RTCPeerConnection === "undefined") throw new Error("当前浏览器不支持 WebRTC");
await ensureMicrophone();
if (sequence !== connectionSequence || socket.readyState !== WebSocket.OPEN || !micStream) return;
const track = micStream.getAudioTracks()[0];
if (!track) throw new Error("没有可用的麦克风音轨");
const microphoneTrack = micStream.getAudioTracks()[0];
if (!microphoneTrack) throw new Error("没有可用的麦克风音轨");
stopCaptureGraph();
const peer = new RTCPeerConnection({ iceServers: [] });
webrtcPeer = peer;
webrtcFallbackStarted = false;
track.enabled = !microphoneMuted.value;
peer.addTrack(track, micStream);
microphoneTrack.enabled = !microphoneMuted.value;
const mixedStream = createWebRtcMixStream();
const mixedTrack = mixedStream.getAudioTracks()[0];
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
peer.addTrack(mixedTrack, mixedStream);
peer.ontrack = (event) => {
const stream = event.streams[0] ?? new MediaStream([event.track]);
const ctx = getAudioCtx();
if (ctx.state === "suspended") void ctx.resume();
webrtcOutputSource?.disconnect();
webrtcOutputGain?.disconnect();
webrtcOutputSource = ctx.createMediaStreamSource(stream);
webrtcOutputGain = ctx.createGain();
webrtcOutputGain.gain.value = outputVolume.value;
webrtcOutputSource.connect(webrtcOutputGain);
webrtcOutputGain.connect(ctx.destination);
// Use the browser's native WebRTC media output. Routing the remote
// track through AudioContext made playback depend on autoplay policy:
// the control channel could report speaking while a suspended context
// silently discarded the actual audio. A hidden autoplaying media
// element keeps WebRTC's decoder and jitter buffer on the native path.
stopWebRtcPlayback();
const output = document.createElement("audio") as SinkAudioElement;
output.autoplay = true;
output.muted = false;
output.setAttribute("playsinline", "");
output.volume = effectiveOutputVolume();
output.setAttribute("aria-hidden", "true");
output.tabIndex = -1;
output.style.position = "fixed";
output.style.width = "1px";
output.style.height = "1px";
output.style.opacity = "0";
output.style.pointerEvents = "none";
output.srcObject = stream;
document.body.append(output);
webrtcOutputElement = output;
webrtcPlaybackStream = stream;
if (selectedOutputDeviceId.value && output.setSinkId) {
void output.setSinkId(selectedOutputDeviceId.value).catch(() => undefined);
}
void syncWebRtcPlayback();
};
startWebRtcMicMonitor(getAudioCtx(), micStream, microphoneTrack);
peer.onconnectionstatechange = () => {
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket);
};
@@ -508,7 +701,11 @@ export function useVoiceWebSocket() {
if (sequence !== connectionSequence || webrtcPeer !== peer || socket.readyState !== WebSocket.OPEN) return;
const description = peer.localDescription;
if (!description) throw new Error("WebRTC offer was not created");
socket.send(JSON.stringify({ type: "webrtcOffer", payload: { sdp: { type: description.type, sdp: description.sdp } } }));
socket.send(JSON.stringify({ type: "webrtcOffer", payload: {
sdp: { type: description.type, sdp: description.sdp },
muted: microphoneMuted.value,
accompanimentActive: accompanimentActive.value,
} }));
window.setTimeout(() => {
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket);
}, 8_000);
@@ -548,6 +745,7 @@ export function useVoiceWebSocket() {
try {
await webrtcPeer.setRemoteDescription(description);
webrtcActive.value = true;
syncWebRtcMemberVolumes();
} catch {
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value);
}
@@ -571,13 +769,66 @@ export function useVoiceWebSocket() {
webrtcPeer = null;
webrtcActive.value = false;
webrtcNegotiationPromise = null;
webrtcOutputSource?.disconnect();
webrtcOutputGain?.disconnect();
webrtcOutputSource = null;
webrtcOutputGain = null;
releaseAccompanimentStream();
stopWebRtcMix();
stopWebRtcMicMonitor();
stopWebRtcPlayback();
if (peer) void peer.close();
}
function stopWebRtcPlayback(): void {
webrtcPlaybackRetryCleanup?.();
webrtcPlaybackStream = null;
webrtcOutputElement?.pause();
if (webrtcOutputElement) {
webrtcOutputElement.srcObject = null;
webrtcOutputElement.remove();
}
webrtcOutputElement = null;
}
function startWebRtcMicMonitor(ctx: AudioContext, stream: MediaStream, track: MediaStreamTrack): void {
stopWebRtcMicMonitor(false);
try {
const source = ctx.createMediaStreamSource(stream);
const analyser = ctx.createAnalyser();
analyser.fftSize = 512;
const silent = ctx.createGain();
silent.gain.value = 0;
source.connect(analyser);
analyser.connect(silent);
silent.connect(ctx.destination);
const samples = new Float32Array(analyser.fftSize);
webrtcMicMonitorSource = source;
webrtcMicMonitorAnalyser = analyser;
webrtcMicMonitorGain = silent;
webrtcMicMonitorTimer = setInterval(() => {
if (!webrtcMicMonitorAnalyser) return;
webrtcMicMonitorAnalyser.getFloatTimeDomainData(samples);
let sum = 0;
for (const sample of samples) sum += sample * sample;
const rms = Math.sqrt(sum / samples.length);
micLevel.value = Math.min(1, rms * 6);
if (!microphoneMuted.value && track.enabled && rms >= voxThreshold.value) markSpeaking(state.tsClientId);
else if (state.tsClientId) clearSpeaking(state.tsClientId);
}, 50);
} catch {
stopWebRtcMicMonitor(false);
}
}
function stopWebRtcMicMonitor(resetLevel = true): void {
if (webrtcMicMonitorTimer) clearInterval(webrtcMicMonitorTimer);
webrtcMicMonitorTimer = null;
webrtcMicMonitorSource?.disconnect();
webrtcMicMonitorAnalyser?.disconnect();
webrtcMicMonitorGain?.disconnect();
webrtcMicMonitorSource = null;
webrtcMicMonitorAnalyser = null;
webrtcMicMonitorGain = null;
if (resetLevel) micLevel.value = 0;
}
function isSessionDescription(value: unknown, type: "answer"): value is RTCSessionDescriptionInit {
return Boolean(value) && typeof value === "object"
&& (value as { type?: unknown }).type === type
@@ -604,6 +855,8 @@ export function useVoiceWebSocket() {
function stopMicrophone(closeContext = true): void {
stopCaptureGraph();
releaseAccompanimentStream();
stopWebRtcMix();
micStream?.getTracks().forEach((track) => track.stop());
micStream = null;
if (closeContext) {
@@ -696,7 +949,7 @@ export function useVoiceWebSocket() {
}
function playNotification(kind: "connected" | "disconnected" | "poke" | "private" | "reconnectFailed"): void {
if (notificationVolume.value <= 0 || typeof window === "undefined") return;
if (notificationVolume.value <= 0 || outputMuted.value || effectiveOutputVolume() <= 0 || typeof window === "undefined") return;
try {
const ctx = getAudioCtx();
if (ctx.state === "suspended") return;
@@ -713,7 +966,7 @@ export function useVoiceWebSocket() {
oscillator.frequency.setValueAtTime(frequencies[kind][0], now);
oscillator.frequency.setValueAtTime(frequencies[kind][1], now + 0.08);
gain.gain.setValueAtTime(0.0001, now);
gain.gain.exponentialRampToValueAtTime(Math.max(0.0001, notificationVolume.value * 0.12), now + 0.01);
gain.gain.exponentialRampToValueAtTime(Math.max(0.0001, notificationVolume.value * effectiveOutputVolume() * 0.12), now + 0.01);
gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.18);
oscillator.connect(gain);
gain.connect(ctx.destination);
@@ -731,7 +984,6 @@ export function useVoiceWebSocket() {
const now = ctx.currentTime;
const scheduledUntil = remotePlayTimes.get(clientId) ?? now;
const decodeQueueSize = decoder?.decodeQueueSize ?? 0;
audioCounters.peakDecodeQueueFrames = Math.max(audioCounters.peakDecodeQueueFrames, decodeQueueSize);
if (
decoder &&
(scheduledUntil > now + MAX_REMOTE_PLAY_AHEAD_SECONDS || decodeQueueSize >= MAX_REMOTE_DECODE_QUEUE_FRAMES)
@@ -742,7 +994,7 @@ export function useVoiceWebSocket() {
if (!decoder) {
const gainNode = ctx.createGain();
gainNode.gain.value = (volumes[clientId] ?? 1) * outputVolume.value;
gainNode.gain.value = (volumes[clientId] ?? 1) * effectiveOutputVolume();
gainNode.connect(ctx.destination);
remoteGains.set(clientId, gainNode);
const generation = ++nextRemoteDecoderGeneration;
@@ -754,8 +1006,6 @@ export function useVoiceWebSocket() {
}
try {
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
audioCounters.decoderOutputFrames++;
audioCounters.lastDecodeOutputAt = Date.now();
const buffer = ctx.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
for (let ch = 0; ch < numberOfChannels; ch++) {
const data = new Float32Array(numberOfFrames);
@@ -787,17 +1037,7 @@ export function useVoiceWebSocket() {
return;
}
source.start(playTime);
audioCounters.playbackStarts++;
audioCounters.lastPlaybackStartAt = Date.now();
remotePlayTimes.set(clientId, playTime + numberOfFrames / sampleRate);
audioCounters.lastPlayAheadMs = Math.max(
0,
Math.round((playTime + numberOfFrames / sampleRate - ctx.currentTime) * 1_000),
);
audioCounters.peakPlayAheadMs = Math.max(
audioCounters.peakPlayAheadMs,
audioCounters.lastPlayAheadMs,
);
} catch {
// A decoder can finish while the audio context is being torn down.
}
@@ -820,8 +1060,6 @@ export function useVoiceWebSocket() {
const timestamp = remoteDecodeTimestamps.get(clientId) ?? 0;
decoder.decode(new EncodedAudioChunk({ type: "key", timestamp, duration: 20_000, data: opusData }));
remoteDecodeTimestamps.set(clientId, timestamp + 20_000);
audioCounters.downlinkFrames++;
publishAudioDiagnostics();
} catch {
// Ignore malformed frames; the next valid frame can still be decoded.
}
@@ -848,13 +1086,11 @@ export function useVoiceWebSocket() {
function resetRemotePlayback(clientId: number): void {
clearRemotePlayback(clientId);
audioCounters.playbackResets++;
publishAudioDiagnostics();
}
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 = "";
@@ -863,15 +1099,15 @@ export function useVoiceWebSocket() {
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 };
if (!response.ok || typeof result.ticket !== "string") {
@@ -910,38 +1146,75 @@ export function useVoiceWebSocket() {
};
socket.onclose = (event) => {
if (sequence !== connectionSequence) return;
clearLatencyProbes();
state.connected = false;
state.connecting = false;
state.reconnecting = false;
if (event.code !== 1000 && !state.error && !state.reconnectFailed) state.error = closeReason(event.code);
// 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.errorCode = closeErrorCode(event.code, event.reason);
state.error = closeReason(event.code, event.reason);
}
stopWebRtcTransport();
stopMicrophone();
whisperTargetIds.clear();
whisperActive.value = false;
};
socket.onerror = () => {
if (sequence !== connectionSequence) return;
state.error = "连接服务器失败,请检查邀请链接或服务器状态";
// The following close event contains the actionable close code. Do not
// overwrite it with a generic browser WebSocket error first.
};
}
function joinTicketReason(code: string): string {
if (code === "NOT_INITIALIZED") return "WebSpeak 尚未完成首次配置";
if (code === "TARGET_NOT_ALLOWED") return "此 TeamSpeak 服务器地址不允许连接";
if (code === "ACCELERATION_UNAVAILABLE") return "大陆节点智能加速尚未在当前网关配置";
if (code === "INVALID_NICKNAME") return "请输入有效的昵称";
if (code === "INVITE_INVALID") return "邀请链接已失效或已被撤销";
return "连接服务器失败,请检查邀请链接或服务器状态";
}
function closeReason(code: number): string {
function closeErrorCode(code: number, reason = ""): string {
const known = new Set(["INVALID_TARGET", "UNREACHABLE", "TIMEOUT", "SERVER_PASSWORD_REQUIRED", "INVALID_SERVER_PASSWORD", "PROTOCOL_NEGOTIATION_FAILED", "SERVER_REJECTED", "CONNECTION_FAILED"]);
if (known.has(reason)) return reason;
if (code === 4002) return "INVALID_TARGET";
if (code === 4004) return "SERVER_REJECTED";
if (code === 4005) return "IDENTITY_IN_USE";
return "CONNECTION_FAILED";
}
function connectionFailureMessage(code: string): string {
const messages: Record<string, string> = {
INVALID_TARGET: "TeamSpeak 服务器地址无效",
UNREACHABLE: "无法到达 TeamSpeak 服务器,请检查网络或地址",
TIMEOUT: "连接 TeamSpeak 超时,请检查网络或服务器状态",
SERVER_PASSWORD_REQUIRED: "该服务器需要密码,请输入密码后重试",
INVALID_SERVER_PASSWORD: "服务器密码错误,请重新输入",
PROTOCOL_NEGOTIATION_FAILED: "TeamSpeak 协议协商失败",
SERVER_REJECTED: "TeamSpeak 服务器拒绝了连接",
IDENTITY_IN_USE: "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试",
CONNECTION_FAILED: "TeamSpeak 连接失败,请检查地址、网络或服务器状态",
};
return messages[code] ?? "连接已断开";
}
function closeReason(code: number, reason = ""): string {
const failureCode = closeErrorCode(code, reason);
if (failureCode !== "CONNECTION_FAILED") return connectionFailureMessage(failureCode);
if (code === 4002) return "TeamSpeak 服务器地址无效";
if (code === 4003) return "TeamSpeak 服务器连接失败";
if (code === 4004) return "服务器当前已满,请稍后重试";
if (code === 4005) return "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试";
return "连接已断开";
}
function disconnect(preserveConnection = false): void {
connectionSequence++;
clearLatencyProbes();
const keepRememberedIdentity = lastConnection?.rememberIdentity === true;
if (!preserveConnection) lastConnection = null;
stopMicrophone();
const socket = ws.value;
@@ -955,7 +1228,8 @@ export function useVoiceWebSocket() {
state.reconnectFailed = false;
state.tsClientId = 0;
state.errorCode = "";
identityMaterial.value = "";
state.channelSwitchedChannelId = "";
if (!keepRememberedIdentity) identityMaterial.value = "";
members.length = 0;
channels.length = 0;
chatMessages.length = 0;
@@ -971,6 +1245,14 @@ export function useVoiceWebSocket() {
for (const key of Object.keys(volumes)) delete volumes[Number(key)];
}
function clearLatencyProbes(): void {
for (const [sequence, pending] of pendingLatencyProbes) {
clearTimeout(pending.timer);
pendingLatencyProbes.delete(sequence);
pending.resolve(null);
}
}
function handleMessage(msg: any): void {
switch (msg.type) {
case "connected":
@@ -982,6 +1264,7 @@ export function useVoiceWebSocket() {
state.reconnectFailed = false;
state.error = "";
state.errorCode = "";
state.channelSwitchedChannelId = "";
state.tsClientId = Number(msg.tsClientId) || 0;
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
if (Array.isArray(msg.members)) {
@@ -1038,10 +1321,14 @@ export function useVoiceWebSocket() {
case "chatMessage":
if (Number(msg.invokerId) === state.tsClientId) break;
const incomingScope = msg.scope === "private" || msg.scope === "server" || msg.scope === "channel" ? msg.scope : "system";
const rawTargetId = typeof msg.targetId === "string" || typeof msg.targetId === "number" ? String(msg.targetId) : undefined;
// Older gateways and TeamSpeak channel notifications may use 0 as
// the broadcast sentinel. It must not be compared with a channel id.
const incomingTargetId = rawTargetId && rawTargetId !== "0" ? rawTargetId : undefined;
chatMessages.push({
id: `remote-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
scope: incomingScope,
targetId: typeof msg.targetId === "string" ? msg.targetId : undefined,
...(incomingTargetId ? { targetId: incomingTargetId } : {}),
...(incomingScope === "private" ? { conversationId: String(Number(msg.invokerId) || 0) } : {}),
senderId: Number(msg.invokerId) || undefined,
senderUid: typeof msg.senderUid === "string" ? msg.senderUid : undefined,
@@ -1064,7 +1351,24 @@ export function useVoiceWebSocket() {
});
break;
case "channelSwitched":
state.channelSwitchedChannelId = typeof msg.channelId === "string" || typeof msg.channelId === "number" ? String(msg.channelId) : "";
state.error = "";
state.errorCode = "";
break;
case "latencyPong": {
const sequence = typeof msg.sequence === "string" ? msg.sequence : "";
const pending = pendingLatencyProbes.get(sequence);
if (!pending) break;
pendingLatencyProbes.delete(sequence);
clearTimeout(pending.timer);
pending.resolve({
browserRttMs: Math.max(0, Math.round(performance.now() - pending.startedAt)),
teamSpeakLatencyMs: typeof msg.teamSpeakLatencyMs === "number" ? msg.teamSpeakLatencyMs : null,
teamSpeakReachable: msg.teamSpeakReachable === true,
...(typeof msg.teamSpeakErrorCode === "string" ? { teamSpeakErrorCode: msg.teamSpeakErrorCode } : {}),
});
break;
}
case "disconnected":
state.connected = false;
state.connecting = false;
@@ -1096,7 +1400,8 @@ export function useVoiceWebSocket() {
state.connecting = false;
state.reconnecting = false;
state.reconnectFailed = true;
state.error = "连接已中断,无法自动恢复";
state.errorCode = typeof msg.code === "string" ? msg.code : "CONNECTION_FAILED";
state.error = connectionFailureMessage(state.errorCode);
whisperTargetIds.clear();
whisperActive.value = false;
break;
@@ -1131,12 +1436,6 @@ export function useVoiceWebSocket() {
if (data.length < 4) return;
const clientId = (data[1] << 8) | data[2];
if (clientId === state.tsClientId) return;
const receivedAt = Date.now();
if (audioCounters.lastDownlinkAt !== null) {
audioCounters.downlinkMaxGapMs = Math.max(audioCounters.downlinkMaxGapMs, receivedAt - audioCounters.lastDownlinkAt);
}
audioCounters.downlinkFirstAt ??= receivedAt;
audioCounters.lastDownlinkAt = receivedAt;
markSpeaking(clientId);
playAudioFrame(clientId, data.slice(3));
}
@@ -1148,9 +1447,24 @@ export function useVoiceWebSocket() {
function switchChannel(channelId: string, password = ""): void {
state.error = "";
state.errorCode = "";
state.channelSwitchedChannelId = "";
sendCmd("switchChannel", { channelId, ...(password ? { password } : {}) });
}
function measureLatency(timeoutMs = 2_200): Promise<LatencyProbeResult | null> {
const socket = ws.value;
if (!socket || socket.readyState !== WebSocket.OPEN) return Promise.resolve(null);
const sequence = `latency-${Date.now().toString(36)}-${(latencyProbeSequence++).toString(36)}`;
return new Promise((resolve) => {
const timer = setTimeout(() => {
pendingLatencyProbes.delete(sequence);
resolve(null);
}, timeoutMs);
pendingLatencyProbes.set(sequence, { startedAt: performance.now(), resolve, timer });
sendCmd("latencyProbe", { sequence });
});
}
function sendTextMessage(message: string, targetId = ""): void {
const trimmed = message.trim();
if (!trimmed || trimmed.length > 500) return;
@@ -1215,7 +1529,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 {
@@ -1224,6 +1538,9 @@ export function useVoiceWebSocket() {
voxRelease = 0;
accumLen = 0;
if (webrtcActive.value) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
if (webrtcMixMicGain) webrtcMixMicGain.gain.value = muted ? 0 : inputVolume.value;
if (webrtcActive.value) sendCmd("setMicrophoneMuted", { muted });
if (muted && state.tsClientId) clearSpeaking(state.tsClientId);
void saveAudioPreferences();
}
@@ -1246,6 +1563,7 @@ export function useVoiceWebSocket() {
INVALID_POKE_MESSAGE: "戳一戳消息无效",
INVALID_AWAY_STATUS: "离开状态无效",
INVALID_AUDIO_FRAME: "音频帧格式无效",
INVALID_MEMBER_VOLUME: "成员音量无效",
INVALID_WHISPER_TARGETS: "私语目标无效",
INVALID_WHISPER_STATE: "私语状态无效",
NO_WHISPER_TARGETS: "请先选择私语目标",
@@ -1269,22 +1587,37 @@ export function useVoiceWebSocket() {
void saveAudioPreferences();
}
const gain = remoteGains.get(clientId);
if (gain) gain.gain.value = normalized * outputVolume.value;
if (gain) gain.gain.value = normalized * effectiveOutputVolume();
if (webrtcPeer || webrtcActive.value) sendCmd("setMemberVolume", { clientId, volume: normalized });
}
function syncWebRtcMemberVolumes(): void {
if (!webrtcActive.value || ws.value?.readyState !== WebSocket.OPEN) return;
for (const [rawClientId, volume] of Object.entries(volumes)) {
const clientId = Number(rawClientId);
if (!Number.isInteger(clientId) || clientId <= 0) continue;
sendCmd("setMemberVolume", { clientId, volume });
}
}
function setInputVolume(volume: number): void {
inputVolume.value = Math.max(0, Math.min(1, volume));
if (micGain) micGain.gain.value = inputVolume.value;
if (webrtcMixMicGain) webrtcMixMicGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
void saveAudioPreferences();
}
function setOutputVolume(volume: number): void {
outputVolume.value = Math.max(0, Math.min(1, volume));
for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * outputVolume.value;
if (webrtcOutputGain) webrtcOutputGain.gain.value = outputVolume.value;
applyOutputVolume();
void saveAudioPreferences();
}
function toggleOutputMute(): void {
outputMuted.value = !outputMuted.value;
applyOutputVolume();
}
function setVoxThreshold(threshold: number): void {
voxThreshold.value = clamp(threshold, 0.001, 0.08);
void saveAudioPreferences();
@@ -1306,6 +1639,7 @@ export function useVoiceWebSocket() {
microphoneMuted,
inputVolume,
outputVolume,
outputMuted,
notificationVolume,
voxThreshold,
inputDevices,
@@ -1315,7 +1649,6 @@ export function useVoiceWebSocket() {
outputDeviceSupported,
audioPermission,
audioContextState,
audioDiagnostics,
identityMaterial,
micLevel,
microphoneTestActive,
@@ -1324,9 +1657,13 @@ export function useVoiceWebSocket() {
whisperTargetIds,
whisperActive,
volumes,
accompanimentActive,
accompanimentSupported,
accompanimentErrorCode,
setVolume,
setInputVolume,
setOutputVolume,
toggleOutputMute,
setVoxThreshold,
setNotificationVolume,
prepareInputDevices,
@@ -1348,7 +1685,10 @@ export function useVoiceWebSocket() {
setWhisperTargets,
setWhisperActive,
setMicrophoneMuted,
startAccompaniment,
stopAccompaniment,
checkSupport,
clearError,
measureLatency,
};
}
+13 -1
View File
@@ -35,7 +35,7 @@ export interface LocalPreferences {
theme?: "system" | "light" | "dark";
microphoneMuted?: boolean;
voxThreshold?: number;
language?: "zh" | "en";
language?: "zh" | "en" | "de";
preferredInputDeviceId?: string;
preferredOutputDeviceId?: string;
inputGain?: number;
@@ -118,6 +118,18 @@ export async function saveStoredIdentity(privateMaterial: string, label = "此
}
}
export async function removeStoredIdentity(): Promise<void> {
try {
await request("identities", "readwrite", (store, resolve, reject) => {
const remove = store.delete(CURRENT_IDENTITY_KEY);
remove.onsuccess = () => resolve(undefined);
remove.onerror = () => reject(remove.error);
});
} catch {
// Identity removal is best effort when browser storage is unavailable.
}
}
export async function loadLocalPreferences(): Promise<LocalPreferences> {
const defaults: LocalPreferences = { schemaVersion: 1, volumesByUid: {} };
try {
+9 -1
View File
@@ -17,8 +17,16 @@ export function saveTheme(theme: ThemeMode): void {
applyTheme(theme);
}
export function isDarkTheme(theme: ThemeMode): boolean {
if (theme === "dark") return true;
if (theme === "light") return false;
return typeof window !== "undefined" && typeof window.matchMedia === "function"
? window.matchMedia("(prefers-color-scheme: dark)").matches
: false;
}
export function nextTheme(theme: ThemeMode): ThemeMode {
return theme === "system" ? "light" : theme === "light" ? "dark" : "system";
return isDarkTheme(theme) ? "light" : "dark";
}
applyTheme(getStoredTheme());
+487 -45
View File
@@ -7,7 +7,7 @@
<div class="admin-brand centered"><span><Icon name="waveform" :size="24" /></span><div><strong>WebSpeak</strong><small>{{ tr('adminConsole') }}</small></div></div>
<header><h1>{{ tr('changePasswordTitle') }}</h1><p>{{ tr('changePasswordLead') }}</p></header>
<form @submit.prevent="changePassword"><div v-if="errorMessage" class="alert error">{{ errorMessage }}</div><label><span>{{ tr('newPassword') }}</span><input v-model="newPassword" type="password" autocomplete="new-password" maxlength="1024" autofocus :placeholder="tr('passwordPlaceholder')" /></label><label><span>{{ tr('confirmPassword') }}</span><input v-model="confirmNewPassword" type="password" autocomplete="new-password" maxlength="1024" /></label><div class="strength"><i :style="{ width: `${passwordStrength}%` }"></i></div><button class="primary-button wide" :disabled="submitting" type="submit"><span v-if="submitting" class="spinner small"></span>{{ tr('savePassword') }}</button></form>
<p class="security-note">{{ tr('defaultCredentialNotice') }}</p><button class="language-link" type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button>
<p class="security-note">{{ tr('defaultCredentialNotice') }}</p><LanguageSwitcher v-model="language" class="language-link" :menu-label="tr('languageMenu')" @change="persistLanguage" />
</section>
</main>
@@ -16,7 +16,7 @@
<div class="admin-brand centered"><span><Icon name="waveform" :size="24" /></span><div><strong>WebSpeak</strong><small>{{ tr('adminConsole') }}</small></div></div>
<header><h1>{{ tr('welcomeAdmin') }}</h1><p>{{ tr('loginLead') }}</p></header>
<form @submit.prevent="login"><div v-if="errorMessage" class="alert error">{{ errorMessage }}</div><label><span>{{ tr('adminUsername') }}</span><input v-model.trim="loginUsername" autocomplete="username" autofocus /></label><label><span>{{ tr('adminPassword') }}</span><input v-model="loginPassword" type="password" autocomplete="current-password" /></label><button class="primary-button wide" :disabled="submitting" type="submit"><span v-if="submitting" class="spinner small"></span>{{ tr('login') }}</button></form>
<button class="language-link" type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button>
<div class="login-actions"><RouterLink to="/" class="home-link"><Icon name="home" :size="15" />{{ tr('backHome') }}</RouterLink><LanguageSwitcher v-model="language" class="language-link" :menu-label="tr('languageMenu')" @change="persistLanguage" /></div>
</section>
</main>
@@ -28,15 +28,16 @@
</aside>
<main class="admin-main">
<header class="admin-topbar"><div><small>{{ tr('adminConsole') }}</small><h1>{{ currentPageTitle }}</h1></div><div><span class="running-dot"></span>{{ tr('gatewayRunning') }}<button type="button" :title="themeLabel" @click="cycleTheme">{{ themeLabel }}</button><button type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button></div></header>
<header class="admin-topbar"><div><small>{{ tr('adminConsole') }}</small><h1>{{ currentPageTitle }}</h1></div><div><span class="running-dot"></span>{{ tr('gatewayRunning') }}<button type="button" class="theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon :name="themeIcon" :size="17" /><span>{{ themeLabel }}</span></button><LanguageSwitcher v-model="language" :menu-label="tr('languageMenu')" @change="persistLanguage" /></div></header>
<div v-if="errorMessage" class="alert error page-alert">{{ errorMessage }}</div>
<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('welcomeText') }}</span><textarea v-model="serverForm.welcomeText" maxlength="500" rows="4"></textarea></label></article>
<article class="settings-card webrtc-card"><div><h3>{{ tr('webrtcSettings') }}</h3><p class="card-help">{{ tr('webrtcLead') }}</p></div><label class="choice toggle-choice"><input v-model="serverForm.webRtcEnabled" type="checkbox" /><span><strong>{{ tr('webrtcEnabled') }}</strong><small>{{ tr('webrtcEnabledLead') }}</small></span></label><small class="field-help">{{ tr('webrtcApplyHint') }}</small></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><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 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>
@@ -48,7 +49,11 @@
<article class="operation-card operation-wide"><header><div><h3>{{ tr('sessions') }}</h3><p>{{ tr('sessionsLead') }}</p></div><strong>{{ operations.sessions.length }}</strong></header><div v-if="operations.sessions.length" class="table-wrap"><table><thead><tr><th>{{ tr('nickname') }}</th><th>{{ tr('sessionState') }}</th><th>{{ tr('age') }}</th><th>{{ tr('memberCount') }}</th><th></th></tr></thead><tbody><tr v-for="session in operations.sessions" :key="session.id"><td><strong>{{ session.nickname }}</strong><small>{{ session.target }}</small></td><td><span class="state-pill">{{ sessionStateLabel(session.state) }}</span></td><td>{{ formatAge(session.ageSeconds) }}</td><td>{{ session.memberCount }}</td><td><button class="danger-button" type="button" :disabled="terminatingSession === session.id" @click="terminateSession(session)">{{ terminatingSession === session.id ? tr('terminating') : tr('endSession') }}</button></td></tr></tbody></table></div><div v-else class="operation-empty"><Icon name="users" :size="22" /><span>{{ tr('sessionEmpty') }}</span></div></article>
<article class="operation-card"><header><div><h3>{{ tr('invites') }}</h3><p>{{ tr('invitesLead') }}</p></div></header><form class="invite-form" @submit.prevent="createInvite"><label><span>{{ tr('inviteChannel') }}</span><input v-model.trim="inviteForm.channel" maxlength="100" :placeholder="tr('inviteChannelPlaceholder')" /></label><div class="invite-form-grid"><label><span>{{ tr('expiresIn') }}</span><input v-model.number="inviteForm.expiresInHours" type="number" min="1" max="720" /></label><label><span>{{ tr('maxUses') }}</span><input v-model.number="inviteForm.maxUses" type="number" min="0" max="10000" /></label></div><small class="field-help">{{ tr('unlimitedUses') }}</small><button class="primary-button" type="submit" :disabled="submitting"><span v-if="submitting" class="spinner small"></span>{{ tr('createInvite') }}</button></form><div v-if="createdInvite" class="generated-invite"><strong>{{ tr('inviteCreated') }}</strong><div class="generated-link"><input :value="createdInvite.link" readonly /><button class="secondary-button" type="button" @click="copyInviteLink">{{ tr('copyLink') }}</button></div><small>{{ tr('inviteSecurity') }}</small></div><div v-if="operations.invites.length" class="invite-list"><div v-for="invite in operations.invites" :key="invite.id" class="invite-row"><div><strong>{{ invite.channel || tr('defaultChannel') }}</strong><small>{{ invite.target }} · {{ formatDate(invite.expiresAt) }}</small></div><div class="invite-row-meta"><span :class="['state-pill', invite.status]">{{ inviteStatusLabel(invite.status) }}</span><span>{{ invite.useCount }}/{{ invite.maxUses || '∞' }}</span><button v-if="invite.status === 'active'" class="text-danger" type="button" @click="revokeInvite(invite)">{{ tr('revoke') }}</button></div></div></div></article>
</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.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-else 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>
<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><small v-if="record.reason">{{ tr('failureReason') }}:{{ connectionFailureText(record.reason) }}</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>
<section v-else class="page-content overview-page">
@@ -57,6 +62,7 @@
<div class="metric-grid"><article><span><Icon name="activity" :size="20" /></span><small>{{ tr('gateway') }}</small><strong>{{ overview.gateway.version || '—' }}</strong><em>{{ formatUptime(overview.gateway.uptimeSeconds) }}</em></article><article><span><Icon name="server" :size="20" /></span><small>{{ tr('teamSpeakTarget') }}</small><strong>{{ overview.teamSpeak.target || '—' }}</strong><em>{{ targetStatusText }}</em></article><article><span><Icon name="users" :size="20" /></span><small>{{ tr('activeSessions') }}</small><strong>{{ overview.sessions.active }} / {{ overview.sessions.limit }}</strong><em>{{ tr('peakSessions', { count: overview.sessions.peak }) }}</em></article></div>
<div class="overview-columns"><article class="overview-card target-health-card"><header><div><h3>{{ tr('targetHealth') }}</h3><p>{{ tr('targetHealthLead') }}</p></div><RouterLink to="/admin/server">{{ tr('manage') }}</RouterLink></header><dl><div><dt>{{ tr('status') }}</dt><dd><i :class="overview.teamSpeak.status"></i>{{ targetStatusText }}</dd></div><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(overview.teamSpeak.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ overview.teamSpeak.latencyMs == null ? '—' : `${overview.teamSpeak.latencyMs} ms` }}</dd></div></dl></article><article class="overview-card recent-events-card"><header><div><h3>{{ tr('recentEvents') }}</h3><p>{{ tr('recentEventsLead') }}</p></div></header><ul class="event-list"><li v-for="event in overview.recentEvents" :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="!overview.recentEvents.length" class="empty-event">{{ tr('noRecentEvents') }}</li></ul></article></div>
</section>
<div v-if="webrtcPortNoticeOpen" class="modal-backdrop" @click.self="webrtcPortNoticeOpen = false"><section class="modal-card" role="dialog" aria-modal="true" :aria-label="tr('webrtcPortNoticeTitle')"><div class="modal-icon"><Icon name="info" :size="21" /></div><h2>{{ tr('webrtcPortNoticeTitle') }}</h2><p>{{ tr('webrtcPortNotice', { range: webrtcPortRangeText }) }}</p><button class="primary-button wide" type="button" @click="webrtcPortNoticeOpen = false">{{ tr('gotIt') }}</button></section></div>
</main>
</div>
</div>
@@ -66,19 +72,23 @@
import { computed, onMounted, reactive, ref, watch } from "vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import Icon from "../components/Icon.vue";
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
import { applyTheme, getStoredTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
type Language = "zh" | "en";
type Language = "zh" | "en" | "de";
type Screen = "login" | "change-password" | "admin";
type AccessMode = "fixed" | "open";
interface ProbeState { ok: boolean; latencyMs?: number; serverName?: string | null; code?: 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 }
const route = useRoute();
const router = useRouter();
const language = ref<Language>((localStorage.getItem("webspeak:language") as Language) || "zh");
const storedLanguage = localStorage.getItem("webspeak:language");
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" ? storedLanguage : "zh");
const themeMode = ref<ThemeMode>(getStoredTheme());
const themeLabel = computed(() => themeMode.value === "dark" ? tr("themeDark") : themeMode.value === "light" ? tr("themeLight") : tr("themeSystem"));
const themeIcon = computed(() => isDarkTheme(themeMode.value) ? "sun" : "moon");
const themeLabel = computed(() => isDarkTheme(themeMode.value) ? tr("switchToLightTheme") : tr("switchToDarkTheme"));
applyTheme(themeMode.value);
const loading = ref(true);
const screen = ref<Screen>("login");
@@ -92,16 +102,18 @@ 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: "", webRtcEnabled: false, 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: "", 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 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 }
const operationsLoading = ref(false);
const terminatingSession = ref("");
const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 });
const createdInvite = ref<{ token: string; link: string } | null>(null);
const operations = reactive({ sessions: [] as AdminSession[], invites: [] as ManagedInvite[], diagnostics: { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 }, logs: { available: false, entries: [] as AdminLog[] }, audit: [] as Array<{ event: string; createdAt: string }> });
const webrtcPortNoticeOpen = ref(false);
const operations = reactive({ sessions: [] as AdminSession[], invites: [] as ManagedInvite[], diagnostics: { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 }, logs: { available: false, entries: [] as AdminLog[], sessions: [] as AdminConnectionRecord[] }, audit: [] as Array<{ event: string; createdAt: string }> });
const copy = {
zh: {
@@ -116,14 +128,18 @@ const copy = {
passwordPlaceholder: "至少 12 个字符",
passwordHint: "建议使用长且唯一的密码。",
confirmPassword: "确认管理员密码",
languageMenu: "语言",
languageSwitch: "English",
themeSystem: "跟随系统",
themeLight: "浅色主题",
themeDark: "深色主题",
switchToLightTheme: "切换到浅色主题",
switchToDarkTheme: "切换到深色主题",
welcomeAdmin: "欢迎回来",
loginLead: "输入管理员账号和密码以管理此 WebSpeak 实例。",
adminPassword: "管理员密码",
login: "登录",
backHome: "返回首页",
overview: "概览",
server: "服务器",
operations: "运维",
@@ -148,21 +164,59 @@ const copy = {
remove: "移除",
testConnection: "测试连接",
testing: "正在测试…",
connectionReady: "连接成功",
connectionFailed: "连接失败",
connectionReady: "连接成功",
connectionFailed: "连接失败",
packetLoss: "丢包率",
networkReachable: "网络可达(未验证密码)",
networkReachableHint: "Ping 成功;管理员测试不会创建额外 TeamSpeak 成员,因此未验证服务器密码。",
failureReason: "原因",
hostNotFoundError: "找不到服务器",
networkUnreachableError: "网络不可达",
networkTimeoutError: "网络请求超时",
serverPasswordRequiredError: "服务器需要密码",
invalidServerPasswordError: "服务器密码错误",
protocolFailureError: "TeamSpeak 协议协商失败",
serverRejectedError: "服务器拒绝连接",
pingUnavailableError: "无法执行网络探测",
accessAndIdentity: "访问与站点信息",
advancedSettings: "高级参数",
advancedSettingsLead: "仅在需要时调整网关的高级传输参数。",
webrtcSettings: "WebRTC 语音",
webrtcLead: "由当前 WebSpeak 网关直接提供低延迟语音传输,无需配置其他服务器。",
webrtcEnabled: "启用 WebRTC",
webrtcEnabledLead: "浏览器和网络支持时使用实时语音通道,否则自动回退到兼容模式。",
webrtcApplyHint: "保存后对新连接生效;已连接用户重新进入语音空间后使用新设置。媒体端口由网关自动管理。",
webrtcPortRange: "WebRTC UDP 端口范围",
webrtcPortRangeLead: "请在 WebSpeak 所在主机的防火墙和安全组放行整个范围。",
webrtcPortStart: "起始端口",
webrtcPortEnd: "结束端口",
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: "欢迎文本",
welcomeText: "公告",
welcomeTextZh: "中文公告",
welcomeTextEn: "英文公告",
runtimeFacts: "运行时信息",
lastTest: "最近测试",
latency: "延迟",
@@ -240,7 +294,16 @@ const copy = {
downloadReport: "下载诊断报告",
exportBackup: "导出数据库备份",
logViewer: "运行日志",
logViewerLead: "最近的网关日志,不包含聊天内容。",
logViewerLead: "最近的网关日志及用户连接记录,不包含聊天内容。",
connectionHistory: "用户连接记录",
connectionHistoryLead: "按用户合并连接、断开与持续时间。",
connectionActive: "连接中",
connectionConnecting: "准备连接",
connectionDisconnected: "已断开",
connectedAt: "接入",
connectionAttemptedAt: "尝试",
disconnectedAt: "断开",
duration: "时长",
logsUnavailable: "未配置日志文件",
noLogs: "暂无可查看日志。",
operationFailed: "运维操作失败,请稍后重试。",
@@ -262,14 +325,18 @@ const copy = {
passwordPlaceholder: "At least 12 characters",
passwordHint: "Use a long, unique password.",
confirmPassword: "Confirm admin password",
languageMenu: "Language",
languageSwitch: "中文",
themeSystem: "System theme",
themeLight: "Light theme",
themeDark: "Dark theme",
switchToLightTheme: "Switch to light theme",
switchToDarkTheme: "Switch to dark theme",
welcomeAdmin: "Welcome back",
loginLead: "Enter the admin account and password to manage this WebSpeak instance.",
adminPassword: "Admin password",
login: "Sign in",
backHome: "Back to home",
overview: "Overview",
server: "Server",
operations: "Operations",
@@ -294,21 +361,59 @@ const copy = {
remove: "Remove",
testConnection: "Test connection",
testing: "Testing…",
connectionReady: "Connection ready",
connectionFailed: "Connection failed",
connectionReady: "Connection ready",
connectionFailed: "Connection failed",
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",
hostNotFoundError: "Server not found",
networkUnreachableError: "Network unreachable",
networkTimeoutError: "Network request timed out",
serverPasswordRequiredError: "Server password required",
invalidServerPasswordError: "Invalid server password",
protocolFailureError: "TeamSpeak protocol negotiation failed",
serverRejectedError: "Server rejected the connection",
pingUnavailableError: "Network probe unavailable",
accessAndIdentity: "Access and site identity",
advancedSettings: "Advanced settings",
advancedSettingsLead: "Adjust gateway transport options only when needed.",
webrtcSettings: "WebRTC audio",
webrtcLead: "Low-latency voice is provided by this WebSpeak gateway; no extra server is required.",
webrtcEnabled: "Enable WebRTC",
webrtcEnabledLead: "Use realtime audio when supported; browsers and networks fall back automatically.",
webrtcApplyHint: "Saved settings apply to new connections; media ports are managed by the gateway.",
webrtcPortRange: "WebRTC UDP port range",
webrtcPortRangeLead: "Allow the complete range through the host firewall and security group.",
webrtcPortStart: "Start port",
webrtcPortEnd: "End port",
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: "Welcome text",
welcomeText: "Announcement",
welcomeTextZh: "Chinese announcement",
welcomeTextEn: "English announcement",
runtimeFacts: "Runtime facts",
lastTest: "Last test",
latency: "Latency",
@@ -386,7 +491,16 @@ const copy = {
downloadReport: "Download diagnostic report",
exportBackup: "Export database backup",
logViewer: "Runtime logs",
logViewerLead: "Recent gateway logs; chat content is not recorded.",
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.",
connectionActive: "Connected",
connectionConnecting: "Connecting",
connectionDisconnected: "Disconnected",
connectedAt: "Connected",
connectionAttemptedAt: "Attempted",
disconnectedAt: "Disconnected",
duration: "Duration",
logsUnavailable: "Log file unavailable",
noLogs: "No logs are available.",
operationFailed: "The operation failed. Try again later.",
@@ -398,11 +512,183 @@ const copy = {
},
} as const;
function tr(key: keyof typeof copy.zh, vars: Record<string, string | number> = {}): string { let value: string = language.value === "zh" ? 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 germanCopy = {
...copy.en,
loading: "Administrationskonsole wird geladen…",
adminConsole: "Administrationskonsole",
changePasswordTitle: "Standardpasswort ändern",
changePasswordLead: "Das Standardpasswort ist nur für die erste Anmeldung gedacht. Lege ein neues Passwort mit mindestens 12 Zeichen fest.",
savePassword: "Neues Passwort speichern",
defaultCredentialNotice: "Standardkonto: admin. Standardpasswort: admin. Das alte Passwort wird nach dem Speichern sofort ungültig.",
adminUsername: "Administratorname",
newPassword: "Neues Administratorpasswort",
passwordPlaceholder: "Mindestens 12 Zeichen",
passwordHint: "Verwende ein langes, eindeutiges Passwort.",
confirmPassword: "Administratorpasswort bestätigen",
languageMenu: "Sprache",
languageSwitch: "中文",
welcomeAdmin: "Willkommen zurück",
loginLead: "Melde dich an, um diese WebSpeak-Instanz zu verwalten.",
adminPassword: "Administratorpasswort",
login: "Anmelden",
backHome: "Zur Startseite",
overview: "Übersicht",
server: "Server",
operations: "Betrieb",
openGuest: "Gastseite öffnen",
logout: "Abmelden",
gatewayRunning: "Gateway läuft",
serverSettings: "Servereinstellungen",
serverSettingsLead: "Standard-TeamSpeak-Ziel, Zugriffsregeln und Inhalte der Gastseite verwalten.",
saving: "Wird gespeichert…",
saveChanges: "Änderungen speichern",
teamSpeakTarget: "Standard-TeamSpeak-Ziel",
serverAddress: "TeamSpeak-Serveradresse",
serverPlaceholder: "z. B. ts.example.com oder 127.0.0.1",
serverPort: "Sprachport",
serverHint: "Serveradresse und Sprachport getrennt eingeben. IPv6-Adressen benötigen keine Klammern.",
serverPassword: "Serverpasswort",
optional: "Optional",
optionalPassword: "Leer lassen, wenn kein Passwort verwendet wird",
passwordConfigured: "Passwort konfiguriert (leer lassen, um es beizubehalten)",
change: "Ändern",
remove: "Entfernen",
testConnection: "Verbindung testen",
testing: "Wird getestet…",
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",
hostNotFoundError: "Server nicht gefunden",
networkUnreachableError: "Netzwerk nicht erreichbar",
networkTimeoutError: "Netzwerk-Zeitüberschreitung",
serverPasswordRequiredError: "Serverpasswort erforderlich",
invalidServerPasswordError: "Falsches Serverpasswort",
protocolFailureError: "Aushandlung des TeamSpeak-Protokolls fehlgeschlagen",
serverRejectedError: "Server hat die Verbindung abgelehnt",
pingUnavailableError: "Netzwerkprüfung nicht verfügbar",
accessAndIdentity: "Zugriff und Website-Informationen",
advancedSettings: "Erweiterte Einstellungen",
advancedSettingsLead: "Erweiterte Gateway-Transportparameter nur bei Bedarf ändern.",
webrtcSettings: "WebRTC-Audio",
webrtcEnabled: "WebRTC aktivieren",
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",
runtimeFacts: "Laufzeitinformationen",
lastTest: "Letzter Test",
latency: "Latenz",
internalPort: "Interner Port",
unknown: "Unbekannt",
gotIt: "Verstanden",
systemStatus: "SYSTEMSTATUS",
everythingRunning: "WebSpeak läuft",
overviewLead: "Der Verwaltungsdienst ist verfügbar. Die Erreichbarkeit von TeamSpeak entspricht dem letzten Verbindungstest.",
running: "Läuft",
gateway: "Gateway",
activeSessions: "Aktive Sitzungen",
targetHealth: "Zielstatus",
status: "Status",
recentEvents: "Letzte Ereignisse",
noRecentEvents: "Keine aktuellen Ereignisse",
reachable: "Erreichbar",
unreachable: "Nicht erreichbar",
notTested: "Nicht getestet",
invalidPassword: "Das Administratorpasswort ist falsch.",
rateLimited: "Zu viele Versuche. Bitte später erneut versuchen.",
requestFailed: "Anfrage fehlgeschlagen. Prüfe die Eingaben und versuche es erneut.",
refresh: "Aktualisieren",
sessions: "Aktive Sitzungen",
sessionEmpty: "Keine aktiven Sitzungen.",
nickname: "Name",
sessionState: "Status",
age: "Dauer",
memberCount: "Mitglieder",
endSession: "Trennen",
terminating: "Wird getrennt…",
sessionTerminated: "Sitzung getrennt.",
invites: "Verwaltete Einladungen",
inviteChannel: "Zielkanal",
expiresIn: "Gültig für (Stunden)",
maxUses: "Maximale Nutzungen",
createInvite: "Einladungslink erstellen",
inviteCreated: "Einladungslink erstellt",
copyLink: "Link kopieren",
copiedLink: "Einladungslink kopiert.",
revoke: "Widerrufen",
inviteRevoked: "Einladungslink widerrufen.",
active: "Aktiv",
expired: "Abgelaufen",
exhausted: "Aufgebraucht",
revoked: "Widerrufen",
diagnostics: "Diagnose",
downloadReport: "Diagnosebericht herunterladen",
exportBackup: "Datenbanksicherung exportieren",
logViewer: "Laufzeitprotokoll",
connectionHistory: "Verbindungsaufzeichnungen",
connectionActive: "Verbunden",
connectionConnecting: "Verbindung wird hergestellt",
connectionDisconnected: "Getrennt",
connectedAt: "Verbunden",
connectionAttemptedAt: "Versuch",
disconnectedAt: "Getrennt",
duration: "Dauer",
logsUnavailable: "Protokolldatei nicht verfügbar",
noLogs: "Keine Protokolle verfügbar.",
operationFailed: "Vorgang fehlgeschlagen. Bitte später erneut versuchen.",
version: "Version",
audit: "Prüfprotokoll",
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 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 ""; if (!testResult.value.ok) return errorText(testResult.value.code); return [testResult.value.serverName, testResult.value.latencyMs == null ? null : `${testResult.value.latencyMs} ms`].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",
HOST_NOT_FOUND: "hostNotFoundError",
UNREACHABLE: "networkUnreachableError",
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}`);
onMounted(loadAdminView);
watch(() => [serverForm.address, serverForm.port, serverForm.serverPassword, serverForm.passwordAction], () => { if (!testing.value && screen.value === "admin") testResult.value = null; });
@@ -413,29 +699,60 @@ 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 }); }
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 : [] }; operations.audit = Array.isArray(audit.events) ? audit.events : []; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { operationsLoading.value = false; } }
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", 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; } }
async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('confirmRevoke'))) return; try { await sendJson(`/api/admin/invites/${encodeURIComponent(invite.id)}/revoke`, "POST", {}); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } }
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 }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
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?.ok) { await loadOverview(); serverForm.lastTestAt = new Date().toISOString(); serverForm.lastTestLatencyMs = testResult.value.latencyMs ?? 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, webRtcEnabled: serverForm.webRtcEnabled }; }
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), 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 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, 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 toggleLanguage() { language.value = language.value === "zh" ? "en" : "zh"; localStorage.setItem("webspeak:language", language.value); }
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" : "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} 分钟` : `Up ${hours}h ${minutes}m`; }
function formatAge(seconds: number) { if (seconds < 60) return language.value === "zh" ? `${seconds} 秒` : `${seconds}s`; const minutes = Math.floor(seconds / 60); if (minutes < 60) return language.value === "zh" ? `${minutes} 分钟` : `${minutes}m`; const hours = Math.floor(minutes / 60); return language.value === "zh" ? `${hours} 小时 ${minutes % 60} 分钟` : `${hours}h ${minutes % 60}m`; }
function sessionStateLabel(state: string) { const names: Record<string, { zh: string; en: string }> = { connecting: { zh: "连接中", en: "Connecting" }, authenticating: { zh: "认证中", en: "Authenticating" }, syncing: { zh: "同步中", en: "Syncing" }, connected: { zh: "已连接", en: "Connected" }, interrupted: { zh: "已中断", en: "Interrupted" }, reconnecting: { zh: "重连中", en: "Reconnecting" }, disconnecting: { zh: "断开中", en: "Disconnecting" }, failed: { zh: "失败", en: "Failed" }, idle: { zh: "空闲", en: "Idle" } }; return names[state]?.[language.value] ?? state; }
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 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 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'); const probe: Record<string, { zh: string; en: string }> = { INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid." }, HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved." }, UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable." }, TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out." }, PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed." }, SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection." }, TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode." } }; return probe[code || ""]?.[language.value] ?? tr('requestFailed'); }
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 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 || ""][language.value]; 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 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",
HOST_NOT_FOUND: "hostNotFoundError",
UNREACHABLE: "networkUnreachableError",
TIMEOUT: "networkTimeoutError",
PROTOCOL_NEGOTIATION_FAILED: "protocolFailureError",
SERVER_REJECTED: "serverRejectedError",
PING_UNAVAILABLE: "pingUnavailableError",
};
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); }
@@ -445,19 +762,22 @@ async function parseResponse(response: Response) { const value = await response.
<style scoped>
.intro-copy h1{font-size:clamp(38px,4.2vw,56px)!important;line-height:1.05!important;letter-spacing:-.055em!important}
.admin-topbar .theme-toggle{display:inline-flex;align-items:center;gap:6px}
:global(*){box-sizing:border-box}:global(body){margin:0;font-family:Inter,"Segoe UI","PingFang SC",sans-serif;color:#20302c;background:#f4f8f6}.admin-root{min-height:100dvh}.auth-layout{display:grid;min-height:100dvh;grid-template-columns:minmax(360px,.82fr) minmax(520px,1.18fr)}.auth-intro{display:flex;flex-direction:column;padding:48px clamp(38px,6vw,92px);color:#e8fffa;background:radial-gradient(circle at 20% 0,rgba(90,211,191,.28),transparent 32rem),#063f3b}.admin-brand{display:flex;align-items:center;gap:12px}.admin-brand>span{display:grid;place-items:center;width:42px;height:42px;color:#fff;background:#07877d;border-radius:12px;box-shadow:0 8px 22px rgba(0,0,0,.15)}.admin-brand strong,.admin-brand small{display:block}.admin-brand strong{font-size:20px;letter-spacing:-.04em}.admin-brand small{margin-top:3px;color:#9bc9c2;font-size:11px}.intro-copy{margin:auto 0 48px}.intro-copy i{color:#75e3d2;font-size:12px;font-style:normal;font-weight:800;letter-spacing:.12em}.intro-copy h1{max-width:540px;margin:16px 0;font-size:clamp(40px,5vw,66px);line-height:1.03;letter-spacing:-.065em}.intro-copy p{max-width:530px;color:#a9d0ca;font-size:16px;line-height:1.75}.step-list{display:grid;gap:10px}.step-list button{display:flex;align-items:center;gap:13px;width:100%;padding:13px;color:#89bbb4;text-align:left;background:transparent;border:1px solid transparent;border-radius:12px}.step-list button.active{color:#fff;background:rgba(255,255,255,.08);border-color:rgba(255,255,255,.1)}.step-list button.done{color:#8ee4d7}.step-list button>span{display:grid;place-items:center;width:28px;height:28px;flex:none;border:1px solid currentColor;border-radius:50%;font-size:12px;font-weight:800}.step-list strong,.step-list small{display:block}.step-list strong{font-size:13px}.step-list small{margin-top:3px;font-size:10px;opacity:.75}.auth-panel{position:relative;display:grid;place-items:center;padding:80px 40px;background:radial-gradient(circle at 80% 10%,rgba(99,205,188,.15),transparent 25rem),#f5f9f7}.panel-tools{position:absolute;top:28px;right:34px}.panel-tools button,.language-link,.admin-topbar button{color:#08766e;background:#e4f3ef;border:1px solid #cae7e0;border-radius:8px;padding:8px 12px;font-size:11px;font-weight:700;cursor:pointer}.setup-card,.login-card{width:min(560px,100%);padding:36px;background:#fff;border:1px solid #dfeae6;border-radius:20px;box-shadow:0 20px 55px rgba(27,69,61,.09)}.setup-card header small{color:#07877d;font-size:11px;font-weight:800;letter-spacing:.08em}.setup-card header h2,.login-card h1{margin:10px 0 7px;font-size:29px;letter-spacing:-.045em}.setup-card header p,.login-card header p{margin:0;color:#71817c;font-size:13px;line-height:1.6}.form-stack,.login-card form{display:grid;gap:17px;margin-top:27px}label>span,fieldset legend{display:block;margin-bottom:7px;color:#40514c;font-size:12px;font-weight:700}label em{color:#91a09c;font-size:10px;font-style:normal;font-weight:500}label small{display:block;margin-top:6px;color:#899792;font-size:10px;line-height:1.5}input,textarea{width:100%;padding:11px 12px;color:#22332f;background:#fbfdfc;border:1px solid #dbe7e3;border-radius:9px;font:inherit;font-size:13px;outline:none}input{height:43px}input:focus,textarea:focus{border-color:#54bdb2;box-shadow:0 0 0 3px rgba(84,189,178,.13)}textarea{resize:vertical}.strength{height:4px;overflow:hidden;background:#e7eeeb;border-radius:4px}.strength i{display:block;height:100%;background:linear-gradient(90deg,#e7a452,#50c5a2);transition:.2s}fieldset{display:grid;gap:9px;margin:0;padding:0;border:0}.choice{display:flex;align-items:flex-start;gap:10px;padding:13px;border:1px solid #dfe9e6;border-radius:10px;cursor:pointer}.choice:has(input:checked){border-color:#62bfb5;background:#eff8f6}.choice input{width:16px;height:16px;flex:none;margin:2px 0}.choice strong,.choice small{display:block}.choice strong{font-size:12px}.choice small{margin-top:4px;color:#7b8985;font-size:10px;line-height:1.45}.setup-card footer{display:flex;align-items:center;justify-content:space-between;margin-top:28px;padding-top:20px;border-top:1px solid #edf1ef}.primary-button,.secondary-button,.text-button{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:42px;padding:0 18px;border:0;border-radius:9px;font-size:12px;font-weight:800;cursor:pointer}.primary-button{color:#fff;background:#087d74}.primary-button:hover{background:#056b63}.primary-button:disabled,.secondary-button:disabled{opacity:.55;cursor:not-allowed}.secondary-button{color:#08776e;background:#eaf6f3;border:1px solid #cfe9e3}.text-button{color:#687a74;background:transparent}.wide{width:100%}.spinner{display:inline-block;width:22px;height:22px;border:2px solid #cde6df;border-top-color:#087d74;border-radius:50%;animation:spin .7s linear infinite}.spinner.small{width:15px;height:15px;border-color:rgba(255,255,255,.35);border-top-color:currentColor}@keyframes spin{to{transform:rotate(360deg)}}.alert{padding:12px 14px;border-radius:9px;font-size:12px;linLine truncated
@media(max-width:850px){.auth-layout{display:block}.auth-intro{min-height:auto;padding:28px 24px}.intro-copy{margin:55px 0 35px}.step-list{display:none}.auth-panel{padding:35px 18px 60px}.panel-tools{top:18px;right:18px}.admin-shell{display:block}.admin-sidebar{position:static;width:100%;height:auto;flex-direction:row;align-items:center;padding:12px 16px}.admin-sidebar .admin-brand{padding:0}.admin-sidebar .admin-brand small{display:none}.admin-sidebar nav{display:flex;margin-left:auto}.admin-sidebar nav a{font-size:0}.admin-sidebar nav a .ui-icon{width:20px;height:20px}.sidebar-bottom{display:flex;margin:0 0 0 8px;padding:0;border:0}.sidebar-bottom a{display:none}.sidebar-bottom button{font-size:0}.settings-grid,.overview-columns{grid-template-columns:1fr}.readonly-card dl{grid-template-columns:1fr 1fr}.admin-topbar{padding:0 18px}.page-content{width:min(100% - 28px,700px);padding-top:24px}.metric-grid{grid-template-columns:1fr}.hero-status{align-items:flex-start;gap:20px}.hero-status p{max-width:75%}}
@media(max-width:520px){.setup-card,.login-card{padding:25px 20px;border-radius:15px}.setup-card header h2{font-size:24px}.admin-topbar>div:last-child{font-size:0}.page-heading{gap:15px}.page-heading .primary-button{padding-inline:12px}.settings-card,.readonly-card,.overview-card{padding:18px}.readonly-card dl,.overview-card dl{grid-template-columns:1fr}.password-row{grid-template-columns:1fr}.password-actions{padding:0}.hero-status{padding:23px}.status-badge{display:none}}
.security-note{margin:18px 0 0;color:#879590;font-size:11px;line-height:1.5}
:global(:root[data-theme="dark"]) .admin-root, :global(:root[data-theme="dark"]) .login-page, :global(:root[data-theme="dark"]) .auth-panel { color: #e8f3f0; background: #101918; }
:global(:root[data-theme="dark"]) .admin-topbar, :global(:root[data-theme="dark"]) .setup-card, :global(:root[data-theme="dark"]) .login-card, :global(:root[data-theme="dark"]) .settings-card, :global(:root[data-theme="dark"]) .readonly-card, :global(:root[data-theme="dark"]) .overview-card, :global(:root[data-theme="dark"]) input, :global(:root[data-theme="dark"]) textarea { color: #e8f3f0; background: #172321; border-color: #30413d; }
:global(:root[data-theme="dark"]) .admin-topbar, :global(:root[data-theme="dark"]) .settings-card, :global(:root[data-theme="dark"]) .readonly-card, :global(:root[data-theme="dark"]) .overview-card { border-color: #30413d; }
:global(:root[data-theme="dark"]) .admin-topbar h1, :global(:root[data-theme="dark"]) .page-heading h2, :global(:root[data-theme="dark"]) .settings-card h3, :global(:root[data-theme="dark"]) .readonly-card h3, :global(:root[data-theme="dark"]) .overview-card h3, :global(:root[data-theme="dark"]) .login-card h1 { color: #e8f3f0; }
:global(:root[data-theme="dark"]) .page-heading p, :global(:root[data-theme="dark"]) .admin-topbar small, :global(:root[data-theme="dark"]) label > span, :global(:root[data-theme="dark"]) .page-heading p { color: #9bb0aa; }
:global(:root[data-theme="dark"]) .metric-grid article, :global(:root[data-theme="dark"]) .readonly-card dl div, :global(:root[data-theme="dark"]) .overview-card dl div, :global(:root[data-theme="dark"]) .event-list li { background: #202f2c; border-color: #30413d; }
@media (prefers-color-scheme: dark) { :global(:root[data-theme="system"]) .admin-root, :global(:root[data-theme="system"]) .login-page, :global(:root[data-theme="system"]) .auth-panel { color: #e8f3f0; background: #101918; } :global(:root[data-theme="system"]) .admin-topbar, :global(:root[data-theme="system"]) .setup-card, :global(:root[data-theme="system"]) .login-card, :global(:root[data-theme="system"]) .settings-card, :global(:root[data-theme="system"]) .readonly-card, :global(:root[data-theme="system"]) .overview-card { background: #172321; border-color: #30413d; } }
:global(html[data-theme="dark"] .admin-root), :global(html[data-theme="dark"] .login-page), :global(html[data-theme="dark"] .auth-panel) { color: #e8f3f0; background: #101918; }
:global(html[data-theme="dark"] .admin-topbar), :global(html[data-theme="dark"] .setup-card), :global(html[data-theme="dark"] .login-card), :global(html[data-theme="dark"] .settings-card), :global(html[data-theme="dark"] .readonly-card), :global(html[data-theme="dark"] .overview-card), :global(html[data-theme="dark"] input), :global(html[data-theme="dark"] textarea) { color: #e8f3f0; background: #172321; border-color: #30413d; }
:global(html[data-theme="dark"] .admin-topbar), :global(html[data-theme="dark"] .settings-card), :global(html[data-theme="dark"] .readonly-card), :global(html[data-theme="dark"] .overview-card) { border-color: #30413d; }
:global(html[data-theme="dark"] .admin-topbar h1), :global(html[data-theme="dark"] .page-heading h2), :global(html[data-theme="dark"] .settings-card h3), :global(html[data-theme="dark"] .readonly-card h3), :global(html[data-theme="dark"] .overview-card h3), :global(html[data-theme="dark"] .login-card h1) { color: #e8f3f0; }
:global(html[data-theme="dark"] .page-heading p), :global(html[data-theme="dark"] .admin-topbar small), :global(html[data-theme="dark"] label > span) { color: #9bb0aa; }
:global(html[data-theme="dark"] .metric-grid article), :global(html[data-theme="dark"] .readonly-card dl div), :global(html[data-theme="dark"] .overview-card dl div), :global(html[data-theme="dark"] .event-list li) { background: #202f2c; border-color: #30413d; }
:global(html[data-theme="dark"] .admin-topbar button), :global(html[data-theme="dark"] .admin-topbar .language-select), :global(html[data-theme="dark"] .language-link), :global(html[data-theme="dark"] .home-link) { color: #a9d9d1; background: #203531; border-color: #38564f; }
@media (prefers-color-scheme: dark) { :global(html[data-theme="system"] .admin-root), :global(html[data-theme="system"] .login-page), :global(html[data-theme="system"] .auth-panel) { color: #e8f3f0; background: #101918; } :global(html[data-theme="system"] .admin-topbar), :global(html[data-theme="system"] .setup-card), :global(html[data-theme="system"] .login-card), :global(html[data-theme="system"] .settings-card), :global(html[data-theme="system"] .readonly-card), :global(html[data-theme="system"] .overview-card) { background: #172321; border-color: #30413d; } }
.operations-grid{display:grid;grid-template-columns:minmax(0,1.12fr) minmax(340px,.88fr);gap:18px}.system-notice{display:flex;align-items:center;gap:8px;margin-bottom:18px}.operation-card{min-width:0;padding:22px;background:#fff;border:1px solid #dfe8e5;border-radius:14px}.operation-card header{display:flex;align-items:flex-start;justify-content:space-between;gap:15px}.operation-card h3{margin:0;font-size:15px}.operation-card header p{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}.operation-card header>strong{color:#087d74;font-size:22px}.table-wrap{margin:18px -22px -22px;overflow:auto;border-top:1px solid #edf1ef}.table-wrap table{width:100%;min-width:600px;border-collapse:collapse;text-align:left}.table-wrap th,.table-wrap td{padding:12px 14px;border-bottom:1px solid #edf1ef;font-size:11px;white-space:nowrap}.table-wrap th{color:#83928d;font-size:10px;font-weight:700}.table-wrap td strong,.table-wrap td small{display:block}.table-wrap td small{margin-top:3px;color:#8a9994;font-size:9px}.state-pill{display:inline-flex;padding:4px 7px;color:#236c63;background:#e5f5f1;border-radius:99px;font-size:10px;font-weight:700}.state-pill.expired,.state-pill.exhausted,.state-pill.revoked{color:#8b6259;background:#f8ece9}.danger-button,.text-danger{color:#a34f48;background:#fff0ee;border:1px solid #f1d2cd;border-radius:7px;font-size:10px;font-weight:700;cursor:pointer}.danger-button{padding:7px 9px}.text-danger{padding:4px 7px;border:0}.danger-button:disabled{opacity:.55;cursor:wait}.operation-empty{display:grid;place-items:center;gap:8px;min-height:130px;color:#8b9994;text-align:center;font-size:11px}.operation-empty .ui-icon{color:#72afa7}.invite-form{display:grid;gap:14px;margin-top:18px}.invite-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}.field-help{margin-top:-8px;color:#899792;font-size:10px}.generated-invite{display:grid;gap:8px;margin-top:17px;padding:12px;color:#29685f;background:#eaf7f3;border-radius:9px}.generated-invite strong{font-size:11px}.generated-invite small{color:#648780;font-size:9px;line-height:1.45}.generated-link{display:flex;gap:6px}.generated-link input{height:36px;min-width:0;padding:8px;font-size:10px}.generated-link .secondary-button{min-height:36px;padding-inline:9px;white-space:nowrap;font-size:10px}.invite-list{display:grid;gap:9px;margin-top:18px;padding-top:15px;border-top:1px solid #edf1ef}.invite-row{display:flex;align-items:center;justify-content:space-between;gap:9px;padding:10px;background:#f6f9f8;border-radius:9px}.invite-row>div:first-child{min-width:0}.invite-row strong,.invite-row small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.invite-row strong{font-size:11px}.invite-row small{max-width:260px;margin-top:4px;color:#86958f;font-size:9px}.invite-row-meta{display:flex;align-items:center;gap:7px;flex:none;color:#70827b;font-size:9px}.lower-operations{margin-top:18px}.text-link{color:#087d74;font-size:10px;font-weight:700;text-decoration:none;white-space:nowrap}.diagnostic-list{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin:18px 0}.diagnostic-list div{padding:10px;background:#f6f9f8;border-radius:8px}.diagnostic-list dt{color:#8a9893;font-size:9px}.diagnostic-list dd{margin:4px 0 0;overflow:hidden;font-size:11px;font-weight:700;text-overflow:ellipsis;white-space:nowrap}.logs-card{display:flex;min-height:250px;flex-direction:column}.audit-card{min-height:250px}.muted-label{color:#9aa6a2;font-size:9px}.log-list{display:grid;gap:7px;max-height:280px;margin-top:16px;overflow:auto}.log-row{display:flex;align-items:flex-start;gap:8px;padding:8px;background:#f6f9f8;border-radius:7px}.log-row>div{min-width:0}.log-row strong,.log-row small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.log-row strong{font-size:10px}.log-row small{margin-top:4px;color:#899792;font-size:8px}.log-level{flex:none;padding:3px 5px;border-radius:4px;color:#356c62;background:#e3f3ef;font-size:8px;font-weight:800}.log-level.warn{color:#8b6a3e;background:#fbf1dc}.log-level.error,.log-level.fatal{color:#a34f48;background:#fff0ee}
:global(:root[data-theme="dark"]) .operation-card,:global(:root[data-theme="dark"]) .invite-row,:global(:root[data-theme="dark"]) .diagnostic-list div,:global(:root[data-theme="dark"]) .log-row{color:#e8f3f0;background:#202f2c;border-color:#30413d}:global(:root[data-theme="dark"]) .table-wrap{border-color:#30413d}:global(:root[data-theme="dark"]) .table-wrap th,:global(:root[data-theme="dark"]) .table-wrap td,:global(:root[data-theme="dark"]) .invite-list{border-color:#30413d}:global(:root[data-theme="dark"]) .operation-card header p,:global(:root[data-theme="dark"]) .table-wrap th,:global(:root[data-theme="dark"]) .table-wrap td small,:global(:root[data-theme="dark"]) .invite-row small{color:#9bb0aa}
:global(html[data-theme="dark"] .connection-row),:global(html[data-theme="dark"] .connection-history-heading){color:#e8f3f0;background:#202f2c;border-color:#30413d}
:global(html[data-theme="dark"] .operation-card),:global(html[data-theme="dark"] .invite-row),:global(html[data-theme="dark"] .diagnostic-list div),:global(html[data-theme="dark"] .log-row){color:#e8f3f0;background:#202f2c;border-color:#30413d}:global(html[data-theme="dark"] .table-wrap){border-color:#30413d}:global(html[data-theme="dark"] .table-wrap th),:global(html[data-theme="dark"] .table-wrap td),:global(html[data-theme="dark"] .invite-list){border-color:#30413d}:global(html[data-theme="dark"] .operation-card header p),:global(html[data-theme="dark"] .table-wrap th),:global(html[data-theme="dark"] .table-wrap td small),:global(html[data-theme="dark"] .invite-row small){color:#9bb0aa}
@media(max-width:850px){.operations-grid{grid-template-columns:1fr}.operation-wide{overflow:hidden}}
@media(max-width:520px){.operation-card{padding:18px}.table-wrap{margin-left:-18px;margin-right:-18px;margin-bottom:-18px}.invite-form-grid,.diagnostic-list{grid-template-columns:1fr}.generated-link{display:grid}.invite-row{align-items:flex-start;flex-direction:column}.invite-row-meta{width:100%;justify-content:flex-end}.lower-operations{margin-top:14px}}
.target-fields{display:grid;grid-template-columns:minmax(0,1fr) 132px;gap:12px}
@@ -564,4 +884,126 @@ async function parseResponse(response: Response) { const value = await response.
.operations-page .lower-operations{grid-auto-rows:190px}
.operations-page .lower-operations{flex:1 1 0}
}
.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}
.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}
.port-fields-heading small{margin-top:4px;color:#899792;font-size:10px;line-height:1.45}
.port-inputs{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.port-inputs label>span{font-size:10px}
.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"] .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}}
/* 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
three nested scrollbars. The section itself is the only fallback scroll
surface when a small viewport cannot show the complete form. */
.server-page{overflow-x:hidden;overflow-y:auto}
.server-page .settings-grid{flex:0 0 auto;min-height:auto;align-items:start;overflow:visible;grid-auto-rows:auto}
.server-page .settings-card{height:auto;min-height:0;overflow:visible;padding:16px;gap:12px}
.server-page .settings-card input{height:40px}
.server-page .settings-card .choice{padding:10px;gap:8px}
.server-page .settings-card .choice small{margin-top:3px}
.server-page .webrtc-port-fields{padding:12px;gap:8px}
.server-page .readonly-card{margin-top:12px;padding:14px 16px}
.server-page .readonly-card dl{gap:8px;margin-top:10px}
@media(max-width:850px){
.server-page .settings-grid{overflow:visible;grid-auto-rows:auto}
.server-page .settings-card{overflow:visible}
}
/* Mobile admin pages should read like one continuous form. Keep the desktop
viewport shell untouched, but let the document grow vertically on narrow
screens instead of trapping content inside cards and nested panes. */
@media(max-width:850px){
:global(html),:global(body),:global(#app){height:auto;min-height:100%;max-height:none;overflow:auto}
.admin-root{height:auto;min-height:100dvh;overflow:visible}
.admin-shell{height:auto;min-height:100dvh;overflow:visible}
.admin-main{height:auto;min-height:0;overflow:visible}
.page-content{display:block;height:auto;min-height:0;overflow:visible}
.login-page{height:auto;min-height:100dvh;overflow:visible}
.login-card{max-height:none;overflow:visible}
.overview-page{height:auto;min-height:0;overflow:visible}
.overview-page .overview-columns{grid-template-rows:auto;overflow:visible}
.overview-page .target-health-card,.overview-page .recent-events-card{height:auto;min-height:0;overflow:visible}
.overview-page .recent-events-card .event-list{max-height:none;overflow:visible}
.server-page{height:auto;min-height:0;overflow:visible}
.server-page .settings-grid{height:auto;overflow:visible}
.operations-page{height:auto;min-height:0;overflow:visible}
.operations-page .operations-primary,.operations-page .lower-operations{height:auto;min-height:0;overflow:visible;grid-auto-rows:auto;flex:none}
.operations-page .operation-card{height:auto;min-height:0;overflow:visible}
.operations-primary .table-wrap{max-height:none;overflow-x:auto;overflow-y:visible}
.operations-primary .invite-list{max-height:none;overflow:visible}
.logs-card .log-list,.audit-card .event-list{max-height:none;overflow:visible;flex:none}
.logs-card .log-list{width:100%;min-width:0}
.logs-card .log-row{min-width:0;max-width:100%;overflow:hidden}
.logs-card .log-row>div{width:0;max-width:100%;flex:1 1 auto;min-width:0;overflow:hidden}
.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word}
}
/* Long log messages should wrap on every screen size instead of widening the
log card or introducing page-level horizontal scrolling. */
.logs-card .log-row{min-width:0}
.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word}
.connection-list{display:grid;gap:7px;max-height:180px;margin-top:12px;overflow-y:auto}
.connection-history-heading{display:grid;gap:3px;padding:0 0 6px;border-bottom:1px solid #edf1ef}
.connection-history-heading strong{font-size:10px}
.connection-history-heading small{color:#899792;font-size:8px}
.connection-row{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;padding:8px;background:#f6f9f8;border-radius:7px}
.connection-person,.connection-detail{min-width:0}
.connection-person{flex:1 1 auto}
.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-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}
.connection-status.disconnected{color:#687a74;background:#e9efed}
.connection-status.failed{color:#a34f48;background:#fff0ee}
.connection-status.connecting{color:#8b6a3e;background:#fbf1dc}
@media(max-width:520px){
.connection-row{display:grid;gap:7px}
.connection-detail{justify-items:start;text-align:left}
}
.login-actions{display:flex;align-items:center;justify-content:center;gap:12px;margin-top:20px;flex-wrap:wrap}
.login-actions .language-link{margin-top:0}
.home-link{display:inline-flex;align-items:center;gap:6px;padding:8px 12px;color:#08766e;background:#e4f3ef;border:1px solid #cae7e0;border-radius:8px;font-size:11px;font-weight:700;text-decoration:none}
.home-link:hover{background:#d8eee9}
.language-link{margin-top:20px!important;padding:0!important;background:transparent!important;border:0!important;border-radius:0!important}
.login-actions .language-link{margin-top:0!important}
</style>
+11 -8
View File
@@ -2,7 +2,7 @@
<div class="demo-page">
<header class="demo-header">
<div class="demo-brand"><span><Icon name="waveform" :size="21" /></span><div><strong>WebSpeak</strong><small>{{ copy.browserClient }}</small></div></div>
<div class="demo-tools"><span class="demo-badge">{{ copy.demoBadge }}</span><button type="button" @click="toggleLanguage">{{ copy.languageSwitch }}</button><a href="/">{{ copy.back }}</a></div>
<div class="demo-tools"><span class="demo-badge">{{ copy.demoBadge }}</span><LanguageSwitcher v-model="language" :menu-label="copy.languageMenu" @change="persistLanguage" /><a href="/">{{ copy.back }}</a></div>
</header>
<div v-if="reconnecting" class="demo-reconnect" role="status"><Icon name="refresh" :size="17" /><span>{{ copy.reconnecting }}</span><button type="button" @click="reconnecting = false">{{ copy.restore }}</button></div>
@@ -34,12 +34,14 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import Icon from "../components/Icon.vue";
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
type Language = "zh" | "en";
type Language = "zh" | "en" | "de";
interface DemoMessage { id: number; author: string; time: string; text: string; zhText?: string; enText?: string; mine: boolean }
type Tab = "channel" | "server";
const language = ref<Language>(localStorage.getItem("webspeak:language") === "en" ? "en" : "zh");
const copy = computed(() => language.value === "zh" ? zh : en);
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 selectedChannelId = ref("quiet");
const activeTab = ref<Tab>("channel");
const speakingId = ref("illusia");
@@ -56,13 +58,14 @@ const messages = ref<DemoMessage[]>([
{ id: 1, author: "illusia", time: "10:24", text: "", zhText: "大家好,欢迎来到 WebSpeak。", enText: "Hello everyone, welcome to WebSpeak.", mine: true },
{ id: 2, author: "msicbot", time: "10:25", text: "", zhText: "语音和文字频道都已同步。", enText: "Voice and text channels are in sync.", mine: false },
]);
const zh = { 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 = { 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 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 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 : []);
function toggleLanguage() { language.value = language.value === "zh" ? "en" : "zh"; localStorage.setItem("webspeak:language", language.value); }
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; }
@@ -90,5 +93,5 @@ function avatarStyle(name: string) { let hash = 0; for (const char of name) hash
:global(:root[data-theme="dark"]) .demo-message p, :global(:root[data-theme="dark"]) .demo-composer, :global(:root[data-theme="dark"]) .demo-actions-panel > button { background: #202f2c; color: #d7e7e3; }
:global(:root[data-theme="dark"]) .demo-chat-head, :global(:root[data-theme="dark"]) .demo-user { border-color: #30413d; }
@media (prefers-color-scheme: dark) { :global(:root[data-theme="system"]) .demo-channel-panel, :global(:root[data-theme="system"]) .demo-actions-panel, :global(:root[data-theme="system"]) .demo-main, :global(:root[data-theme="system"]) .demo-voice-card { background: #172321; border-color: #30413d; } }
:global(button:focus-visible), :global(a:focus-visible), :global(input:focus-visible) { outline: 3px solid #69d2c7; outline-offset: 2px; }
:global(button:focus-visible), :global(a:focus-visible), :global(input:focus-visible), :global(select:focus-visible) { outline: 3px solid #69d2c7; outline-offset: 2px; }
</style>
File diff suppressed because it is too large. Load diff
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB