Compare commits

..
30 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
illusia 9788e7fa1c release: prepare v0.1.2 2026-09-02 16:11:59 +08:00
illusia 66da7efe4a fix(web): align settings icons on narrow screens 2026-09-02 15:48:39 +08:00
illusia 3fb7000d02 feat(web): add prominent GitHub repository link 2026-09-02 15:35:54 +08:00
illusia 03c95abcf7 docs(deploy): simplify Docker startup and document demo 2026-09-02 12:51:43 +08:00
illusia d2ffbee873 refactor(admin): hide protocol details from users 2026-09-02 10:38:46 +08:00
illusia 413dbaf3a8 docs: record microphone mute update 2026-09-02 08:01:08 +08:00
illusia 9187d2faed fix(web): replace browser ptt with microphone mute 2026-09-02 07:52:54 +08:00
illusia af85a73c7d feat(web): optimize mobile client experience 2026-09-02 06:23:07 +08:00
31 changed files with 1989 additions and 446 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:
+47
View File
@@ -2,6 +2,51 @@
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
- Current-version badge and a direct changelog link on the welcome page, next to the prominent GitHub repository button.
- Mobile member actions through a three-dot menu, while desktop member actions remain available through the context menu.
### Changed
- Mobile and narrow-screen header controls now collapse longer labels into icons to preserve usable spacing.
- The welcome page and connected workspace now present the GitHub, version, changelog, admin, theme, language, exit, and microphone controls as a consistent responsive control group.
- The version shown on the welcome page is read from the gateway's public configuration so it stays aligned with the running backend.
- Consolidated the post-0.1.1 mobile voice controls, microphone mute replacement for focus-dependent PTT, automatic protocol detection, simplified Docker Compose startup, and live-demo documentation.
### Fixed
- Replaced the visually off-center settings glyph and normalized icon alignment for settings-related controls across the client.
- Fixed narrow-screen exit and microphone controls so their text-collapse rules apply correctly.
- Bounded browser and gateway voice buffering, reset stale browser playback queues, and exposed low-overhead in-memory audio counters for diagnosing jitter without per-frame log writes.
- Moved microphone frame assembly to an `AudioWorklet` with a compatibility fallback to `ScriptProcessorNode`; both paths emit fixed 960-sample frames.
## [0.1.1] — 2026-09-02
### Added
@@ -19,6 +64,8 @@ All notable changes to WebSpeak are documented here. Versions follow SemVer.
- The README architecture section now uses GitHub-native Markdown instead of a Mermaid rich-display block.
- The README badge set now uses stable static Shields badges without a repository-metadata 404 dependency.
- Version tags publish Windows/Linux deployment packages to GitHub Releases and publish the matching Docker image.
- Removed the focus-dependent normal browser Space-key PTT mode and replaced it with a one-click microphone mute/unmute control on desktop and mobile.
- Persisted the microphone mute state in browser preferences and suppresses upstream audio before it is sent to TeamSpeak while muted.
### Fixed
+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))"
+155 -31
View File
@@ -9,9 +9,12 @@
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/)
**在线 Demo:** [https://webspeak.example.invalid](https://webspeak.example.invalid)
**[中文](#中文)**<br />
[更新日志](#更新日志) · [为什么是 WebSpeak](#为什么是-webspeak) · [核心能力](#核心能力) · [架构](#架构) · [快速开始](#快速开始) · [首次登录与默认目标](#首次登录与默认目标) · [访问模式与邀请](#访问模式与邀请) · [音频与设备](#音频与设备) · [数据与安全边界](#数据与安全边界) · [旧版本升级](#旧版本升级) · [健康检查](#健康检查开发与验证) · [项目结构](#项目结构) · [已知边界](#已知边界) · [社区](#社区)
@@ -28,13 +31,33 @@ 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
- 优化移动端浏览器体验:频道、成员、聊天和语音操作适配窄屏;移动端成员操作提供三个点菜单,桌面端继续使用右键菜单。
- 将首页 GitHub 入口改为显眼按钮,并增加当前版本标识和更新日志入口;窄屏时自动收敛为图标,避免按钮文字互相挤占。
- 修复设置齿轮图标和相关操作按钮的对齐问题,统一设置、退出、麦克风等控制的触控尺寸与视觉反馈。
- 将上一个版本之后的移动端语音控制、闭麦替代按键说话、目标协议自动探测、Docker Compose 简化启动和在线 Demo 文档整理为本次版本内容。
#### 2026-09-02 · v0.1.1
- 汇总并正式发布浏览器客户端、管理员控制台、受控邀请、Session 运维、审计记录、诊断报告和 SQLite 备份能力。
- 修复晚进入 WebSpeak 的浏览器会话无法看到先进入成员的问题;连接建立后会完成目录同步,并合并分阶段成员事件。
- 修复私聊消息到达后网页端断开连接的问题,完善成员右键菜单、悬停高亮和语音活动状态展示。
- 完成中英文界面、默认 TeamSpeak 目标、旧版配置迁移和首次登录强制改密流程。
- 移除依赖页面焦点的普通空格键按键说话模式;改为桌面端和移动端均可用的一键闭麦/开麦,静音状态会保存在当前浏览器中。
- 闭麦会在上行音频发送前直接阻断声音,同时保留 VOX 语音激活、输入设备选择、音量与阈值调节能力。
- 发布流程稳定生成 Windows/Linux 部署包并同步发布 Docker 镜像;Docker 构建会正确处理依赖安装脚本。
- 简化 Docker Compose 部署:默认使用已发布镜像,自动创建并持久化数据卷,支持通过 `WEBSPEAK_PORT` 修改宿主机端口。
#### 2026-08-31 · v0.1.0
@@ -54,40 +77,73 @@ A self-hosted TeamSpeak 3 / TeamSpeak 6 web client and voice gateway. Join your
| 领域 | 已提供 |
| --- | --- |
| 语音 | Opus / PCM 桥接、自由麦、按键说话、VOX、连接状态与重连提示 |
| 语音 | Opus / PCM 桥接、可选 WebRTC 低延迟通道、VOX 语音激活、一键闭麦/开麦、连接状态与重连提示 |
| 设备 | 浏览器麦克风与扬声器选择、音量调节、实时输入电平、本地麦克风测试 |
| 频道 | 频道树、频道切换、成员移动、频道文字聊天、服务器事件与状态展示 |
| 成员 | 在线成员、发言绿色头像边框、Away 状态、私聊、Poke、昵称复制、成员音量 |
| 管理 | 默认账号首次登录强制改密、默认 TeamSpeak 目标、站点信息、真实连接测试 |
| 运维 | 活动 Session、邀请创建与撤销、审计事件、结构化日志、诊断报告、SQLite 备份 |
| 浏览器体验 | 响应式布局、移动端按住说话、紧凑滚动布局、浏览器本地收藏与最近连接 |
| 浏览器体验 | 响应式布局、桌面与移动端语音控制、紧凑滚动布局、浏览器本地收藏与最近连接 |
### 架构
| 层级 | 职责 | 连接 |
| --- | --- | --- |
| 浏览器会话 | 昵称、设备、频道、成员、文字和语音交互 | HTTPS / WSS → WebSpeak |
| 浏览器会话 | 昵称、设备、频道、成员、文字和语音交互 | HTTPS / WSS → WebSpeak;可选 WebRTC 音频 |
| WebSpeak 网关 | 会话管理、访问控制、语音桥接、目录同步、管理控制台 | TeamSpeak 客户端协议 |
| TeamSpeak 3 / 6 | 提供频道、成员、文字和语音服务 | 目标地址与语音端口 |
### 快速开始
#### 方式 A:从 Dockerfile 构建
#### 方式 A:Docker Compose(推荐)
Docker Compose 默认从 GitHub Container Registry 拉取已经发布的 WebSpeak 镜像,自动创建数据卷并启动服务。普通部署不需要本地 Node.js、编译工具或 Dockerfile 构建环境。
```bash
docker build -t webspeak:local .
docker volume create webspeak-data
docker run -d \
--name webspeak \
--restart unless-stopped \
-p 3040:3040 \
-v webspeak-data:/data \
webspeak:local
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
容器固定监听 `3040`,SQLite 数据库、安装级主密钥和日志保存在 `/data`。公网部署时,请在前面配置 HTTPS 反向代理;麦克风和部分浏览器音频能力需要安全上下文。
查看状态和日志:
#### 方式 B:源码运行
```bash
docker compose ps
docker compose logs -f webspeak
curl http://127.0.0.1:3040/health
```
启动完成后打开 [http://127.0.0.1:3040/](http://127.0.0.1:3040/)。首次进入管理后台 `/admin` 使用 `admin / admin`,并按提示修改密码。
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
```
容器内部监听 `3040`,并在 `40000–40099/UDP` 提供内置 WebRTC 媒体;SQLite 数据库、安装级主密钥和日志保存在 `/data`。Dockerfile 仅用于项目 CI、发布资产和开发者本地构建,不是普通用户的默认部署入口。
#### 方式 B:源码运行(开发者)
环境要求:
@@ -137,13 +193,19 @@ WebSpeak 的 HTTP 端口固定为 `3040`,TeamSpeak 默认语音端口为 `9987
进入语音空间后,在设置中可以:
- 选择浏览器检测到的麦克风与扬声器;
- 切换自由麦和按键说话;
- 一键闭麦或开麦;
- 调整输入、输出、通知音量与 VOX 阈值;
- 查看麦克风权限、实时输入电平和音频上下文状态;
- 使用最多 5 秒的本地麦克风测试,录音只在浏览器本地播放,不发送到 TeamSpeak。
设备标签由浏览器权限模型决定。首次选择设备前,浏览器可能要求授予麦克风权限;输出设备选择依赖浏览器支持,不支持时会明确回退到默认扬声器。
#### 可选 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`:
@@ -243,15 +305,38 @@ QQ群:`869500475`
WebSpeak brings TeamSpeak voice spaces to the browser. It is a self-hosted gateway and web client for TeamSpeak 3 and TeamSpeak 6: open a link, choose a nickname, and join from a modern browser without installing a desktop client.
**Live demo:** [https://webspeak.example.invalid](https://webspeak.example.invalid)
### 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
- Consolidated and officially released the browser client, administrator console, managed invites, session operations, audit records, diagnostics, and SQLite backup support.
- Fixed late WebSpeak browser sessions missing members who joined earlier by reconciling the directory after connect and merging staged member events.
- Fixed browser sessions disconnecting after receiving a private message, and improved member context menus, hover highlighting, and speaking-state presentation.
- Added the bilingual interface, default TeamSpeak target, legacy configuration migration, and mandatory first-login password rotation.
- Stabilized release publishing for Windows/Linux packages and the matching Docker image; Docker builds now handle the dependency patch script correctly.
- 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 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
@@ -271,40 +356,73 @@ WebSpeak brings TeamSpeak voice spaces to the browser. It is a self-hosted gatew
| Area | Included |
| --- | --- |
| Voice | Opus / PCM bridging, free mic, push-to-talk, VOX, 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 |
| Administration | Mandatory first-login password rotation, default TeamSpeak target, site information, and real connection tests |
| Operations | Active sessions, invite creation and revocation, audit events, structured logs, diagnostics, and SQLite backup |
| Browser experience | Responsive layouts, press-and-hold mobile PTT, compact scrolling regions, local favorites, and recent connections |
| Browser experience | Responsive layouts, desktop and mobile voice controls, compact scrolling regions, local favorites, and recent connections |
### Architecture
| Layer | Responsibility | Connection |
| --- | --- | --- |
| Browser session | Nickname, device, channel, member, text, and voice interactions | HTTPS / WSS → WebSpeak |
| 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 |
### Quick Start
#### Option A: Build with Docker
#### Option A: Docker Compose (recommended)
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
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
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
The container listens on `3040`. SQLite data, the installation master key, and logs are stored in `/data`. If `certs/cert.pem` and `certs/key.pem` are present, the service enables HTTPS directly; for public deployments, an HTTPS reverse proxy is recommended. Microphone access and some browser audio features require a secure context.
Check the service and health endpoint:
#### Option B: Run from source
```bash
docker compose ps
docker compose logs -f webspeak
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.
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
```
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.
#### Option B: Run from source (developers)
Requirements:
@@ -356,13 +474,19 @@ In open mode, DNS resolution is followed by blocking loopback, private, link-loc
Inside a voice space, the settings panel lets users:
- Choose a microphone and speaker detected by the browser.
- Switch between free mic and push-to-talk.
- Mute or unmute the microphone with one click.
- Adjust input, output, notification, and VOX-threshold volumes.
- Inspect microphone permission, live input level, and audio-context state.
- Run a local microphone test of up to five seconds; the recording is played in the browser and is not sent to TeamSpeak.
Device labels are controlled by the browser permission model. The first device selection may request microphone permission. Output-device selection depends on browser support; unsupported browsers clearly fall back to the default speaker.
#### 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:
+4 -3
View File
@@ -1,10 +1,11 @@
services:
webspeak:
image: ghcr.io/EchoSixHIYA/webspeak:latest
container_name: webspeak
image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest}
pull_policy: missing
restart: unless-stopped
ports:
- "3040:3040"
- "${WEBSPEAK_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.1",
"version": "0.1.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.1.1",
"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.1",
"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 -2
View File
@@ -208,7 +208,6 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
},
teamSpeak: {
status: overview.teamSpeak.status,
protocol: overview.teamSpeak.protocol,
lastTestAt: overview.teamSpeak.lastTestAt,
latencyMs: overview.teamSpeak.latencyMs,
lastError: overview.teamSpeak.lastError,
@@ -333,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,
};
}
@@ -402,7 +402,6 @@ interface AdminOverview {
teamSpeak: {
target: string;
status: string;
protocol: string | null;
lastTestAt: string | null;
latencyMs: number | null;
lastError: string | null;
+18 -4
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 {
@@ -88,6 +90,7 @@ export class AdminService {
getPublicConfig(): Record<string, unknown> {
const settings = this.database.getSettings();
return {
version: this.version,
initialized: this.isInitialized(),
siteName: settings.siteName,
welcomeText: settings.welcomeText,
@@ -104,15 +107,20 @@ export class AdminService {
accessMode: settings.accessMode,
siteName: settings.siteName,
welcomeText: settings.welcomeText,
detectedProtocol: settings.detectedProtocol,
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);
@@ -136,7 +144,7 @@ export class AdminService {
};
}
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<TeamSpeakProbeResult> {
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<Omit<TeamSpeakProbeResult, "protocol">> {
let target: TeamSpeakTarget;
try {
target = parseTeamSpeakTarget(targetText);
@@ -149,7 +157,8 @@ export class AdminService {
this.database.recordConnectionTest({ protocol: result.protocol, latencyMs: result.latencyMs, error: null });
this.database.addAudit("CONNECTION_TEST_SUCCEEDED", { protocol: result.protocol, latencyMs: result.latencyMs });
}
return result;
const { protocol: _protocol, ...publicResult } = result;
return publicResult;
} catch (error: unknown) {
const probeError = error instanceof TeamSpeakProbeError
? error
@@ -173,7 +182,6 @@ export class AdminService {
teamSpeak: {
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
status: settings.lastTestError ? "unreachable" : settings.lastTestAt ? "reachable" : "unknown",
protocol: settings.detectedProtocol,
lastTestAt: settings.lastTestAt,
latencyMs: settings.lastTestLatencyMs,
lastError: settings.lastTestError,
@@ -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);
}
}
+7 -3
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,13 +139,15 @@ 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);
const report = await request(origin, "/api/admin/diagnostics/report", { cookie });
assert.equal(report.response.status, 200);
assert.match(report.response.headers.get("content-disposition") ?? "", /diagnostic-report\.json/);
assert.equal("target" in report.body.teamSpeak, false);
assert.equal("protocol" in report.body.teamSpeak, false);
assert.equal("serverPassword" in report.body, false);
const revoked = await request(origin, `/api/admin/invites/${encodeURIComponent(invite.body.invite.id)}/revoke`, {
@@ -168,9 +172,9 @@ test("admin API requires the default password to be changed before administratio
csrf: login.body.csrfToken,
body: { target: "voice.example.com:9988", passwordAction: "remove" },
});
assert.equal(probe.body.protocol, "ts6");
assert.equal("protocol" in probe.body, false);
const settings = await request(origin, "/api/admin/server", { cookie });
assert.equal(settings.body.detectedProtocol, "ts6");
assert.equal("detectedProtocol" in settings.body, false);
assert.equal(settings.body.lastTestLatencyMs, 7);
const logout = await request(origin, "/api/admin/logout", { method: "POST", cookie, csrf: login.body.csrfToken, body: {} });
+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);
+2 -1
View File
@@ -26,8 +26,8 @@
<path d="M12 3v12m0 0 4-4m-4 4-4-4M4 19v2h16v-2" />
</template>
<template v-else-if="name === 'settings'">
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0L6.2 6.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-1.42 1.42-.06-.06a1.7 1.7 0 0 0-1.88-.34 1.7 1.7 0 0 0-1.03 1.56V20h-2v-.09a1.7 1.7 0 0 0-1.03-1.56 1.7 1.7 0 0 0-1.88.34l-.06.06-1.42-1.42.06-.06A1.7 1.7 0 0 0 9.4 15a1.7 1.7 0 0 0-1.56-1.03H7v-2h.84A1.7 1.7 0 0 0 9.4 11a1.7 1.7 0 0 0-.34-1.88L9 9.06l1.42-1.42.06.06a1.7 1.7 0 0 0 1.88.34A1.7 1.7 0 0 0 13.39 6.5V6h2v.5a1.7 1.7 0 0 0 1.03 1.54 1.7 1.7 0 0 0 1.88-.34l.06-.06 1.42 1.42-.06.06A1.7 1.7 0 0 0 19.4 11a1.7 1.7 0 0 0 1.56 1.03H21v2h-.04A1.7 1.7 0 0 0 19.4 15Z" />
</template>
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
@@ -69,6 +69,7 @@
<path v-else-if="name === 'waveform'" d="M3 12h2l2-6 3 12 3-9 2 6h6" />
<path v-else-if="name === 'shield'" d="M12 21s8-3.5 8-10V5l-8-3-8 3v6c0 6.5 8 10 8 10Z" />
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
<path v-else-if="name === 'github'" fill="currentColor" stroke="none" d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.53-1.33-1.28-1.68-1.28-1.68-1.04-.71.08-.7.08-.7 1.15.08 1.75 1.18 1.75 1.18 1.02 1.75 2.68 1.24 3.33.95.1-.74.4-1.24.73-1.52-2.55-.29-5.23-1.28-5.23-5.68 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.45.11-3.03 0 0 .96-.31 3.15 1.17.91-.25 1.88-.38 2.85-.38.97 0 1.94.13 2.85.38 2.19-1.48 3.15-1.17 3.15-1.17.62 1.58.23 2.74.11 3.03.73.8 1.18 1.82 1.18 3.07 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.04.78 2.1 0 1.52-.01 2.75-.01 3.12 0 .3.21.67.8.56C20.71 21.39 24 17.08 24 12 24 5.65 18.35.5 12 .5Z" />
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
<circle v-else cx="12" cy="12" r="8" />
</svg>
+387 -50
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;
@@ -105,8 +116,7 @@ export function useVoiceWebSocket() {
const testAudioUrl = ref("");
let testRecorder: MediaRecorder | null = null;
let testRecorderTimer: ReturnType<typeof setTimeout> | null = null;
let pttPressed = false;
const micMode = ref<"vox" | "ptt">("vox");
const microphoneMuted = ref(false);
const inputVolume = ref(1);
const outputVolume = ref(1);
const notificationVolume = ref(0.5);
@@ -114,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;
@@ -122,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>>({});
@@ -131,15 +144,56 @@ 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({
schemaVersion: 1,
preferredInputDeviceId: selectedInputDeviceId.value,
inputDeviceId: selectedInputDeviceId.value,
voiceMode: micMode.value,
microphoneMuted: microphoneMuted.value,
voxThreshold: voxThreshold.value,
inputGain: inputVolume.value,
outputVolume: outputVolume.value,
@@ -159,7 +213,7 @@ export function useVoiceWebSocket() {
void loadLocalPreferences().then((preferences) => {
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
if (preferences.voiceMode === "vox" || preferences.voiceMode === "ptt") micMode.value = preferences.voiceMode;
if (typeof preferences.microphoneMuted === "boolean") microphoneMuted.value = preferences.microphoneMuted;
if (typeof preferences.voxThreshold === "number") voxThreshold.value = clamp(preferences.voxThreshold, 0.001, 0.08);
if (typeof preferences.inputGain === "number") inputVolume.value = Math.max(0, Math.min(1, preferences.inputGain));
if (typeof preferences.outputVolume === "number") outputVolume.value = Math.max(0, Math.min(1, preferences.outputVolume));
@@ -296,37 +350,42 @@ 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 = !microphoneTestActive.value
const shouldSend = !microphoneMuted.value
&& !microphoneTestActive.value
&& !webrtcActive.value
&& socket?.readyState === WebSocket.OPEN
&& (micMode.value === "ptt" ? pttPressed : voxGate(input));
&& voxGate(input);
if (!shouldSend) {
accumLen = 0;
if (microphoneMuted.value) {
voxAttack = 0;
voxRelease = 0;
}
return;
}
if (!socket) {
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;
}
@@ -336,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();
}
@@ -379,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;
}
}
@@ -407,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;
@@ -507,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);
@@ -526,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);
}
@@ -547,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 };
@@ -596,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") {
@@ -617,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;
@@ -648,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;
@@ -660,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();
@@ -699,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 : "请检查浏览器权限"}`;
});
}
@@ -711,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;
}
@@ -759,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;
@@ -769,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;
@@ -789,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 || "操作失败"));
@@ -797,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));
}
@@ -881,16 +1218,15 @@ export function useVoiceWebSocket() {
connect(lastConnection.target, lastConnection.channel, lastConnection.nickname, lastConnection.serverPassword, lastConnection.rememberIdentity ? identityMaterial.value || lastConnection.identity : "", lastConnection.rememberIdentity);
}
function setMicMode(mode: "vox" | "ptt"): void {
micMode.value = mode;
if (mode === "vox") pttPressed = false;
function setMicrophoneMuted(muted: boolean): void {
microphoneMuted.value = muted;
voxAttack = 0;
voxRelease = 0;
accumLen = 0;
if (webrtcActive.value) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
void saveAudioPreferences();
}
function setPTT(pressed: boolean): void {
pttPressed = pressed;
}
function clearError(): void {
state.error = "";
state.errorCode = "";
@@ -945,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();
}
@@ -966,7 +1303,7 @@ export function useVoiceWebSocket() {
chatMessages,
serverEvents,
pokeNotifications,
micMode,
microphoneMuted,
inputVolume,
outputVolume,
notificationVolume,
@@ -978,6 +1315,7 @@ export function useVoiceWebSocket() {
outputDeviceSupported,
audioPermission,
audioContextState,
audioDiagnostics,
identityMaterial,
micLevel,
microphoneTestActive,
@@ -1009,8 +1347,7 @@ export function useVoiceWebSocket() {
setAway,
setWhisperTargets,
setWhisperActive,
setMicMode,
setPTT,
setMicrophoneMuted,
checkSupport,
clearError,
};
+1 -1
View File
@@ -33,7 +33,7 @@ export interface LocalPreferences {
schemaVersion: 1;
locale?: "auto" | "zh-CN" | "en";
theme?: "system" | "light" | "dark";
voiceMode?: "vox" | "ptt";
microphoneMuted?: boolean;
voxThreshold?: number;
language?: "zh" | "en";
preferredInputDeviceId?: string;
+22 -12
View File
@@ -36,8 +36,9 @@
<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('detectedProtocol') }}</dt><dd>{{ serverForm.detectedProtocol?.toUpperCase() || tr('unknown') }}</dd></div><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>
<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>
<section v-else-if="route.path === '/admin/operations'" class="page-content operations-page">
@@ -54,7 +55,7 @@
<div v-if="overview.legacyConfigImported" class="alert info import-notice"><span>{{ tr('legacyImported') }}</span><button type="button" @click="dismissLegacyNotice">{{ tr('gotIt') }}</button></div>
<div class="hero-status"><div><small>{{ tr('systemStatus') }}</small><h2>{{ tr('everythingRunning') }}</h2><p>{{ tr('overviewLead') }}</p></div><span class="status-badge"><i></i>{{ tr('running') }}</span></div>
<div class="metric-grid"><article><span><Icon name="activity" :size="20" /></span><small>{{ tr('gateway') }}</small><strong>{{ overview.gateway.version || '—' }}</strong><em>{{ formatUptime(overview.gateway.uptimeSeconds) }}</em></article><article><span><Icon name="server" :size="20" /></span><small>{{ tr('teamSpeakTarget') }}</small><strong>{{ overview.teamSpeak.target || '—' }}</strong><em>{{ targetStatusText }}</em></article><article><span><Icon name="users" :size="20" /></span><small>{{ tr('activeSessions') }}</small><strong>{{ overview.sessions.active }} / {{ overview.sessions.limit }}</strong><em>{{ tr('peakSessions', { count: overview.sessions.peak }) }}</em></article></div>
<div class="overview-columns"><article class="overview-card target-health-card"><header><div><h3>{{ tr('targetHealth') }}</h3><p>{{ tr('targetHealthLead') }}</p></div><RouterLink to="/admin/server">{{ tr('manage') }}</RouterLink></header><dl><div><dt>{{ tr('status') }}</dt><dd><i :class="overview.teamSpeak.status"></i>{{ targetStatusText }}</dd></div><div><dt>{{ tr('detectedProtocol') }}</dt><dd>{{ overview.teamSpeak.protocol?.toUpperCase() || tr('unknown') }}</dd></div><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(overview.teamSpeak.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ overview.teamSpeak.latencyMs == null ? '—' : `${overview.teamSpeak.latencyMs} ms` }}</dd></div></dl></article><article class="overview-card recent-events-card"><header><div><h3>{{ tr('recentEvents') }}</h3><p>{{ tr('recentEventsLead') }}</p></div></header><ul class="event-list"><li v-for="event in overview.recentEvents" :key="`${event.event}-${event.createdAt}`"><span><Icon name="check" :size="14" /></span><div><strong>{{ eventName(event.event) }}</strong><small>{{ formatDate(event.createdAt) }}</small></div></li><li v-if="!overview.recentEvents.length" class="empty-event">{{ tr('noRecentEvents') }}</li></ul></article></div>
<div class="overview-columns"><article class="overview-card target-health-card"><header><div><h3>{{ tr('targetHealth') }}</h3><p>{{ tr('targetHealthLead') }}</p></div><RouterLink to="/admin/server">{{ tr('manage') }}</RouterLink></header><dl><div><dt>{{ tr('status') }}</dt><dd><i :class="overview.teamSpeak.status"></i>{{ targetStatusText }}</dd></div><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(overview.teamSpeak.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ overview.teamSpeak.latencyMs == null ? '—' : `${overview.teamSpeak.latencyMs} ms` }}</dd></div></dl></article><article class="overview-card recent-events-card"><header><div><h3>{{ tr('recentEvents') }}</h3><p>{{ tr('recentEventsLead') }}</p></div></header><ul class="event-list"><li v-for="event in overview.recentEvents" :key="`${event.event}-${event.createdAt}`"><span><Icon name="check" :size="14" /></span><div><strong>{{ eventName(event.event) }}</strong><small>{{ formatDate(event.createdAt) }}</small></div></li><li v-if="!overview.recentEvents.length" class="empty-event">{{ tr('noRecentEvents') }}</li></ul></article></div>
</section>
</main>
</div>
@@ -71,7 +72,7 @@ import { applyTheme, getStoredTheme, nextTheme, saveTheme, type ThemeMode } from
type Language = "zh" | "en";
type Screen = "login" | "change-password" | "admin";
type AccessMode = "fixed" | "open";
interface ProbeState { ok: boolean; protocol?: string | null; latencyMs?: number; serverName?: string | null; code?: string }
interface ProbeState { ok: boolean; latencyMs?: number; serverName?: string | null; code?: string }
const route = useRoute();
const router = useRouter();
@@ -91,8 +92,8 @@ 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: "", detectedProtocol: null as string | null, lastTestAt: null as string | null, lastTestLatencyMs: null as number | null });
const overview = reactive({ gateway: { version: "", uptimeSeconds: 0 }, teamSpeak: { target: "", status: "unknown", protocol: null as string | null, 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 });
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" }
interface AdminLog { timestamp: string | null; level: string; message: string; context: Record<string, string | number | boolean> }
@@ -150,6 +151,11 @@ const copy = {
connectionReady: "连接成功",
connectionFailed: "连接失败",
accessAndIdentity: "访问与站点信息",
webrtcSettings: "WebRTC 语音",
webrtcLead: "由当前 WebSpeak 网关直接提供低延迟语音传输,无需配置其他服务器。",
webrtcEnabled: "启用 WebRTC",
webrtcEnabledLead: "浏览器和网络支持时使用实时语音通道,否则自动回退到兼容模式。",
webrtcApplyHint: "保存后对新连接生效;已连接用户重新进入语音空间后使用新设置。媒体端口由网关自动管理。",
accessMode: "访客访问模式",
fixedMode: "仅限此 TeamSpeak 服务器",
fixedModeLead: "访客只需填写昵称,目标和密码由 WebSpeak 管理。",
@@ -158,7 +164,6 @@ const copy = {
siteName: "站点显示名称",
welcomeText: "欢迎文本",
runtimeFacts: "运行时信息",
detectedProtocol: "检测到的协议",
lastTest: "最近测试",
latency: "延迟",
internalPort: "内部端口",
@@ -292,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.",
@@ -300,7 +310,6 @@ const copy = {
siteName: "Site display name",
welcomeText: "Welcome text",
runtimeFacts: "Runtime facts",
detectedProtocol: "Detected protocol",
lastTest: "Last test",
latency: "Latency",
internalPort: "Internal port",
@@ -392,7 +401,7 @@ const copy = {
function tr(key: keyof typeof copy.zh, vars: Record<string, string | number> = {}): string { let value: string = language.value === "zh" ? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; }
const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.value.length * 5 + (/[\s\W]/.test(newPassword.value) ? 15 : 0))));
const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : route.path === "/admin/operations" ? tr('operations') : tr('overview'));
const testResultText = computed(() => { if (!testResult.value) return ""; if (!testResult.value.ok) return errorText(testResult.value.code); return [testResult.value.protocol?.toUpperCase(), testResult.value.serverName, testResult.value.latencyMs == null ? null : `${testResult.value.latencyMs} ms`].filter(Boolean).join(" · "); });
const testResultText = computed(() => { if (!testResult.value) return ""; if (!testResult.value.ok) return errorText(testResult.value.code); return [testResult.value.serverName, testResult.value.latencyMs == null ? null : `${testResult.value.latencyMs} ms`].filter(Boolean).join(" · "); });
const targetStatusText = computed(() => overview.teamSpeak.status === "reachable" ? tr('reachable') : overview.teamSpeak.status === "unreachable" ? tr('unreachable') : tr('notTested'));
onMounted(loadAdminView);
@@ -404,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; } }
@@ -412,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 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.detectedProtocol = testResult.value.protocol ?? null; 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 }; }
async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", webRtcEnabled: result.settings.webRtcEnabled === true }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
async function testServerConnection() { await runTest("/api/admin/server/test", { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction }); if (testResult.value?.ok) { await loadOverview(); serverForm.lastTestAt = new Date().toISOString(); serverForm.lastTestLatencyMs = testResult.value.latencyMs ?? null; } }
function serverPayload() { return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText, webRtcEnabled: serverForm.webRtcEnabled }; }
async function 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); }
@@ -452,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
+221 -90
View File
@@ -1,5 +1,5 @@
<template>
<div class="web-client" @keydown="onKeyDown" @keyup="onKeyUp" tabindex="0">
<div class="web-client">
<!-- Connection / welcome screen -->
<section v-if="!voiceState.connected && !voiceState.reconnecting && !voiceState.reconnectFailed" class="join-page">
<header class="join-header">
@@ -10,7 +10,7 @@
<small>{{ t('browserWorkspace') }}</small>
</div>
</div>
<div class="header-tools"><div class="header-note"><span class="tiny-dot"></span> {{ t('secureGateway') }}</div><a class="guide-button" href="/admin"><Icon name="settings" :size="15" /> {{ t('adminConsole') }}</a><button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon name="monitor" :size="17" /></button><button class="language-switch" :aria-label="t('langSwitch')" @click="toggleLanguage">{{ t('langSwitch') }}</button></div>
<div class="header-tools"><div class="header-note"><span class="tiny-dot"></span> {{ t('secureGateway') }}</div><a class="github-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak" target="_blank" rel="noreferrer" :title="t('githubRepository')" :aria-label="t('githubRepository')"><Icon name="github" :size="18" /><span>{{ t('githubRepository') }}</span></a><span class="version-badge" :title="`${t('currentVersion')}: v${appVersion}`" :aria-label="`${t('currentVersion')}: v${appVersion}`">v{{ appVersion }}</span><a class="changelog-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/CHANGELOG.md" target="_blank" rel="noreferrer" :title="t('viewChangelog')" :aria-label="t('viewChangelog')"><Icon name="clock" :size="16" /><span>{{ t('viewChangelog') }}</span></a><a class="guide-button" href="/admin" :title="t('adminConsole')" :aria-label="t('adminConsole')"><Icon name="settings" :size="15" /><span>{{ t('adminConsole') }}</span></a><button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon name="monitor" :size="17" /></button><button class="language-switch" :aria-label="t('langSwitch')" @click="toggleLanguage">{{ t('langSwitch') }}</button></div>
</header>
<main class="join-content">
@@ -78,7 +78,7 @@
</main>
<footer class="join-footer">
<span>WebSpeak</span><span class="footer-separator">·</span><span>{{ t('teamSpeakClient') }}</span><span class="footer-spacer"></span><button type="button" class="clear-local-button" @click="clearBrowserData">{{ t('clearLocalData') }}</button><span class="footer-separator">·</span><a href="https://github.com/EchoSixHIYA/web-gateway-for-TeamSpeak" target="_blank" rel="noreferrer">{{ t('sourceCode') }}</a><span class="footer-separator">·</span><span>{{ t('browserSupport') }}</span>
<span>WebSpeak</span><span class="footer-separator">·</span><span>{{ t('teamSpeakClient') }}</span><span class="footer-spacer"></span><button type="button" class="clear-local-button" @click="clearBrowserData">{{ t('clearLocalData') }}</button><span class="footer-separator">·</span><span>{{ t('browserSupport') }}</span>
</footer>
</section>
@@ -95,10 +95,11 @@
</select>
</label>
<button class="header-action" :title="t('copyInvite')" @click="doShare"><Icon name="share" :size="18" /></button>
<button class="header-action microphone-header-toggle" :class="{ muted: microphoneMuted }" :title="microphoneMuted ? t('unmuteMic') : t('muteMic')" :aria-label="microphoneMuted ? t('microphoneMuted') : t('microphoneActive')" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /></button>
<button class="header-action" :title="t('audioSettings')" :aria-label="t('audioSettings')" @click="settingsOpen = true"><Icon name="settings" :size="18" /></button>
<button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon name="monitor" :size="17" /></button>
<button class="language-switch workspace-language" :aria-label="t('langSwitch')" @click="toggleLanguage">{{ t('langSwitch') }}</button>
<button class="disconnect-button" @click="doDisconnect"><Icon name="door" :size="17" /> {{ t('exit') }}</button>
<button class="disconnect-button" @click="doDisconnect"><Icon name="door" :size="17" /><span>{{ t('exit') }}</span></button>
</div>
</header>
@@ -125,6 +126,7 @@
<div class="section-heading"><div><span class="section-kicker">{{ t('voiceActivity') }}</span><h2>{{ t('speakingNow') }}</h2></div><span class="section-counter">{{ t('onlineShort', { count: currentMembers.length }) }}</span></div>
<div v-if="currentMembers.length" class="voice-grid">
<article v-for="member in roomMembers" :key="member.id" :class="['voice-card', { speaking: isSpeaking(member), self: member.isSelf }]">
<button v-if="isMobileViewport && !member.isSelf" type="button" class="voice-member-action" :aria-label="t('moreMemberOptions')" @click.stop="openMemberActions(member)"><Icon name="more" :size="17" /></button>
<div class="voice-avatar-wrap"><div :class="['voice-avatar', { speaking: isSpeaking(member) }]" :style="avatarStyle(member.nickname, member.isSelf)">{{ avatarInitial(member.nickname) }}</div></div>
<strong>{{ member.isSelf ? t('you') : member.nickname }}</strong><span>{{ isSpeaking(member) ? t('speaking') : member.isSelf ? t('connectedYou') : t('connected') }}</span>
</article>
@@ -136,6 +138,10 @@
<button type="button" class="text-button" @click="clearWhisperTargets">{{ t('clearWhisperTargets') }}</button>
<button type="button" class="whisper-ptt-button" :class="{ active: whisperPttActive || whisperActive }" :aria-pressed="whisperPttActive || whisperActive" @pointerdown.prevent="onWhisperPttDown" @pointerup.prevent="onWhisperPttUp" @pointercancel.prevent="onWhisperPttUp" @lostpointercapture="onWhisperPttUp"><Icon name="mic" :size="18" /> {{ whisperPttActive || whisperActive ? t('releaseWhisper') : t('whisperHoldToTalk') }}</button>
</div>
<div class="mobile-voice-controls">
<button type="button" class="mobile-voice-toggle" :class="{ muted: microphoneMuted }" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /><span>{{ microphoneMuted ? t('unmuteMic') : t('muteMic') }}</span></button>
<button type="button" class="mobile-voice-settings" @click="settingsOpen = true"><Icon name="settings" :size="17" /><span>{{ t('audioSettings') }}</span></button>
</div>
</section>
<section :class="['chat-panel', { 'mobile-section-hidden': mobileSection !== 'chat' }]">
@@ -163,7 +169,6 @@
<input v-model="messageDraft" maxlength="500" :placeholder="chatPlaceholder" :aria-label="t('send')" />
<button class="send-button" type="submit" :disabled="!messageDraft.trim()" :title="t('send')"><Icon name="send" :size="18" /></button>
</form>
<button v-if="micMode === 'ptt'" type="button" class="mobile-ptt-button" :class="{ active: pttActive }" @pointerdown.prevent="onMobilePttDown" @pointerup.prevent="onMobilePttUp" @pointercancel.prevent="onMobilePttUp" @lostpointercapture="onMobilePttUp"><Icon name="mic" :size="20" /> {{ pttActive ? t('releaseToTalk') : t('holdToTalk') }}</button>
</section>
</div>
</div>
@@ -186,6 +191,7 @@
<div class="member-copy"><strong>{{ memberDisplayName(member) }}</strong><span>{{ member.away ? t('away') : isSpeaking(member) ? t('speaking') : member.isSelf ? t('yourDevice') : t('memberOnline') }}</span></div>
<div class="member-flags" :aria-label="t('memberStates')"><span v-if="member.away" :title="t('away')" :aria-label="t('away')"><Icon name="clock" :size="13" /></span><span v-if="member.inputMuted" :title="t('inputMuted')" :aria-label="t('inputMuted')"><Icon name="mic-off" :size="13" /></span><span v-if="member.outputMuted" :title="t('outputMuted')" :aria-label="t('outputMuted')"><Icon name="volume-off" :size="13" /></span><span v-if="member.channelCommander" :title="t('channelCommander')" :aria-label="t('channelCommander')"><Icon name="shield" :size="13" /></span></div>
<div class="member-volume"><Icon :name="(volumes[member.id] ?? 1) === 0 ? 'volume-off' : 'volume'" :size="14" /><input type="range" min="0" max="400" :value="(volumes[member.id] ?? 1) * 100" :style="rangeStyle((volumes[member.id] ?? 1) / 4, 1)" :aria-label="t('memberVolume')" @input="onVolInput(member.id, $event)" /></div>
<button v-if="isMobileViewport && !member.isSelf" type="button" class="member-action-button" :aria-label="t('moreMemberOptions')" @click.stop="openMemberActions(member)"><Icon name="more" :size="18" /></button>
</div>
</div>
<div v-else class="channel-no-members">{{ t('noMembersInChannel') }}</div>
@@ -198,6 +204,7 @@
<section v-if="mobileSection === 'more'" class="mobile-more-panel">
<span class="section-kicker">{{ t('mobileMore') }}</span>
<h2>{{ t('mobileMore') }}</h2>
<button type="button" :class="{ muted: microphoneMuted }" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /> {{ microphoneMuted ? t('unmuteMic') : t('muteMic') }}</button>
<button type="button" @click="settingsOpen = true"><Icon name="settings" :size="18" /> {{ t('audioSettings') }}</button>
<button type="button" @click="cycleTheme"><Icon name="monitor" :size="18" /> {{ themeLabel }}</button>
<button type="button" @click="toggleLanguage"><Icon name="globe" :size="18" /> {{ t('langSwitch') }}</button>
@@ -212,8 +219,9 @@
</nav>
</div>
<div v-if="memberMenu && isMobileViewport" class="member-menu-backdrop" @click="memberMenu = null"></div>
<div v-if="memberMenu" class="member-context-menu" :style="memberMenuStyle" @click.stop>
<strong>{{ memberMenu.member.nickname }}</strong>
<div class="member-menu-header"><strong>{{ memberMenu.member.nickname }}</strong><button type="button" class="member-menu-close" :aria-label="t('close')" @click="memberMenu = null"><Icon name="close" :size="17" /></button></div>
<label class="menu-volume"><span>{{ t('memberVolume') }}</span><input type="range" min="0" max="400" :value="(volumes[memberMenu.member.id] ?? 1) * 100" :style="rangeStyle((volumes[memberMenu.member.id] ?? 1) / 4, 1)" :aria-label="t('memberVolume')" @input="onVolInput(memberMenu.member.id, $event)" /></label>
<button type="button" @click="openPrivateChat(memberMenu.member.id); memberMenu = null"><Icon name="message" :size="15" /> {{ t('privateMessage') }}</button>
<button type="button" @click="pokeMember(memberMenu.member); memberMenu = null"><Icon name="bell" :size="15" /> {{ t('poke') }}</button>
@@ -225,7 +233,7 @@
<div v-if="settingsOpen" class="modal-backdrop" @click.self="settingsOpen = false">
<section class="settings-modal" role="dialog" aria-modal="true" :aria-labelledby="'settings-title'">
<div class="settings-main"><header class="settings-header"><h2 id="settings-title">{{ t('audioConfiguration') }}</h2><button class="round-icon" :title="t('close')" @click="settingsOpen = false"><Icon name="close" :size="19" /></button></header><div class="settings-content">
<section class="settings-section"><h3><Icon name="mic" :size="20" /> {{ t('inputDevice') }}</h3><label class="settings-label" for="input-device">{{ t('microphone') }}</label><select id="input-device" class="settings-select" :value="selectedInputDeviceId" :disabled="!inputDevices.length" @change="onInputDeviceChange"><option value="">{{ t('defaultMicrophone') }}</option><option v-for="(device, index) in inputDevices" :key="device.deviceId || `microphone-${index}`" :value="device.deviceId">{{ device.label || t('microphoneNumber', { index: index + 1 }) }}</option></select><p v-if="audioSettingsError" class="settings-error">{{ localizedMessage(audioSettingsError) }}</p><p class="audio-diagnostic"><span>{{ t('permission') }}</span><strong :class="`permission-${audioPermission}`">{{ audioPermission === 'granted' ? t('permissionGranted') : audioPermission === 'denied' ? t('permissionDenied') : t('permissionUnknown') }}</strong></p><label class="settings-label">{{ t('microphoneMode') }}</label><div class="mic-mode-switch settings-mode-switch" role="group" :aria-label="t('microphoneMode')"><button type="button" :class="{ active: micMode === 'vox' }" @click="setMicMode('vox')"><Icon name="mic" :size="15" /> {{ t('freeMic') }}</button><button type="button" :class="{ active: micMode === 'ptt' }" @click="setMicMode('ptt')"><Icon name="lock" :size="14" /> {{ t('pushToTalk') }}</button></div><p class="settings-hint">{{ micMode === 'ptt' ? t('pushToTalkHint') : t('micReady') }}</p><div class="settings-range-row"><label class="settings-label">{{ t('inputVolume') }}</label><strong>{{ Math.round(inputVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="inputVolume * 100" :style="rangeStyle(inputVolume, 1)" :aria-label="t('inputVolume')" @input="onInputVolume" /><div v-if="micMode === 'vox'" class="settings-range-row"><label class="settings-label">{{ t('voxThreshold') }}</label><strong>{{ (voxThreshold * 100).toFixed(1) }}%</strong></div><input v-if="micMode === 'vox'" class="settings-range" type="range" min="1" max="80" :value="voxThreshold * 1000" :style="rangeStyle(voxThreshold, 0.08)" :aria-label="t('voxThreshold')" @input="onVoxThreshold" /><div class="audio-level-row"><span>{{ t('micLevel') }}</span><strong>{{ Math.round(micLevel * 100) }}%</strong></div><div class="audio-level-track"><i :style="{ width: `${Math.round(micLevel * 100)}%` }"></i></div><div class="mic-test"><div class="mic-test-header"><strong>{{ t('microphoneTest') }}</strong><button type="button" @click="toggleMicTest">{{ microphoneTestActive ? t('stopTest') : t('startTest') }}</button></div><div class="meter"><i v-for="index in 24" :key="index" :class="{ active: microphoneTestActive && index <= micMeterBars }" :style="{ height: `${meterBarHeight(index) }px` }"></i></div><div class="meter-labels"><span>{{ t('silence') }}</span><span>{{ t('optimal') }}</span><span>{{ t('loud') }}</span></div><p class="settings-hint">{{ t('localMicTestHint') }}</p><audio v-if="testAudioUrl" class="test-audio" :src="testAudioUrl" controls :aria-label="t('microphoneTest')"></audio></div></section>
<section class="settings-section"><h3><Icon name="mic" :size="20" /> {{ t('inputDevice') }}</h3><label class="settings-label" for="input-device">{{ t('microphone') }}</label><select id="input-device" class="settings-select" :value="selectedInputDeviceId" :disabled="!inputDevices.length" @change="onInputDeviceChange"><option value="">{{ t('defaultMicrophone') }}</option><option v-for="(device, index) in inputDevices" :key="device.deviceId || `microphone-${index}`" :value="device.deviceId">{{ device.label || t('microphoneNumber', { index: index + 1 }) }}</option></select><p v-if="audioSettingsError" class="settings-error">{{ localizedMessage(audioSettingsError) }}</p><p class="audio-diagnostic"><span>{{ t('permission') }}</span><strong :class="`permission-${audioPermission}`">{{ audioPermission === 'granted' ? t('permissionGranted') : audioPermission === 'denied' ? t('permissionDenied') : t('permissionUnknown') }}</strong></p><div class="microphone-control"><div><label class="settings-label">{{ t('microphoneState') }}</label><p class="settings-hint">{{ microphoneMuted ? t('microphoneMutedHint') : t('microphoneActiveHint') }}</p></div><button type="button" class="microphone-toggle" :class="{ muted: microphoneMuted }" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="16" /> {{ microphoneMuted ? t('unmuteMic') : t('muteMic') }}</button></div><div class="settings-range-row"><label class="settings-label">{{ t('inputVolume') }}</label><strong>{{ Math.round(inputVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="inputVolume * 100" :style="rangeStyle(inputVolume, 1)" :aria-label="t('inputVolume')" @input="onInputVolume" /><div class="settings-range-row"><label class="settings-label">{{ t('voxThreshold') }}</label><strong>{{ (voxThreshold * 100).toFixed(1) }}%</strong></div><input class="settings-range" type="range" min="1" max="80" :value="voxThreshold * 1000" :style="rangeStyle(voxThreshold, 0.08)" :aria-label="t('voxThreshold')" @input="onVoxThreshold" /><div class="audio-level-row"><span>{{ t('micLevel') }}</span><strong>{{ Math.round(micLevel * 100) }}%</strong></div><div class="audio-level-track"><i :style="{ width: `${Math.round(micLevel * 100)}%` }"></i></div><div class="mic-test"><div class="mic-test-header"><strong>{{ t('microphoneTest') }}</strong><button type="button" @click="toggleMicTest">{{ microphoneTestActive ? t('stopTest') : t('startTest') }}</button></div><div class="meter"><i v-for="index in 24" :key="index" :class="{ active: microphoneTestActive && index <= micMeterBars }" :style="{ height: `${meterBarHeight(index) }px` }"></i></div><div class="meter-labels"><span>{{ t('silence') }}</span><span>{{ t('optimal') }}</span><span>{{ t('loud') }}</span></div><p class="settings-hint">{{ t('localMicTestHint') }}</p><audio v-if="testAudioUrl" class="test-audio" :src="testAudioUrl" controls :aria-label="t('microphoneTest')"></audio></div></section>
<div class="settings-separator"></div><section class="settings-section"><h3><Icon name="volume" :size="20" /> {{ t('outputVolume') }}</h3><label v-if="outputDeviceSupported" class="settings-label" for="output-device">{{ t('outputDevice') }}</label><select v-if="outputDeviceSupported" id="output-device" class="settings-select" :value="selectedOutputDeviceId" :disabled="!outputDevices.length" @change="onOutputDeviceChange"><option value="">{{ t('defaultOutput') }}</option><option v-for="(device, index) in outputDevices" :key="device.deviceId || `speaker-${index}`" :value="device.deviceId">{{ device.label || t('speakerNumber', { index: index + 1 }) }}</option></select><p v-else class="mode-note"><Icon name="info" :size="16" /><span>{{ t('outputDeviceUnsupported') }}</span></p><div class="settings-range-row"><label class="settings-label">{{ t('speakers') }}</label><strong>{{ Math.round(outputVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="outputVolume * 100" :style="rangeStyle(outputVolume, 1)" :aria-label="t('outputVolume')" @input="onOutputVolume" /><div class="settings-range-row"><label class="settings-label">{{ t('notificationVolume') }}</label><strong>{{ Math.round(notificationVolume * 100) }}%</strong></div><input class="settings-range" type="range" min="0" max="100" :value="notificationVolume * 100" :style="rangeStyle(notificationVolume, 1)" :aria-label="t('notificationVolume')" @input="onNotificationVolume" /><div class="audio-diagnostic"><span>{{ t('audioStatus') }}</span><strong>{{ audioContextState === 'running' ? t('audioReady') : audioContextState === 'suspended' ? t('audioSuspended') : t('audioUnknown') }}</strong></div><div class="mode-note"><Icon name="shield" :size="16" /><span>{{ t('audioPrivacy') }}</span></div></section>
</div><footer class="settings-footer"><button class="primary-button save-button" @click="settingsOpen = false">{{ t('done') }}</button></footer></div>
</section>
@@ -255,7 +263,7 @@ const {
chatMessages,
serverEvents,
pokeNotifications,
micMode,
microphoneMuted,
inputVolume,
outputVolume,
notificationVolume,
@@ -298,8 +306,7 @@ const {
setAway,
setWhisperTargets,
setWhisperActive,
setMicMode,
setPTT,
setMicrophoneMuted,
checkSupport,
clearError,
} = useVoiceWebSocket();
@@ -320,6 +327,7 @@ const recentServers = ref<RecentServer[]>([]);
const initialized = ref(false);
const siteName = ref("WebSpeak");
const welcomeText = ref("");
const appVersion = ref("0.1.2");
const browserError = ref("");
const serverConfigLoading = ref(true);
const memberQuery = ref("");
@@ -327,7 +335,6 @@ const messageDraft = ref("");
const selectedChannelId = ref("");
const settingsOpen = ref(false);
const audioSettingsError = ref("");
const pttActive = ref(false);
const toast = ref("");
const chatListEl = ref<HTMLElement | null>(null);
const localPersistenceAvailable = isLocalPersistenceAvailable();
@@ -337,6 +344,7 @@ const away = ref(false);
const awayMessage = ref("");
const memberMenu = ref<{ member: ChannelMember; x: number; y: number } | null>(null);
const mobileSection = ref<"channels" | "chat" | "voice" | "more">("channels");
const isMobileViewport = ref(false);
const whisperPttActive = ref(false);
let toastTimer: ReturnType<typeof setTimeout> | undefined;
@@ -353,6 +361,8 @@ const translations: Record<Language, Record<string, string>> = {
browserWorkspace: "浏览器语音工作台",
secureGateway: "安全语音网关",
adminConsole: "管理控制台",
currentVersion: "当前版本",
viewChangelog: "查看更新日志",
notConfigured: "WebSpeak 尚未配置 TeamSpeak 目标。",
configureNow: "打开管理控制台",
privateAudio: "私密社区语音",
@@ -397,7 +407,7 @@ const translations: Record<Language, Record<string, string>> = {
connecting: "正在连接…",
enterVoice: "进入语音空间",
connectionAuthorized: "连接信息仅用于本次语音会话",
sourceCode: "获取源代码",
githubRepository: "GitHub 仓库",
browserSupport: "Chrome / Edge 94+",
teamSpeakClient: "TeamSpeak 浏览器客户端",
home: "首页",
@@ -474,13 +484,13 @@ const translations: Record<Language, Record<string, string>> = {
emojiUnavailable: "表情暂不可用",
sendMessagePlaceholder: "发送消息给频道成员…",
send: "发送",
freeMic: "自由麦",
pushToTalk: "按键说话",
pushToTalkHint: "按住空格说话",
holdToTalk: "按住说话",
releaseToTalk: "松开结束",
muteMic: "闭麦",
unmuteMic: "开麦",
microphoneActive: "麦克风已开启",
microphoneMuted: "麦克风已关闭",
microphoneActiveHint: "关闭麦克风后不会向服务器发送声音",
microphoneMutedHint: "麦克风已关闭,其他人听不到你的声音",
sending: "正在发送",
micReady: "麦克风已就绪",
exitVoice: "退出语音",
people: "成员",
searchMembers: "搜索成员",
@@ -514,7 +524,7 @@ const translations: Record<Language, Record<string, string>> = {
audioConfiguration: "音频配置",
inputDevice: "输入设备",
microphone: "麦克风",
microphoneMode: "麦克风模式",
microphoneState: "麦克风状态",
defaultMicrophone: "默认浏览器麦克风",
microphoneNumber: "麦克风 {{index}}",
speakerNumber: "扬声器 {{index}}",
@@ -568,6 +578,8 @@ const translations: Record<Language, Record<string, string>> = {
browserWorkspace: "Browser voice workspace",
secureGateway: "Secure voice gateway",
adminConsole: "Admin console",
currentVersion: "Current version",
viewChangelog: "View changelog",
notConfigured: "The WebSpeak TeamSpeak target has not been configured.",
configureNow: "Open admin console",
privateAudio: "Private community audio",
@@ -612,7 +624,7 @@ const translations: Record<Language, Record<string, string>> = {
connecting: "Connecting…",
enterVoice: "Enter voice space",
connectionAuthorized: "Connection details are used only for this voice session",
sourceCode: "Source code",
githubRepository: "GitHub repository",
browserSupport: "Chrome / Edge 94+",
teamSpeakClient: "TeamSpeak browser client",
home: "Home",
@@ -689,13 +701,13 @@ const translations: Record<Language, Record<string, string>> = {
emojiUnavailable: "Emoji unavailable",
sendMessagePlaceholder: "Message the channel…",
send: "Send",
freeMic: "Open mic",
pushToTalk: "Push to talk",
pushToTalkHint: "Hold Space to talk",
holdToTalk: "Hold to talk",
releaseToTalk: "Release to stop",
muteMic: "Mute mic",
unmuteMic: "Unmute mic",
microphoneActive: "Microphone on",
microphoneMuted: "Microphone off",
microphoneActiveHint: "When muted, no microphone audio is sent to the server",
microphoneMutedHint: "Your microphone is muted and other members cannot hear you",
sending: "Sending",
micReady: "Microphone ready",
exitVoice: "Leave voice",
people: "People",
searchMembers: "Search members",
@@ -729,7 +741,7 @@ const translations: Record<Language, Record<string, string>> = {
audioConfiguration: "Audio configuration",
inputDevice: "Input device",
microphone: "Microphone",
microphoneMode: "Microphone mode",
microphoneState: "Microphone state",
defaultMicrophone: "Default browser microphone",
microphoneNumber: "Microphone {{index}}",
speakerNumber: "Speaker {{index}}",
@@ -977,10 +989,7 @@ watch([rememberIdentity, identityMaterial], ([remember, material]) => {
if (!remember && material) identityMaterial.value = "";
});
watch(() => voiceState.connected, (connected) => {
if (!connected) {
stopPointerTalk();
return;
}
if (!connected) return;
playNotification("connected");
const address = currentServerTarget();
if (!address) return;
@@ -996,7 +1005,6 @@ watch(() => voiceState.connected, (connected) => {
});
watch(() => voiceState.reconnecting, (reconnecting, wasReconnecting) => {
if (reconnecting && !wasReconnecting) {
stopPointerTalk();
playNotification("disconnected");
}
});
@@ -1005,7 +1013,8 @@ watch(() => voiceState.reconnectFailed, (failed, wasFailed) => {
});
let deviceChangeHandler: (() => void) | undefined;
let releasePttHandler: (() => void) | undefined;
let viewportMediaQuery: MediaQueryList | undefined;
let viewportChangeHandler: (() => void) | undefined;
onMounted(() => {
browserError.value = checkSupport() ?? "";
@@ -1027,18 +1036,18 @@ onMounted(() => {
void listRecentServers().then((items) => { recentServers.value = items; });
deviceChangeHandler = () => { void refreshAudioDevices().catch(() => undefined); };
navigator.mediaDevices?.addEventListener("devicechange", deviceChangeHandler);
releasePttHandler = () => stopPointerTalk();
window.addEventListener("blur", releasePttHandler);
document.addEventListener("visibilitychange", releasePttHandler);
viewportMediaQuery = window.matchMedia("(max-width: 740px)");
viewportChangeHandler = () => {
isMobileViewport.value = viewportMediaQuery?.matches ?? false;
if (!isMobileViewport.value) memberMenu.value = null;
};
viewportChangeHandler();
viewportMediaQuery.addEventListener?.("change", viewportChangeHandler);
});
onUnmounted(() => {
stopPointerTalk();
disconnect();
if (deviceChangeHandler) navigator.mediaDevices?.removeEventListener("devicechange", deviceChangeHandler);
if (releasePttHandler) {
window.removeEventListener("blur", releasePttHandler);
document.removeEventListener("visibilitychange", releasePttHandler);
}
if (viewportMediaQuery && viewportChangeHandler) viewportMediaQuery.removeEventListener?.("change", viewportChangeHandler);
if (toastTimer) clearTimeout(toastTimer);
});
@@ -1057,7 +1066,6 @@ function doConnect() {
}
function doDisconnect() {
stopPointerTalk();
disconnect();
selectedChannelId.value = "";
showToast(t("leftToast"));
@@ -1147,7 +1155,8 @@ async function loadPublicConfig() {
try {
const response = await fetch("/api/public-config", { headers: { accept: "application/json" } });
if (!response.ok) return;
const config = await response.json() as { initialized?: unknown; siteName?: unknown; welcomeText?: unknown; accessMode?: unknown; target?: unknown };
const config = await response.json() as { version?: unknown; initialized?: unknown; siteName?: unknown; welcomeText?: unknown; accessMode?: unknown; target?: unknown };
if (typeof config.version === "string" && config.version.trim()) appVersion.value = config.version.trim();
initialized.value = config.initialized === true;
if (typeof config.siteName === "string" && config.siteName.trim()) siteName.value = config.siteName.trim();
if (typeof config.welcomeText === "string") welcomeText.value = config.welcomeText;
@@ -1177,6 +1186,7 @@ function openPrivateChat(clientId: number): void {
if (!clientId || clientId === voiceState.tsClientId) return;
privateClientId.value = clientId;
chatTab.value = "private";
if (isMobileViewport.value) mobileSection.value = "chat";
memberMenu.value = null;
nextTick(scrollChatToEnd);
}
@@ -1187,6 +1197,11 @@ function openMemberMenu(member: ChannelMember, event: Event): void {
memberMenu.value = { member, x: Math.min((point?.clientX ?? 20), Math.max(12, window.innerWidth - 210)), y: Math.min((point?.clientY ?? 20), Math.max(12, window.innerHeight - 170)) };
}
function openMemberActions(member: ChannelMember): void {
if (member.isSelf) return;
memberMenu.value = { member, x: 0, y: 0 };
}
function toggleWhisperTarget(member: ChannelMember): void {
if (member.isSelf) return;
const targets = new Set(whisperTargetIds);
@@ -1245,7 +1260,7 @@ function avatarStyle(name: string, isSelf = false) {
}
function isSpeaking(member: ChannelMember) {
return speakingIds.has(member.id) || Boolean(member.isSelf && pttActive.value);
return speakingIds.has(member.id);
}
function memberDisplayName(member: ChannelMember): string {
@@ -1328,47 +1343,9 @@ function meterBarHeight(index: number) {
return 5 + Math.round(intensity * 34);
}
function onKeyDown(event: KeyboardEvent) {
const target = event.target as HTMLElement | null;
if (target?.tagName === "INPUT" || target?.tagName === "TEXTAREA") return;
if (event.code === "Space" && micMode.value === "ptt" && !pttActive.value) {
event.preventDefault();
startPointerTalk();
}
}
function onKeyUp(event: KeyboardEvent) {
if (event.code === "Space" && micMode.value === "ptt") {
event.preventDefault();
stopPointerTalk();
}
}
function startPointerTalk() {
if (micMode.value !== "ptt") return;
pttActive.value = true;
setPTT(true);
}
function stopPointerTalk() {
if (pttActive.value) {
pttActive.value = false;
setPTT(false);
}
stopWhisperTalk();
}
function onMobilePttDown(event: PointerEvent) {
if (micMode.value !== "ptt") return;
const target = event.currentTarget as HTMLElement | null;
if (target?.setPointerCapture && !target.hasPointerCapture(event.pointerId)) target.setPointerCapture(event.pointerId);
startPointerTalk();
}
function onMobilePttUp(event: PointerEvent) {
const target = event.currentTarget as HTMLElement | null;
if (target?.releasePointerCapture && target.hasPointerCapture(event.pointerId)) target.releasePointerCapture(event.pointerId);
stopPointerTalk();
function toggleMicrophone(): void {
setMicrophoneMuted(!microphoneMuted.value);
showToast(microphoneMuted.value ? t("microphoneMuted") : t("microphoneActive"));
}
function onWhisperPttDown(event: PointerEvent): void {
@@ -1409,6 +1386,12 @@ function stopWhisperTalk(): void {
.brand-lockup strong span { color: #24312f; font-weight: 500; }
.brand-lockup small { display: block; margin-top: 2px; color: #7b8885; font-size: 10px; letter-spacing: .08em; text-transform: uppercase; }
.header-tools { display: flex; align-items: center; gap: 17px; }
.github-button { display: inline-flex; align-items: center; gap: 8px; min-height: 34px; padding: 0 13px; color: #fff; background: #1f2d2b; border: 1px solid #1f2d2b; border-radius: 9px; box-shadow: 0 5px 12px rgba(31,45,43,.16); font-size: 12px; font-weight: 800; text-decoration: none; transition: .18s; }
.github-button:hover { color: #fff; background: #006a64; border-color: #006a64; box-shadow: 0 7px 16px rgba(0,106,100,.2); transform: translateY(-1px); }
.github-button .ui-icon { flex: 0 0 auto; }
.version-badge { display: inline-flex; align-items: center; min-height: 30px; padding: 0 9px; color: #006a64; background: #e7f4f1; border: 1px solid #cfe9e4; border-radius: 999px; font-size: 11px; font-weight: 800; letter-spacing: .02em; white-space: nowrap; }
.changelog-button { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 30px; padding: 0 10px; color: #006a64; background: #f2f8f6; border: 1px solid #dcebe7; border-radius: 8px; font-size: 11px; font-weight: 700; text-decoration: none; transition: .18s; }
.changelog-button:hover { color: #fff; background: #006a64; border-color: #006a64; }
.header-note { display: flex; align-items: center; gap: 8px; color: #71807c; font-size: 12px; }
.language-switch { min-width: 50px; min-height: 28px; padding: 0 9px; color: #006a64; background: #e2f2ef; border: 1px solid #c8e6e1; border-radius: 7px; font-size: 10px; font-weight: 700; cursor: pointer; transition: .18s; }
.language-switch:hover { color: #fff; background: #006a64; border-color: #006a64; }
@@ -1643,6 +1626,7 @@ function stopWhisperTalk(): void {
/* Keep connected controls in the header; the old bottom dock consumed the
chat viewport and made the settings action appear detached from its icon. */
.header-tools { align-items: center; }
.header-action, .round-icon { line-height: 0; }
.guide-button { display: inline-flex; align-items: center; gap: 6px; min-height: 30px; padding: 0 10px; color: #006a64; background: #edf7f4; border: 1px solid #d7ebe6; border-radius: 8px; font-size: 12px; font-weight: 700; text-decoration: none; cursor: pointer; }
.guide-button:hover { color: #fff; background: #006a64; border-color: #006a64; }
.workspace-actions { align-items: center; flex-wrap: nowrap; }
@@ -1653,7 +1637,9 @@ function stopWhisperTalk(): void {
@media (max-width: 740px) {
.header-tools { gap: 7px; }
.header-note, .guide-button span { display: none; }
.header-note, .github-button span, .changelog-button span, .guide-button span { display: none; }
.github-button { width: 34px; justify-content: center; padding: 0; }
.changelog-button { width: 32px; min-width: 32px; min-height: 32px; padding: 0; }
.guide-button { width: 32px; justify-content: center; padding: 0; }
}
.chat-tabs { display: flex; align-items: center; gap: 6px; max-width: 100%; margin-top: 18px; overflow-x: auto; padding-bottom: 3px; }
@@ -1691,9 +1677,6 @@ function stopWhisperTalk(): void {
.audio-level-track { height: 7px; margin: 7px 0 17px; overflow: hidden; background: #e8efec; border-radius: 999px; }
.audio-level-track i { display: block; height: 100%; min-width: 0; background: linear-gradient(90deg, #69c8bb, #58d675); border-radius: inherit; transition: width .08s linear; }
.test-audio { display: block; width: 100%; height: 34px; margin-top: 11px; }
.mobile-ptt-button { display: none; align-items: center; justify-content: center; gap: 9px; min-height: 54px; margin-top: 12px; color: #fff; background: #006a64; border-radius: 12px; font-size: 14px; font-weight: 700; cursor: pointer; touch-action: none; user-select: none; }
.mobile-ptt-button.active { background: #2f9d5c; box-shadow: 0 0 0 4px rgba(47,157,92,.16); }
@media (max-width: 740px) { .mobile-ptt-button { display: flex; } }
/* M008 semantic theme tokens and keyboard-safe surfaces. */
:global(:root) { color-scheme: light; --surface-0: #f7f9f8; --surface-1: #fff; --surface-2: #f1f6f4; --text-primary: #192120; --text-muted: #71807c; --border: #e4ece9; --accent: #006a64; --success: #65d879; --warning: #c89143; --danger: #c95a54; }
@@ -1722,7 +1705,7 @@ function stopWhisperTalk(): void {
.member-row:hover, .member-row:focus-within { background: color-mix(in srgb, var(--accent) 10%, var(--surface-1)); box-shadow: 0 4px 12px color-mix(in srgb, var(--text-primary) 8%, transparent); }
:global(button:focus-visible), :global(a:focus-visible), :global(input:focus-visible), :global(select:focus-visible), :global(textarea:focus-visible) { outline: 3px solid color-mix(in srgb, var(--accent) 55%, transparent); outline-offset: 2px; }
.message-composer { position: sticky; bottom: env(safe-area-inset-bottom, 0px); z-index: 3; }
@media (max-width: 740px) { .workspace-scroll { overscroll-behavior: contain; }.workspace-content { width: min(100% - 24px, 650px); padding-bottom: calc(24px + env(safe-area-inset-bottom, 0px)); }.message-composer { margin-bottom: 8px; }.mobile-ptt-button { position: sticky; bottom: env(safe-area-inset-bottom, 0px); z-index: 3; } }
@media (max-width: 740px) { .workspace-scroll { overscroll-behavior: contain; }.workspace-content { width: min(100% - 24px, 650px); padding-bottom: calc(24px + env(safe-area-inset-bottom, 0px)); }.message-composer { margin-bottom: 8px; } }
@media (max-width: 740px) { .member-context-menu { left: 12px !important; right: 12px; top: auto !important; bottom: env(safe-area-inset-bottom, 0px); min-width: 0; border-radius: 16px 16px 0 0; padding: 14px; } .member-context-menu button { min-height: 42px; font-size: 13px; } .member-context-menu strong { padding: 4px 8px 11px; font-size: 14px; } .menu-volume { font-size: 12px; } }
/* M007 whisper target controls and M008 mobile navigation. */
@@ -1800,4 +1783,152 @@ function stopWhisperTalk(): void {
:global(:root[data-theme="dark"] *) { scrollbar-color: #438f88 transparent; }
:global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb) { background: #438f88; border-color: transparent; }
:global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb:hover) { background: #69c7bc; }
/* Mobile interaction pass: keep the browser viewport fixed and give each
mobile surface its own touch-friendly scroll area. */
.mobile-voice-controls, .voice-member-action, .member-action-button, .member-menu-backdrop { display: none; }
.microphone-header-toggle.muted { color: var(--danger); background: color-mix(in srgb, var(--danger) 12%, transparent); }
.microphone-control { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 18px; padding: 12px; background: var(--surface-2); border: 1px solid var(--border); border-radius: 11px; }
.microphone-control .settings-label { margin-bottom: 4px; }
.microphone-control .settings-hint { max-width: 390px; margin: 0; }
.microphone-toggle { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 38px; flex: 0 0 auto; padding: 0 12px; color: #fff; background: var(--accent); border-radius: 8px; font-size: 12px; font-weight: 700; cursor: pointer; }
.microphone-toggle.muted { color: var(--danger); background: color-mix(in srgb, var(--danger) 13%, var(--surface-1)); }
.member-menu-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.member-menu-close { display: none; }
@media (max-width: 740px) {
:global(html), :global(body), :global(#app) { height: 100%; min-height: 100%; max-height: none; }
.web-client { height: 100dvh; height: 100svh; min-height: 100dvh; min-height: 100svh; max-height: 100dvh; max-height: 100svh; }
.app-shell { height: 100dvh; height: 100svh; min-height: 100dvh; min-height: 100svh; max-height: 100dvh; max-height: 100svh; padding-bottom: calc(74px + env(safe-area-inset-bottom, 0px)); overflow: hidden; }
.app-shell .workspace { height: calc(100dvh - 74px - env(safe-area-inset-bottom, 0px)); height: calc(100svh - 74px - env(safe-area-inset-bottom, 0px)); min-height: 0; max-height: calc(100dvh - 74px - env(safe-area-inset-bottom, 0px)); max-height: calc(100svh - 74px - env(safe-area-inset-bottom, 0px)); overflow: hidden; }
.app-shell .workspace-scroll { height: 100%; min-height: 0; overflow-y: auto; overscroll-behavior: contain; scrollbar-gutter: stable; }
.workspace-header { min-height: calc(60px + env(safe-area-inset-top, 0px)); padding: env(safe-area-inset-top, 0px) 14px 0; box-sizing: border-box; position: sticky; top: 0; z-index: 6; background: color-mix(in srgb, var(--surface-1) 94%, transparent); backdrop-filter: blur(14px); }
.breadcrumbs { flex: 1 1 auto; min-width: 0; gap: 6px; font-size: 13px; }
.breadcrumbs .crumb-muted, .breadcrumbs > .ui-icon { display: none; }
.mobile-brand { display: inline; font-size: 18px; }
.workspace-actions { flex: 0 0 auto; gap: 3px; }
.workspace-actions .header-action { width: 36px; height: 36px; flex-basis: 36px; }
.workspace-actions .theme-toggle, .workspace-actions .workspace-language { display: none; }
.channel-switcher { max-width: 132px; min-height: 36px; padding-inline: 9px; }
.channel-switcher select { max-width: 92px; font-size: 12px; }
.disconnect-button { width: 36px; height: 36px; min-height: 36px; margin-left: 0; padding: 0; justify-content: center; }
.disconnect-button .ui-icon { display: block; margin: 0; }
.disconnect-button span { display: none; }
.workspace-content { display: block; width: 100%; max-width: none; min-height: 100%; margin: 0; padding: 14px 14px calc(18px + env(safe-area-inset-bottom, 0px)); box-sizing: border-box; }
.room-hero { min-height: 152px; padding: 22px 20px; border-radius: 18px; }
.room-hero h1 { margin-top: 14px; font-size: 25px; }
.room-hero p { max-width: 72%; font-size: 12px; }
.room-stats { margin-top: 15px; font-size: 11px; }
.hero-visual { right: -28px; bottom: -2px; transform: scale(.72); transform-origin: right bottom; }
.voice-section { margin-top: 21px; }
.section-heading { gap: 10px; }
.section-heading h2 { font-size: 22px; }
.voice-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin-top: 14px; }
.voice-card { position: relative; min-height: 136px; padding: 18px 8px 14px; border-radius: 16px; }
.voice-avatar-wrap, .voice-avatar { width: 60px; height: 60px; }
.voice-avatar-wrap { margin-bottom: 10px; }
.voice-avatar { font-size: 18px; }
.voice-status { width: 21px; height: 21px; }
.app-shell .voice-card > strong { max-width: 100%; font-size: 14px; }
.app-shell .voice-card > span { margin-top: 4px; font-size: 11px; }
.voice-member-action { position: absolute; top: 7px; right: 7px; display: grid; place-items: center; width: 34px; height: 34px; color: var(--text-muted); background: color-mix(in srgb, var(--surface-2) 78%, transparent); border-radius: 10px; cursor: pointer; }
.voice-member-action:hover, .voice-member-action:active { color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, var(--surface-1)); }
.mobile-voice-controls { display: flex; align-items: stretch; gap: 8px; margin-top: 14px; padding: 8px; background: var(--surface-2); border: 1px solid var(--border); border-radius: 14px; }
.mobile-voice-toggle, .mobile-voice-settings { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 44px; min-width: 0; padding: 0 11px; color: var(--accent); background: var(--surface-1); border: 1px solid var(--border); border-radius: 10px; font-size: 12px; font-weight: 700; cursor: pointer; }
.mobile-voice-toggle { flex: 1 1 auto; }
.mobile-voice-toggle.muted, .mobile-more-panel button.muted { color: var(--danger); }
.mobile-voice-settings { flex: 0 0 auto; width: 82px; }
.mobile-voice-settings span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.app-shell .member-panel.mobile-section-visible { display: flex !important; flex: 1 1 auto; width: 100%; height: auto; min-height: 0; max-height: none; padding: 18px 14px 16px; border-top: 0; border-right: 0; overflow: hidden; }
.member-panel-heading { flex: 0 0 auto; }
.member-panel-heading h2 { font-size: 23px; }
.status-button { min-height: 34px; padding-inline: 10px; font-size: 12px; }
.member-search { flex: 0 0 auto; min-height: 44px; margin-top: 14px; padding: 0 12px; border-radius: 11px; }
.member-search input { font-size: 15px; }
.app-shell .member-panel .member-tree { flex: 1 1 auto; min-height: 0; max-height: none; margin-top: 12px; padding: 0 2px 4px 0; overflow-y: auto; scrollbar-gutter: stable; }
.member-channel-group { padding: 7px 0 12px; }
.member-channel-heading { min-height: 44px; padding: 0 9px; border-radius: 11px; font-size: 14px; }
.member-channel-heading small { font-size: 12px; }
.member-list { gap: 3px; margin-top: 5px; }
.member-row { min-height: 58px; margin: 0; padding: 7px 7px; gap: 9px; border-radius: 12px; }
.member-avatar { width: 40px; height: 40px; border-radius: 12px; font-size: 12px; }
.member-presence { width: 10px; height: 10px; }
.member-copy strong { font-size: 14px; }
.member-copy span { margin-top: 3px; font-size: 12px; }
.member-flags, .member-volume, .member-panel-tip { display: none; }
.member-action-button { display: grid; place-items: center; width: 38px; height: 38px; flex: 0 0 38px; color: var(--text-muted); background: transparent; border-radius: 10px; cursor: pointer; }
.member-action-button:hover, .member-action-button:active { color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, var(--surface-1)); }
.app-shell.mobile-view-chat .workspace-scroll { overflow: hidden; }
.app-shell.mobile-view-chat .workspace-content { display: flex; flex-direction: column; min-height: 100%; padding: 0 14px calc(8px + env(safe-area-inset-bottom, 0px)); }
.app-shell.mobile-view-chat .chat-panel { display: flex; flex: 1 1 auto; flex-direction: column; min-height: 0; margin-top: 0; padding: 0; border-top: 0; }
.app-shell.mobile-view-chat .chat-tabs { flex: 0 0 auto; margin-top: 0; padding: 10px 0 9px; border-bottom: 1px solid var(--border); scrollbar-width: none; }
.app-shell.mobile-view-chat .chat-tabs::-webkit-scrollbar { display: none; }
.app-shell.mobile-view-chat .chat-heading { flex: 0 0 auto; padding: 13px 0 9px; }
.app-shell.mobile-view-chat .chat-heading h2 { font-size: 21px; }
.app-shell.mobile-view-chat .message-list { flex: 1 1 auto; min-height: 0; max-height: none; padding: 10px 2px 16px; overflow-y: auto; overscroll-behavior: contain; }
.app-shell.mobile-view-chat .message-row { max-width: 94%; gap: 9px; }
.app-shell.mobile-view-chat .message-avatar { width: 36px; height: 36px; }
.app-shell.mobile-view-chat .message-meta strong { font-size: 12px; }
.app-shell.mobile-view-chat .message-bubble { padding: 10px 12px; font-size: 14px; }
.app-shell.mobile-view-chat .message-composer { position: relative; flex: 0 0 auto; min-height: 54px; margin: 0 0 4px; padding: 7px 8px 7px 13px; border: 1px solid var(--border); }
.app-shell.mobile-view-chat .message-composer input { font-size: 14px; }
.mobile-more-panel { width: calc(100% - 28px); max-height: none; margin: 16px auto 0; padding: 18px; border-radius: 18px; overflow-y: auto; }
.mobile-more-panel h2 { font-size: 25px; }
.mobile-more-panel button { min-height: 52px; font-size: 14px; }
.mobile-nav { min-height: 74px; padding: 8px 8px calc(8px + env(safe-area-inset-bottom, 0px)); }
.mobile-nav button { min-height: 52px; font-size: 12px; }
.member-menu-backdrop { position: fixed; z-index: 39; inset: 0; display: block; background: rgba(13, 29, 26, .38); backdrop-filter: blur(2px); }
.member-context-menu { z-index: 40; left: 10px !important; right: 10px; top: auto !important; bottom: calc(74px + env(safe-area-inset-bottom, 0px)) !important; min-width: 0; max-height: calc(100svh - 100px); padding: 12px; border-radius: 18px; box-shadow: 0 18px 42px rgba(13, 38, 33, .25); }
.member-menu-header strong { padding: 4px 8px 11px; font-size: 16px; }
.member-menu-close { display: grid; place-items: center; width: 36px; height: 36px; flex: 0 0 36px; padding: 0 !important; color: var(--text-muted); background: var(--surface-2); border-radius: 10px; }
.member-context-menu button { min-height: 50px; padding: 8px 10px; border-radius: 10px; font-size: 14px; }
.member-context-menu .member-menu-close { min-height: 36px; }
.menu-volume { padding: 5px 8px 11px; font-size: 12px; }
.menu-volume input { height: 7px; }
.modal-backdrop { align-items: flex-end; padding: 0; }
.settings-modal { width: 100%; max-height: calc(100svh - env(safe-area-inset-top, 0px)); border-radius: 22px 22px 0 0; }
.settings-main { min-height: 0; overflow: hidden; }
.settings-header { min-height: 64px; padding-inline: 18px; }
.settings-content { min-height: 0; padding: 20px 18px; overflow-y: auto; }
.settings-footer { min-height: 68px; padding: 8px 18px calc(8px + env(safe-area-inset-bottom, 0px)); }
.settings-footer .save-button { min-height: 48px; }
.microphone-control { align-items: stretch; flex-direction: column; gap: 10px; }
.microphone-control .settings-hint { max-width: none; }
.microphone-toggle { width: 100%; min-height: 44px; }
.join-page { height: 100dvh; height: 100svh; min-height: 100dvh; min-height: 100svh; max-height: 100dvh; max-height: 100svh; }
.join-header { min-height: calc(62px + env(safe-area-inset-top, 0px)); padding-top: env(safe-area-inset-top, 0px); box-sizing: border-box; }
.join-content { align-items: stretch; justify-content: flex-start; gap: 24px; width: min(100% - 28px, 560px); padding: 24px 0 28px; overflow-y: auto; }
.join-copy h1 { margin: 14px 0 14px; font-size: clamp(40px, 12vw, 58px); }
.join-description { font-size: 15px; line-height: 1.65; }
.promise-list { margin-top: 23px; }
.join-card { padding: 22px 18px; border-radius: 18px; }
.join-card h2 { font-size: 25px; }
.field-grid { grid-template-columns: minmax(0, 1fr) 112px; }
.join-footer { width: min(100% - 28px, 560px); }
}
@media (max-width: 390px) {
.join-page .header-tools { gap: 4px; }
.join-page .github-button, .join-page .changelog-button, .join-page .guide-button { width: 32px; min-width: 32px; min-height: 32px; height: 32px; }
.join-page .version-badge { min-height: 32px; padding-inline: 6px; font-size: 10px; }
.join-page .language-switch { min-width: 44px; padding-inline: 6px; font-size: 11px; }
.workspace-header { padding-inline: 10px; }
.channel-switcher { max-width: 112px; }
.channel-switcher select { max-width: 72px; }
.workspace-actions .header-action { width: 32px; height: 32px; flex-basis: 32px; }
.disconnect-button { width: 32px; height: 32px; }
.room-hero { padding-inline: 16px; }
.mobile-voice-settings { width: 56px; padding-inline: 4px; }
.mobile-voice-toggle { flex: 0 0 44px; padding-inline: 0; }
.mobile-voice-toggle span { display: none; }
.mobile-voice-settings span { display: none; }
.join-content { gap: 18px; }
.join-card { padding-inline: 15px; }
}
</style>