Compare commits

...
22 Commits
Author SHA1 Message Date
illusia e79ad66e1f docs: document WebRTC public UDP setup 2026-09-03 11:59:03 +08:00
illusia 522fa8f409 fix: remove obsolete WebRTC error labels 2026-09-03 11:02:42 +08:00
illusia c7def28a8f feat: make WebRTC media service self-contained 2026-09-03 10:56:39 +08:00
illusia d6c8ccb73f fix(ui): remove real IP from WebRTC placeholder 2026-09-03 08:01:08 +08:00
illusia ab5851935c merge: admin-managed WebRTC settings 2026-09-03 07:52:21 +08:00
illusia 5c3d1b7e5d feat(admin): manage WebRTC settings from console 2026-09-03 07:52:13 +08:00
illusia ecff06e9a1 docs: record SDK migration in v0.1.3 2026-09-03 07:32:11 +08:00
illusia 9c3f09b55b merge: release v0.1.3 2026-09-03 07:28:29 +08:00
illusia b42c455e7f release: prepare v0.1.3 2026-09-03 07:28:14 +08:00
illusia 40ea30b9e2 fix(audio): cleanly fall back from WebRTC 2026-09-03 01:29:34 +08:00
illusia a4cf5b5359 fix(audio): use OpusEncoder decoder API 2026-09-03 01:23:34 +08:00
illusia 1d41d5a3e7 fix(audio): honor negotiated WebRTC Opus payload 2026-09-03 01:17:01 +08:00
illusia 46b190a913 fix(audio): avoid duplicate WebRTC playback 2026-09-03 01:02:18 +08:00
illusia 8abd2d6228 feat(audio): add experimental WebRTC transport 2026-09-03 00:47:51 +08:00
illusia 7ff6836a7e fix(audio): tighten gateway voice backpressure 2026-09-03 00:23:16 +08:00
illusia a6187c18af chore(audio): attribute egress frames by client 2026-09-03 00:19:45 +08:00
illusia 8ab2fbe8ea fix(audio): move capture framing to audio worklet 2026-09-03 00:13:48 +08:00
illusia 3e7674c94f chore(audio): capture sampled flow timing 2026-09-03 00:04:17 +08:00
illusia 30c0d09a33 chore(audio): include session flow counters in teardown 2026-09-03 00:01:50 +08:00
illusia d9904fa154 fix(audio): bound realtime voice buffering 2026-09-02 23:56:24 +08:00
illusia afbbd1e2d4 refactor: migrate to maintained TeamSpeak SDK 2026-09-02 23:27:32 +08:00
illusia adca8cc1db docs(deploy): standardize published Docker image flow 2026-09-02 16:26:20 +08:00
28 changed files with 1646 additions and 337 deletions

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ on:
version:
description: Release version without the v prefix
required: true
default: 0.1.1
default: 0.1.3
type: string
permissions:
+26
View File
@@ -2,6 +2,30 @@
All notable changes to WebSpeak are documented here. Versions follow SemVer.
## [0.1.3] — 2026-09-03
### Added
- Optional WebRTC audio transport for deployments that need lower and more stable realtime voice latency.
- A self-contained WebRTC media service controlled by one administrator switch; the gateway derives the media host from the current WebSpeak address and owns a fixed UDP range.
- Migrated the TeamSpeak integration to the maintained `EchoSixHIYA/teamspeak-js` fork, including live directory snapshots and member/channel synchronization.
### Changed
- WebRTC audio uses negotiated Opus parameters and a bounded newest-frame mixer instead of allowing stale audio to accumulate.
- The browser keeps the WebSocket path available for signaling, control, and compatibility fallback; Docker Compose publishes the built-in `40000–40099/UDP` media range alongside the web port.
### Fixed
- Prevented duplicate playback when WebRTC and the WebSocket audio path overlap during negotiation or fallback.
- Made WebRTC teardown and fallback explicit so a failed negotiation does not leave a server-side media session behind.
- Corrected native Opus decoder usage and cleaned up negotiated payload handling for TeamSpeak-to-browser audio.
### Verification
- After allowing inbound `40000–40099/UDP` on the public WebSpeak host, two browser sessions were tested against the same TeamSpeak target with WebRTC enabled: audio frames flowed in both directions, packet drops remained at `0`, ingress frame gaps peaked at about `27 ms`, and egress gaps peaked at about `81–83 ms`.
- The measured WebRTC path stayed below the previous WebSocket jitter peaks of about `268–376 ms` in the same browser test setup; these figures describe the observed test path, not a universal latency guarantee.
## [0.1.2] — 2026-09-02
### Added
@@ -20,6 +44,8 @@ All notable changes to WebSpeak are documented here. Versions follow SemVer.
- Replaced the visually off-center settings glyph and normalized icon alignment for settings-related controls across the client.
- Fixed narrow-screen exit and microphone controls so their text-collapse rules apply correctly.
- Bounded browser and gateway voice buffering, reset stale browser playback queues, and exposed low-overhead in-memory audio counters for diagnosing jitter without per-frame log writes.
- Moved microphone frame assembly to an `AudioWorklet` with a compatibility fallback to `ScriptProcessorNode`; both paths emit fixed 960-sample frames.
## [0.1.1] — 2026-09-02
+8 -5
View File
@@ -9,8 +9,8 @@ Browser (PCM capture) → WebSocket → Node.js server (PCM→Opus) → TeamSpea
Browser (playback) ← WebSocket ← Node.js server (Opus relay) ← TeamSpeak server
```
- Each browser user = one independent TS3 virtual client via `@honeybbq/teamspeak-client`
- Frontend captures PCM via `ScriptProcessorNode`, sends as Int16 binary over WebSocket
- Each browser user = one independent TS3 virtual client via `@echosixhiya/teamspeak-client`
- Frontend captures PCM in an `AudioWorklet` when available (with a `ScriptProcessorNode` fallback), assembles fixed 960-sample frames, and sends Int16 binary over WebSocket
- Server encodes PCM → Opus using `@discordjs/opus` (CJS, loaded via `createRequire`)
- Server sends Opus to TS via `client.sendVoice(data, codec=4)`
- Incoming TS voice → Opus frames → binary WebSocket → browser `AudioDecoder` → playback
@@ -30,16 +30,19 @@ src/
server/
server.ts # Express + HTTPS + WS setup
voice-bridge.ts # /ws/voice endpoint, PCM→Opus encoding, WebQuery API
ts-client.ts # TS3Client wrapper around @honeybbq/teamspeak-client
ts-client.ts # TS3Client wrapper around @echosixhiya/teamspeak-client
```
## Key Technical Details
### Audio Pipeline
1. Browser mic → `getUserMedia` (48kHz mono) → `ScriptProcessorNode` (1024 samples)
1. Browser mic → `getUserMedia` (48kHz mono) → `AudioWorklet` frame assembler (960 samples); older browsers use `ScriptProcessorNode` (1024-sample chunks) before the same assembler
2. Float32 → Int16 conversion → PTT/VOX gate → WebSocket binary send
3. Server accumulates PCM → every 1920 bytes (960 samples, 20ms) → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
3. Server encodes each 1920-byte (960-sample, 20ms) PCM frame → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
4. Incoming: TS → `voiceData` event → 3-byte header `[codec][clientId BE]` → WS binary → browser `AudioDecoder` → playback
5. Browser uplink is capped at 10 PCM frames (about 200ms); gateway egress applies a bounded WebSocket byte guard; browser playback resets stale decoder/source queues above 120ms.
Audio flow counters are kept in memory and exposed in admin session summaries. Do not add per-frame persistent logging to the voice path.
### CJS Interop
`@discordjs/opus` is CommonJS, loaded via:
+2 -4
View File
@@ -2,13 +2,11 @@ FROM node:22-bookworm-slim AS build
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends python3 make g++ \
&& apt-get install -y --no-install-recommends git python3 make g++ \
&& rm -rf /var/lib/apt/lists/*
COPY package.json package-lock.json ./
COPY web/package.json web/package-lock.json ./web/
# The root postinstall hook patches the TeamSpeak SDK during npm ci.
COPY scripts ./scripts
RUN npm ci
RUN npm --prefix web ci
@@ -37,7 +35,7 @@ COPY --from=build --chown=node:node /app/web/dist ./web/dist
USER node
VOLUME ["/data"]
EXPOSE 3040
EXPOSE 3040/tcp 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))"
+89 -45
View File
@@ -9,6 +9,7 @@
A self-hosted TeamSpeak 3 / TeamSpeak 6 web client and voice gateway. Join your voice space from a modern browser without installing a desktop client.
[![License](https://img.shields.io/badge/License-AGPL--3.0--only-0f766e?style=flat-square)](LICENSE)
[![Version](https://img.shields.io/badge/version-0.1.3-0f766e?style=flat-square)](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3)
[![Node.js](https://img.shields.io/badge/Node.js-%3E%3D22.5.0-0f766e?style=flat-square)](https://nodejs.org/)
[![TeamSpeak](https://img.shields.io/badge/TeamSpeak-3%20%7C%206-0f766e?style=flat-square)](https://www.teamspeak.com/)
@@ -30,6 +31,16 @@ A self-hosted TeamSpeak 3 / TeamSpeak 6 web client and voice gateway. Join your
### 更新日志
#### 2026-09-03 · v0.1.3
- 新增可选的 WebRTC 语音传输,为需要更低、更稳定实时语音延迟的部署提供同机媒体通道。
- WebRTC 媒体服务由网关自带,按当前访问地址自动生成候选地址,Docker Compose 自动发布固定 UDP 媒体端口。
- 将 TeamSpeak 集成迁移到我们维护的 `EchoSixHIYA/teamspeak-js`,带来实时目录快照以及成员、频道同步能力。
- WebRTC 语音按协商得到的 Opus 参数传输,并且每位发言者只保留最新音频帧,避免网络抖动时旧语音持续堆积。
- 修复 WebRTC 与兼容性语音链路切换时的重复播放、残留会话和回退不完整问题。
- 修复原生 Opus 解码调用和浏览器端协商负载类型处理,并整理连接关闭时的资源清理。
- 实测公网主机放行入站 `40000–40099/UDP` 后,两个浏览器会话的 WebRTC 音频帧可双向流通,丢帧为 `0`,入口最大间隔约 `27ms`、出口最大间隔约 `81–83ms`;该数据是测试链路结果,不代表所有网络环境的固定延迟。
#### 2026-09-02 · v0.1.2
- 优化移动端浏览器体验:频道、成员、聊天和语音操作适配窄屏;移动端成员操作提供三个点菜单,桌面端继续使用右键菜单。
@@ -46,7 +57,7 @@ A self-hosted TeamSpeak 3 / TeamSpeak 6 web client and voice gateway. Join your
- 移除依赖页面焦点的普通空格键按键说话模式;改为桌面端和移动端均可用的一键闭麦/开麦,静音状态会保存在当前浏览器中。
- 闭麦会在上行音频发送前直接阻断声音,同时保留 VOX 语音激活、输入设备选择、音量与阈值调节能力。
- 发布流程稳定生成 Windows/Linux 部署包并同步发布 Docker 镜像;Docker 构建会正确处理依赖安装脚本。
- 简化 Docker Compose 部署:默认从当前代码构建,自动创建并持久化数据卷,支持通过 `WEBSPEAK_PORT` 修改宿主机端口。
- 简化 Docker Compose 部署:默认使用已发布镜像,自动创建并持久化数据卷,支持通过 `WEBSPEAK_PORT` 修改宿主机端口。
#### 2026-08-31 · v0.1.0
@@ -66,7 +77,7 @@ A self-hosted TeamSpeak 3 / TeamSpeak 6 web client and voice gateway. Join your
| 领域 | 已提供 |
| --- | --- |
| 语音 | Opus / PCM 桥接、VOX 语音激活、一键闭麦/开麦、连接状态与重连提示 |
| 语音 | Opus / PCM 桥接、可选 WebRTC 低延迟通道、VOX 语音激活、一键闭麦/开麦、连接状态与重连提示 |
| 设备 | 浏览器麦克风与扬声器选择、音量调节、实时输入电平、本地麦克风测试 |
| 频道 | 频道树、频道切换、成员移动、频道文字聊天、服务器事件与状态展示 |
| 成员 | 在线成员、发言绿色头像边框、Away 状态、私聊、Poke、昵称复制、成员音量 |
@@ -78,7 +89,7 @@ A self-hosted TeamSpeak 3 / TeamSpeak 6 web client and voice gateway. Join your
| 层级 | 职责 | 连接 |
| --- | --- | --- |
| 浏览器会话 | 昵称、设备、频道、成员、文字和语音交互 | HTTPS / WSS → WebSpeak |
| 浏览器会话 | 昵称、设备、频道、成员、文字和语音交互 | HTTPS / WSS → WebSpeak;可选 WebRTC 音频 |
| WebSpeak 网关 | 会话管理、访问控制、语音桥接、目录同步、管理控制台 | TeamSpeak 客户端协议 |
| TeamSpeak 3 / 6 | 提供频道、成员、文字和语音服务 | 目标地址与语音端口 |
@@ -86,12 +97,13 @@ A self-hosted TeamSpeak 3 / TeamSpeak 6 web client and voice gateway. Join your
#### 方式 A:Docker Compose(推荐)
Docker Compose 会直接使用当前目录的 Dockerfile 构建 WebSpeak,自动创建数据卷并启动服务,不需要手动创建镜像或数据卷。
Docker Compose 默认从 GitHub Container Registry 拉取已经发布的 WebSpeak 镜像,自动创建数据卷并启动服务。普通部署不需要本地 Node.js、编译工具或 Dockerfile 构建环境。
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose up -d --build
docker compose pull
docker compose up -d
```
查看状态和日志:
@@ -104,30 +116,34 @@ curl http://127.0.0.1:3040/health
启动完成后打开 [http://127.0.0.1:3040/](http://127.0.0.1:3040/)。首次进入管理后台 `/admin` 使用 `admin / admin`,并按提示修改密码。
默认数据保存在 Docker volume `webspeak-data` 中。升级代码后再次执行 `docker compose up -d --build` 即可;停止服务使用 `docker compose down`,不要添加 `-v`,否则会删除数据库、密钥和管理员配置。
Compose 会同时发布内置 WebRTC 使用的 `40000–40099/UDP`。启用 WebRTC 时只需在管理后台打开开关;不需要填写公网地址,也不需要另行部署媒体服务器。
如果用户需要从公网浏览器接入,还必须在部署主机所在云平台的安全组或上游防火墙中添加一条“入站 UDP `40000–40099`”规则。Docker Compose 只能发布端口,不能替你修改云安全组;Ubuntu 使用 UFW 时可执行 `sudo ufw allow 40000:40099/udp`。网页和 WSS 继续使用 TCP `80/443`,TeamSpeak 的 `9987` 只需由 WebSpeak 主机访问目标 TeamSpeak,不需要在 WebSpeak 主机对公网开放,也不要把 WebRTC 媒体转发到反向代理的 `443/udp`。
默认数据保存在 Docker volume `webspeak-data` 中。升级时先拉取新镜像,再重新创建应用容器;停止服务使用 `docker compose down`,不要添加 `-v`,否则会删除数据库、密钥和管理员配置。
```bash
docker compose pull
docker compose up -d
```
如需固定到某个发布版本,可在启动前指定 GHCR 镜像标签;发布标签与 GitHub Release 一致:
```bash
export WEBSPEAK_IMAGE=ghcr.io/echosixhiya/webspeak:v0.1.3
docker compose pull
docker compose up -d
```
WebSpeak 默认对外提供 `3040` 端口。如需修改宿主机端口,只需设置 `WEBSPEAK_PORT`,容器内部端口无需修改:
```bash
WEBSPEAK_PORT=3041 docker compose up -d --build
WEBSPEAK_PORT=3041 docker compose up -d
```
#### 方式 B:Dockerfile 手动运行(可选)
容器内部监听 `3040`,并在 `40000–40099/UDP` 提供内置 WebRTC 媒体;SQLite 数据库、安装级主密钥和日志保存在 `/data`。Dockerfile 仅用于项目 CI、发布资产和开发者本地构建,不是普通用户的默认部署入口。
```bash
docker build -t webspeak:local .
docker volume create webspeak-data
docker run -d \
--name webspeak \
--restart unless-stopped \
-p 3040:3040 \
-v webspeak-data:/data \
webspeak:local
```
容器内部监听 `3040`,SQLite 数据库、安装级主密钥和日志保存在 `/data`。手动运行时也请保留 `webspeak-data:/data` 数据卷。
#### 方式 C:源码运行
#### 方式 B:源码运行(开发者)
环境要求:
@@ -184,6 +200,12 @@ WebSpeak 的 HTTP 端口固定为 `3040`,TeamSpeak 默认语音端口为 `9987
设备标签由浏览器权限模型决定。首次选择设备前,浏览器可能要求授予麦克风权限;输出设备选择依赖浏览器支持,不支持时会明确回退到默认扬声器。
#### 可选 WebRTC 语音传输
WebSpeak 自带 WebRTC 媒体服务。管理员只需在 `/admin` → “服务器” → “WebRTC 语音”中启用开关;网关会根据用户当前访问的域名或地址自动生成媒体候选地址,固定 UDP 媒体端口由 Docker Compose 自动发布,不需要配置额外的媒体服务器、STUN/TURN 地址或公网主机字段。保存后对新语音会话生效。
使用 Docker Compose 时,项目会同时发布 WebSpeak HTTP 端口和内置的 UDP 媒体端口范围;公网部署还需要在云安全组或上游防火墙放行入站 UDP `40000–40099`。反向代理仍只负责 HTTPS/WSS 信令;UDP 媒体直接进入同一台 WebSpeak 主机。非 Docker 启动时也要确保同机防火墙允许该固定 UDP 范围。若浏览器或网络不支持 WebRTC,客户端会自动回退到兼容性语音链路。
### 数据与安全边界
运行数据默认位于 `data/`,Docker 环境默认位于 `/data`:
@@ -287,12 +309,23 @@ WebSpeak brings TeamSpeak voice spaces to the browser. It is a self-hosted gatew
### Changelog
#### 2026-09-03 · v0.1.3
- Added an optional WebRTC audio transport for deployments that need lower and more stable realtime voice latency, with media served by the same gateway.
- Bundled the WebRTC media service into the gateway; it derives candidates from the current access address and Docker Compose publishes the fixed UDP media range automatically.
- Migrated the TeamSpeak integration to our maintained `EchoSixHIYA/teamspeak-js` fork, adding live directory snapshots and member/channel synchronization.
- WebRTC audio now uses negotiated Opus parameters and keeps only the newest frame per speaker, preventing stale voice from accumulating during network jitter.
- Fixed duplicate playback, incomplete fallback, and leftover server-side media sessions when switching between WebRTC and the compatibility voice path.
- Fixed native Opus decoder usage and browser-side negotiated payload handling, and tightened cleanup when a connection closes.
- Verified the public deployment after allowing inbound `UDP 40000–40099`: two browser sessions exchanged WebRTC audio with `0` dropped frames, about `27 ms` peak ingress gaps, and `81–83 ms` peak egress gaps. These are measurements from the test path, not a universal latency guarantee.
#### 2026-09-02 · v0.1.2
- Improved the mobile browser experience across channel, member, chat, and voice surfaces; mobile member actions now use a three-dot menu while desktop keeps the context menu.
- Promoted the GitHub entry on the welcome page and added a current-version badge plus a changelog link; narrow layouts collapse text controls into icons to prevent crowding.
- Fixed alignment for the settings gear and related controls, with consistent touch sizing and visual treatment for settings, exit, and microphone actions.
- Consolidated the post-0.1.1 mobile voice controls, microphone mute replacement for focus-dependent PTT, automatic protocol detection, simplified Docker Compose startup, and live-demo documentation into this release.
- Migrated TeamSpeak directory tracking and whisper packet support into the maintained WebSpeak SDK, removing the install-time compiled SDK patch step.
#### 2026-09-02 · v0.1.1
@@ -302,8 +335,8 @@ WebSpeak brings TeamSpeak voice spaces to the browser. It is a self-hosted gatew
- Added the bilingual interface, default TeamSpeak target, legacy configuration migration, and mandatory first-login password rotation.
- Removed the focus-dependent normal Space-key PTT mode and replaced it with a one-click microphone mute/unmute control on desktop and mobile; the mute state is persisted in the current browser.
- Mute now suppresses upstream microphone audio before it is sent, while VOX activation, input-device selection, volume controls, and threshold tuning remain available.
- Stabilized release publishing for Windows/Linux packages and the matching Docker image; Docker builds now handle the dependency patch script correctly.
- Simplified Docker Compose deployment: it builds from the current checkout, creates and persists the data volume automatically, and supports changing the host port with `WEBSPEAK_PORT`.
- Stabilized release publishing for Windows/Linux packages and the matching Docker image; Docker builds now build the pinned SDK dependency during installation.
- Simplified Docker Compose deployment: it uses the published image by default, creates and persists the data volume automatically, and supports changing the host port with `WEBSPEAK_PORT`.
#### 2026-08-31 · v0.1.0
@@ -323,7 +356,7 @@ WebSpeak brings TeamSpeak voice spaces to the browser. It is a self-hosted gatew
| Area | Included |
| --- | --- |
| Voice | Opus / PCM bridging, VOX activation, one-click microphone mute/unmute, connection state, reconnect feedback, and speaking indicators |
| Voice | Opus / PCM bridging, optional WebRTC low-latency transport, VOX activation, one-click microphone mute/unmute, connection state, reconnect feedback, and speaking indicators |
| Devices | Browser microphone and speaker selection, volume controls, live input level, and a local microphone test |
| Channels | Channel tree, channel switching, member movement, channel text chat, server events, and status display |
| Members | Online members, green speaking borders, Away state, private messages, Poke, nickname copy, and per-member volume |
@@ -335,7 +368,7 @@ WebSpeak brings TeamSpeak voice spaces to the browser. It is a self-hosted gatew
| Layer | Responsibility | Connection |
| --- | --- | --- |
| Browser session | Nickname, device, channel, member, text, and voice interactions | HTTPS / WSS → WebSpeak |
| Browser session | Nickname, device, channel, member, text, and voice interactions | HTTPS / WSS → WebSpeak; optional WebRTC audio |
| WebSpeak gateway | Session management, access control, voice bridging, directory synchronization, and admin console | TeamSpeak client protocol |
| TeamSpeak 3 / 6 | Channel, member, text, and voice services | Configured host and voice port |
@@ -343,12 +376,13 @@ WebSpeak brings TeamSpeak voice spaces to the browser. It is a self-hosted gatew
#### Option A: Docker Compose (recommended)
Docker Compose builds WebSpeak from the Dockerfile in the current checkout, creates the persistent data volume automatically, and starts the service without a separate image-pull or volume-creation step.
Docker Compose pulls the published WebSpeak image from GitHub Container Registry by default, creates the persistent data volume automatically, and starts the service. A normal deployment does not require Node.js, native build tools, or a local Dockerfile build.
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose up -d --build
docker compose pull
docker compose up -d
```
Check the service and health endpoint:
@@ -361,30 +395,34 @@ curl http://127.0.0.1:3040/health
Then open [http://127.0.0.1:3040/](http://127.0.0.1:3040/). On the first admin login, use `admin / admin` and follow the prompt to change the password.
Runtime data is kept in the `webspeak-data` Docker volume. After updating the checkout, run `docker compose up -d --build` again. Stop the service with `docker compose down`; do not add `-v`, because that removes the database, master key, and administrator settings.
Compose also publishes `40000–40099/UDP` for the built-in WebRTC media service. Enabling WebRTC only requires the administrator switch; no public-host field or separate media server is needed.
For browsers connecting over the public internet, also add an inbound `UDP 40000–40099` rule in the cloud security group or upstream firewall for the WebSpeak host. Docker Compose publishes the ports but cannot change a provider-level security group; with Ubuntu UFW, use `sudo ufw allow 40000:40099/udp`. Keep TCP `80/443` for the web page and WSS signaling. TeamSpeak port `9987` only needs to be reachable from WebSpeak to the target TeamSpeak server; it does not need to be exposed publicly on the WebSpeak host, and WebRTC media must not be routed through the reverse proxy's `443/udp`.
Runtime data is kept in the `webspeak-data` Docker volume. To upgrade, pull the new image and recreate the application container. Stop the service with `docker compose down`; do not add `-v`, because that removes the database, master key, and administrator settings.
```bash
docker compose pull
docker compose up -d
```
To pin a specific release, set the GHCR image tag to match the GitHub Release tag:
```bash
export WEBSPEAK_IMAGE=ghcr.io/echosixhiya/webspeak:v0.1.3
docker compose pull
docker compose up -d
```
The default host port is `3040`. To use another host port, set `WEBSPEAK_PORT`; the container port stays unchanged:
```bash
WEBSPEAK_PORT=3041 docker compose up -d --build
WEBSPEAK_PORT=3041 docker compose up -d
```
#### Option B: Run the Dockerfile manually (optional)
The container listens on `3040` internally and provides built-in WebRTC media on `40000–40099/UDP`. SQLite data, the installation master key, and logs are stored in `/data`. The Dockerfile is used by project CI, release assets, and developer builds; it is not the default deployment path for users.
```bash
docker build -t webspeak:local .
docker volume create webspeak-data
docker run -d \
--name webspeak \
--restart unless-stopped \
-p 3040:3040 \
-v webspeak-data:/data \
webspeak:local
```
The container listens on `3040` internally. SQLite data, the installation master key, and logs are stored in `/data`; keep the `webspeak-data:/data` volume when running the image manually.
#### Option C: Run from source
#### Option B: Run from source (developers)
Requirements:
@@ -443,6 +481,12 @@ Inside a voice space, the settings panel lets users:
Device labels are controlled by the browser permission model. The first device selection may request microphone permission. Output-device selection depends on browser support; unsupported browsers clearly fall back to the default speaker.
#### Optional WebRTC audio transport
WebSpeak includes its own WebRTC media service. An administrator only needs to enable the switch at `/admin` → “Server” → “WebRTC audio”; the gateway derives media candidates from the address used by the browser, while Docker Compose publishes the fixed UDP media range automatically. No extra media server, STUN/TURN address, or public-host field is required. Saved settings apply to new voice sessions.
With Docker Compose, the WebSpeak HTTP port and the built-in UDP media range are published together, but a public deployment must also allow inbound UDP `40000–40099` in the cloud security group or upstream firewall. The reverse proxy continues to handle HTTPS/WSS signaling, while UDP media enters the same WebSpeak host directly. For non-Docker startup, the same fixed UDP range must be permitted on that host. If WebRTC is unavailable because of the network or browser, the client automatically falls back to the compatibility voice path.
### Data and Security Boundary
Runtime data is stored in `data/` by default and in `/data` in Docker:
+3 -4
View File
@@ -1,12 +1,11 @@
services:
webspeak:
build:
context: .
dockerfile: Dockerfile
image: webspeak:local
image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest}
pull_policy: missing
restart: unless-stopped
ports:
- "${WEBSPEAK_PORT:-3040}:3040"
- "40000-40099:40000-40099/udp"
volumes:
- webspeak-data:/data
+533 -10
View File
@@ -1,19 +1,19 @@
{
"name": "webspeak-webclient",
"version": "0.1.2",
"version": "0.1.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.1.2",
"hasInstallScript": true,
"version": "0.1.3",
"license": "AGPL-3.0-only",
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@honeybbq/teamspeak-client": "^0.2.2",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6",
"express": "^5.2.1",
"pino": "^10.3.1",
"werift": "0.24.4",
"ws": "^8.20.0"
},
"devDependencies": {
@@ -61,6 +61,17 @@
"node": ">=12.0.0"
}
},
"node_modules/@echosixhiya/teamspeak-client": {
"version": "0.2.4",
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6cd83c0fd4f6e00fc9c1ff4ec79dcbfd55",
"license": "MIT",
"dependencies": {
"@noble/curves": "^2.0.1"
},
"engines": {
"node": ">=20.19"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
@@ -503,16 +514,26 @@
"node": ">=18"
}
},
"node_modules/@honeybbq/teamspeak-client": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak-client/-/teamspeak-client-0.2.2.tgz",
"integrity": "sha512-JQ4yHEUwAxK2kHmIxelEf3grzMM8lVeuf7RzxK1g24U6XH8ZJO28S477FUtSTRe68PwUBkAlsa1Z/7BhLKh+AA==",
"node_modules/@fidm/asn1": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@fidm/asn1/-/asn1-1.0.4.tgz",
"integrity": "sha512-esd1jyNvRb2HVaQGq2Gg8Z0kbQPXzV9Tq5Z14KNIov6KfFD6PTaRIO8UpcsYiTNzOqJpmyzWgVTrUwFV3UF4TQ==",
"license": "MIT",
"engines": {
"node": ">= 8"
}
},
"node_modules/@fidm/x509": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@fidm/x509/-/x509-1.2.1.tgz",
"integrity": "sha512-nwc2iesjyc9hkuzcrMCBXQRn653XuAUKorfWM8PZyJawiy1QzLj4vahwzaI25+pfpwOLvMzbJ0uKpWLDNmo16w==",
"license": "MIT",
"dependencies": {
"@noble/curves": "^2.0.1"
"@fidm/asn1": "^1.0.4",
"tweetnacl": "^1.0.1"
},
"engines": {
"node": ">=20.19"
"node": ">= 8"
}
},
"node_modules/@isaacs/fs-minipass": {
@@ -527,6 +548,12 @@
"node": ">=18.0.0"
}
},
"node_modules/@leichtgewicht/ip-codec": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",
"integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==",
"license": "MIT"
},
"node_modules/@noble/curves": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.2.0.tgz",
@@ -554,12 +581,212 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@peculiar/asn1-cms": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.9.4.tgz",
"integrity": "sha512-cben7oxmQsUGZqotus7yt0srYdncOT6RNWcTQ77T2RFOXejYVYkXadrfePdRcrVpO9K95IRLKKglG2k38jKXuw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.9.4",
"@peculiar/asn1-x509": "^2.9.4",
"@peculiar/asn1-x509-attr": "^2.9.4",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/asn1-csr": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.9.4.tgz",
"integrity": "sha512-xd4YN4vpRjkDAQWVfZZkeu12IEND7DOpkqaHSIHxZl1uggUNa9Ju0QxY2jHvDAS9pP0zhRBytg8ifsnGo3V0jw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.9.4",
"@peculiar/asn1-x509": "^2.9.4",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/asn1-ecc": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.9.4.tgz",
"integrity": "sha512-JJXefFshRAuVAjWQo/39bkg1ywc1VaiO44S8RRC+Ykvf/u2KDmYffoDb0ZBPCR5uJy4AGKQhl8mX+Q8ShcWaXQ==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.9.4",
"@peculiar/asn1-x509": "^2.9.4",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/asn1-pfx": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.9.4.tgz",
"integrity": "sha512-khuGzHTzNzk4GDlIBEILyIs6Lce0yn0ZBdoI9v93kmNncfZRhD+AQ5ODFqdhvoE8cMJF/JMTQ8yA+t1D14kqCw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.9.4",
"@peculiar/asn1-pkcs8": "^2.9.4",
"@peculiar/asn1-rsa": "^2.9.4",
"@peculiar/asn1-schema": "^2.9.4",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/asn1-pkcs8": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.9.4.tgz",
"integrity": "sha512-duRdotlUx9eDZe6QrQpQKl61RbWykCHBCkKayP8V8XdEFwlKHZ8qGGDMyS6Pye7OX7nLFttTTpRkJeet78ckwQ==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.9.4",
"@peculiar/asn1-x509": "^2.9.4",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/asn1-pkcs9": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.9.4.tgz",
"integrity": "sha512-kaL4cNxBpdQE2dKlyZBqz4ygCrwffO+8wfoxTEqM1Z8RadvCeELBRzcv0dzM8aY9azHMwODO5nxU65zXmhToOQ==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.9.4",
"@peculiar/asn1-pfx": "^2.9.4",
"@peculiar/asn1-pkcs8": "^2.9.4",
"@peculiar/asn1-schema": "^2.9.4",
"@peculiar/asn1-x509": "^2.9.4",
"@peculiar/asn1-x509-attr": "^2.9.4",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/asn1-rsa": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.9.4.tgz",
"integrity": "sha512-pZ96eD1PptovcWQ/GSmuNFXd/7EQJNlKfDaNCyE2rx3W0v6QFelkzquVqRSRyyDXXCYD69ZXJDzZ8GhIiQzKoA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.9.4",
"@peculiar/asn1-x509": "^2.9.4",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/asn1-schema": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.9.4.tgz",
"integrity": "sha512-GjzePcT9Iw8NzeOPf73iNS9xM+TBhd/FilAfP+RQGkTMQJTVWtytN3JHJACCjf/ABNau5S7mS3g+DcuxmRgYEg==",
"license": "MIT",
"dependencies": {
"@peculiar/utils": "^2.0.2",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/asn1-x509": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.9.4.tgz",
"integrity": "sha512-CxhBo/RdEbMMob7T31ZdQjGuoyRFLVwrDzTn25bihzBasRg9kRm/0IxIPvhgQtcK/9dNcO1XQL2fuPugwELL0Q==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.9.4",
"@peculiar/utils": "^2.0.2",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/asn1-x509-attr": {
"version": "2.9.4",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.9.4.tgz",
"integrity": "sha512-ehQXbpQaQYycgu8OrvigwSPTFfVRcu0ECNYCWw+yzBp02Lw5paRqzzhUpfOgO2K38+WfFZuEz/0RPtam5g0OMg==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.9.4",
"@peculiar/asn1-x509": "^2.9.4",
"asn1js": "^3.0.10",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14"
}
},
"node_modules/@peculiar/utils": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz",
"integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==",
"license": "MIT",
"dependencies": {
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/x509": {
"version": "1.14.3",
"resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz",
"integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-csr": "^2.6.0",
"@peculiar/asn1-ecc": "^2.6.0",
"@peculiar/asn1-pkcs9": "^2.6.0",
"@peculiar/asn1-rsa": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"pvtsutils": "^1.3.6",
"reflect-metadata": "^0.2.2",
"tslib": "^2.8.1",
"tsyringe": "^4.10.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
"integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",
"license": "MIT"
},
"node_modules/@shinyoshiaki/binary-data": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/@shinyoshiaki/binary-data/-/binary-data-0.6.1.tgz",
"integrity": "sha512-7HDb/fQAop2bCmvDIzU5+69i+UJaFgIVp99h1VzK1mpg1JwSODOkjbqD7ilTYnqlnadF8C4XjpwpepxDsGY6+w==",
"license": "MIT",
"dependencies": {
"generate-function": "^2.3.1",
"is-plain-object": "^2.0.3"
},
"engines": {
"node": ">=6"
}
},
"node_modules/@types/body-parser": {
"version": "1.19.6",
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
@@ -581,6 +808,21 @@
"@types/node": "*"
}
},
"node_modules/@types/dom-mediacapture-transform": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",
"integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",
"license": "MIT",
"dependencies": {
"@types/dom-webcodecs": "*"
}
},
"node_modules/@types/dom-webcodecs": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
"integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",
"license": "MIT"
},
"node_modules/@types/express": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
@@ -728,6 +970,20 @@
"node": ">=10"
}
},
"node_modules/asn1js": {
"version": "3.0.10",
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",
"integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==",
"license": "BSD-3-Clause",
"dependencies": {
"pvtsutils": "^1.3.6",
"pvutils": "^1.1.5",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/atomic-sleep": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
@@ -743,6 +999,26 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/body-parser": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
@@ -790,6 +1066,30 @@
"concat-map": "0.0.1"
}
},
"node_modules/buffer": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.2.1"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -939,6 +1239,18 @@
"node": ">=8"
}
},
"node_modules/dns-packet": {
"version": "5.6.1",
"resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz",
"integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==",
"license": "MIT",
"dependencies": {
"@leichtgewicht/ip-codec": "^2.0.1"
},
"engines": {
"node": ">=6"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -1194,6 +1506,15 @@
"node": ">=10"
}
},
"node_modules/generate-function": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
"license": "MIT",
"dependencies": {
"is-property": "^1.0.2"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
@@ -1343,6 +1664,26 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "BSD-3-Clause"
},
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -1378,12 +1719,39 @@
"node": ">=8"
}
},
"node_modules/is-plain-object": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz",
"integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==",
"license": "MIT",
"dependencies": {
"isobject": "^3.0.1"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/is-promise": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT"
},
"node_modules/is-property": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
"license": "MIT"
},
"node_modules/isobject": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
"integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/make-dir": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
@@ -1426,6 +1794,24 @@
"node": ">= 0.8"
}
},
"node_modules/mediabunny": {
"version": "1.55.5",
"resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.55.5.tgz",
"integrity": "sha512-m0v6y8FGXiK+HKOc3AZqU+kJPLYsSKaLitmQNQIIHZKIGlTwQ34OF+X6Ul0K8iV4b03oPse10apwuoqbvmKeAA==",
"license": "MPL-2.0",
"workspaces": [
".",
"packages/*"
],
"dependencies": {
"@types/dom-mediacapture-transform": "^0.1.11",
"@types/dom-webcodecs": "0.1.13"
},
"funding": {
"type": "individual",
"url": "https://github.com/sponsors/Vanilagy"
}
},
"node_modules/merge-descriptors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
@@ -1502,6 +1888,19 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/multicast-dns": {
"version": "7.2.5",
"resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz",
"integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==",
"license": "MIT",
"dependencies": {
"dns-packet": "^5.2.2",
"thunky": "^1.0.2"
},
"bin": {
"multicast-dns": "cli.js"
}
},
"node_modules/negotiator": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
@@ -1713,6 +2112,24 @@
"node": ">= 0.10"
}
},
"node_modules/pvtsutils": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.8.1"
}
},
"node_modules/pvutils": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
"integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
"license": "MIT",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/qs": {
"version": "6.15.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",
@@ -1781,6 +2198,12 @@
"node": ">= 12.13.0"
}
},
"node_modules/reflect-metadata": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
"license": "Apache-2.0"
},
"node_modules/rimraf": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
@@ -2091,6 +2514,12 @@
"integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",
"license": "MIT"
},
"node_modules/thunky": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz",
"integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",
"license": "MIT"
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
@@ -2106,6 +2535,12 @@
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT"
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tsx": {
"version": "4.22.3",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.3.tgz",
@@ -2125,6 +2560,30 @@
"fsevents": "~2.3.3"
}
},
"node_modules/tsyringe": {
"version": "4.10.0",
"resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz",
"integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",
"license": "MIT",
"dependencies": {
"tslib": "^1.9.3"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/tsyringe/node_modules/tslib": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
"license": "0BSD"
},
"node_modules/tweetnacl": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
"license": "Unlicense"
},
"node_modules/type-is": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
@@ -2207,6 +2666,70 @@
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"license": "BSD-2-Clause"
},
"node_modules/werift": {
"version": "0.24.4",
"resolved": "https://registry.npmjs.org/werift/-/werift-0.24.4.tgz",
"integrity": "sha512-NoROZ11L/ZqAB5ombCB4VBuVNdIZfwI493zlxlIX7BlwfWRy55eDJdtWMC2VX35yBXFaWwA8NtYbmJ8qWtVk9Q==",
"license": "MIT",
"dependencies": {
"@fidm/x509": "^1.2.1",
"@noble/curves": "^1.8.1",
"@peculiar/x509": "^1.12.3",
"@shinyoshiaki/binary-data": "^0.6.1",
"buffer": "^6.0.3",
"debug": "4.4.0",
"mediabunny": "^1.45.2",
"multicast-dns": "^7.2.5",
"tweetnacl": "^1.0.3"
},
"engines": {
"node": ">=16"
}
},
"node_modules/werift/node_modules/@noble/curves": {
"version": "1.9.7",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz",
"integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "1.8.0"
},
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/werift/node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/werift/node_modules/debug": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
"integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "webspeak-webclient",
"version": "0.1.2",
"version": "0.1.3",
"private": true,
"license": "AGPL-3.0-only",
"type": "module",
@@ -13,15 +13,15 @@
"build": "tsc",
"test": "tsx --test \"test/**/*.test.ts\"",
"start": "node dist/index.js",
"postinstall": "node scripts/patch-teamspeak-sdk.mjs",
"web:dev": "cd web && npx vite --host",
"web:build": "cd web && npx vite build"
},
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@honeybbq/teamspeak-client": "^0.2.2",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6",
"express": "^5.2.1",
"pino": "^10.3.1",
"werift": "0.24.4",
"ws": "^8.20.0"
},
"devDependencies": {
-183
View File
@@ -1,183 +0,0 @@
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageRoot = path.join(root, "node_modules", "@honeybbq", "teamspeak-client");
const marker = "webspeak-directory-snapshot-v2";
const whisperMarker = "webspeak-team-whisper-v1";
const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
if (packageJson.version !== "0.2.2") {
throw new Error(`Unsupported @honeybbq/teamspeak-client version: ${packageJson.version}`);
}
const cjsPath = path.join(packageRoot, "dist", "index.cjs");
const mjsPath = path.join(packageRoot, "dist", "index.mjs");
const handlerCjsPath = path.join(packageRoot, "dist", "handler-CqCD93f0.cjs");
const handlerMjsPath = path.join(packageRoot, "dist", "handler-C_JhqGTd.js");
const [cjs, mjs, handlerCjs, handlerMjs] = await Promise.all([
readFile(cjsPath, "utf8"),
readFile(mjsPath, "utf8"),
readFile(handlerCjsPath, "utf8"),
readFile(handlerMjsPath, "utf8"),
]);
const patchedCjs = patchWhisperClient(patchCjs(cjs), "cjs");
const patchedMjs = patchWhisperClient(patchMjs(mjs), "mjs");
const patchedHandlerCjs = patchWhisperHandler(handlerCjs, "cjs");
const patchedHandlerMjs = patchWhisperHandler(handlerMjs, "mjs");
await Promise.all([
writeFile(cjsPath, patchedCjs, "utf8"),
writeFile(mjsPath, patchedMjs, "utf8"),
writeFile(handlerCjsPath, patchedHandlerCjs, "utf8"),
writeFile(handlerMjsPath, patchedHandlerMjs, "utf8"),
]);
function patchWhisperClient(source, format) {
if (source.includes(whisperMarker)) return source;
if (format === "cjs") {
const needle = "sendVoice(e,t){this.handler.sendVoicePacket(e,t)}";
if (!source.includes(needle)) throw new Error("Could not patch CJS SDK client whisper method");
return source.replace(needle, `${needle}sendWhisper(e,t,n){this.handler.sendWhisperPacket(e,t,n)}`) + `/* ${whisperMarker} */`;
}
const needle = "\tsendVoice(e, t) {\n\t\tthis.handler.sendVoicePacket(e, t);\n\t}\n";
if (!source.includes(needle)) throw new Error("Could not patch MJS SDK client whisper method");
return source.replace(needle, `${needle}\tsendWhisper(e, t, n) {\n\t\tthis.handler.sendWhisperPacket(e, t, n);\n\t}\n`) + `/* ${whisperMarker} */`;
}
function patchWhisperHandler(source, format) {
if (source.includes(whisperMarker)) return source;
if (format === "cjs") {
const needle = "this.#b(u)}close(){";
if (!source.includes(needle)) throw new Error("Could not patch CJS SDK whisper packet handler");
const method = `/* ${whisperMarker} */sendWhisperPacket(e,t,n){if(t.length>32)throw new Error(\`too many whisper targets\`);let a=this.#c[r.VoiceWhisper],o=this.#l[r.VoiceWhisper];this.#c[r.VoiceWhisper]=a+1&65535,this.#c[r.VoiceWhisper]===0&&this.#l[r.VoiceWhisper]++;let s=5+2*t.length+e.length,l=new Uint8Array(s),u=new DataView(l.buffer);u.setUint16(0,a,!1),l[2]=n,l[3]=0,l[4]=t.length;for(let n=0;n<t.length;n++)u.setUint16(5+2*n,t[n],!1);l.set(e,5+2*t.length);let c0=c({typeFlagged:r.VoiceWhisper|i.Unencrypted,id:a,clientID:this.#r,generationID:o,data:l,receivedAt:0}),d=new Uint8Array(x+b+s);d.set(this.#e.fakeSignature,0),d.set(c0,x),d.set(l,x+b),this.#b(d)}`;
return source.replace(needle, `this.#b(u)}${method}close(){`);
}
const needle = "this.#b(u);\n\t}\n\tclose() {";
if (!source.includes(needle)) throw new Error("Could not patch MJS SDK whisper packet handler");
const method = `\t/* ${whisperMarker} */\n\tsendWhisperPacket(e, t, n) {\n\t\tif (t.length > 32) throw new Error("too many whisper targets");\n\t\tlet a = this.#c[r.VoiceWhisper], o = this.#l[r.VoiceWhisper];\n\t\tthis.#c[r.VoiceWhisper] = a + 1 & 65535;\n\t\tif (this.#c[r.VoiceWhisper] === 0) this.#l[r.VoiceWhisper]++;\n\t\tconst s = 5 + 2 * t.length + e.length, l = new Uint8Array(s), u = new DataView(l.buffer);\n\t\tu.setUint16(0, a, false);\n\t\tl[2] = n;\n\t\tl[3] = 0;\n\t\tl[4] = t.length;\n\t\tfor (let n = 0; n < t.length; n++) u.setUint16(5 + 2 * n, t[n], false);\n\t\tl.set(e, 5 + 2 * t.length);\n\t\tconst c0 = c({ typeFlagged: r.VoiceWhisper | i.Unencrypted, id: a, clientID: this.#r, generationID: o, data: l, receivedAt: 0 });\n\t\tconst d = new Uint8Array(x + b + s);\n\t\td.set(this.#e.fakeSignature, 0);\n\t\td.set(c0, x);\n\t\td.set(l, x + b);\n\t\tthis.#b(d);\n\t}\n\tclose() {`;
return source.replace(needle, `this.#b(u);\n\t}\n${method}`);
}
function patchCjs(source) {
if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source;
const helper = `/* ${marker} */
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}}
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
`;
source = source.replace("var K=class", `${helper}var K=class`);
// TS6 reports a client that moved out of our current view as
// notifyclientleftview with a non-zero ctid. Preserve that client and apply
// the target channel; ctid=0 is the actual server leave case.
const replacements = [
[
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t;return r!==0&&n.delete(r),{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t,o=A(e.params.ctid??``),s=o!==0n;if(r!==0)if(s){let e=n.get(r);e&&n.set(r,{...e,channelID:o})}else n.delete(r);return s?{kind:`clientMoved`,event:{id:r,targetChannelID:o,reasonID:i,invokerID:j(e.params.invokerid??``),invokerName:e.params.invokername??``,invokerUID:e.params.invokeruid??``}}:{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
],
[
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#q=new Map;#R=[];#L=!1;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
],
[
"case`voiceData`:this.#h.push(t);break;case`connected`:",
"case`voiceData`:this.#h.push(t);break;case`directorySnapshot`:this.#R.push(t);break;case`connected`:",
],
[
"this.#o.reset(),this.#s.reset(),this.#c.clear(),this.clid=0",
"this.#o.reset(),this.#s.reset(),this.#q.clear(),this.#c.clear(),this.#L=!1,this.clid=0",
],
[
"case`initserver`:w(this,t.params);break;case`error`:this.#A(t.params);break;default:{",
"case`initserver`:w(this,t.params);break;case`channellist`:{let e=webSpeakDirectoryChannel(t.params,a.i);e&&this.#q.set(e.id,e),this.#Y();break}case`channelclientlist`:{let e=webSpeakDirectoryClient(t.params,a.i);e&&this.#c.set(e.id,e),this.#Y();break}case`error`:this.#A(t.params);break;default:{",
],
[
"if(t.name.startsWith(`notify`)){let e=F(t,this.clid,this.#c,this.nickname);this.#j(e,t.params);return}",
"if(t.name.startsWith(`notify`)){let e=webSpeakDirectoryChannelNotification(t.name,t.params,a.i,this.#q),n=F(t,this.clid,this.#c,this.nickname);this.#j(n,t.params),e&&this.#Y();return}",
],
[
"case`clientEnter`:{let t=e.info;t.id!==0&&N(this.nickname,t.nickname)&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete()),this.#M(`clientEnter`,t);break}",
"case`clientEnter`:{let t=e.info,r=webSpeakDirectoryBigInt(arguments[1]?.cid??arguments[1]?.ctid??\"0\");r!==0n&&(t={...t,channelID:r},this.#c.set(t.id,t));let n=this.#c.get(t.id);n&&t.channelID===0n&&n.channelID!==0n&&(t={...t,channelID:n.channelID},this.#c.set(t.id,t));let i=t.id!==0&&N(this.nickname,t.nickname);i&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete(),this.#Y()),this.#M(`clientEnter`,t),!i&&this.#i===2&&this.#Y();break}",
],
[
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event);break;",
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),this.#i===2&&this.#Y(),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event),this.#i===2&&this.#Y();break;",
],
[
"#M(e,t){this.#S(t)}#N(e,t){",
"#Y(){if(this.#L)return;this.#L=!0,setImmediate(()=>{this.#L=!1;const e={channels:Array.from(this.#q.values()).map(e=>({...e})),clients:Array.from(this.#c.values()).map(e=>({...e,serverGroups:[...(e.serverGroups??[])]}))};for(const t of this.#R)setImmediate(()=>t(e))})}#M(e,t){this.#S(t)}#N(e,t){",
],
];
for (const [before, after] of replacements) {
if (!source.includes(before)) throw new Error(`Could not patch CJS SDK segment: ${before.slice(0, 80)}`);
source = source.replace(before, after);
}
return source;
}
function patchMjs(source) {
if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source;
const helper = `/* ${marker} */
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}}
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
`;
source = source.replace("var k = class", `${helper}var k = class`);
// Keep the readable ESM build behavior identical to the minified CJS build.
const replacements = [
[
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t;\n\treturn r !== 0 && n.delete(r), {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t, targetChannelID = J(e.params.ctid ?? \"\"), moved = targetChannelID !== 0n;\n\tif (r !== 0) {\n\t\tif (moved) {\n\t\t\tconst current = n.get(r);\n\t\t\tif (current) n.set(r, { ...current, channelID: targetChannelID });\n\t\t} else {\n\t\t\tn.delete(r);\n\t\t}\n\t}\n\treturn moved ? {\n\t\tkind: \"clientMoved\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\ttargetChannelID,\n\t\t\treasonID: i,\n\t\t\tinvokerID: Y(e.params.invokerid ?? \"\"),\n\t\t\tinvokerName: e.params.invokername ?? \"\",\n\t\t\tinvokerUID: e.params.invokeruid ?? \"\"\n\t\t}\n\t} : {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
],
[
"\t#c = /* @__PURE__ */ new Map();\n\t#l = [];",
"\t#c = /* @__PURE__ */ new Map();\n\t#q = /* @__PURE__ */ new Map();\n\t#R = [];\n\t#L = false;\n\t#l = [];",
],
[
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"directorySnapshot\":\n\t\t\t\tthis.#R.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
],
[
"this.#o.reset(), this.#s.reset(), this.#c.clear(), this.clid = 0",
"this.#o.reset(), this.#s.reset(), this.#q.clear(), this.#c.clear(), this.#L = false, this.clid = 0",
],
[
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":",
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"channellist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryChannel(t.params, S);\n\t\t\t\t\tif (e) this.#q.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"channelclientlist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryClient(t.params, S);\n\t\t\t\t\tif (e) this.#c.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"error\":",
],
[
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tconst directoryChanged = webSpeakDirectoryChannelNotification(t.name, t.params, S, this.#q);\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\tif (directoryChanged) this.#Y();\n\t\t\t\treturn;\n\t\t\t}",
],
[
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tt.id !== 0 && Z(this.nickname, t.nickname) && (this.clid = t.id, this.handler.setClientID(t.id), this.#o.signalWelcomeComplete()), this.#M(\"clientEnter\", t);\n\t\t\t\tbreak;\n\t\t\t}",
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tconst rawChannelID = webSpeakDirectoryBigInt(arguments[1]?.cid ?? arguments[1]?.ctid ?? \"0\");\n\t\t\t\tif (rawChannelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: rawChannelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst cached = this.#c.get(t.id);\n\t\t\t\tif (cached && t.channelID === 0n && cached.channelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: cached.channelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst own = t.id !== 0 && Z(this.nickname, t.nickname);\n\t\t\t\tif (own) {\n\t\t\t\t\tthis.clid = t.id;\n\t\t\t\t\tthis.handler.setClientID(t.id);\n\t\t\t\t\tthis.#o.signalWelcomeComplete();\n\t\t\t\t\tthis.#Y();\n\t\t\t\t}\n\t\t\t\tthis.#M(\"clientEnter\", t);\n\t\t\t\tif (!own && this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;\n\t\t\t}",
],
[
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), this.#i === n.Connected && this.#Y(), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
],
[
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tbreak;",
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tif (this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;",
],
[
"\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
"\t#Y() {\n\t\tif (this.#L) return;\n\t\tthis.#L = true;\n\t\tsetImmediate(() => {\n\t\t\tthis.#L = false;\n\t\t\tconst e = {\n\t\t\t\tchannels: Array.from(this.#q.values()).map((item) => ({ ...item })),\n\t\t\t\tclients: Array.from(this.#c.values()).map((item) => ({ ...item, serverGroups: [...(item.serverGroups ?? [])] })),\n\t\t\t};\n\t\t\tfor (const handler of this.#R) setImmediate(() => handler(e));\n\t\t});\n\t}\n\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
],
];
for (const [before, after] of replacements) {
if (!source.includes(before)) throw new Error(`Could not patch MJS SDK segment: ${before.slice(0, 80)}`);
source = source.replace(before, after);
}
return source;
}
+1
View File
@@ -332,6 +332,7 @@ 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),
webRtcEnabled: body.webRtcEnabled === true,
};
}
+14
View File
@@ -7,6 +7,7 @@ import { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpea
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 type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
export interface AdminSettingsInput {
target: string;
@@ -15,6 +16,7 @@ export interface AdminSettingsInput {
accessMode: AccessMode;
siteName: string;
welcomeText: string;
webRtcEnabled: boolean;
}
export interface ConnectionPolicy {
@@ -108,11 +110,17 @@ export class AdminService {
lastTestAt: settings.lastTestAt,
lastTestLatencyMs: settings.lastTestLatencyMs,
lastTestError: settings.lastTestError,
webRtcEnabled: settings.webRtcEnabled,
internalPort: 3040,
updatedAt: settings.updatedAt,
};
}
getWebRtcAudioOptions(): WebRtcAudioOptions {
const settings = this.database.getSettings();
return { enabled: settings.webRtcEnabled };
}
updateSettings(input: AdminSettingsInput): void {
const current = this.database.getSettings();
const settings = this.normalizeSettings(input, current);
@@ -252,6 +260,9 @@ export class AdminService {
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");
}
let encryptedPassword = current.tsPasswordEncrypted;
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
@@ -264,6 +275,7 @@ export class AdminService {
tsHost: target.host,
tsPort: target.port,
tsPasswordEncrypted: encryptedPassword,
webRtcEnabled: input.webRtcEnabled,
};
}
@@ -292,6 +304,7 @@ export class AdminService {
tsHost: settings.tsHost,
tsPort: settings.tsPort,
tsPasswordEncrypted: settings.tsPasswordEncrypted,
webRtcEnabled: settings.webRtcEnabled,
};
}
@@ -307,6 +320,7 @@ export class AdminService {
tsHost: legacy.tsHost,
tsPort: legacy.tsPort,
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
webRtcEnabled: current.webRtcEnabled,
}, "LEGACY_CONFIG_IMPORTED");
this.database.setMeta("legacy_config_imported", "1");
this.database.setMeta("legacy_import_notice_pending", "1");
+1
View File
@@ -48,6 +48,7 @@ async function main() {
certDir: hasCert ? CERT_DIR : undefined,
voiceBridgeOptions: {
joinTickets,
webRtc: () => adminService.getWebRtcAudioOptions(),
},
adminService,
logger,
+25 -2
View File
@@ -5,7 +5,7 @@ import { DatabaseSync } from "node:sqlite";
import type { AdminCredential } from "../security/admin-password.js";
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
export const DATABASE_SCHEMA_VERSION = 2;
export const DATABASE_SCHEMA_VERSION = 3;
export type AccessMode = "fixed" | "open";
export interface PersistedSettings {
@@ -19,6 +19,7 @@ export interface PersistedSettings {
lastTestAt: string | null;
lastTestLatencyMs: number | null;
lastTestError: string | null;
webRtcEnabled: boolean;
updatedAt: string;
}
@@ -29,6 +30,7 @@ export interface SettingsUpdate {
tsHost: string;
tsPort: number;
tsPasswordEncrypted: string | null;
webRtcEnabled: boolean;
}
export interface ManagedInviteRecord {
@@ -70,6 +72,10 @@ interface SettingsRow extends Record<string, unknown> {
last_test_at: string | null;
last_test_latency_ms: number | null;
last_test_error: string | null;
webrtc_enabled: number;
webrtc_public_host: string;
webrtc_udp_start: number;
webrtc_udp_end: number;
updated_at: string;
}
@@ -140,6 +146,7 @@ export class WebSpeakDatabase {
lastTestAt: row.last_test_at,
lastTestLatencyMs: row.last_test_latency_ms,
lastTestError: row.last_test_error,
webRtcEnabled: row.webrtc_enabled === 1,
updatedAt: row.updated_at,
};
}
@@ -349,6 +356,21 @@ export class WebSpeakDatabase {
`);
this.database.exec("PRAGMA user_version = 2");
});
version = 2;
}
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.
ALTER TABLE settings ADD COLUMN webrtc_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_enabled IN (0, 1));
ALTER TABLE settings ADD COLUMN webrtc_public_host TEXT NOT NULL DEFAULT '';
ALTER TABLE settings ADD COLUMN webrtc_udp_start INTEGER NOT NULL DEFAULT 40000 CHECK (webrtc_udp_start BETWEEN 1 AND 65535);
ALTER TABLE settings ADD COLUMN webrtc_udp_end INTEGER NOT NULL DEFAULT 40099 CHECK (webrtc_udp_end BETWEEN 1 AND 65535);
`);
this.database.exec("PRAGMA user_version = 3");
});
}
}
@@ -356,7 +378,7 @@ export class WebSpeakDatabase {
this.database.prepare(
`UPDATE settings SET
site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?,
ts_password_encrypted = ?, updated_at = ?
ts_password_encrypted = ?, webrtc_enabled = ?, updated_at = ?
WHERE id = 1`,
).run(
settings.siteName,
@@ -365,6 +387,7 @@ export class WebSpeakDatabase {
settings.tsHost,
settings.tsPort,
settings.tsPasswordEncrypted,
settings.webRtcEnabled ? 1 : 0,
now,
);
}
+1 -1
View File
@@ -1,4 +1,4 @@
import type { ClientInfo } from "@honeybbq/teamspeak-client";
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
import type { TSDirectorySnapshot } from "./ts-client.js";
type DirectoryDelta =
+1 -1
View File
@@ -10,7 +10,7 @@ import { createAdminRouter } from "../admin/admin-router.js";
import type { AdminService } from "../admin/admin-service.js";
import { AdminSessionStore } from "../admin/admin-session.js";
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
import { identityFromString } from "@honeybbq/teamspeak-client";
import { identityFromString } from "@echosixhiya/teamspeak-client";
import { JoinRateLimiter } from "./join-rate-limit.js";
export interface WebServerOptions {
+1 -1
View File
@@ -3,7 +3,7 @@ import {
generateIdentity,
type ClientOptions,
type Identity,
} from "@honeybbq/teamspeak-client";
} from "@echosixhiya/teamspeak-client";
import type { Logger } from "../logger.js";
import { normalizeTeamSpeakError } from "../errors.js";
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
+10 -28
View File
@@ -9,10 +9,10 @@ import {
generateIdentity,
type Identity,
type VoiceData,
type ChannelInfo,
type ClientInfo,
type DirectoryClientInfo,
type DirectorySnapshot,
type TextMessage,
} from "@honeybbq/teamspeak-client";
} from "@echosixhiya/teamspeak-client";
import type { Logger } from "../logger.js";
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
@@ -32,18 +32,8 @@ export interface TSVoiceData {
data: Buffer;
}
export interface TSDirectorySnapshot {
channels: ChannelInfo[];
clients: TSDirectoryClient[];
}
export interface TSDirectoryClient extends ClientInfo {
away?: boolean;
awayMessage?: string;
inputMuted?: boolean;
outputMuted?: boolean;
channelCommander?: boolean;
}
export type TSDirectorySnapshot = DirectorySnapshot;
export type TSDirectoryClient = DirectoryClientInfo;
export type TSChatScope = "channel" | "server" | "private";
@@ -172,12 +162,10 @@ export class TSClient extends EventEmitter {
} as TSVoiceData);
});
// The SDK patch exposes the directory that TeamSpeak sends during the
// normal client welcome sequence. The connect path also reconciles this
// event stream with a complete client-protocol snapshot.
(client as unknown as {
on(event: "directorySnapshot", handler: (snapshot: TSDirectorySnapshot) => void): unknown;
}).on("directorySnapshot", (snapshot) => {
// The SDK exposes the directory that TeamSpeak sends during the normal
// client welcome sequence. The connect path also reconciles this event
// stream with a complete client-protocol snapshot.
client.on("directorySnapshot", (snapshot) => {
this.emit("directorySnapshot", {
channels: snapshot.channels.slice(),
clients: snapshot.clients.slice(),
@@ -222,13 +210,7 @@ export class TSClient extends EventEmitter {
if (!this.client || !this.connected) return;
const targets = [...new Set(clientIds)].filter((clientId) => Number.isInteger(clientId) && clientId > 0 && clientId <= 65535 && clientId !== this.getClientId());
if (!targets.length) throw new Error("Whisper requires at least one valid target");
const whisperClient = this.client as unknown as {
sendWhisper?: (voiceData: Uint8Array, targetClientIds: number[], voiceCodec: number) => void;
};
if (typeof whisperClient.sendWhisper !== "function") {
throw new Error("TeamSpeak SDK whisper support is unavailable");
}
whisperClient.sendWhisper(data, targets, codec);
this.client.sendWhisper(data, targets, codec);
}
async sendTextMessage(scope: TSChatScope, message: string, targetId = 0n): Promise<void> {
+258 -4
View File
@@ -1,7 +1,7 @@
import { WebSocketServer, WebSocket } from "ws";
import type { IncomingMessage, Server } from "node:http";
import { createRequire } from "node:module";
import { identityFromString } from "@honeybbq/teamspeak-client";
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";
@@ -11,6 +11,7 @@ import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.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";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
@@ -19,9 +20,17 @@ const { OpusEncoder } = require("@discordjs/opus") as {
const HEARTBEAT_INTERVAL_MS = 30_000;
const AUDIO_FRAME_BYTES = 1_920;
// A browser audio frame is 20 ms of mono 48 kHz PCM. Keep the server-side
// WebSocket egress queue small enough that a slow browser cannot turn old
// voice into seconds of latency. Opus frames are variable-sized, so this is
// deliberately a conservative byte backpressure guard for roughly 10–20
// small Opus frames; the browser also enforces a time-based playback limit
// before scheduling decoded audio.
const MAX_SERVER_AUDIO_BUFFERED_BYTES = 4_096;
export interface VoiceBridgeOptions {
joinTickets: JoinTicketStore;
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
}
export interface AdminSessionSummary {
@@ -34,6 +43,35 @@ export interface AdminSessionSummary {
tsClientId: number | null;
channelId: string | null;
memberCount: number;
audio: AudioFlowStats;
}
export interface AudioFlowStats {
ingressFrames: number;
ingressDroppedFrames: number;
ingressFirstAt: number | null;
ingressLastAt: number | null;
ingressMaxGapMs: number;
tsSendFrames: number;
tsSendErrors: number;
tsSendFirstAt: number | null;
tsSendLastAt: number | null;
tsSendMaxGapMs: number;
tsEncodeMaxMs: number;
tsReceiveFrames: number;
tsReceiveFirstAt: number | null;
tsReceiveLastAt: number | null;
tsReceiveMaxGapMs: number;
egressFrames: number;
egressDroppedFrames: number;
egressFirstAt: number | null;
egressLastAt: number | null;
egressMaxGapMs: number;
egressSentFirstAt: number | null;
egressSentLastAt: number | null;
egressSentMaxGapMs: number;
egressPeakBufferedBytes: number;
egressFramesByClient: Record<string, number>;
}
interface ChannelMember {
@@ -62,6 +100,7 @@ interface WebClientEntry {
nickname: string;
rememberIdentity: boolean;
target: TeamSpeakTarget;
webrtcPublicHost?: string;
channelTree: unknown[];
members: Map<number, ChannelMember>;
eventLog: ServerEvent[];
@@ -70,6 +109,8 @@ interface WebClientEntry {
whisperActive: boolean;
isAlive: boolean;
reconnectTimer: ReturnType<typeof setTimeout> | null;
audio: AudioFlowStats;
webrtc: WebRtcAudioSession | null;
}
export class VoiceBridge {
@@ -100,6 +141,7 @@ export class VoiceBridge {
const { target, serverPassword, nickname } = connection;
const channelName = connection.channel;
const webrtcPublicHost = resolveWebRtcPublicHost(req);
let identity;
try {
identity = connection.identity ? identityFromString(connection.identity) : undefined;
@@ -136,6 +178,7 @@ export class VoiceBridge {
nickname,
rememberIdentity: connection.rememberIdentity === true,
target,
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
channelTree: [],
members: new Map(),
eventLog: [],
@@ -144,6 +187,8 @@ export class VoiceBridge {
whisperActive: false,
isAlive: true,
reconnectTimer: null,
audio: createAudioFlowStats(),
webrtc: null,
};
this.entries.set(entryId, entry!);
try {
@@ -238,6 +283,7 @@ export class VoiceBridge {
serverEventLog: entry!.eventLog,
whisperTargetIds: [...entry!.whisperTargetIds],
whisperActive: entry!.whisperActive,
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
});
sendJson({ type: "channelList", channels: entry!.channelTree });
@@ -392,12 +438,48 @@ export class VoiceBridge {
});
tsClient.on("voiceData", (data: TSVoiceData) => {
const receivedAt = Date.now();
if (entry!.audio.tsReceiveLastAt !== null) entry!.audio.tsReceiveMaxGapMs = Math.max(entry!.audio.tsReceiveMaxGapMs, receivedAt - entry!.audio.tsReceiveLastAt);
entry!.audio.tsReceiveFirstAt ??= receivedAt;
entry!.audio.tsReceiveLastAt = receivedAt;
entry!.audio.tsReceiveFrames++;
if (ws.readyState !== WebSocket.OPEN || data.clientId === selfId) return;
const webRtc = entry!.webrtc;
webRtc?.pushTeamSpeakVoice(data);
const now = receivedAt;
if (entry!.audio.egressLastAt !== null) entry!.audio.egressMaxGapMs = Math.max(entry!.audio.egressMaxGapMs, now - entry!.audio.egressLastAt);
entry!.audio.egressFirstAt ??= now;
entry!.audio.egressLastAt = now;
const sourceKey = String(data.clientId);
entry!.audio.egressFramesByClient[sourceKey] = (entry!.audio.egressFramesByClient[sourceKey] ?? 0) + 1;
// A negotiated WebRTC session owns the browser's realtime audio
// egress. Do not also send the same TeamSpeak packet over the
// reliable WebSocket, otherwise the browser plays two copies and
// the TCP path can still accumulate stale audio behind the peer.
if (webRtc) {
entry!.audio.egressFrames++;
return;
}
const packet = Buffer.allocUnsafe(3 + data.data.length);
packet[0] = data.codec;
packet.writeUInt16BE(data.clientId, 1);
data.data.copy(packet, 3);
ws.send(packet);
const bufferedBytes = ws.bufferedAmount;
entry!.audio.egressPeakBufferedBytes = Math.max(entry!.audio.egressPeakBufferedBytes, bufferedBytes);
if (bufferedBytes > MAX_SERVER_AUDIO_BUFFERED_BYTES) {
entry!.audio.egressDroppedFrames++;
return;
}
try {
ws.send(packet);
entry!.audio.egressFrames++;
const sentAt = Date.now();
if (entry!.audio.egressSentLastAt !== null) entry!.audio.egressSentMaxGapMs = Math.max(entry!.audio.egressSentMaxGapMs, sentAt - entry!.audio.egressSentLastAt);
entry!.audio.egressSentFirstAt ??= sentAt;
entry!.audio.egressSentLastAt = sentAt;
} catch {
entry!.audio.egressDroppedFrames++;
}
});
tsClient.on("textMessage", (message) => {
@@ -434,22 +516,57 @@ export class VoiceBridge {
if (isBinary) {
const frame = typeof data === "string" ? Buffer.from(data) : data;
if (!tsReady || frame.length !== AUDIO_FRAME_BYTES) {
entry!.audio.ingressDroppedFrames++;
sendProtocolError(sendJson, "INVALID_AUDIO_FRAME", "音频帧格式无效");
return;
}
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++;
const encodeStartedAt = Date.now();
try {
if (entry!.opusEncoder) {
const encoded = entry!.opusEncoder.encode(frame);
const encodedAt = Date.now();
entry!.audio.tsEncodeMaxMs = Math.max(entry!.audio.tsEncodeMaxMs, encodedAt - encodeStartedAt);
if (entry!.whisperActive && entry!.whisperTargetIds.size) tsClient.sendWhisper(encoded, [...entry!.whisperTargetIds], 4);
else tsClient.sendVoice(encoded, 4);
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 {
// A frame arriving during shutdown is safe to discard.
entry!.audio.tsSendErrors++;
}
return;
}
const command = parseClientCommand(typeof data === "string" ? data : data.toString("utf-8"));
const rawMessage = typeof data === "string" ? data : data.toString("utf-8");
const webRtcOffer = parseWebRtcOffer(rawMessage);
if (webRtcOffer) {
if (this.getWebRtcOptions()?.enabled !== true) {
sendProtocolError(sendJson, "WEBRTC_DISABLED", "WebRTC 音频传输未启用");
return;
}
if (!tsReady || session.state !== "connected") {
sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪");
return;
}
void this.handleWebRtcOffer(entry!, webRtcOffer, sendJson);
return;
}
if (isWebRtcStopMessage(rawMessage)) {
const webRtc = entry!.webrtc;
entry!.webrtc = null;
if (webRtc) void webRtc.close();
return;
}
const command = parseClientCommand(rawMessage);
if ("error" in command) {
sendProtocolError(sendJson, command.error.code, command.error.message);
return;
@@ -537,6 +654,7 @@ export class VoiceBridge {
tsClientId,
channelId,
memberCount: entry.members.size,
audio: { ...entry.audio },
};
});
}
@@ -558,6 +676,11 @@ export class VoiceBridge {
entry.reconnectTimer = null;
}
entry.opusEncoder = null;
const webRtc = entry.webrtc;
entry.webrtc = null;
if (webRtc) {
try { await webRtc.close(); } catch { /* peer teardown is idempotent */ }
}
entry.whisperTargetIds.clear();
entry.whisperActive = false;
entry.channelTree = [];
@@ -569,7 +692,7 @@ 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 }, "Client session torn down");
this.logger.info({ entryId: entry.id, reason, audio: { ...entry.audio } }, "Client session torn down");
}
private startHeartbeat(): void {
@@ -593,6 +716,85 @@ export class VoiceBridge {
const token = url.searchParams.get("ticket");
return token ? this.options.joinTickets.consume(token) : null;
}
private getWebRtcOptions(): WebRtcAudioOptions | undefined {
const configured = this.options.webRtc;
return typeof configured === "function" ? configured() : configured;
}
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 */ }
entry.webrtc = null;
}
const config = this.getWebRtcOptions();
if (!config?.enabled) return;
const peer = new WebRtcAudioSession({
connectionId: entry.id,
...(entry.webrtcPublicHost ? { publicHost: entry.webrtcPublicHost } : {}),
logger: this.logger,
onVoiceFrame: (data) => {
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);
} catch {
// A packet arriving while the TeamSpeak session is being replaced
// is discarded; the WebRTC peer remains independently closable.
}
},
onVoiceActivity: (clientIds) => {
if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "voiceActivity", clientIds });
},
});
entry.webrtc = peer;
try {
const answer = await peer.createAnswer(offer);
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");
} catch (error: unknown) {
if (entry.webrtc === peer) entry.webrtc = null;
try { await peer.close(); } catch { /* best effort */ }
this.logger.warn({ entryId: entry.id, err: error instanceof Error ? error.message : String(error) }, "WebRTC audio negotiation failed");
if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" });
}
}
}
function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
const origin = firstHeader(request.headers.origin);
const forwardedHost = firstHeader(request.headers["x-forwarded-host"]);
const directHost = firstHeader(request.headers.host);
for (const candidate of [origin, forwardedHost, directHost]) {
const host = normalizeWebRtcHost(candidate);
if (host) return host;
}
return undefined;
}
function firstHeader(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value[0] : value;
}
function normalizeWebRtcHost(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.split(",", 1)[0]?.trim();
if (!trimmed || trimmed.toLowerCase() === "null") return undefined;
try {
const parsed = new URL(trimmed.includes("://") ? trimmed : `https://${trimmed}`);
return parsed.hostname || undefined;
} catch {
return undefined;
}
}
async function handleCommand(
@@ -685,10 +887,62 @@ function sendProtocolError(sendJson: (message: Record<string, unknown>) => void,
sendJson({ type: "error", error: { code, message, recoverable: false } });
}
function parseWebRtcOffer(raw: string): WebRtcSessionDescription | null {
let value: unknown;
try { value = JSON.parse(raw); } catch { return 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 };
}
function isWebRtcStopMessage(raw: string): boolean {
try {
const value: unknown = JSON.parse(raw);
return isRecord(value) && value.type === "webrtcStop";
} catch {
return false;
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function isChannelRecord(value: unknown): value is { id: string; name: string } {
return Boolean(value) && typeof value === "object" && typeof (value as { id?: unknown }).id === "string" && typeof (value as { name?: unknown }).name === "string";
}
function createAudioFlowStats(): AudioFlowStats {
return {
ingressFrames: 0,
ingressDroppedFrames: 0,
ingressFirstAt: null,
ingressLastAt: null,
ingressMaxGapMs: 0,
tsSendFrames: 0,
tsSendErrors: 0,
tsSendFirstAt: null,
tsSendLastAt: null,
tsSendMaxGapMs: 0,
tsEncodeMaxMs: 0,
tsReceiveFrames: 0,
tsReceiveFirstAt: null,
tsReceiveLastAt: null,
tsReceiveMaxGapMs: 0,
egressFrames: 0,
egressDroppedFrames: 0,
egressFirstAt: null,
egressLastAt: null,
egressMaxGapMs: 0,
egressSentFirstAt: null,
egressSentLastAt: null,
egressSentMaxGapMs: 0,
egressPeakBufferedBytes: 0,
egressFramesByClient: {},
};
}
function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
return snapshot.channels.map((channel) => ({
id: String(channel.id),
+230
View File
@@ -0,0 +1,230 @@
import { randomInt } from "node:crypto";
import { createRequire } from "node:module";
import {
MediaStreamTrack,
RtpHeader,
RtpPacket,
RTCPeerConnection,
} from "werift";
import type { Logger as LoggerType } from "../logger.js";
import type { TSVoiceData } from "./ts-client.js";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
OpusEncoder: new (sampleRate: number, channels: number) => {
decode(data: Buffer): Buffer;
encode(data: Buffer): Buffer;
};
};
const AUDIO_SAMPLE_RATE = 48_000;
const AUDIO_FRAME_SAMPLES = 960;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
const AUDIO_CLOCK_INTERVAL_MS = 20;
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
// 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];
export interface WebRtcAudioOptions {
enabled: boolean;
}
export interface WebRtcSessionDescription {
type: "offer" | "answer";
sdp: string;
}
export interface WebRtcAudioSessionOptions {
connectionId: string;
publicHost?: string;
logger: LoggerType;
onVoiceFrame: (data: Buffer) => void;
onVoiceActivity: (clientIds: number[]) => void;
}
/**
* 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.
*/
export class WebRtcAudioSession {
readonly peer: RTCPeerConnection;
private readonly logger: LoggerType;
private readonly onVoiceFrame: (data: Buffer) => 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 activeSpeakerIds = new Set<number>();
private readonly opusPayloadTypes = new Set<number>();
private readonly audioTimer: ReturnType<typeof setInterval>;
private readonly activityTimer: ReturnType<typeof setInterval>;
private encoder: { encode(data: Buffer): Buffer } | null;
private sequenceNumber = randomInt(0, 65_536);
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
private closed = false;
constructor(options: WebRtcAudioSessionOptions) {
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
this.onVoiceFrame = options.onVoiceFrame;
this.onVoiceActivity = options.onVoiceActivity;
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
this.peer = new RTCPeerConnection({
iceServers: [],
iceUseIpv4: true,
iceUseIpv6: false,
iceUseTcp: false,
icePortRange: [...WEBRTC_UDP_PORT_RANGE] 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));
});
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track");
});
});
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
});
try {
this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
} catch (error: unknown) {
this.encoder = null;
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder");
}
if (!this.encoder) {
this.outgoingTrack.stop();
throw new Error("WebRTC mixer encoder is unavailable");
}
this.audioTimer = setInterval(() => this.flushAudio(), AUDIO_CLOCK_INTERVAL_MS);
this.audioTimer.unref?.();
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
this.activityTimer.unref?.();
this.peer.onconnectionstatechange = () => {
this.logger.info({ state: this.peer.connectionState }, "WebRTC connection state changed");
};
}
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
if (this.closed) throw new Error("WebRTC session is closed");
this.setOpusPayloadTypes(offer.sdp);
await this.peer.setRemoteDescription(offer);
const transceiver = this.peer.getTransceivers().find((candidate) => candidate.kind === "audio");
if (transceiver) await transceiver.sender.replaceTrack(this.outgoingTrack);
const answer = await this.peer.createAnswer();
await this.peer.setLocalDescription(answer);
const description = this.peer.localDescription;
if (!description) throw new Error("WebRTC answer was not created");
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
return { type: description.type, sdp: description.sdp };
}
pushTeamSpeakVoice(data: TSVoiceData): void {
if (this.closed || data.codec !== 4) return;
this.activeSpeakerIds.add(data.clientId);
let decoder = this.decoderByClient.get(data.clientId);
if (!decoder) {
try {
// @discordjs/opus exposes decoding on OpusEncoder instances too;
// there is no separate OpusDecoder constructor in that package.
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
this.decoderByClient.set(data.clientId, decoder);
} catch (error: unknown) {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
return;
}
}
try {
const pcm = decoder.decode(data.data);
if (pcm.length >= AUDIO_FRAME_BYTES) this.pendingFrames.set(data.clientId, pcm.subarray(0, AUDIO_FRAME_BYTES));
} catch {
// A malformed or codec-transition packet is discarded without touching
// the peer connection. The next valid Opus frame can recover the stream.
}
}
async close(): Promise<void> {
if (this.closed) return;
this.closed = true;
clearInterval(this.audioTimer);
clearInterval(this.activityTimer);
this.pendingFrames.clear();
this.activeSpeakerIds.clear();
this.decoderByClient.clear();
this.encoder = null;
this.outgoingTrack.stop();
await this.peer.close();
}
private flushAudio(): void {
if (this.closed || !this.encoder || !this.pendingFrames.size) return;
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);
}
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)));
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);
} 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 flushSpeakerActivity(): void {
if (this.closed || !this.activeSpeakerIds.size) return;
const ids = [...this.activeSpeakerIds];
this.activeSpeakerIds.clear();
this.onVoiceActivity(ids);
}
private setOpusPayloadTypes(sdp: string): void {
this.opusPayloadTypes.clear();
for (const match of sdp.matchAll(/^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?/gim)) {
const payloadType = Number(match[1]);
if (!Number.isInteger(payloadType) || payloadType < 0 || payloadType > 127) continue;
this.opusPayloadTypes.add(payloadType);
this.outgoingPayloadType = payloadType;
}
if (!this.opusPayloadTypes.size) this.opusPayloadTypes.add(DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE);
}
}
+3 -1
View File
@@ -111,11 +111,13 @@ test("admin API requires the default password to be changed before administratio
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",
@@ -137,7 +139,7 @@ test("admin API requires the default password to be changed before administratio
const sessions = await request(origin, "/api/admin/sessions", { cookie });
assert.deepEqual(sessions.body.sessions, []);
const diagnostics = await request(origin, "/api/admin/diagnostics", { cookie });
assert.equal(diagnostics.body.database.schemaVersion, 2);
assert.equal(diagnostics.body.database.schemaVersion, 3);
assert.equal("target" in diagnostics.body.teamSpeak, true);
assert.equal("protocol" in diagnostics.body.teamSpeak, false);
+4 -1
View File
@@ -54,6 +54,7 @@ test("legacy config imports once, seeds the default admin, and allows password r
accessMode: "open",
siteName: "Open WebSpeak",
welcomeText: "Public gateway",
webRtcEnabled: true,
});
const publicConfig = service.getPublicConfig();
assert.equal(publicConfig.target, "public.example.com:9987");
@@ -61,6 +62,8 @@ test("legacy config imports once, seeds the default admin, and allows password r
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();
});
@@ -106,7 +109,7 @@ test("managed invites are opaque, bounded, revocable, and included in database b
assert.ok(backup.length > 100);
database.close();
const reopened = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
assert.equal(reopened.schemaVersion, 2);
assert.equal(reopened.schemaVersion, 3);
assert.equal(reopened.listManagedInvites().length, 3);
reopened.close();
});
+1 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { ChannelInfo, ClientInfo } from "@honeybbq/teamspeak-client";
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: "", };
+1 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { generateIdentity } from "@honeybbq/teamspeak-client";
import { generateIdentity } from "@echosixhiya/teamspeak-client";
import { JoinTicketStore } from "../src/server/join-ticket.js";
test("join tickets are opaque, one-time, and expire", () => {
+8 -2
View File
@@ -23,6 +23,7 @@ test("SQLite persistence initializes schema and stores the single admin/settings
tsHost: "voice.example.com",
tsPort: 9988,
tsPasswordEncrypted: "v1:ciphertext",
webRtcEnabled: true,
});
assert.equal(database.hasAdmin(), true);
assert.equal(database.getAdminCredential()?.hash, credential.hash);
@@ -37,6 +38,7 @@ test("SQLite persistence initializes schema and stores the single admin/settings
lastTestAt: null,
lastTestLatencyMs: null,
lastTestError: null,
webRtcEnabled: true,
updatedAt: database.getSettings().updatedAt,
});
assert.equal(database.recentAudit()[0]?.event, "ADMIN_INITIALIZED");
@@ -48,7 +50,7 @@ test("SQLite persistence initializes schema and stores the single admin/settings
reopened.close();
});
test("SQLite schema v1 upgrades to v2 with a migration copy", () => {
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);
@@ -68,7 +70,11 @@ test("SQLite schema v1 upgrades to v2 with a migration copy", () => {
legacy.close();
const upgraded = new WebSpeakDatabase(dbPath);
assert.equal(upgraded.schemaVersion, 2);
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();
+1 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { generateIdentity } from "@honeybbq/teamspeak-client";
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";
+35
View File
@@ -0,0 +1,35 @@
const FRAME_SAMPLES = 960;
class WebSpeakMicCaptureProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.frame = new Float32Array(FRAME_SAMPLES);
this.offset = 0;
}
process(inputs, outputs) {
const input = inputs[0]?.[0];
const output = outputs[0]?.[0];
if (output) output.fill(0);
if (!input) return true;
let inputOffset = 0;
while (inputOffset < input.length) {
const count = Math.min(input.length - inputOffset, FRAME_SAMPLES - this.offset);
this.frame.set(input.subarray(inputOffset, inputOffset + count), this.offset);
this.offset += count;
inputOffset += count;
if (this.offset !== FRAME_SAMPLES) continue;
let sum = 0;
for (let index = 0; index < this.frame.length; index++) sum += this.frame[index] * this.frame[index];
const frame = this.frame;
this.frame = new Float32Array(FRAME_SAMPLES);
this.offset = 0;
this.port.postMessage({ samples: frame, rms: Math.sqrt(sum / FRAME_SAMPLES) }, [frame.buffer]);
}
return true;
}
}
registerProcessor("webspeak-mic-capture", WebSpeakMicCaptureProcessor);
+370 -34
View File
@@ -1,6 +1,8 @@
import { reactive, ref } from "vue";
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
const micCaptureWorkletUrl = "/mic-capture-worklet.js";
export interface VoiceState {
connected: boolean;
connecting: boolean;
@@ -80,16 +82,25 @@ export function useVoiceWebSocket() {
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 webrtcPeer: RTCPeerConnection | null = null;
let webrtcOutputSource: MediaStreamAudioSourceNode | null = null;
let webrtcOutputGain: GainNode | null = null;
let webrtcNegotiationPromise: Promise<void> | null = null;
let webrtcFallbackStarted = false;
const webrtcActive = ref(false);
const identityMaterial = ref("");
const storedVolumesByUid = reactive<Record<string, number>>({});
let microphoneStartPromise: Promise<void> | null = null;
// Audio capture. The ScriptProcessor path remains the most compatible option
// for the current browser support matrix, but the graph now has an explicit
// input gain and a silent output to avoid monitoring the microphone locally.
// WebRTC carries audio when the gateway advertises it. The bounded PCM
// WebSocket path remains the compatibility fallback for older browsers and
// for deployments where the gateway's built-in UDP media range is unavailable.
let audioCtx: SinkAudioContext | null = null;
let micStream: MediaStream | null = null;
let scriptNode: ScriptProcessorNode | null = null;
let workletNode: AudioWorkletNode | null = null;
let workletContext: AudioContext | null = null;
let workletModulePromise: Promise<void> | null = null;
let micSource: MediaStreamAudioSourceNode | null = null;
let micGain: GainNode | null = null;
let silentGain: GainNode | null = null;
@@ -113,7 +124,7 @@ export function useVoiceWebSocket() {
let voxAttack = 0;
let voxRelease = 0;
const VOX_HOLD = 15;
const VOX_ATTACK_FRAMES = 2;
const VOX_ATTACK_FRAMES = 1;
let convBuf = new Int16Array(1024);
let accumBuf = new Int16Array(2048);
let accumLen = 0;
@@ -121,7 +132,10 @@ export function useVoiceWebSocket() {
// Playback is kept per client so frames from multiple speakers cannot
// interleave into one decoder or one scheduling queue.
const remoteDecoders = new Map<number, AudioDecoder>();
const remoteDecoderGenerations = new Map<number, number>();
let nextRemoteDecoderGeneration = 0;
const remotePlayTimes = new Map<number, number>();
const remotePlaybackSources = new Map<number, Set<AudioBufferSourceNode>>();
const remoteGains = new Map<number, GainNode>();
const remoteDecodeTimestamps = new Map<number, number>();
const volumes = reactive<Record<number, number>>({});
@@ -130,8 +144,49 @@ export function useVoiceWebSocket() {
const whisperActive = ref(false);
const speakingTimers = new Map<number, ReturnType<typeof setTimeout>>();
const SPEAKING_HOLD_MS = 360;
const MAX_AUDIO_BUFFERED_BYTES = 192_000;
let droppedAudioFrames = 0;
const AUDIO_FRAME_SAMPLES = 960;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
const MAX_AUDIO_BUFFERED_FRAMES = 10;
const MAX_AUDIO_BUFFERED_BYTES = AUDIO_FRAME_BYTES * MAX_AUDIO_BUFFERED_FRAMES;
// Keep the WebSocket playback buffer below the 100 ms latency target. A
// 20 ms frame plus three queued decoder frames leaves only a short cushion
// 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({
@@ -295,18 +350,16 @@ export function useVoiceWebSocket() {
micSource = ctx.createMediaStreamSource(micStream);
micGain = ctx.createGain();
micGain.gain.value = inputVolume.value;
scriptNode = ctx.createScriptProcessor(1024, 1, 1);
silentGain = ctx.createGain();
silentGain.gain.value = 0;
scriptNode.onaudioprocess = (event) => {
const input = event.inputBuffer.getChannelData(0);
let sum = 0;
for (let i = 0; i < input.length; i++) sum += input[i] * input[i];
micLevel.value = Math.min(1, Math.sqrt(sum / Math.max(1, input.length)) * 6);
const handleCaptureChunk = (input: Float32Array, rms?: number): void => {
if (!input.length) return;
micLevel.value = Math.min(1, (rms ?? Math.sqrt(input.reduce((sum, sample) => sum + sample * sample, 0) / input.length)) * 6);
const socket = ws.value;
const shouldSend = !microphoneMuted.value
&& !microphoneTestActive.value
&& !webrtcActive.value
&& socket?.readyState === WebSocket.OPEN
&& voxGate(input);
if (!shouldSend) {
@@ -321,16 +374,18 @@ export function useVoiceWebSocket() {
accumLen = 0;
return;
}
if (socket.bufferedAmount > MAX_AUDIO_BUFFERED_BYTES) {
const bufferedBytes = socket.bufferedAmount;
audioCounters.peakBufferedBytes = Math.max(audioCounters.peakBufferedBytes, bufferedBytes);
if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) {
accumLen = 0;
droppedAudioFrames++;
audioCounters.uplinkDroppedFrames++;
publishAudioDiagnostics();
return;
}
markSpeaking(state.tsClientId);
if (convBuf.length < input.length) convBuf = new Int16Array(input.length);
for (let i = 0; i < input.length; i++) {
const sample = Math.max(-1, Math.min(1, input[i]));
const sample = Math.max(-1, Math.min(1, input[i]!));
convBuf[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
}
@@ -340,17 +395,50 @@ export function useVoiceWebSocket() {
accumLen = need;
let offset = 0;
while (offset + 960 <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) {
socket.send(accumBuf.slice(offset, offset + 960).buffer);
offset += 960;
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;
if (offset > 0) accumBuf.set(accumBuf.subarray(offset, offset + accumLen), 0);
};
if (typeof AudioWorkletNode !== "undefined" && ctx.audioWorklet) {
try {
if (workletContext !== ctx || !workletModulePromise) {
workletContext = ctx;
workletModulePromise = ctx.audioWorklet.addModule(micCaptureWorkletUrl);
}
await workletModulePromise;
workletNode = new AudioWorkletNode(ctx, "webspeak-mic-capture", {
numberOfInputs: 1,
numberOfOutputs: 1,
outputChannelCount: [1],
});
workletNode.port.onmessage = (event: MessageEvent<{ samples?: Float32Array; rms?: number }>) => {
const samples = event.data?.samples;
if (samples instanceof Float32Array) handleCaptureChunk(samples, event.data.rms);
};
} catch {
workletNode?.disconnect();
workletNode = null;
workletContext = null;
workletModulePromise = null;
}
}
if (!workletNode) {
scriptNode = ctx.createScriptProcessor(1024, 1, 1);
scriptNode.onaudioprocess = (event) => handleCaptureChunk(event.inputBuffer.getChannelData(0));
}
micSource.connect(micGain);
micGain.connect(scriptNode);
scriptNode.connect(silentGain);
const captureNode = workletNode ?? scriptNode!;
micGain.connect(captureNode);
captureNode.connect(silentGain);
silentGain.connect(ctx.destination);
await refreshAudioDevices();
}
@@ -383,24 +471,146 @@ export function useVoiceWebSocket() {
return false;
}
function stopMicrophone(closeContext = true): void {
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("没有可用的麦克风音轨");
stopCaptureGraph();
const peer = new RTCPeerConnection({ iceServers: [] });
webrtcPeer = peer;
webrtcFallbackStarted = false;
track.enabled = !microphoneMuted.value;
peer.addTrack(track, micStream);
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);
};
peer.onconnectionstatechange = () => {
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket);
};
const negotiation = (async () => {
webrtcActive.value = true;
const offer = await peer.createOffer();
await peer.setLocalDescription(offer);
await waitForIceGathering(peer);
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 } } }));
window.setTimeout(() => {
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket);
}, 8_000);
})();
webrtcNegotiationPromise = negotiation;
try {
await negotiation;
} catch (error) {
if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket);
throw error;
} finally {
if (webrtcNegotiationPromise === negotiation) webrtcNegotiationPromise = null;
}
}
async function waitForIceGathering(peer: RTCPeerConnection): Promise<void> {
if (peer.iceGatheringState === "complete") return;
await new Promise<void>((resolve) => {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
window.clearTimeout(timer);
peer.removeEventListener("icegatheringstatechange", onStateChange);
resolve();
};
const onStateChange = () => {
if (peer.iceGatheringState === "complete") finish();
};
const timer = window.setTimeout(finish, 5_000);
peer.addEventListener("icegatheringstatechange", onStateChange);
});
}
async function applyWebRtcAnswer(description: unknown): Promise<void> {
if (!webrtcPeer || !isSessionDescription(description, "answer")) return;
try {
await webrtcPeer.setRemoteDescription(description);
webrtcActive.value = true;
} catch {
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value);
}
}
async function fallbackFromWebRtc(sequence: number, socket: WebSocket): Promise<void> {
if (sequence !== connectionSequence || webrtcFallbackStarted) return;
webrtcFallbackStarted = true;
webrtcActive.value = false;
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: "webrtcStop" }));
stopWebRtcTransport();
if (socket.readyState === WebSocket.OPEN && state.connected) {
try { await startMicrophone(); } catch (error: unknown) {
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
}
}
}
function stopWebRtcTransport(): void {
const peer = webrtcPeer;
webrtcPeer = null;
webrtcActive.value = false;
webrtcNegotiationPromise = null;
webrtcOutputSource?.disconnect();
webrtcOutputGain?.disconnect();
webrtcOutputSource = null;
webrtcOutputGain = null;
if (peer) void peer.close();
}
function isSessionDescription(value: unknown, type: "answer"): value is RTCSessionDescriptionInit {
return Boolean(value) && typeof value === "object"
&& (value as { type?: unknown }).type === type
&& typeof (value as { sdp?: unknown }).sdp === "string";
}
function stopCaptureGraph(): void {
accumLen = 0;
voxAttack = 0;
voxRelease = 0;
micLevel.value = 0;
scriptNode?.disconnect();
workletNode?.port.close();
workletNode?.disconnect();
micGain?.disconnect();
micSource?.disconnect();
silentGain?.disconnect();
scriptNode = null;
workletNode = null;
micGain = null;
micSource = null;
silentGain = null;
}
function stopMicrophone(closeContext = true): void {
stopCaptureGraph();
micStream?.getTracks().forEach((track) => track.stop());
micStream = null;
if (closeContext) {
audioCtx?.close();
audioCtx = null;
workletContext = null;
workletModulePromise = null;
}
}
@@ -411,11 +621,17 @@ export function useVoiceWebSocket() {
async function setInputDevice(deviceId: string): Promise<void> {
const previousDeviceId = selectedInputDeviceId.value;
const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value);
selectedInputDeviceId.value = deviceId;
localStorage.setItem("webspeak:input-device", deviceId);
void saveAudioPreferences();
try {
if (shouldRestartWebRtc) stopWebRtcTransport();
if (micStream) await startMicrophone();
if (shouldRestartWebRtc && ws.value) {
stopWebRtcTransport();
await startWebRtcTransport(connectionSequence, ws.value);
}
await refreshAudioDevices();
} catch (error) {
selectedInputDeviceId.value = previousDeviceId;
@@ -511,16 +727,35 @@ export function useVoiceWebSocket() {
function playAudioFrame(clientId: number, opusData: Uint8Array): void {
if (opusData.length < 3) return;
let decoder = remoteDecoders.get(clientId);
const ctx = getAudioCtx();
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)
) {
resetRemotePlayback(clientId);
decoder = undefined;
}
if (!decoder) {
const ctx = getAudioCtx();
const gainNode = ctx.createGain();
gainNode.gain.value = (volumes[clientId] ?? 1) * outputVolume.value;
gainNode.connect(ctx.destination);
remoteGains.set(clientId, gainNode);
decoder = new AudioDecoder({
const generation = ++nextRemoteDecoderGeneration;
const nextDecoder = new AudioDecoder({
output: (chunk: AudioData) => {
if (remoteDecoderGenerations.get(clientId) !== generation) {
chunk.close();
return;
}
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);
@@ -530,20 +765,54 @@ export function useVoiceWebSocket() {
const source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(gainNode);
let sources = remotePlaybackSources.get(clientId);
if (!sources) {
sources = new Set<AudioBufferSourceNode>();
remotePlaybackSources.set(clientId, sources);
}
sources.add(source);
source.addEventListener("ended", () => {
source.disconnect();
sources?.delete(source);
if (sources?.size === 0) remotePlaybackSources.delete(clientId);
}, { once: true });
let playTime = remotePlayTimes.get(clientId) ?? ctx.currentTime;
if (playTime < ctx.currentTime) playTime = ctx.currentTime;
if (playTime + numberOfFrames / sampleRate > ctx.currentTime + MAX_REMOTE_PLAY_AHEAD_SECONDS) {
source.disconnect();
sources.delete(source);
if (sources.size === 0) remotePlaybackSources.delete(clientId);
chunk.close();
resetRemotePlayback(clientId);
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.
}
chunk.close();
},
error: () => {
remoteDecoders.delete(clientId);
if (remoteDecoderGenerations.get(clientId) === generation) {
remoteDecoderGenerations.delete(clientId);
remoteDecoders.delete(clientId);
}
},
});
decoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
nextDecoder.configure({ codec: "opus", sampleRate: 48000, numberOfChannels: 1 });
decoder = nextDecoder;
remoteDecoderGenerations.set(clientId, generation);
remoteDecoders.set(clientId, decoder);
}
@@ -551,11 +820,38 @@ 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.
}
}
function clearRemotePlayback(clientId: number): void {
const decoder = remoteDecoders.get(clientId);
if (decoder) {
try { decoder.close(); } catch { /* already closed */ }
}
remoteDecoders.delete(clientId);
remoteDecoderGenerations.delete(clientId);
remotePlayTimes.delete(clientId);
remoteDecodeTimestamps.delete(clientId);
const sources = remotePlaybackSources.get(clientId);
if (sources) {
for (const source of sources) {
try { source.stop(); } catch { /* already ended */ }
source.disconnect();
}
remotePlaybackSources.delete(clientId);
}
}
function resetRemotePlayback(clientId: number): void {
clearRemotePlayback(clientId);
audioCounters.playbackResets++;
publishAudioDiagnostics();
}
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false, inviteToken = ""): void {
disconnect(true);
lastConnection = { target, channel, nickname, serverPassword, ...(identity ? { identity } : {}), rememberIdentity };
@@ -600,9 +896,6 @@ export function useVoiceWebSocket() {
socket.close(1000);
return;
}
ensureMicrophone().catch((error: unknown) => {
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
});
};
socket.onmessage = (event) => {
if (typeof event.data === "string") {
@@ -621,6 +914,7 @@ export function useVoiceWebSocket() {
state.connecting = false;
state.reconnecting = false;
if (event.code !== 1000 && !state.error && !state.reconnectFailed) state.error = closeReason(event.code);
stopWebRtcTransport();
stopMicrophone();
whisperTargetIds.clear();
whisperActive.value = false;
@@ -652,6 +946,7 @@ export function useVoiceWebSocket() {
stopMicrophone();
const socket = ws.value;
ws.value = null;
stopWebRtcTransport();
if (socket && socket.readyState < WebSocket.CLOSING) socket.close(1000);
state.connected = false;
state.connecting = false;
@@ -664,8 +959,8 @@ export function useVoiceWebSocket() {
members.length = 0;
channels.length = 0;
chatMessages.length = 0;
for (const decoder of remoteDecoders.values()) decoder.close();
remoteDecoders.clear();
for (const clientId of new Set([...remoteDecoders.keys(), ...remotePlaybackSources.keys()])) clearRemotePlayback(clientId);
remoteDecoderGenerations.clear();
remotePlayTimes.clear();
remoteDecodeTimestamps.clear();
for (const gain of remoteGains.values()) gain.disconnect();
@@ -703,7 +998,18 @@ export function useVoiceWebSocket() {
if (lastConnection) lastConnection.identity = msg.identity;
}
if (wasReconnecting) {
ensureMicrophone().catch((error: unknown) => {
const start = msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined"
? (ws.value ? startWebRtcTransport(connectionSequence, ws.value) : Promise.resolve())
: ensureMicrophone();
start.catch((error: unknown) => {
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
});
} else if (msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined" && ws.value) {
void startWebRtcTransport(connectionSequence, ws.value).catch((error: unknown) => {
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
});
} else {
void ensureMicrophone().catch((error: unknown) => {
state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`;
});
}
@@ -715,8 +1021,10 @@ export function useVoiceWebSocket() {
}
break;
case "memberLeave": {
clearSpeaking(Number(msg.id));
const index = members.findIndex((member) => member.id === msg.id);
const clientId = Number(msg.id);
clearSpeaking(clientId);
clearRemotePlayback(clientId);
const index = members.findIndex((member) => member.id === clientId);
if (index >= 0) members.splice(index, 1);
break;
}
@@ -763,6 +1071,7 @@ export function useVoiceWebSocket() {
state.reconnecting = Boolean(msg.recoverable !== false);
state.reconnectFailed = false;
if (!state.reconnecting) state.error = "TeamSpeak 连接已断开";
stopWebRtcTransport();
stopMicrophone();
whisperTargetIds.clear();
whisperActive.value = false;
@@ -773,6 +1082,7 @@ export function useVoiceWebSocket() {
state.reconnecting = true;
state.reconnectFailed = false;
state.reconnectAttempt = Number(msg.attempt) || state.reconnectAttempt + 1;
stopWebRtcTransport();
stopMicrophone();
whisperTargetIds.clear();
whisperActive.value = false;
@@ -793,6 +1103,19 @@ export function useVoiceWebSocket() {
case "whisperTargets":
applyWhisperState(msg.targetIds, msg.active);
break;
case "webrtcAnswer":
void applyWebRtcAnswer(msg.payload?.sdp);
break;
case "webrtcError":
if (ws.value) void fallbackFromWebRtc(connectionSequence, ws.value);
break;
case "voiceActivity":
if (Array.isArray(msg.clientIds)) {
for (const clientId of msg.clientIds) {
if (typeof clientId === "number" && Number.isInteger(clientId) && clientId > 0) markSpeaking(clientId);
}
}
break;
case "error":
state.errorCode = String(msg.error?.code || "");
state.error = protocolErrorMessage(state.errorCode, String(msg.error?.message || msg.message || "操作失败"));
@@ -801,9 +1124,19 @@ export function useVoiceWebSocket() {
}
function handleAudioFrame(data: Uint8Array): void {
// WebRTC carries the realtime downlink after negotiation. Ignore any
// in-flight fallback WebSocket packets so a transport switch cannot
// produce duplicate or delayed playback.
if (webrtcActive.value) return;
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));
}
@@ -890,6 +1223,7 @@ export function useVoiceWebSocket() {
voxAttack = 0;
voxRelease = 0;
accumLen = 0;
if (webrtcActive.value) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
void saveAudioPreferences();
}
@@ -947,6 +1281,7 @@ export function useVoiceWebSocket() {
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;
void saveAudioPreferences();
}
@@ -980,6 +1315,7 @@ export function useVoiceWebSocket() {
outputDeviceSupported,
audioPermission,
audioContextState,
audioDiagnostics,
identityMaterial,
micLevel,
microphoneTestActive,
+16 -4
View File
@@ -36,6 +36,7 @@
<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>
</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>
@@ -91,7 +92,7 @@ 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: "", 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: "", webRtcEnabled: false, 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" }
@@ -150,6 +151,11 @@ const copy = {
connectionReady: "连接成功",
connectionFailed: "连接失败",
accessAndIdentity: "访问与站点信息",
webrtcSettings: "WebRTC 语音",
webrtcLead: "由当前 WebSpeak 网关直接提供低延迟语音传输,无需配置其他服务器。",
webrtcEnabled: "启用 WebRTC",
webrtcEnabledLead: "浏览器和网络支持时使用实时语音通道,否则自动回退到兼容模式。",
webrtcApplyHint: "保存后对新连接生效;已连接用户重新进入语音空间后使用新设置。媒体端口由网关自动管理。",
accessMode: "访客访问模式",
fixedMode: "仅限此 TeamSpeak 服务器",
fixedModeLead: "访客只需填写昵称,目标和密码由 WebSpeak 管理。",
@@ -291,6 +297,11 @@ const copy = {
connectionReady: "Connection ready",
connectionFailed: "Connection failed",
accessAndIdentity: "Access and site identity",
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.",
accessMode: "Guest access mode",
fixedMode: "Only this TeamSpeak server",
fixedModeLead: "Guests enter only a nickname; WebSpeak manages the target and password.",
@@ -402,7 +413,7 @@ 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" }); }
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; } }
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; } }
@@ -410,9 +421,9 @@ async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('con
async function copyInviteLink() { if (!createdInvite.value) return; try { await navigator.clipboard.writeText(createdInvite.value.link); showOperationNotice(tr('copiedLink')); } catch { errorMessage.value = tr('operationFailed'); } }
function showOperationNotice(message: string) { errorMessage.value = message; window.setTimeout(() => { if (errorMessage.value === message) errorMessage.value = ""; }, 2200); }
async function downloadBackup() { try { const response = await fetch("/api/admin/backup", { headers: { accept: "application/octet-stream" } }); if (!response.ok) throw new Error("BACKUP_FAILED"); const blob = await response.blob(); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url; anchor.download = `webspeak-backup-${new Date().toISOString().slice(0, 10)}.db`; anchor.click(); URL.revokeObjectURL(url); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } }
async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep" }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", 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 }; }
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 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); }
@@ -450,6 +461,7 @@ async function parseResponse(response: Response) { const value = await response.
@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}
.webrtc-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}.toggle-choice{margin:0}.webrtc-card>.field-help{margin-top:-8px}
@media(max-width:520px){.target-fields{grid-template-columns:1fr}}
/* Keep administration inside the browser viewport. Long data sets scroll in