mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-01 02:52:49 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84bdf63514 | ||
|
|
54e154be1a | ||
|
|
4375f01d05 | ||
|
|
6f5f4c9f4d | ||
|
|
a9f5a47163 | ||
|
|
6bf6544fd6 | ||
|
|
9c3b86dc7a | ||
|
|
411ab57b63 | ||
|
|
4de532e56b | ||
|
|
e9cec18345 | ||
|
|
82957832a5 | ||
|
|
5cf7331223 | ||
|
|
9873d27222 | ||
|
|
0ef9b84237 | ||
|
|
bcc78177c2 | ||
|
|
bfa26da9eb | ||
|
|
7715214f43 | ||
|
|
69c2f4776e | ||
|
|
7977572362 | ||
|
|
96f7fd6783 | ||
|
|
4816c7ea62 | ||
|
|
feb50d29c1 | ||
|
|
62af82f253 |
No files matched your search
@@ -9,7 +9,7 @@ on:
|
||||
version:
|
||||
description: Release version without the v prefix
|
||||
required: true
|
||||
default: 0.2.7
|
||||
default: 0.2.8
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -138,6 +138,7 @@ Settings responses merge against the submitted snapshot instead of replacing new
|
||||
| Legacy `config.json` | One-time import of `tsHost`, `tsPort` and `tsServerPassword`; later changes do not replace database settings |
|
||||
| `WEBSPEAK_DATA_DIR` | Persistent data directory; defaults to project `data/`, while Docker uses `/data` |
|
||||
| `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` | Screen-sharing ICE configuration read at startup |
|
||||
| `WEBSPEAK_TRUSTED_PROXIES` | Comma-separated IPs/CIDRs whose `X-Forwarded-For` may be believed; defaults to loopback so a same-host reverse proxy keeps working |
|
||||
| Relay environment variables | Standalone relay mode; public gateway relay choices come from saved admin settings |
|
||||
| Browser IndexedDB and localStorage | Local identities, preferences, server history and skin state |
|
||||
|
||||
|
||||
@@ -36,6 +36,11 @@
|
||||
| **WHY** | 无需安装桌面客户端,用户打开网页即可加入频道;部署者仍然掌控目标服务器、访问策略和数据。 | Users can join a voice channel from a browser without installing a desktop client, while the operator keeps control of servers, access, and data. |
|
||||
| **HOW** | 部署后在管理员控制台配置 TeamSpeak 目标和访问方式,浏览器负责交互与音频,WebSpeak 负责网关连接。 | Configure the TeamSpeak target and access policy in the administration console. The browser handles interaction and audio; WebSpeak provides the gateway connection. |
|
||||
|
||||
## 在线演示 · Live Demo
|
||||
|
||||
- 上海节点 / Shanghai: <https://shanghai.webspeak.online>
|
||||
- 香港节点 / Hong Kong: <https://webspeak.online>
|
||||
|
||||
## 文档 · Documentation
|
||||
|
||||
- [简体中文](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.zh-CN.md)
|
||||
|
||||
+17
-3
@@ -4,13 +4,14 @@
|
||||
|
||||
WebSpeak ist ein selbst gehosteter Webclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer können ohne Desktop-Client im Browser Kanälen beitreten; Administratoren verwalten Zielserver, Zugriff und Laufzeitstatus über die Webkonsole.
|
||||
|
||||
Aktuelle Version: [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7).
|
||||
Aktuelle Version: [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8).
|
||||
|
||||
## Live-Demo
|
||||
|
||||
Adresse: <https://webspeak.online>
|
||||
- Shanghai: <https://shanghai.webspeak.online>
|
||||
- Hongkong: <https://webspeak.online>
|
||||
|
||||
Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung können instabil sein; Latenz, Verbindungsabbrüche oder kurze Ausfälle beschreiben nicht jede eigene Bereitstellung.
|
||||
Netzwerkbedingungen und Auslastung können bei beiden Demos schwanken; Latenz, Verbindungsabbrüche oder kurze Ausfälle beschreiben nicht jede eigene Bereitstellung.
|
||||
|
||||
## ✨ Funktionen
|
||||
|
||||
@@ -157,6 +158,19 @@ Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entf
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### Bildschirmfreigabe und Verbindungsstabilität
|
||||
|
||||
- Aushandlung und Verarbeitung der Videospur für Bildschirmfreigaben zwischen Browsern und nativen TeamSpeak-Clients korrigiert.
|
||||
- Schnelle Kanalwechsel werden zuverlässiger verarbeitet, um inkonsistente Clientzustände zu vermeiden.
|
||||
- Darstellungsfehler in einigen Skin-Komponenten und der KAAK-Übersetzung behoben.
|
||||
|
||||
#### Verbesserungen der Oberfläche
|
||||
|
||||
- Audiogerätenamen werden vollständig angezeigt und bei wenig Platz umgebrochen, damit lange Namen unterscheidbar bleiben.
|
||||
- Unbeabsichtigte Textauswahl des Avatar-Platzhalters behoben.
|
||||
|
||||
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
|
||||
|
||||
#### Offeneres Skin-System
|
||||
|
||||
+17
-3
@@ -4,15 +4,16 @@
|
||||
|
||||
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors can join channels without installing a desktop client, while administrators manage the target servers, access policy, and runtime state from the web console.
|
||||
|
||||
Latest release: [read the 0.2.7 changelog on this page](#latest-release-notes).
|
||||
Latest release: [read the 0.2.8 changelog on this page](#latest-release-notes).
|
||||
|
||||
Skin authors should start with the [current skin development guide](./SKIN_DEVELOPMENT.md), which combines the `.wskin` package format, current runtime APIs, permission boundaries, and authoring workflow. The repository also includes the [WebSpeak skin development skill for agents](../.agents/skills/webspeak-skin-development/SKILL.md).
|
||||
|
||||
## Live demo
|
||||
|
||||
URL: <https://webspeak.online>
|
||||
- Shanghai: <https://shanghai.webspeak.online>
|
||||
- Hong Kong: <https://webspeak.online>
|
||||
|
||||
The public demo is hosted in Hong Kong and its network conditions and load may be unstable. Latency, disconnections, or temporary downtime do not represent every self-hosted deployment.
|
||||
Network conditions and load may vary at either demo. Latency, disconnections, or temporary downtime do not represent every self-hosted deployment.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
@@ -167,6 +168,19 @@ Disable and save the relay configuration to remove the relay option from the wel
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### Screen sharing and connection reliability
|
||||
|
||||
- Fixed negotiation and video-track handling for screen sharing between browsers and native TeamSpeak clients.
|
||||
- Improved handling of rapid channel switches to reduce inconsistent client state.
|
||||
- Fixed content rendering in some skin components and localization in the KAAK skin.
|
||||
|
||||
#### Interface improvements
|
||||
|
||||
- Audio device names now display in full and wrap when space is limited, making long names easier to distinguish.
|
||||
- Fixed avatar fallback text being selected unintentionally.
|
||||
|
||||
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
|
||||
|
||||
#### A more open skin system
|
||||
|
||||
+17
-3
@@ -4,7 +4,7 @@
|
||||
|
||||
## プロジェクト概要
|
||||
|
||||
最新リリース:[v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7)。
|
||||
最新リリース:[v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8)。
|
||||
|
||||
| 観点 | 説明 |
|
||||
| --- | --- |
|
||||
@@ -14,9 +14,10 @@
|
||||
|
||||
## オンラインデモ
|
||||
|
||||
アドレス: <https://webspeak.online>
|
||||
- 上海: <https://shanghai.webspeak.online>
|
||||
- 香港: <https://webspeak.online>
|
||||
|
||||
デモは香港にあります。ネットワークと負荷が不安定な場合があるため、遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
|
||||
各デモのネットワークや負荷は変動する場合があります。遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
|
||||
|
||||
## ✨ 機能
|
||||
|
||||
@@ -139,6 +140,19 @@ npm start
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### 画面共有と接続の安定性
|
||||
|
||||
- ブラウザーと TeamSpeak ネイティブクライアント間の画面共有で、接続ネゴシエーションと映像トラックの処理を修正しました。
|
||||
- チャンネルをすばやく切り替えた際の処理を改善し、クライアント状態の不整合を減らしました。
|
||||
- 一部スキンコンポーネントの内容表示と KAAK の多言語表示を修正しました。
|
||||
|
||||
#### インターフェースの改善
|
||||
|
||||
- 音声デバイス名を省略せず表示し、幅が足りない場合は折り返して、長い名前を判別しやすくしました。
|
||||
- アバターの代替テキストが誤って選択される問題を修正しました。
|
||||
|
||||
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
|
||||
|
||||
#### より開かれたスキンシステム
|
||||
|
||||
+19
-3
@@ -4,7 +4,7 @@
|
||||
|
||||
## О проекте
|
||||
|
||||
Последний выпуск: [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7).
|
||||
Последний выпуск: [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8).
|
||||
|
||||
| Логика | Описание |
|
||||
| --- | --- |
|
||||
@@ -14,9 +14,12 @@
|
||||
|
||||
## Онлайн-демо
|
||||
|
||||
Адрес: <https://webspeak.online>
|
||||
Адреса:
|
||||
|
||||
Демо-сервер находится в Гонконге; сеть и нагрузка могут быть нестабильными. Задержки, разрывы или временная недоступность демо не характеризуют самостоятельное развертывание.
|
||||
- Шанхай: <https://shanghai.webspeak.online>
|
||||
- Гонконг: <https://webspeak.online>
|
||||
|
||||
Сеть и нагрузка на обоих демо-серверах могут быть нестабильными. Задержки, разрывы или временная недоступность не характеризуют самостоятельное развертывание.
|
||||
|
||||
## ✨ Возможности
|
||||
|
||||
@@ -139,6 +142,19 @@ npm start
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### Демонстрация экрана и стабильность соединения
|
||||
|
||||
- Исправлены согласование соединения и обработка видеопотока при демонстрации экрана между браузерами и нативными клиентами TeamSpeak.
|
||||
- Улучшена обработка быстрых переключений каналов, чтобы избежать несогласованного состояния клиента.
|
||||
- Исправлено отображение содержимого некоторых компонентов скинов и локализации KAAK.
|
||||
|
||||
#### Улучшения интерфейса
|
||||
|
||||
- Названия аудиоустройств теперь отображаются полностью и переносятся при нехватке места, чтобы длинные названия было легче различать.
|
||||
- Исправлено случайное выделение текста-заглушки аватара.
|
||||
|
||||
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
|
||||
|
||||
#### Более открытая система скинов
|
||||
|
||||
+17
-3
@@ -8,11 +8,12 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
|
||||
|
||||
## 在线 Demo
|
||||
|
||||
地址:<https://webspeak.online>
|
||||
- 上海节点:<https://shanghai.webspeak.online>
|
||||
- 香港节点:<https://webspeak.online>
|
||||
|
||||
公共 Demo 位于香港,网络和负载可能不稳定。延迟、断线或暂时不可用不代表自行部署后的实际表现。
|
||||
演示站点的网络和负载可能不稳定;延迟、断线或暂时不可用不代表自行部署后的实际表现。
|
||||
|
||||
最新版本:[查看本页的 0.2.7 更新日志](#latest-release-notes)。
|
||||
最新版本:[查看本页的 0.2.8 更新日志](#latest-release-notes)。
|
||||
|
||||
## ✨ 特性
|
||||
|
||||
@@ -169,6 +170,19 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
|
||||
|
||||
#### 屏幕共享与连接稳定性
|
||||
|
||||
- 修复网页与 TeamSpeak 原生客户端之间屏幕共享的协商和视频轨道处理问题。
|
||||
- 改善快速切换频道时的队列处理,减少客户端状态错乱。
|
||||
- 修复部分皮肤组件内容和 KAAK 皮肤多语言显示问题。
|
||||
|
||||
#### 界面改进
|
||||
|
||||
- 音频设备名称会完整显示;空间不足时自动换行,便于区分名称较长的设备。
|
||||
- 修复头像占位文字被意外选中的问题。
|
||||
|
||||
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
|
||||
|
||||
#### 更开放的皮肤系统
|
||||
|
||||
@@ -261,6 +261,8 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
`content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例:
|
||||
|
||||
声明式 `components.json` 也可以显示皮肤自己的多语言文案。文本节点、字符串属性,以及组件 `name` / `accessibleName` 可使用 `{{skin.messages.<key>}}` 绑定。WebSpeak 会把皮肤 `content.json` 中 `defaultLocale`、当前语言代码和完整语言代码的 `messages` 合并到 `skin.messages`,当前语言内容覆盖默认文案;这个绑定适用于首页、语音页和 Demo 页的声明式组件。没有匹配的 key 会显示为空字符串,因此组件引用的 key 应在默认语言中提供。该本地化路径只提供皮肤包自身的文案,不会扩展 Wasm 插件的权限化运行时数据。
|
||||
|
||||
```json
|
||||
{
|
||||
"defaultLocale": "en",
|
||||
|
||||
@@ -14,7 +14,7 @@ While the WebSpeak performance card is sampling, its refresh icon spins to show
|
||||
|
||||
KAAK is a schema v3 open-skin package with full connection and voice-workspace surfaces. Its desktop voice page follows KOOK's proportions: an 86px server rail with 58px icons and 18px vertical spacing, a 290px channel pane, a 40px top bar, a central participant stage, right-side chat attached to the current voice channel, and a lower-left voice dock. The server rail uses KOOK's rounded-square silhouette, a 2px green active outline and left-edge marker, with neutral fallback tiles and the muted purple active tile from the reference. The identity tile stays pinned at the bottom with a 54px circular monogram and connection-aware online dot; the server list scrolls when the window is short. The host provides a stable color-tone value derived only from the privacy-safe label, but the rail keeps the KOOK neutral tile treatment rather than exposing those tones. The KOOK voice room is the point-to-point visual reference: composition, member presentation, styling, and motion should be compared directly, rather than treating matching component types or approximate placement as sufficient. The left tree contains the TeamSpeak voice channels only; KOOK's separate text-channel group is outside this pass because TeamSpeak has no equivalent channel type. The current voice channel's text chat remains on the right. Closing it hides the entire panel, expands the participant stage, and leaves a reopen button in the stage heading; this happens without leaving the voice room. Its header uses the `#` channel mark and an unobtrusive close control; the composer sits at the bottom edge. Messages use author monograms, a separate identity/time line, and readable message text. The central stage uses WebSpeak's reusable member-card widget so available TeamSpeak profile avatars appear inside KAAK's participant tiles; the tiles use a wide 1.82:1 layout with a responsive grid to match KOOK's participant presentation. Member names stay hidden at rest while chat is open and fade upward into the lower-left label on hover; they remain visible while chat is collapsed. KAAK's CSS adds hover depth and a smoothly transitioning speaking ring driven by live voice state. Active screen shares appear on member cards with a live badge and a themed watch action; the share player remains a WebSpeak host component. The dock retains WebSpeak's trusted connection-quality, audio, and disconnect controls. Input/output volume buttons open hover or keyboard-focus panels with live numeric levels; sliders use a skin-colored progress track, a distinct thumb, and visible focus feedback. Audio input and output devices use a reusable keyboard-accessible picker with a scrollable option list, selected/highlighted states, and an animated chevron; KAAK styles the trigger and open list. The connection surface, voice workspace, and audio settings share KOOK's PingFang SC-first font stack; audio settings use 16px/600 section headings and observed 14px/400 field labels. Audio sliders use a 16px thumb with hover/focus feedback. The performance card opens with a short entrance motion and readable network/audio metrics. No real device, volume, or microphone state is changed during visual checks. The roster shows connected TeamSpeak clients only; it does not invent an offline list. Channel selection is single-click; joining is double-click. The narrow layout keeps the host's mobile controls available while retaining readable member tiles.
|
||||
|
||||
The single TeamSpeak voice-channel group in the left tree collapses and expands with a short two-way height and fade transition like KOOK's voice group; the separate KOOK text-channel group remains outside this pass. A first click selects a channel and reveals a brief “双击加入” hint; the hint disappears on the active room. The current voice-room heading keeps the channel name and live member count visible above the participant stage while the attached chat is expanded, matching KOOK's room view. Member cards expose WebSpeak's trusted member-actions menu from a small hover or keyboard-focus control; desktop cards also open it on right-click, and touch layouts keep the control visible. KAAK gives the host menu KOOK's compact dark panel, separated volume section, and highlighted action rows while keeping WebSpeak's own individual-volume slider and member actions; it does not add KOOK menu actions or skin-side audio logic.
|
||||
The single TeamSpeak voice-channel group in the left tree collapses and expands with a short two-way height and fade transition like KOOK's voice group; the separate KOOK text-channel group remains outside this pass. A first click selects a channel and reveals a brief “双击加入” hint; the hint disappears on the active room. The current voice-room heading keeps the channel name and live member count visible above the participant stage while the attached chat is expanded, matching KOOK's room view. Member cards expose WebSpeak's trusted member-actions menu from a small hover or keyboard-focus control; desktop cards also open it on right-click, and touch layouts keep the control visible. KAAK gives the host menu KOOK's compact dark panel, separated volume section, and highlighted action rows while keeping WebSpeak's own individual-volume slider and member actions; it does not add KOOK menu actions or skin-side audio logic. While a screen-share peer is active, the voice-status panel also displays its browser-side video codec and transport statistics.
|
||||
|
||||
The design target is the voice-client portion of KOOK, as requested by the project owner. It does not include discovery, companion/party, event, store, advertising, administrator, or other service-operator pages. It does not add a KOOK account flow, direct messages, server administration, or channels absent from the connected TeamSpeak server. The voice performance card also closes on outside click or Escape; Escape returns focus to its trigger, and its entrance/exit motion respects reduced-motion preferences.
|
||||
|
||||
@@ -30,7 +30,7 @@ The owner authorized inspection of the first two voice rooms in the KOOK server.
|
||||
|
||||
## Components and permissions
|
||||
|
||||
The connection page and voice workspace are full-page declarative surfaces in [components.json](./kaak-voice/components.json). The voice surface requests only the capabilities it uses: visible server shortcuts, channel and member data, cached profile-avatar display inside the trusted member-card widget, channel joining, channel chat, voice status, microphone/output controls, whisper controls, disconnect, and screen-share status/read/control. Its member-card widget explicitly enables share status and watch actions; the KAAK dock uses the host's screen-share control. The performance panel hides only share transport metrics. The host renders trusted connection, language, skin, and audio controls. KAAK 3.1.78 keeps the shared-screen player inside the central voice-stage column with an explicit responsive height, so the player cannot collapse when the host applies its inline video sizing; member cards scroll in the remaining area. The full source image remains visible with black letterboxing. Server and channel password prompts use the compact dark KAAK dialog style while retaining WebSpeak's trusted password, error, cancel, and retry behavior. It rechecks permissions and connection state when each action runs; approval is local to this skin version and can be revoked from the host access control.
|
||||
The connection page and voice workspace are full-page declarative surfaces in [components.json](./kaak-voice/components.json). The voice surface requests only the capabilities it uses: visible server shortcuts, channel and member data, cached profile-avatar display inside the trusted member-card widget, channel joining, channel chat, voice status, microphone/output controls, whisper controls, disconnect, and screen-share status/read/control. Its member-card widget explicitly enables share status and watch actions; the KAAK dock uses the host's screen-share control. When a screen-share peer is active, the performance panel shows browser-side video codec and transport metrics. The host renders trusted connection, language, skin, and audio controls. KAAK keeps the shared-screen player inside the central voice-stage column with an explicit responsive height, so the player cannot collapse when the host applies its inline video sizing; member cards scroll in the remaining area. The full source image remains visible with black letterboxing. Server and channel password prompts use the compact dark KAAK dialog style while retaining WebSpeak's trusted password, error, cancel, and retry behavior. It rechecks permissions and connection state when each action runs; approval is local to this skin version and can be revoked from the host access control.
|
||||
|
||||
The server header uses the live, privacy-filtered TeamSpeak server label and a trusted `voice.server-switcher` menu backed by favorites and recent connections. Its click handler reuses WebSpeak's existing connection flow with an opaque local ID; addresses and credentials never enter skin data. The left panel uses the trusted `voice.channel-tree` widget to retain TeamSpeak channel nesting, member counts and capacity, available avatars, and mute/speaking/away states. Expanding a branch is local UI state, a single click selects a channel, and double-click joins it. With `memberActions` enabled, right-clicking another member row opens WebSpeak's existing host-owned action menu. With `memberDragDrop` enabled, another member can be dragged onto a different channel row; the member row and target channel receive visual feedback, and the host reuses its existing move-client operation. Both options default off for other skins. The skin does not add KOOK's separate text-channel list.
|
||||
|
||||
|
||||
Binary file not shown.
@@ -3,10 +3,10 @@
|
||||
"components": [
|
||||
{
|
||||
"id": "kaak-home",
|
||||
"name": "KAAK connection home",
|
||||
"name": "{{skin.messages.kaakHomeComponentName}}",
|
||||
"page": "home",
|
||||
"mode": "surface",
|
||||
"accessibleName": "KAAK 连接页 / Connection page",
|
||||
"accessibleName": "{{skin.messages.kaakHomeAccessibleName}}",
|
||||
"permissions": [
|
||||
"ui.surface.replace",
|
||||
"session.status.read"
|
||||
@@ -49,7 +49,7 @@
|
||||
"part": "slogan",
|
||||
"children": [
|
||||
{
|
||||
"text": "YOUR VOICE, EVERYWHERE."
|
||||
"text": "{{skin.messages.kaakTagline}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -67,7 +67,7 @@
|
||||
"attributes": {
|
||||
"viewbox": "0 0 640 480",
|
||||
"role": "img",
|
||||
"aria-label": "WebSpeak voice connection illustration"
|
||||
"aria-label": "{{skin.messages.kaakHomeIllustrationAlt}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -298,7 +298,7 @@
|
||||
"part": "welcome-title",
|
||||
"children": [
|
||||
{
|
||||
"text": "欢迎来到 WebSpeak"
|
||||
"text": "{{skin.messages.kaakWelcomeTitle}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -315,7 +315,7 @@
|
||||
"part": "connection-title",
|
||||
"children": [
|
||||
{
|
||||
"text": "连接 TeamSpeak 服务器"
|
||||
"text": "{{skin.messages.kaakConnectTitle}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -334,7 +334,7 @@
|
||||
"part": "description",
|
||||
"children": [
|
||||
{
|
||||
"text": "无需注册账号,填写服务器信息即可加入语音"
|
||||
"text": "{{skin.messages.kaakConnectDescription}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -347,7 +347,7 @@
|
||||
"part": "note",
|
||||
"children": [
|
||||
{
|
||||
"text": "浏览器直连 · 无需安装 TeamSpeak 客户端"
|
||||
"text": "{{skin.messages.kaakBrowserDirect}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -374,10 +374,10 @@
|
||||
},
|
||||
{
|
||||
"id": "kaak-workspace",
|
||||
"name": "KAAK voice workspace",
|
||||
"name": "{{skin.messages.kaakVoiceComponentName}}",
|
||||
"page": "voice",
|
||||
"mode": "surface",
|
||||
"accessibleName": "KAAK 语音工作区 / Voice workspace",
|
||||
"accessibleName": "{{skin.messages.kaakVoiceAccessibleName}}",
|
||||
"stateScope": "session.status.channelId",
|
||||
"permissions": [
|
||||
"ui.surface.replace",
|
||||
@@ -480,7 +480,7 @@
|
||||
"tag": "nav",
|
||||
"part": "server-rail",
|
||||
"attributes": {
|
||||
"aria-label": "收藏与历史服务器 / Favorites and history"
|
||||
"aria-label": "{{skin.messages.kaakFavoritesAndHistory}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -549,7 +549,7 @@
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "收藏"
|
||||
"text": "{{skin.messages.kaakFavorites}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -562,7 +562,7 @@
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "最近"
|
||||
"text": "{{skin.messages.kaakRecent}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -586,7 +586,7 @@
|
||||
"tag": "header",
|
||||
"part": "mobile-room-topbar",
|
||||
"attributes": {
|
||||
"aria-label": "语音房间控制"
|
||||
"aria-label": "{{skin.messages.kaakVoiceRoomControls}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -594,7 +594,7 @@
|
||||
"part": "mobile-room-back",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "返回频道树,不断开语音"
|
||||
"aria-label": "{{skin.messages.kaakReturnChannelsNoDisconnect}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-mobile-page"
|
||||
@@ -630,7 +630,7 @@
|
||||
"part": "mobile-room-mode",
|
||||
"children": [
|
||||
{
|
||||
"text": "语音感应"
|
||||
"text": "{{skin.messages.kaakVoiceRoom}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -640,7 +640,7 @@
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-expanded": "{{state.roommenu}}",
|
||||
"aria-label": "更多语音功能"
|
||||
"aria-label": "{{skin.messages.kaakMoreVoiceActions}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-room-menu"
|
||||
@@ -706,7 +706,7 @@
|
||||
},
|
||||
"attributes": {
|
||||
"role": "menu",
|
||||
"aria-label": "更多语音功能"
|
||||
"aria-label": "{{skin.messages.kaakMoreVoiceActions}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -715,14 +715,14 @@
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"role": "menuitem",
|
||||
"aria-label": "打开聊天记录"
|
||||
"aria-label": "{{skin.messages.kaakOpenChatHistory}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-chat-panel"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "聊天记录"
|
||||
"text": "{{skin.messages.kaakChatHistory}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -732,14 +732,14 @@
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"role": "menuitem",
|
||||
"aria-label": "复制邀请链接 / Copy invite link"
|
||||
"aria-label": "{{skin.messages.kaakCopyInviteLink}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "copy-invite-link"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "复制邀请链接 / Copy invite link"
|
||||
"text": "{{skin.messages.kaakCopyInviteLink}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -755,7 +755,7 @@
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "关闭菜单"
|
||||
"text": "{{skin.messages.kaakCloseMenu}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -765,7 +765,7 @@
|
||||
"tag": "section",
|
||||
"part": "mobile-room-head",
|
||||
"attributes": {
|
||||
"aria-label": "当前语音频道"
|
||||
"aria-label": "{{skin.messages.kaakCurrentVoiceChannel}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -814,7 +814,7 @@
|
||||
"part": "mobile-room-connection-label",
|
||||
"children": [
|
||||
{
|
||||
"text": "TeamSpeak · 已加入语音"
|
||||
"text": "{{skin.messages.kaakVoiceConnected}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -851,7 +851,7 @@
|
||||
"tag": "aside",
|
||||
"part": "channel-panel",
|
||||
"attributes": {
|
||||
"aria-label": "服务器频道 / Server channels"
|
||||
"aria-label": "{{skin.messages.kaakServerChannels}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -866,7 +866,7 @@
|
||||
"tag": "nav",
|
||||
"part": "channel-list",
|
||||
"attributes": {
|
||||
"aria-label": "频道 / Channels"
|
||||
"aria-label": "{{skin.messages.kaakChannels}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -875,7 +875,7 @@
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-expanded": "{{state.voicegroupopen}}",
|
||||
"aria-label": "展开或收起语音分组 / Toggle voice group"
|
||||
"aria-label": "{{skin.messages.kaakToggleVoiceGroup}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-voice-group"
|
||||
@@ -898,7 +898,7 @@
|
||||
"part": "voice-group-name",
|
||||
"children": [
|
||||
{
|
||||
"text": "语音分组"
|
||||
"text": "{{skin.messages.kaakVoiceGroup}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -936,7 +936,7 @@
|
||||
},
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "返回当前语音房间"
|
||||
"aria-label": "{{skin.messages.kaakReturnVoiceRoom}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-mobile-page"
|
||||
@@ -959,7 +959,7 @@
|
||||
"part": "mobile-room-return-copy",
|
||||
"children": [
|
||||
{
|
||||
"text": "语音已连接 · 点击返回房间"
|
||||
"text": "{{skin.messages.kaakReturnVoiceRoomConnected}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -992,7 +992,7 @@
|
||||
"tag": "section",
|
||||
"part": "conversation",
|
||||
"attributes": {
|
||||
"aria-label": "聊天 / Chat",
|
||||
"aria-label": "{{skin.messages.kaakChat}}",
|
||||
"data-chat-open": "{{chat.status.panelOpen}}"
|
||||
},
|
||||
"children": [
|
||||
@@ -1015,7 +1015,7 @@
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-expanded": "{{chat.status.panelOpen}}",
|
||||
"aria-label": "收起或展开聊天面板 / Toggle chat panel"
|
||||
"aria-label": "{{skin.messages.kaakToggleChatPanel}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-chat-panel"
|
||||
@@ -1065,7 +1065,7 @@
|
||||
"tag": "aside",
|
||||
"part": "voice-stage",
|
||||
"attributes": {
|
||||
"aria-label": "语音房间 / Voice room"
|
||||
"aria-label": "{{skin.messages.kaakVoiceRoomAccessibleName}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -1089,7 +1089,7 @@
|
||||
"part": "mobile-channel-back",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "返回频道树"
|
||||
"aria-label": "{{skin.messages.kaakBackToChannels}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-mobile-page"
|
||||
@@ -1125,7 +1125,7 @@
|
||||
"tag": "span",
|
||||
"part": "voice-stage-member-count",
|
||||
"attributes": {
|
||||
"aria-label": "频道成员数 / Channel member count"
|
||||
"aria-label": "{{skin.messages.kaakChannelMemberCount}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -1152,8 +1152,8 @@
|
||||
"className": "voice-stage-invite",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "复制邀请链接 / Copy invite link",
|
||||
"title": "复制邀请链接 / Copy invite link"
|
||||
"aria-label": "{{skin.messages.kaakCopyInviteLink}}",
|
||||
"title": "{{skin.messages.kaakCopyInviteLink}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "copy-invite-link"
|
||||
@@ -1200,7 +1200,7 @@
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-expanded": "{{chat.status.panelOpen}}",
|
||||
"aria-label": "展开聊天面板 / Expand chat panel"
|
||||
"aria-label": "{{skin.messages.kaakExpandChatPanel}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-chat-panel"
|
||||
@@ -1233,7 +1233,7 @@
|
||||
"tag": "footer",
|
||||
"part": "voice-dock",
|
||||
"attributes": {
|
||||
"aria-label": "语音控制 / Voice controls"
|
||||
"aria-label": "{{skin.messages.kaakVoiceControls}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -1260,24 +1260,21 @@
|
||||
},
|
||||
{
|
||||
"widget": "voice.performance-panel",
|
||||
"part": "performance-panel",
|
||||
"options": {
|
||||
"screenShare": false
|
||||
}
|
||||
"part": "performance-panel"
|
||||
},
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "disconnect-control",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "断开语音"
|
||||
"aria-label": "{{skin.messages.kaakDisconnectVoice}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "disconnect"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "离开"
|
||||
"text": "{{skin.messages.kaakLeaveVoice}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1308,14 +1305,14 @@
|
||||
},
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "停止屏幕共享"
|
||||
"aria-label": "{{skin.messages.kaakStopScreenShare}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "stop-screen-share"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "停止屏幕共享"
|
||||
"text": "{{skin.messages.kaakStopScreenShare}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1327,7 +1324,7 @@
|
||||
"className": "desktop-room-controls",
|
||||
"attributes": {
|
||||
"role": "toolbar",
|
||||
"aria-label": "语音设置 / Audio controls"
|
||||
"aria-label": "{{skin.messages.kaakAudioControls}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -1336,8 +1333,8 @@
|
||||
"className": "desktop-room-control desktop-room-settings",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "语音设置 / Audio settings",
|
||||
"title": "语音设置 / Audio settings"
|
||||
"aria-label": "{{skin.messages.kaakAudioSettings}}",
|
||||
"title": "{{skin.messages.kaakAudioSettings}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "open-audio-settings"
|
||||
@@ -1377,7 +1374,7 @@
|
||||
"className": "desktop-room-control-label",
|
||||
"children": [
|
||||
{
|
||||
"text": "语音设置"
|
||||
"text": "{{skin.messages.kaakAudioSettingsShort}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1389,8 +1386,8 @@
|
||||
"className": "desktop-room-control desktop-room-noise-suppression",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "噪声抑制 / Noise suppression",
|
||||
"title": "噪声抑制 / Noise suppression",
|
||||
"aria-label": "{{skin.messages.kaakNoiseSuppression}}",
|
||||
"title": "{{skin.messages.kaakNoiseSuppression}}",
|
||||
"aria-pressed": "{{audio.status.noiseSuppressionEnabled}}"
|
||||
},
|
||||
"events": {
|
||||
@@ -1440,8 +1437,8 @@
|
||||
"className": "desktop-room-control desktop-room-microphone",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "麦克风 / Microphone",
|
||||
"title": "麦克风 / Microphone",
|
||||
"aria-label": "{{skin.messages.kaakMicrophone}}",
|
||||
"title": "{{skin.messages.kaakMicrophone}}",
|
||||
"aria-pressed": "{{audio.status.microphoneMuted}}"
|
||||
},
|
||||
"events": {
|
||||
@@ -1507,8 +1504,8 @@
|
||||
"className": "desktop-room-control desktop-room-output",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "扬声器静音 / Speaker mute",
|
||||
"title": "扬声器静音 / Speaker mute",
|
||||
"aria-label": "{{skin.messages.kaakSpeakerMute}}",
|
||||
"title": "{{skin.messages.kaakSpeakerMute}}",
|
||||
"aria-pressed": "{{audio.status.outputMuted}}"
|
||||
},
|
||||
"events": {
|
||||
@@ -1566,8 +1563,8 @@
|
||||
"className": "desktop-room-control desktop-room-accompaniment",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "伴奏 / Accompaniment",
|
||||
"title": "伴奏 / Accompaniment",
|
||||
"aria-label": "{{skin.messages.kaakAccompaniment}}",
|
||||
"title": "{{skin.messages.kaakAccompaniment}}",
|
||||
"aria-pressed": "{{audio.status.accompanimentActive}}"
|
||||
},
|
||||
"events": {
|
||||
@@ -1625,7 +1622,7 @@
|
||||
"className": "mobile-room-controls",
|
||||
"attributes": {
|
||||
"role": "toolbar",
|
||||
"aria-label": "语音控制"
|
||||
"aria-label": "{{skin.messages.kaakVoiceControls}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -1634,10 +1631,10 @@
|
||||
"className": "mobile-room-control mobile-room-microphone",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "麦克风",
|
||||
"aria-label": "{{skin.messages.kaakMicrophone}}",
|
||||
"aria-pressed": "{{audio.status.microphoneMuted}}",
|
||||
"data-muted": "{{audio.status.microphoneMuted}}",
|
||||
"title": "麦克风"
|
||||
"title": "{{skin.messages.kaakMicrophone}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-microphone"
|
||||
@@ -1711,7 +1708,7 @@
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "闭麦"
|
||||
"text": "{{skin.messages.kaakMuteMicrophone}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -1724,7 +1721,7 @@
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "开麦"
|
||||
"text": "{{skin.messages.kaakUnmuteMicrophone}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1736,10 +1733,10 @@
|
||||
"className": "mobile-room-control mobile-room-deafen",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "耳机静音",
|
||||
"aria-label": "{{skin.messages.kaakMuteOutput}}",
|
||||
"aria-pressed": "{{audio.status.outputMuted}}",
|
||||
"data-muted": "{{audio.status.outputMuted}}",
|
||||
"title": "耳机静音"
|
||||
"title": "{{skin.messages.kaakMuteOutput}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "toggle-output-mute"
|
||||
@@ -1799,7 +1796,7 @@
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "静音"
|
||||
"text": "{{skin.messages.kaakMute}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -1812,7 +1809,7 @@
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"text": "恢复"
|
||||
"text": "{{skin.messages.kaakUnmute}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1824,8 +1821,8 @@
|
||||
"className": "mobile-room-control mobile-room-speaker",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "扬声器",
|
||||
"title": "扬声器"
|
||||
"aria-label": "{{skin.messages.kaakSpeaker}}",
|
||||
"title": "{{skin.messages.kaakSpeaker}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "open-audio-settings"
|
||||
@@ -1867,7 +1864,7 @@
|
||||
"className": "mobile-room-control-caption",
|
||||
"children": [
|
||||
{
|
||||
"text": "扬声器"
|
||||
"text": "{{skin.messages.kaakSpeaker}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1883,8 +1880,8 @@
|
||||
},
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "屏幕共享",
|
||||
"title": "屏幕共享",
|
||||
"aria-label": "{{skin.messages.kaakScreenShare}}",
|
||||
"title": "{{skin.messages.kaakScreenShare}}",
|
||||
"aria-pressed": false
|
||||
},
|
||||
"events": {
|
||||
@@ -1937,7 +1934,7 @@
|
||||
"className": "mobile-room-control-caption",
|
||||
"children": [
|
||||
{
|
||||
"text": "屏幕共享"
|
||||
"text": "{{skin.messages.kaakScreenShare}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1953,8 +1950,8 @@
|
||||
},
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "停止屏幕共享",
|
||||
"title": "停止屏幕共享",
|
||||
"aria-label": "{{skin.messages.kaakStopScreenShare}}",
|
||||
"title": "{{skin.messages.kaakStopScreenShare}}",
|
||||
"aria-pressed": true
|
||||
},
|
||||
"events": {
|
||||
@@ -2007,7 +2004,7 @@
|
||||
"className": "mobile-room-control-caption",
|
||||
"children": [
|
||||
{
|
||||
"text": "屏幕共享"
|
||||
"text": "{{skin.messages.kaakScreenShare}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -2019,8 +2016,8 @@
|
||||
"className": "mobile-room-control mobile-room-exit",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "退出",
|
||||
"title": "退出"
|
||||
"aria-label": "{{skin.messages.kaakLeaveVoice}}",
|
||||
"title": "{{skin.messages.kaakLeaveVoice}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "disconnect"
|
||||
@@ -2062,7 +2059,7 @@
|
||||
"className": "mobile-room-control-caption",
|
||||
"children": [
|
||||
{
|
||||
"text": "退出"
|
||||
"text": "{{skin.messages.kaakLeaveVoice}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -2080,7 +2077,7 @@
|
||||
},
|
||||
"attributes": {
|
||||
"role": "group",
|
||||
"aria-label": "当前 TeamSpeak 身份"
|
||||
"aria-label": "{{skin.messages.kaakCurrentIdentity}}"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
@@ -2099,7 +2096,7 @@
|
||||
},
|
||||
"attributes": {
|
||||
"role": "img",
|
||||
"aria-label": "在线"
|
||||
"aria-label": "{{skin.messages.kaakOnline}}"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,10 +1,320 @@
|
||||
{
|
||||
"defaultLocale": "zh-CN",
|
||||
"locales": {
|
||||
"zh-CN": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "确定" } },
|
||||
"en": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "Confirm" } },
|
||||
"de": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "Bestätigen" } },
|
||||
"ru": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "Подтвердить" } },
|
||||
"ja": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "確定" } }
|
||||
"zh-CN": {
|
||||
"home": {
|
||||
"brandName": "KAAK"
|
||||
},
|
||||
"messages": {
|
||||
"passwordDialogConfirm": "确定",
|
||||
"kaakHomeComponentName": "KAAK 首页",
|
||||
"kaakVoiceComponentName": "KAAK 语音工作区",
|
||||
"kaakHomeAccessibleName": "KAAK 连接页",
|
||||
"kaakVoiceAccessibleName": "KAAK 语音工作区",
|
||||
"kaakTagline": "你的声音,随时随地。",
|
||||
"kaakHomeIllustrationAlt": "WebSpeak 语音连接插图",
|
||||
"kaakWelcomeTitle": "欢迎来到 WebSpeak",
|
||||
"kaakConnectTitle": "连接 TeamSpeak 服务器",
|
||||
"kaakConnectDescription": "无需注册账号,填写服务器信息即可加入语音",
|
||||
"kaakBrowserDirect": "浏览器直连 · 无需安装 TeamSpeak 客户端",
|
||||
"kaakFavoritesAndHistory": "收藏与最近服务器",
|
||||
"kaakFavorites": "收藏",
|
||||
"kaakRecent": "最近",
|
||||
"kaakVoiceRoomControls": "语音房间控制",
|
||||
"kaakReturnChannelsNoDisconnect": "返回频道树,不断开语音",
|
||||
"kaakVoiceRoom": "语音房间",
|
||||
"kaakMoreVoiceActions": "更多语音功能",
|
||||
"kaakOpenChatHistory": "打开聊天记录",
|
||||
"kaakChatHistory": "聊天记录",
|
||||
"kaakCopyInviteLink": "复制邀请链接",
|
||||
"kaakCloseMenu": "关闭菜单",
|
||||
"kaakCurrentVoiceChannel": "当前语音频道",
|
||||
"kaakVoiceConnected": "TeamSpeak · 已加入语音",
|
||||
"kaakServerChannels": "服务器频道",
|
||||
"kaakChannels": "频道",
|
||||
"kaakToggleVoiceGroup": "展开或收起语音分组",
|
||||
"kaakVoiceGroup": "语音分组",
|
||||
"kaakReturnVoiceRoom": "返回当前语音房间",
|
||||
"kaakReturnVoiceRoomConnected": "语音已连接 · 点击返回房间",
|
||||
"kaakChat": "聊天",
|
||||
"kaakToggleChatPanel": "收起或展开聊天面板",
|
||||
"kaakVoiceRoomAccessibleName": "语音房间",
|
||||
"kaakBackToChannels": "返回频道列表",
|
||||
"kaakChannelMemberCount": "频道成员数",
|
||||
"kaakExpandChatPanel": "展开聊天面板",
|
||||
"kaakVoiceControls": "语音控制",
|
||||
"kaakDisconnectVoice": "断开语音",
|
||||
"kaakStopScreenShare": "停止屏幕共享",
|
||||
"kaakAudioControls": "语音设置",
|
||||
"kaakAudioSettings": "语音设置",
|
||||
"kaakAudioSettingsShort": "语音设置",
|
||||
"kaakNoiseSuppression": "噪声抑制",
|
||||
"kaakMicrophone": "麦克风",
|
||||
"kaakSpeakerMute": "扬声器静音",
|
||||
"kaakAccompaniment": "伴奏",
|
||||
"kaakMuteMicrophone": "闭麦",
|
||||
"kaakUnmuteMicrophone": "开麦",
|
||||
"kaakMuteOutput": "耳机静音",
|
||||
"kaakMute": "静音",
|
||||
"kaakUnmute": "恢复",
|
||||
"kaakSpeaker": "扬声器",
|
||||
"kaakScreenShare": "屏幕共享",
|
||||
"kaakLeaveVoice": "退出",
|
||||
"kaakCurrentIdentity": "当前 TeamSpeak 身份",
|
||||
"kaakOnline": "在线"
|
||||
}
|
||||
},
|
||||
"en": {
|
||||
"home": {
|
||||
"brandName": "KAAK"
|
||||
},
|
||||
"messages": {
|
||||
"passwordDialogConfirm": "Confirm",
|
||||
"kaakHomeComponentName": "KAAK connection home",
|
||||
"kaakVoiceComponentName": "KAAK voice workspace",
|
||||
"kaakHomeAccessibleName": "KAAK connection page",
|
||||
"kaakVoiceAccessibleName": "KAAK voice workspace",
|
||||
"kaakTagline": "YOUR VOICE, EVERYWHERE.",
|
||||
"kaakHomeIllustrationAlt": "WebSpeak voice connection illustration",
|
||||
"kaakWelcomeTitle": "Welcome to WebSpeak",
|
||||
"kaakConnectTitle": "Connect to a TeamSpeak server",
|
||||
"kaakConnectDescription": "No account required. Enter the server details to join voice.",
|
||||
"kaakBrowserDirect": "Connect directly in your browser · No TeamSpeak client needed",
|
||||
"kaakFavoritesAndHistory": "Favorites and recent servers",
|
||||
"kaakFavorites": "Favorites",
|
||||
"kaakRecent": "Recent",
|
||||
"kaakVoiceRoomControls": "Voice room controls",
|
||||
"kaakReturnChannelsNoDisconnect": "Return to channels without disconnecting",
|
||||
"kaakVoiceRoom": "Voice room",
|
||||
"kaakMoreVoiceActions": "More voice actions",
|
||||
"kaakOpenChatHistory": "Open chat history",
|
||||
"kaakChatHistory": "Chat history",
|
||||
"kaakCopyInviteLink": "Copy invite link",
|
||||
"kaakCloseMenu": "Close menu",
|
||||
"kaakCurrentVoiceChannel": "Current voice channel",
|
||||
"kaakVoiceConnected": "TeamSpeak · Voice connected",
|
||||
"kaakServerChannels": "Server channels",
|
||||
"kaakChannels": "Channels",
|
||||
"kaakToggleVoiceGroup": "Expand or collapse voice group",
|
||||
"kaakVoiceGroup": "Voice group",
|
||||
"kaakReturnVoiceRoom": "Return to the current voice room",
|
||||
"kaakReturnVoiceRoomConnected": "Voice connected · Click to return to the room",
|
||||
"kaakChat": "Chat",
|
||||
"kaakToggleChatPanel": "Collapse or expand chat panel",
|
||||
"kaakVoiceRoomAccessibleName": "Voice room",
|
||||
"kaakBackToChannels": "Back to channel list",
|
||||
"kaakChannelMemberCount": "Channel member count",
|
||||
"kaakExpandChatPanel": "Expand chat panel",
|
||||
"kaakVoiceControls": "Voice controls",
|
||||
"kaakDisconnectVoice": "Disconnect voice",
|
||||
"kaakStopScreenShare": "Stop screen sharing",
|
||||
"kaakAudioControls": "Audio controls",
|
||||
"kaakAudioSettings": "Audio settings",
|
||||
"kaakAudioSettingsShort": "Audio settings",
|
||||
"kaakNoiseSuppression": "Noise suppression",
|
||||
"kaakMicrophone": "Microphone",
|
||||
"kaakSpeakerMute": "Mute speakers",
|
||||
"kaakAccompaniment": "Accompaniment",
|
||||
"kaakMuteMicrophone": "Mute microphone",
|
||||
"kaakUnmuteMicrophone": "Unmute microphone",
|
||||
"kaakMuteOutput": "Mute output",
|
||||
"kaakMute": "Mute",
|
||||
"kaakUnmute": "Unmute",
|
||||
"kaakSpeaker": "Speaker",
|
||||
"kaakScreenShare": "Screen share",
|
||||
"kaakLeaveVoice": "Leave",
|
||||
"kaakCurrentIdentity": "Current TeamSpeak identity",
|
||||
"kaakOnline": "Online"
|
||||
}
|
||||
},
|
||||
"de": {
|
||||
"home": {
|
||||
"brandName": "KAAK"
|
||||
},
|
||||
"messages": {
|
||||
"passwordDialogConfirm": "Bestätigen",
|
||||
"kaakHomeComponentName": "KAAK-Verbindungsseite",
|
||||
"kaakVoiceComponentName": "KAAK-Sprachbereich",
|
||||
"kaakHomeAccessibleName": "KAAK-Verbindungsseite",
|
||||
"kaakVoiceAccessibleName": "KAAK-Sprachbereich",
|
||||
"kaakTagline": "DEINE STIMME. ÜBERALL.",
|
||||
"kaakHomeIllustrationAlt": "Illustration zur WebSpeak-Sprachverbindung",
|
||||
"kaakWelcomeTitle": "Willkommen bei WebSpeak",
|
||||
"kaakConnectTitle": "Mit einem TeamSpeak-Server verbinden",
|
||||
"kaakConnectDescription": "Kein Konto nötig. Gib die Serverdaten ein, um dem Sprachkanal beizutreten.",
|
||||
"kaakBrowserDirect": "Direkt im Browser · Kein TeamSpeak-Client erforderlich",
|
||||
"kaakFavoritesAndHistory": "Favoriten und zuletzt verwendete Server",
|
||||
"kaakFavorites": "Favoriten",
|
||||
"kaakRecent": "Zuletzt",
|
||||
"kaakVoiceRoomControls": "Sprachraum-Steuerung",
|
||||
"kaakReturnChannelsNoDisconnect": "Zurück zu den Kanälen, ohne die Verbindung zu trennen",
|
||||
"kaakVoiceRoom": "Sprachraum",
|
||||
"kaakMoreVoiceActions": "Weitere Sprachaktionen",
|
||||
"kaakOpenChatHistory": "Chatverlauf öffnen",
|
||||
"kaakChatHistory": "Chatverlauf",
|
||||
"kaakCopyInviteLink": "Einladungslink kopieren",
|
||||
"kaakCloseMenu": "Menü schließen",
|
||||
"kaakCurrentVoiceChannel": "Aktueller Sprachkanal",
|
||||
"kaakVoiceConnected": "TeamSpeak · Sprachkanal beigetreten",
|
||||
"kaakServerChannels": "Serverkanäle",
|
||||
"kaakChannels": "Kanäle",
|
||||
"kaakToggleVoiceGroup": "Sprachgruppe ein- oder ausklappen",
|
||||
"kaakVoiceGroup": "Sprachgruppe",
|
||||
"kaakReturnVoiceRoom": "Zum aktuellen Sprachraum zurückkehren",
|
||||
"kaakReturnVoiceRoomConnected": "Sprachverbindung aktiv · Klicken, um zum Raum zurückzukehren",
|
||||
"kaakChat": "Chat",
|
||||
"kaakToggleChatPanel": "Chatbereich ein- oder ausklappen",
|
||||
"kaakVoiceRoomAccessibleName": "Sprachraum",
|
||||
"kaakBackToChannels": "Zur Kanalliste",
|
||||
"kaakChannelMemberCount": "Anzahl der Kanalmitglieder",
|
||||
"kaakExpandChatPanel": "Chatbereich erweitern",
|
||||
"kaakVoiceControls": "Sprachsteuerung",
|
||||
"kaakDisconnectVoice": "Sprachverbindung trennen",
|
||||
"kaakStopScreenShare": "Bildschirmfreigabe beenden",
|
||||
"kaakAudioControls": "Audio-Steuerung",
|
||||
"kaakAudioSettings": "Audioeinstellungen",
|
||||
"kaakAudioSettingsShort": "Audioeinstellungen",
|
||||
"kaakNoiseSuppression": "Rauschunterdrückung",
|
||||
"kaakMicrophone": "Mikrofon",
|
||||
"kaakSpeakerMute": "Lautsprecher stummschalten",
|
||||
"kaakAccompaniment": "Begleitton",
|
||||
"kaakMuteMicrophone": "Mikrofon stummschalten",
|
||||
"kaakUnmuteMicrophone": "Mikrofon einschalten",
|
||||
"kaakMuteOutput": "Ausgabe stummschalten",
|
||||
"kaakMute": "Stumm",
|
||||
"kaakUnmute": "Ton einschalten",
|
||||
"kaakSpeaker": "Lautsprecher",
|
||||
"kaakScreenShare": "Bildschirm teilen",
|
||||
"kaakLeaveVoice": "Verlassen",
|
||||
"kaakCurrentIdentity": "Aktuelle TeamSpeak-Identität",
|
||||
"kaakOnline": "Online"
|
||||
}
|
||||
},
|
||||
"ru": {
|
||||
"home": {
|
||||
"brandName": "KAAK"
|
||||
},
|
||||
"messages": {
|
||||
"passwordDialogConfirm": "Подтвердить",
|
||||
"kaakHomeComponentName": "Страница подключения KAAK",
|
||||
"kaakVoiceComponentName": "Голосовое пространство KAAK",
|
||||
"kaakHomeAccessibleName": "Страница подключения KAAK",
|
||||
"kaakVoiceAccessibleName": "Голосовое пространство KAAK",
|
||||
"kaakTagline": "ТВОЙ ГОЛОС — ВЕЗДЕ.",
|
||||
"kaakHomeIllustrationAlt": "Иллюстрация голосового подключения WebSpeak",
|
||||
"kaakWelcomeTitle": "Добро пожаловать в WebSpeak",
|
||||
"kaakConnectTitle": "Подключение к серверу TeamSpeak",
|
||||
"kaakConnectDescription": "Аккаунт не нужен. Укажите данные сервера, чтобы подключиться к голосовому каналу.",
|
||||
"kaakBrowserDirect": "Прямое подключение в браузере · Клиент TeamSpeak не нужен",
|
||||
"kaakFavoritesAndHistory": "Избранные и недавние серверы",
|
||||
"kaakFavorites": "Избранное",
|
||||
"kaakRecent": "Недавние",
|
||||
"kaakVoiceRoomControls": "Управление голосовой комнатой",
|
||||
"kaakReturnChannelsNoDisconnect": "Вернуться к каналам без отключения",
|
||||
"kaakVoiceRoom": "Голосовая комната",
|
||||
"kaakMoreVoiceActions": "Дополнительные голосовые действия",
|
||||
"kaakOpenChatHistory": "Открыть историю чата",
|
||||
"kaakChatHistory": "История чата",
|
||||
"kaakCopyInviteLink": "Скопировать ссылку-приглашение",
|
||||
"kaakCloseMenu": "Закрыть меню",
|
||||
"kaakCurrentVoiceChannel": "Текущий голосовой канал",
|
||||
"kaakVoiceConnected": "TeamSpeak · Подключён к голосовому каналу",
|
||||
"kaakServerChannels": "Каналы сервера",
|
||||
"kaakChannels": "Каналы",
|
||||
"kaakToggleVoiceGroup": "Развернуть или свернуть группу",
|
||||
"kaakVoiceGroup": "Голосовая группа",
|
||||
"kaakReturnVoiceRoom": "Вернуться в текущую голосовую комнату",
|
||||
"kaakReturnVoiceRoomConnected": "Подключено · Нажмите, чтобы вернуться в комнату",
|
||||
"kaakChat": "Чат",
|
||||
"kaakToggleChatPanel": "Свернуть или развернуть панель чата",
|
||||
"kaakVoiceRoomAccessibleName": "Голосовая комната",
|
||||
"kaakBackToChannels": "Вернуться к списку каналов",
|
||||
"kaakChannelMemberCount": "Количество участников канала",
|
||||
"kaakExpandChatPanel": "Развернуть панель чата",
|
||||
"kaakVoiceControls": "Голосовое управление",
|
||||
"kaakDisconnectVoice": "Отключиться от голосового канала",
|
||||
"kaakStopScreenShare": "Остановить демонстрацию экрана",
|
||||
"kaakAudioControls": "Управление звуком",
|
||||
"kaakAudioSettings": "Настройки звука",
|
||||
"kaakAudioSettingsShort": "Настройки звука",
|
||||
"kaakNoiseSuppression": "Шумоподавление",
|
||||
"kaakMicrophone": "Микрофон",
|
||||
"kaakSpeakerMute": "Отключить звук динамиков",
|
||||
"kaakAccompaniment": "Сопровождение",
|
||||
"kaakMuteMicrophone": "Выключить микрофон",
|
||||
"kaakUnmuteMicrophone": "Включить микрофон",
|
||||
"kaakMuteOutput": "Отключить звук",
|
||||
"kaakMute": "Без звука",
|
||||
"kaakUnmute": "Включить звук",
|
||||
"kaakSpeaker": "Динамик",
|
||||
"kaakScreenShare": "Демонстрация экрана",
|
||||
"kaakLeaveVoice": "Выйти",
|
||||
"kaakCurrentIdentity": "Текущая личность TeamSpeak",
|
||||
"kaakOnline": "В сети"
|
||||
}
|
||||
},
|
||||
"ja": {
|
||||
"home": {
|
||||
"brandName": "KAAK"
|
||||
},
|
||||
"messages": {
|
||||
"passwordDialogConfirm": "確定",
|
||||
"kaakHomeComponentName": "KAAK 接続ページ",
|
||||
"kaakVoiceComponentName": "KAAK 音声ワークスペース",
|
||||
"kaakHomeAccessibleName": "KAAK 接続ページ",
|
||||
"kaakVoiceAccessibleName": "KAAK 音声ワークスペース",
|
||||
"kaakTagline": "あなたの声を、どこでも。",
|
||||
"kaakHomeIllustrationAlt": "WebSpeak 音声接続のイラスト",
|
||||
"kaakWelcomeTitle": "WebSpeak へようこそ",
|
||||
"kaakConnectTitle": "TeamSpeak サーバーに接続",
|
||||
"kaakConnectDescription": "アカウント登録は不要です。サーバー情報を入力して音声に参加できます。",
|
||||
"kaakBrowserDirect": "ブラウザーから直接接続 · TeamSpeak クライアント不要",
|
||||
"kaakFavoritesAndHistory": "お気に入りと最近使ったサーバー",
|
||||
"kaakFavorites": "お気に入り",
|
||||
"kaakRecent": "最近",
|
||||
"kaakVoiceRoomControls": "音声ルーム操作",
|
||||
"kaakReturnChannelsNoDisconnect": "切断せずにチャンネル一覧へ戻る",
|
||||
"kaakVoiceRoom": "音声ルーム",
|
||||
"kaakMoreVoiceActions": "その他の音声操作",
|
||||
"kaakOpenChatHistory": "チャット履歴を開く",
|
||||
"kaakChatHistory": "チャット履歴",
|
||||
"kaakCopyInviteLink": "招待リンクをコピー",
|
||||
"kaakCloseMenu": "メニューを閉じる",
|
||||
"kaakCurrentVoiceChannel": "現在の音声チャンネル",
|
||||
"kaakVoiceConnected": "TeamSpeak · 音声に接続中",
|
||||
"kaakServerChannels": "サーバーチャンネル",
|
||||
"kaakChannels": "チャンネル",
|
||||
"kaakToggleVoiceGroup": "音声グループを展開/折りたたむ",
|
||||
"kaakVoiceGroup": "音声グループ",
|
||||
"kaakReturnVoiceRoom": "現在の音声ルームに戻る",
|
||||
"kaakReturnVoiceRoomConnected": "音声接続中 · タップしてルームに戻る",
|
||||
"kaakChat": "チャット",
|
||||
"kaakToggleChatPanel": "チャットパネルを折りたたむ/展開",
|
||||
"kaakVoiceRoomAccessibleName": "音声ルーム",
|
||||
"kaakBackToChannels": "チャンネル一覧に戻る",
|
||||
"kaakChannelMemberCount": "チャンネルの参加者数",
|
||||
"kaakExpandChatPanel": "チャットパネルを展開",
|
||||
"kaakVoiceControls": "音声コントロール",
|
||||
"kaakDisconnectVoice": "音声接続を切断",
|
||||
"kaakStopScreenShare": "画面共有を停止",
|
||||
"kaakAudioControls": "音声コントロール",
|
||||
"kaakAudioSettings": "音声設定",
|
||||
"kaakAudioSettingsShort": "音声設定",
|
||||
"kaakNoiseSuppression": "ノイズ抑制",
|
||||
"kaakMicrophone": "マイク",
|
||||
"kaakSpeakerMute": "スピーカーをミュート",
|
||||
"kaakAccompaniment": "伴奏音声",
|
||||
"kaakMuteMicrophone": "マイクをミュート",
|
||||
"kaakUnmuteMicrophone": "マイクのミュートを解除",
|
||||
"kaakMuteOutput": "出力をミュート",
|
||||
"kaakMute": "ミュート",
|
||||
"kaakUnmute": "ミュート解除",
|
||||
"kaakSpeaker": "スピーカー",
|
||||
"kaakScreenShare": "画面共有",
|
||||
"kaakLeaveVoice": "退出",
|
||||
"kaakCurrentIdentity": "現在の TeamSpeak ID",
|
||||
"kaakOnline": "オンライン"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
"packageType": "open-skin",
|
||||
"id": "community.kaak-voice",
|
||||
"name": "KAAK",
|
||||
"version": "3.1.115",
|
||||
"version": "3.1.121",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A KOOK-inspired WebSpeak skin with a split-screen connection home, searchable server header, TeamSpeak banner, nested channel members, unified chat with local history, and a compact audio dock.",
|
||||
|
||||
@@ -2341,22 +2341,26 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] .desktop-room-control-icon { display: block; flex: 0 0 auto; width: 18px; height: 18px; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"] {
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"] {
|
||||
display: flex;
|
||||
grid-column: 1;
|
||||
grid-row: 2;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
justify-self: stretch;
|
||||
box-sizing: border-box;
|
||||
gap: 8px;
|
||||
width: auto;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
padding: 0 7px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color: #b5c6d8;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"] .desktop-room-control-icon {
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"] .desktop-room-control-icon {
|
||||
display: block;
|
||||
flex: 0 0 15px;
|
||||
width: 15px;
|
||||
@@ -2368,7 +2372,7 @@
|
||||
transform: none;
|
||||
vertical-align: middle;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"] .desktop-room-control-label { display: block; line-height: 16px; white-space: nowrap; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"] .desktop-room-control-label { display: block; min-width: 0; overflow: hidden; line-height: 16px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-noise-suppression"] { grid-column: 2; grid-row: 2; color: #fff; background: #6cbf00; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-microphone"] { grid-column: 3; grid-row: 2; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-output"] { grid-column: 4; grid-row: 2; }
|
||||
@@ -2386,8 +2390,8 @@
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-noise-suppression"][aria-pressed="true"] { color: #fff; background: #6cbf00; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-accompaniment"][aria-pressed="true"] { background: #477f00; box-shadow: inset 0 0 0 1px #9be031; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"]:hover,
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"]:focus-visible { color: #eff0f3; background: #303238; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"]:hover,
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"]:focus-visible { color: #eff0f3; background: #303238; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] .desktop-room-control:hover,
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] .desktop-room-control:focus-visible { color: #eff0f3; background: #303238; outline: none; }
|
||||
[data-ws-plugin-part="kaak-workspace.desktop-room-accompaniment"]:hover,
|
||||
@@ -3043,13 +3047,15 @@
|
||||
min-height: 40px;
|
||||
}
|
||||
[data-ws-part="voice.audio-settings"] .settings-select-option {
|
||||
height: 32px;
|
||||
height: auto;
|
||||
min-height: 32px;
|
||||
margin-bottom: 2px;
|
||||
padding-inline: 8px;
|
||||
padding: 6px 8px;
|
||||
color: #e6eaf0;
|
||||
font-size: 14px;
|
||||
line-height: 32px;
|
||||
line-height: 1.45;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: normal;
|
||||
border-radius: 8px;
|
||||
}
|
||||
[data-ws-part="voice.audio-settings"] .settings-select-option:last-child { margin-bottom: 0; }
|
||||
@@ -4506,8 +4512,6 @@
|
||||
[data-ws-plugin-part="kaak-workspace.conversation-heading"] { min-height: 48px; margin: 0; }
|
||||
[data-ws-plugin-part="kaak-workspace.chat-panel-toggle"] { pointer-events: auto; }
|
||||
[data-ws-plugin-part="kaak-workspace.chat-panel"] { min-height: 0; overflow: hidden; }
|
||||
[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"]:not([data-mobile-channels="true"])[data-chat-open="true"] [data-ws-plugin-part="kaak-workspace.mobile-room-menu"] { display: none; }
|
||||
|
||||
/* The legacy collapsed-chat rule places the room in grid column 2. Keep the
|
||||
connected narrow room in its single-column layout in either chat state. */
|
||||
[data-ws-plugin-part="kaak-workspace"][data-ws-plugin-surface="voice"]:has(
|
||||
@@ -4528,3 +4532,36 @@
|
||||
[data-ws-plugin-part="kaak-workspace.member-cards"] .voice-card { min-height: 116px; height: 116px; }
|
||||
[data-ws-plugin-part="kaak-workspace.member-cards"] .voice-avatar { width: 60px; height: 60px; }
|
||||
}
|
||||
|
||||
/* Keep the compact chat on the content side of the persistent server rail.
|
||||
The room controls remain available after chat is closed, and the rail stays
|
||||
interactive while the chat page is open. */
|
||||
@media (max-width: 820px) {
|
||||
[data-ws-plugin-part="kaak-workspace"][data-ws-plugin-surface="voice"] [data-ws-plugin-part="kaak-workspace.conversation"][data-chat-open="true"] {
|
||||
position: fixed;
|
||||
z-index: 50;
|
||||
inset: 0 0 0 86px;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"][data-mobile-channels="true"] [data-ws-plugin-part="kaak-workspace.conversation"][data-chat-open="true"] {
|
||||
display: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"][data-mobile-channels="true"] [data-ws-plugin-part="kaak-workspace.mobile-room-menu"],
|
||||
[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"]:not([data-mobile-channels="true"])[data-chat-open="true"] [data-ws-plugin-part="kaak-workspace.mobile-room-menu"] {
|
||||
display: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
[data-ws-part="app"]:has([data-ws-plugin-part="kaak-workspace"][data-ws-plugin-surface="voice"]) .modal-backdrop:has([data-ws-part="voice.audio-settings"]) {
|
||||
z-index: 1000;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 360px) {
|
||||
[data-ws-plugin-part="kaak-workspace"][data-ws-plugin-surface="voice"] [data-ws-plugin-part="kaak-workspace.conversation"][data-chat-open="true"] {
|
||||
inset-inline-start: 70px;
|
||||
}
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.7",
|
||||
"version": "0.2.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.7",
|
||||
"version": "0.2.8",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
|
||||
+50
-50
@@ -1,55 +1,55 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.7",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
"description": "Server-side browser gateway for TeamSpeak — deploy on your server, users join from any browser",
|
||||
"engines": {
|
||||
"node": ">=22.5.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.2.8",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
"description": "Server-side browser gateway for TeamSpeak — deploy on your server, users join from any browser",
|
||||
"engines": {
|
||||
"node": ">=22.5.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
"skin:kaak:build": "node web/scripts/build-kaak-voice-skin.mjs",
|
||||
"skin:illusia:build": "node web/scripts/build-illusia-voice-skin.mjs",
|
||||
"start": "node dist/index.js",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "npm --prefix web run build",
|
||||
"skin:wasm:build": "node scripts/build-skin-wasm-interpreter.mjs",
|
||||
"android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs",
|
||||
"android:sync": "npm run android:prepare && cd web && npx cap sync android",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs",
|
||||
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
|
||||
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
|
||||
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
|
||||
"acceleration:relay": "node dist/relay.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"start": "node dist/index.js",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "npm --prefix web run build",
|
||||
"skin:wasm:build": "node scripts/build-skin-wasm-interpreter.mjs",
|
||||
"android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs",
|
||||
"android:sync": "npm run android:prepare && cd web && npx cap sync android",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs",
|
||||
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
|
||||
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
|
||||
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
|
||||
"acceleration:relay": "node dist/relay.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#758a0d7d9120b0f5777d9451fb6b134f0b606f65",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"postcss": "^8.5.29",
|
||||
"postcss-selector-parser": "^7.1.6",
|
||||
"postcss-value-parser": "^4.2.0",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/node": "^22.15.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.2"
|
||||
},
|
||||
"overrides": {
|
||||
"body-parser": "^2.3.0",
|
||||
"esbuild": "^0.28.2",
|
||||
"tar": "^7.5.22"
|
||||
}
|
||||
}
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"postcss": "^8.5.29",
|
||||
"postcss-selector-parser": "^7.1.6",
|
||||
"postcss-value-parser": "^4.2.0",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/node": "^22.15.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.2"
|
||||
},
|
||||
"overrides": {
|
||||
"body-parser": "^2.3.0",
|
||||
"esbuild": "^0.28.2",
|
||||
"tar": "^7.5.22"
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
- 双向 UDP 数据报转发,并保持数据包边界;
|
||||
- 会话之间按随机 ID 隔离;
|
||||
- 错误密钥不能建立会话;
|
||||
- 未开启 `allowPrivate` 时,解析到非公网地址的目标一律被拒绝;
|
||||
- 不修改系统路由,因此不是 VPN。
|
||||
|
||||
## 本地冒烟
|
||||
@@ -19,7 +20,13 @@
|
||||
npm run acceleration:poc
|
||||
```
|
||||
|
||||
成功时会输出 `ACCELERATION_POC_OK`,并显示数据包数量、丢包率和往返延迟。
|
||||
成功时会输出 `ACCELERATION_POC_OK`,并显示数据包数量、丢包率和往返延迟。除吞吐与错误密钥外,该冒烟还会用一个独立的 `allowPrivate: false` 中继断言私网目标防护生效:
|
||||
|
||||
```text
|
||||
ssrf_guard_ok=true blocked=5/5 public_target_allowed=true
|
||||
```
|
||||
|
||||
任一被禁目标未被拦截、或公网目标被误拦,都会输出 `LEAK` / 失败。
|
||||
|
||||
IPv6 回环验证:
|
||||
|
||||
@@ -27,6 +34,12 @@ IPv6 回环验证:
|
||||
npm run acceleration:ipv6-smoke
|
||||
```
|
||||
|
||||
## 私网目标防护与主程序保持一致
|
||||
|
||||
中继的 `isRestrictedAddress()` 是 `src/security/open-target-policy.ts` 中同名函数的镜像。PoC 必须是可直接拷贝到远端运行的 `.mjs` 文件,不能 import 主程序的 TypeScript 模块,因此这段判断是**有意重复**的。`scripts/acceleration-poc/target-guard-parity.test.mjs` 会逐条比对两边的分类结果,任何一侧改动而另一侧未同步都会让 CI 失败。
|
||||
|
||||
该测试放在 PoC 目录内而非 `src/` 下:`.dockerignore` 把 `scripts/acceleration-poc` 排除在 Docker 构建上下文之外,而 Dockerfile 会对 `src/**` 执行 `tsc`,因此 `src/` 下任何 import 该目录的文件都会让镜像构建以 TS2307 失败。
|
||||
|
||||
## 通过隧道连接指定 TeamSpeak
|
||||
|
||||
必须先将下方示例域名替换为你获准测试的 TeamSpeak 地址;脚本不内置真实服务器默认值。下面的命令会让 SDK 连接本地代理端口,再由 PoC 中继把 UDP 数据转发到指定 TeamSpeak。它不进入指定频道,只验证 TeamSpeak 握手和断开:
|
||||
|
||||
@@ -7,38 +7,66 @@ function endpointKey(address, port) {
|
||||
return `${address}/${port}`;
|
||||
}
|
||||
|
||||
function isPrivateAddress(host) {
|
||||
const family = isIP(host);
|
||||
if (family === 4) {
|
||||
const octets = host.split(".").map(Number);
|
||||
return octets[0] === 10
|
||||
|| (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31)
|
||||
|| octets[0] === 192 && octets[1] === 168
|
||||
|| octets[0] === 127
|
||||
|| octets[0] === 169 && octets[1] === 254
|
||||
|| octets[0] === 0;
|
||||
/**
|
||||
* Mirror of `isRestrictedAddress()` in `src/security/open-target-policy.ts`.
|
||||
*
|
||||
* The PoC ships as a plain `.mjs` file that the README documents copying to a
|
||||
* remote host without a build step, so it cannot import the TypeScript policy.
|
||||
* The logic is duplicated rather than shared, and
|
||||
* `scripts/acceleration-poc/target-guard-parity.test.mjs` fails the moment the two
|
||||
* classifications disagree, so drift is caught in CI instead of in production.
|
||||
*
|
||||
* Keep this an exact mirror: fail closed on anything that is not a literal
|
||||
* public address.
|
||||
*/
|
||||
export function isRestrictedAddress(host) {
|
||||
const version = isIP(host);
|
||||
if (version === 4) return isRestrictedIpv4(host);
|
||||
if (version !== 6) return true;
|
||||
|
||||
const normalized = host.toLowerCase();
|
||||
if (normalized === "::" || normalized === "::1") return true;
|
||||
if (normalized.startsWith("::ffff:")) {
|
||||
// IPv4-mapped addresses must be unwrapped before the IPv4 rules apply:
|
||||
// ::ffff:10.0.0.1 is private traffic in IPv6 clothing.
|
||||
const mapped = normalized.slice("::ffff:".length);
|
||||
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
|
||||
}
|
||||
if (family === 6) {
|
||||
const normalized = host.toLowerCase();
|
||||
return normalized === "::1"
|
||||
|| normalized === "::"
|
||||
|| normalized.startsWith("fc")
|
||||
|| normalized.startsWith("fd")
|
||||
|| normalized.startsWith("fe8")
|
||||
|| normalized.startsWith("fe9")
|
||||
|| normalized.startsWith("fea")
|
||||
|| normalized.startsWith("feb");
|
||||
}
|
||||
return host === "localhost" || host.endsWith(".localhost");
|
||||
if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms
|
||||
const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
|
||||
if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
|
||||
if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
|
||||
if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10
|
||||
if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8
|
||||
if (normalized.startsWith("2001:db8:")) return true; // documentation range
|
||||
return false;
|
||||
}
|
||||
|
||||
function isRestrictedIpv4(host) {
|
||||
const parts = host.split(".").map(Number);
|
||||
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return true;
|
||||
const [a, b, c] = parts;
|
||||
return a === 0
|
||||
|| a === 10
|
||||
|| a === 127
|
||||
|| (a === 100 && b >= 64 && b <= 127)
|
||||
|| (a === 169 && b === 254)
|
||||
|| (a === 172 && b >= 16 && b <= 31)
|
||||
|| (a === 192 && b === 0)
|
||||
|| (a === 192 && b === 168)
|
||||
|| (a === 198 && (b === 18 || b === 19))
|
||||
|| (a === 198 && b === 51 && c === 100)
|
||||
|| (a === 203 && b === 0 && c === 113)
|
||||
|| a >= 224;
|
||||
}
|
||||
|
||||
async function resolveTarget(host) {
|
||||
const family = isIP(host);
|
||||
if (family) return { host, family };
|
||||
if (family) return { host, family, resolved: [host] };
|
||||
const records = await lookup(host, { all: true, verbatim: true });
|
||||
const record = records.find((item) => item.family === 4) ?? records[0];
|
||||
if (!record) throw new Error("TARGET_DNS_EMPTY");
|
||||
return { host: record.address, family: record.family };
|
||||
return { host: record.address, family: record.family, resolved: records.map((item) => item.address) };
|
||||
}
|
||||
|
||||
export async function createRelayServer({
|
||||
@@ -71,11 +99,6 @@ export async function createRelayServer({
|
||||
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) {
|
||||
return;
|
||||
}
|
||||
if (!allowPrivate && (isPrivateAddress(request.targetHost) || request.targetHost === "localhost")) {
|
||||
const error = { code: "PRIVATE_TARGET_BLOCKED" };
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address);
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = sessions.get(frame.sessionId);
|
||||
if (existing) cleanup(existing);
|
||||
@@ -92,6 +115,14 @@ export async function createRelayServer({
|
||||
|
||||
try {
|
||||
const target = await resolveTarget(request.targetHost);
|
||||
// Validate the resolved addresses, not the caller-supplied name: a DNS
|
||||
// answer can point any hostname at loopback or an internal address.
|
||||
if (!allowPrivate && target.resolved.some((address) => isRestrictedAddress(address))) {
|
||||
const error = { code: "PRIVATE_TARGET_BLOCKED" };
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address);
|
||||
cleanup(session);
|
||||
return;
|
||||
}
|
||||
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
|
||||
session.targetSocket = targetSocket;
|
||||
targetSocket.on("message", (payload) => {
|
||||
|
||||
@@ -51,6 +51,59 @@ async function run() {
|
||||
rejectedBadToken = true;
|
||||
}
|
||||
|
||||
// SSRF guard: a relay started without allowPrivate must refuse every request
|
||||
// that resolves to a non-public address, and must still serve public ones.
|
||||
// Asserting only the happy path would let the private-address guard regress
|
||||
// unnoticed, since the throughput relay above runs with allowPrivate: true.
|
||||
const guardedRelay = await createRelayServer({
|
||||
host: "127.0.0.1",
|
||||
port: 0,
|
||||
token: TOKEN,
|
||||
allowPrivate: false,
|
||||
});
|
||||
const blockedTargets = ["127.0.0.1", "10.0.0.1", "169.254.169.254", "192.168.1.1", "::ffff:127.0.0.1"];
|
||||
const blockedResults = [];
|
||||
for (const targetHost of blockedTargets) {
|
||||
let allowed = false;
|
||||
try {
|
||||
const tunnel = await createRelayClient({
|
||||
relayHost: "127.0.0.1",
|
||||
relayPort: guardedRelay.port,
|
||||
targetHost,
|
||||
targetPort: 9987,
|
||||
token: TOKEN,
|
||||
timeoutMs: 1_000,
|
||||
});
|
||||
tunnel.close();
|
||||
allowed = true;
|
||||
} catch (error) {
|
||||
// The relay answers OPEN_ERR(PRIVATE_TARGET_BLOCKED); any other failure
|
||||
// (timeout, bad token) would not prove the guard fired.
|
||||
allowed = !(error instanceof Error && error.message === "PRIVATE_TARGET_BLOCKED");
|
||||
}
|
||||
blockedResults.push({ targetHost, blocked: !allowed });
|
||||
}
|
||||
|
||||
let publicTargetAllowed = false;
|
||||
try {
|
||||
const tunnel = await createRelayClient({
|
||||
relayHost: "127.0.0.1",
|
||||
relayPort: guardedRelay.port,
|
||||
targetHost: "8.8.8.8",
|
||||
targetPort: 9987,
|
||||
token: TOKEN,
|
||||
timeoutMs: 2_000,
|
||||
});
|
||||
publicTargetAllowed = true;
|
||||
tunnel.close();
|
||||
} catch {
|
||||
publicTargetAllowed = false;
|
||||
}
|
||||
guardedRelay.close();
|
||||
|
||||
const guardFailures = blockedResults.filter((entry) => !entry.blocked);
|
||||
const ssrfGuardOk = guardFailures.length === 0 && publicTargetAllowed;
|
||||
|
||||
const sender = createSocket("udp4");
|
||||
await bind(sender);
|
||||
const pending = new Map();
|
||||
@@ -90,7 +143,11 @@ async function run() {
|
||||
console.log(`packets=${PACKET_COUNT} received=${received} loss=${loss.toFixed(2)}%`);
|
||||
console.log(`rtt_ms_avg=${average.toFixed(3)} p95=${Number(percentile(0.95)).toFixed(3)} max=${Number(percentile(0.99)).toFixed(3)}`);
|
||||
console.log(`bad_token_rejected=${rejectedBadToken}`);
|
||||
if (received !== PACKET_COUNT || !rejectedBadToken) throw new Error("ACCELERATION_POC_FAILED");
|
||||
console.log(`ssrf_guard_ok=${ssrfGuardOk} blocked=${blockedResults.filter((entry) => entry.blocked).length}/${blockedResults.length} public_target_allowed=${publicTargetAllowed}`);
|
||||
for (const entry of blockedResults) {
|
||||
if (!entry.blocked) console.log(` LEAK: ${entry.targetHost} was not blocked by the private-target guard`);
|
||||
}
|
||||
if (received !== PACKET_COUNT || !rejectedBadToken || !ssrfGuardOk) throw new Error("ACCELERATION_POC_FAILED");
|
||||
console.log("ACCELERATION_POC_OK");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isRestrictedAddress } from "../../src/security/open-target-policy.js";
|
||||
import { isRestrictedAddress as isPocRestrictedAddress } from "./relay-server.mjs";
|
||||
|
||||
/**
|
||||
* The acceleration PoC relay keeps its own copy of the restricted-address
|
||||
* predicate because it is a standalone `.mjs` file that the README documents
|
||||
* copying to a remote host without a build step, so it cannot import the
|
||||
* gateway's TypeScript module. Duplication is only safe while the two stay
|
||||
* identical: these cases pin both classifications to the same answer, so a
|
||||
* change to either side without the other fails here instead of silently
|
||||
* widening the PoC's SSRF boundary.
|
||||
*
|
||||
* This test lives beside the PoC because `.dockerignore` excludes
|
||||
* `scripts/acceleration-poc` from the Docker build context while the Dockerfile
|
||||
* runs `tsc` over `src/**`; a copy under `src/` would make the image build fail
|
||||
* with TS2307.
|
||||
*/
|
||||
const CASES = [
|
||||
// Public addresses that must stay reachable.
|
||||
["8.8.8.8", false],
|
||||
["1.1.1.1", false],
|
||||
["172.32.0.1", false],
|
||||
["100.128.0.1", false],
|
||||
["2001:4860:4860::8888", false],
|
||||
["2606:4700:4700::1111", false],
|
||||
// Private, loopback and link-local.
|
||||
["10.0.0.1", true],
|
||||
["172.16.0.1", true],
|
||||
["172.31.255.255", true],
|
||||
["192.168.1.1", true],
|
||||
["127.0.0.1", true],
|
||||
["169.254.169.254", true],
|
||||
["0.0.0.0", true],
|
||||
["0.1.2.3", true],
|
||||
// Carrier-grade NAT.
|
||||
["100.64.0.1", true],
|
||||
["100.127.255.255", true],
|
||||
// Special-use ranges: the PoC's first implementation missed every one of these.
|
||||
["192.0.0.1", true],
|
||||
["192.0.2.5", true],
|
||||
["198.18.0.1", true],
|
||||
["198.19.5.5", true],
|
||||
["198.51.100.7", true],
|
||||
["203.0.113.9", true],
|
||||
["224.0.0.1", true],
|
||||
["239.1.1.1", true],
|
||||
["255.255.255.255", true],
|
||||
// IPv6 loopback, unspecified, unique-local, link-local, site-local, multicast.
|
||||
["::1", true],
|
||||
["::", true],
|
||||
["fc00::1", true],
|
||||
["fd12::1", true],
|
||||
["fe80::1", true],
|
||||
["fec0::1", true],
|
||||
["ff02::1", true],
|
||||
["2001:db8::1", true],
|
||||
// IPv4-mapped forms must unwrap before the IPv4 rules apply.
|
||||
["::ffff:127.0.0.1", true],
|
||||
["::ffff:10.0.0.1", true],
|
||||
["::ffff:8.8.8.8", false],
|
||||
// Anything that is not a literal address fails closed.
|
||||
["localhost", true],
|
||||
["public.example.invalid", true],
|
||||
["", true],
|
||||
];
|
||||
|
||||
test("the acceleration PoC relay classifies restricted addresses exactly like the gateway policy", () => {
|
||||
const mismatches = [];
|
||||
for (const [address, expected] of CASES) {
|
||||
const policy = isRestrictedAddress(address);
|
||||
const poc = isPocRestrictedAddress(address);
|
||||
assert.equal(policy, expected, `gateway policy disagrees with the pinned expectation for ${address}`);
|
||||
if (poc !== policy) {
|
||||
mismatches.push(`${address}: policy=${policy} poc=${poc}`);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(mismatches, [], "the PoC relay's restricted-address guard drifted from the gateway policy");
|
||||
});
|
||||
|
||||
test("the acceleration PoC relay fails closed on a non-literal address", () => {
|
||||
// `isIP()` returns 0 for a hostname, so the guard must not treat an
|
||||
// unresolved name as public just because it is not a literal address.
|
||||
for (const hostname of ["localhost", "internal.example.invalid", "attacker.example.invalid", ""]) {
|
||||
assert.equal(isPocRestrictedAddress(hostname), true, `${hostname} must fail closed`);
|
||||
}
|
||||
});
|
||||
@@ -58,6 +58,7 @@ async function main() {
|
||||
certDir: hasCert ? CERT_DIR : undefined,
|
||||
voiceBridgeOptions: {
|
||||
joinTickets,
|
||||
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
|
||||
webRtc: () => adminService.getWebRtcAudioOptions(),
|
||||
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
|
||||
// The public gateway only uses the relay configuration explicitly
|
||||
@@ -130,6 +131,11 @@ function parseBoolean(value: string | undefined): boolean {
|
||||
return value === "1" || value?.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
function readTrustedProxies(value: string | undefined): string[] | undefined {
|
||||
const entries = value?.split(/[\s,]+/).filter(Boolean) ?? [];
|
||||
return entries.length ? entries : undefined;
|
||||
}
|
||||
|
||||
function readScreenShareIceServers(value: string | undefined): ScreenShareIceServer[] {
|
||||
const raw = value?.trim();
|
||||
if (!raw) return normalizeScreenShareIceServers();
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createHmac } from "node:crypto";
|
||||
import { createSocket, type Socket } from "node:dgram";
|
||||
import { createAccelerationRelayServer } from "./acceleration-relay.js";
|
||||
|
||||
const TOKEN = "test-acceleration-relay-token";
|
||||
const MAGIC = Buffer.from("WSAT");
|
||||
const HEADER_SIZE = 34;
|
||||
const enum FrameType { OPEN = 1, OPEN_OK = 2, OPEN_ERR = 3 }
|
||||
|
||||
function encodeFrame(type: FrameType, sessionId: number, payload: Buffer): Buffer {
|
||||
const frame = Buffer.alloc(HEADER_SIZE + payload.length);
|
||||
MAGIC.copy(frame, 0);
|
||||
frame[4] = 1;
|
||||
frame[5] = type;
|
||||
frame.writeUInt32BE(sessionId >>> 0, 8);
|
||||
frame.writeUInt32BE(1, 12);
|
||||
frame.writeUInt16BE(payload.length, 16);
|
||||
createHmac("sha256", Buffer.from(TOKEN, "utf8"))
|
||||
.update(frame.subarray(0, 18)).update(payload)
|
||||
.digest().subarray(0, 16).copy(frame, 18);
|
||||
payload.copy(frame, HEADER_SIZE);
|
||||
return frame;
|
||||
}
|
||||
|
||||
function decodeFrame(packet: Buffer): { type: number; sessionId: number; payload: Buffer } | null {
|
||||
if (packet.length < HEADER_SIZE || !packet.subarray(0, 4).equals(MAGIC) || packet[4] !== 1) return null;
|
||||
const length = packet.readUInt16BE(16);
|
||||
if (packet.length !== HEADER_SIZE + length) return null;
|
||||
return { type: packet[5]!, sessionId: packet.readUInt32BE(8), payload: packet.subarray(HEADER_SIZE) };
|
||||
}
|
||||
|
||||
const resolved = (...addresses: string[]) => async () => addresses.map((address) => ({
|
||||
address,
|
||||
family: address.includes(":") ? 6 : 4,
|
||||
}));
|
||||
|
||||
/** Send one OPEN and resolve with the relay's first reply. */
|
||||
function openTarget(server: { host: string; port: number }, targetHost: string, targetPort = 9987): Promise<{ type: number; code?: string }> {
|
||||
const client = createSocket("udp4");
|
||||
const sessionId = 0x5a5a0001;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
client.close();
|
||||
reject(new Error("The relay did not answer the OPEN frame"));
|
||||
}, 3_000);
|
||||
client.on("message", (packet) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || frame.sessionId !== sessionId) return;
|
||||
clearTimeout(timer);
|
||||
let code: string | undefined;
|
||||
try { code = (JSON.parse(frame.payload.toString("utf8")) as { code?: string }).code; } catch { code = undefined; }
|
||||
client.close();
|
||||
resolve({ type: frame.type, code });
|
||||
});
|
||||
const payload = Buffer.from(JSON.stringify({ targetHost, targetPort }), "utf8");
|
||||
client.send(encodeFrame(FrameType.OPEN, sessionId, payload), server.port, server.host);
|
||||
});
|
||||
}
|
||||
|
||||
async function startRelay(options: { allowPrivate?: boolean; lookupAddresses?: () => Promise<{ address: string; family: number }[]> } = {}) {
|
||||
return await createAccelerationRelayServer({ host: "127.0.0.1", port: 0, token: TOKEN, ...options });
|
||||
}
|
||||
|
||||
test("a hostname that resolves to loopback is blocked by the resolved-address check", async () => {
|
||||
const server = await startRelay({ lookupAddresses: resolved("127.0.0.1") });
|
||||
try {
|
||||
// Regression: the name itself is not an IP literal, so a string-only check
|
||||
// used to pass and the relay then connected to the resolved loopback address.
|
||||
const reply = await openTarget(server, "attacker.example.invalid");
|
||||
assert.equal(reply.type, FrameType.OPEN_ERR);
|
||||
assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED");
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("IPv4-mapped IPv6 literals cannot bypass the private-address check", async () => {
|
||||
for (const target of ["::ffff:127.0.0.1", "::ffff:10.0.0.1", "::ffff:169.254.169.254"]) {
|
||||
const server = await startRelay({});
|
||||
try {
|
||||
const reply = await openTarget(server, target);
|
||||
assert.equal(reply.type, FrameType.OPEN_ERR, `${target} should be blocked`);
|
||||
assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED", `${target} should be blocked`);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("private and special-use literals stay blocked", async () => {
|
||||
for (const target of ["10.0.0.5", "172.16.0.1", "192.168.1.1", "127.0.0.1", "169.254.169.254", "100.64.0.1", "::1", "fd00::1"]) {
|
||||
const server = await startRelay({});
|
||||
try {
|
||||
const reply = await openTarget(server, target);
|
||||
assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED", `${target} should be blocked`);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a mixed public/private DNS answer is rejected instead of using the public record", async () => {
|
||||
const server = await startRelay({ lookupAddresses: resolved("8.8.8.8", "192.168.1.10") });
|
||||
try {
|
||||
const reply = await openTarget(server, "mixed.example.invalid");
|
||||
assert.equal(reply.type, FrameType.OPEN_ERR);
|
||||
assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED");
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("allowPrivate keeps the private-target escape hatch working", async () => {
|
||||
const listener = createSocket("udp4");
|
||||
await new Promise<void>((resolve) => listener.bind(0, "127.0.0.1", resolve));
|
||||
const port = (listener.address() as { port: number }).port;
|
||||
const server = await startRelay({ allowPrivate: true });
|
||||
try {
|
||||
const reply = await openTarget(server, "127.0.0.1", port);
|
||||
assert.equal(reply.type, FrameType.OPEN_OK);
|
||||
} finally {
|
||||
server.close();
|
||||
listener.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a public target still opens a relay session", async () => {
|
||||
// UDP connect() only sets the default destination, so a public address opens
|
||||
// the session without sending traffic or needing a real listener.
|
||||
const server = await startRelay({});
|
||||
try {
|
||||
const reply = await openTarget(server, "8.8.8.8");
|
||||
assert.equal(reply.type, FrameType.OPEN_OK);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a bind failure rejects startup instead of throwing out of the error listener", async () => {
|
||||
// Regression: the socket error listener ended with `throw error`, which escaped
|
||||
// EventEmitter.emit, became an uncaught exception, and killed the process. It
|
||||
// also aborted the remaining listeners, so this call never settled at all.
|
||||
const server = await startRelay({});
|
||||
try {
|
||||
await assert.rejects(
|
||||
() => createAccelerationRelayServer({ host: "127.0.0.1", port: server.port, token: TOKEN }),
|
||||
(error: NodeJS.ErrnoException) => error.code === "EADDRINUSE",
|
||||
);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a failed startup leaves the surviving relay serving traffic", async () => {
|
||||
// The thrown error used to take the whole process down with it; the relay that
|
||||
// did bind must stay usable.
|
||||
const server = await startRelay({});
|
||||
try {
|
||||
await assert.rejects(() => createAccelerationRelayServer({ host: "127.0.0.1", port: server.port, token: TOKEN }));
|
||||
const reply = await openTarget(server, "8.8.8.8");
|
||||
assert.equal(reply.type, FrameType.OPEN_OK);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("closing a relay is idempotent after a failed sibling startup", async () => {
|
||||
const server = await startRelay({});
|
||||
// A failed startup already tore its own socket down, so nothing leaks and the
|
||||
// surviving relay still closes cleanly when close() runs more than once.
|
||||
const failed = await createAccelerationRelayServer({ host: "127.0.0.1", port: server.port, token: TOKEN }).catch(() => null);
|
||||
assert.equal(failed, null);
|
||||
server.close();
|
||||
server.close();
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { createSocket } from "node:dgram";
|
||||
import { isIP } from "node:net";
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isRestrictedAddress } from "../security/open-target-policy.js";
|
||||
|
||||
const MAGIC = Buffer.from("WSAT");
|
||||
const VERSION = 1;
|
||||
@@ -36,10 +37,20 @@ export interface AccelerationTarget {
|
||||
port: number;
|
||||
}
|
||||
|
||||
type AddressLookup = (hostname: string) => Promise<{ address: string; family: number }[]>;
|
||||
|
||||
export interface AccelerationRelayClient {
|
||||
readonly localHost: string;
|
||||
readonly localPort: number;
|
||||
readonly sessionId: number;
|
||||
/**
|
||||
* True once the tunnel has torn itself down, whether by {@link close} or on
|
||||
* its own after a socket error, a relay OPEN_ERR/CLOSE frame, or an open
|
||||
* timeout. Callers that route a transport through this tunnel must watch this
|
||||
* flag: after it flips, every sendFrame() call is a silent no-op and both UDP
|
||||
* sockets are closed, so the tunnel can never recover on its own.
|
||||
*/
|
||||
isClosed(): boolean;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
@@ -150,6 +161,7 @@ export async function createAccelerationRelayClient(
|
||||
localHost: "127.0.0.1",
|
||||
localPort: typeof address === "object" ? address.port : 0,
|
||||
sessionId,
|
||||
isClosed: (): boolean => closed,
|
||||
close(): void {
|
||||
if (!closed && ready) {
|
||||
try { sendFrame(FrameType.CLOSE); } catch { /* best effort */ }
|
||||
@@ -165,17 +177,24 @@ export async function createAccelerationRelayServer({
|
||||
token,
|
||||
allowPrivate = false,
|
||||
idleTimeoutMs = 30_000,
|
||||
lookupAddresses = (hostname) => lookup(hostname, { all: true, verbatim: true }),
|
||||
onError = (error) => { console.error(`[acceleration-relay] socket error: ${error.message}`); },
|
||||
}: {
|
||||
host?: string;
|
||||
port?: number;
|
||||
token: string;
|
||||
allowPrivate?: boolean;
|
||||
idleTimeoutMs?: number;
|
||||
lookupAddresses?: AddressLookup;
|
||||
onError?: (error: Error) => void;
|
||||
}): Promise<{ host: string; port: number; close(): void }> {
|
||||
if (!token || token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters");
|
||||
const socket = createSocket(isIP(host) === 6 ? "udp6" : "udp4");
|
||||
const sessions = new Map<number, RelaySession>();
|
||||
let closed = false;
|
||||
let started = false;
|
||||
let sweep: ReturnType<typeof setInterval> | null = null;
|
||||
let rejectStartup: ((error: Error) => void) | null = null;
|
||||
|
||||
const send = (session: RelaySession, type: FrameType, payload: Buffer<ArrayBufferLike> = Buffer.alloc(0)): void => {
|
||||
if (closed) return;
|
||||
@@ -188,12 +207,37 @@ export async function createAccelerationRelayServer({
|
||||
session.targetSocket?.close();
|
||||
};
|
||||
|
||||
const shutdown = (): void => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (sweep) clearInterval(sweep);
|
||||
sweep = null;
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
try { socket.close(); } catch { /* never bound, or already closed */ }
|
||||
};
|
||||
|
||||
// A listener throwing here is an uncaught exception: it escapes EventEmitter.emit
|
||||
// and terminates the whole process, and because the throw aborts the remaining
|
||||
// listeners it also stops the startup promise below from ever settling. Report the
|
||||
// failure instead — a startup error rejects the returned promise, a later one tears
|
||||
// the relay down — so callers can handle it rather than crash.
|
||||
socket.on("error", (error) => {
|
||||
if (!started) {
|
||||
const reject = rejectStartup;
|
||||
rejectStartup = null;
|
||||
shutdown();
|
||||
reject?.(asError(error));
|
||||
return;
|
||||
}
|
||||
shutdown();
|
||||
onError(asError(error));
|
||||
});
|
||||
socket.on("message", (packet, rinfo) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || !verifyFrame(frame, token)) return;
|
||||
const client = { address: rinfo.address, port: rinfo.port };
|
||||
if (frame.type === FrameType.OPEN) {
|
||||
void openRelaySession(frame, client, socket, sessions, token, allowPrivate, send, cleanup);
|
||||
void openRelaySession(frame, client, socket, sessions, token, allowPrivate, send, cleanup, lookupAddresses);
|
||||
return;
|
||||
}
|
||||
const session = sessions.get(frame.sessionId);
|
||||
@@ -203,35 +247,35 @@ export async function createAccelerationRelayServer({
|
||||
else if (frame.type === FrameType.PING) send(session, FrameType.PONG);
|
||||
else if (frame.type === FrameType.CLOSE) { send(session, FrameType.CLOSE); cleanup(session); }
|
||||
});
|
||||
socket.on("error", (error) => {
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
if (!closed) throw error;
|
||||
});
|
||||
|
||||
const sweep = setInterval(() => {
|
||||
sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const session of sessions.values()) if (now - session.lastActivity > idleTimeoutMs) cleanup(session);
|
||||
}, Math.max(1000, Math.min(idleTimeoutMs, 5000)));
|
||||
sweep.unref?.();
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onError = (error: Error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
rejectStartup = reject;
|
||||
socket.once("listening", () => {
|
||||
started = true;
|
||||
rejectStartup = null;
|
||||
resolve();
|
||||
});
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
} catch (error) {
|
||||
// A synchronous bind failure (for example an unusable address) never emits
|
||||
// "error", so release the socket and the sweep interval here too.
|
||||
rejectStartup = null;
|
||||
shutdown();
|
||||
throw error;
|
||||
}
|
||||
const address = socket.address();
|
||||
return {
|
||||
host,
|
||||
port: typeof address === "object" ? address.port : port,
|
||||
close(): void {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(sweep);
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
socket.close();
|
||||
},
|
||||
close: shutdown,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -253,20 +297,27 @@ async function openRelaySession(
|
||||
allowPrivate: boolean,
|
||||
send: (session: RelaySession, type: FrameType, payload?: Buffer) => void,
|
||||
cleanup: (session: RelaySession) => void,
|
||||
lookupAddresses: AddressLookup,
|
||||
): Promise<void> {
|
||||
const request = parseJson(frame.payload);
|
||||
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) return;
|
||||
const targetPort = request.targetPort as number;
|
||||
if (!allowPrivate && isPrivateAddress(request.targetHost)) {
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "PRIVATE_TARGET_BLOCKED" }), token), client.port, client.address);
|
||||
return;
|
||||
}
|
||||
const previous = sessions.get(frame.sessionId);
|
||||
if (previous) cleanup(previous);
|
||||
const session: RelaySession = { id: frame.sessionId, client, targetSocket: null, outSequence: 1, lastActivity: Date.now(), closed: false };
|
||||
sessions.set(session.id, session);
|
||||
try {
|
||||
const target = await resolveTarget(request.targetHost);
|
||||
const target = await resolveTarget(request.targetHost, lookupAddresses);
|
||||
// The private-target check must run on the resolved addresses, never on the
|
||||
// caller-supplied name: a DNS answer can map any hostname onto loopback or
|
||||
// an internal address after a string-only check has already passed. Every
|
||||
// address in the answer set is checked so a mixed public/private response
|
||||
// cannot be used to reach an internal host.
|
||||
if (!allowPrivate && target.resolved.some((address) => isRestrictedAddress(address))) {
|
||||
cleanup(session);
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "PRIVATE_TARGET_BLOCKED" }), token), client.port, client.address);
|
||||
return;
|
||||
}
|
||||
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
|
||||
session.targetSocket = targetSocket;
|
||||
targetSocket.on("message", (payload) => { session.lastActivity = Date.now(); send(session, FrameType.DATA, payload); });
|
||||
@@ -341,26 +392,13 @@ function parseJson(payload: Buffer): Record<string, unknown> | null {
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function isPrivateAddress(host: string): boolean {
|
||||
async function resolveTarget(host: string, lookupAddresses: AddressLookup): Promise<{ host: string; family: number; resolved: string[] }> {
|
||||
const family = isIP(host);
|
||||
if (family === 4) {
|
||||
const parts = host.split(".").map(Number);
|
||||
return parts[0] === 10 || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 192 && parts[1] === 168) || parts[0] === 127 || (parts[0] === 169 && parts[1] === 254) || parts[0] === 0;
|
||||
}
|
||||
if (family === 6) {
|
||||
const normalized = host.toLocaleLowerCase();
|
||||
return normalized === "::" || normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb");
|
||||
}
|
||||
return host === "localhost" || host.endsWith(".localhost");
|
||||
}
|
||||
|
||||
async function resolveTarget(host: string): Promise<{ host: string; family: number }> {
|
||||
const family = isIP(host);
|
||||
if (family) return { host, family };
|
||||
const records = await lookup(host, { all: true, verbatim: true });
|
||||
if (family) return { host, family, resolved: [host] };
|
||||
const records = await lookupAddresses(host);
|
||||
const record = records.find((item) => item.family === 4) ?? records[0];
|
||||
if (!record) throw new Error("TARGET_DNS_EMPTY");
|
||||
return { host: record.address, family: record.family };
|
||||
return { host: record.address, family: record.family, resolved: records.map((item) => item.address) };
|
||||
}
|
||||
|
||||
function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); }
|
||||
@@ -4,16 +4,26 @@ import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { ScreenShareCoordinator, type ScreenShareParticipant } from "./screen-share-coordinator.js";
|
||||
import { parseServerMessage, type ServerMessage } from "../shared/server-messages.js";
|
||||
import type { ScreenShareClientMessage } from "../shared/screen-share.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
|
||||
function fixture() {
|
||||
const entries = new Map<string, ScreenShareParticipant>();
|
||||
const messages: Array<{ to: string; message: ServerMessage }> = [];
|
||||
const commands: Array<{ from: string; command: string }> = [];
|
||||
const logs: Array<{ context: Record<string, unknown>; message: string }> = [];
|
||||
const send = (to: string, message: ServerMessage) => {
|
||||
assert.ok(parseServerMessage(JSON.parse(JSON.stringify(message))), `invalid message: ${message.type}`);
|
||||
messages.push({ to, message });
|
||||
return true;
|
||||
};
|
||||
const coordinator = new ScreenShareCoordinator(entries, send, { debug() {}, warn() {} });
|
||||
const debug = ((contextOrMessage: Record<string, unknown> | string, message?: string) => {
|
||||
logs.push({ context: typeof contextOrMessage === "string" ? {} : contextOrMessage, message: message ?? contextOrMessage.toString() });
|
||||
}) as Logger["debug"];
|
||||
const info = ((contextOrMessage: Record<string, unknown> | string, message?: string) => {
|
||||
logs.push({ context: typeof contextOrMessage === "string" ? {} : contextOrMessage, message: message ?? contextOrMessage.toString() });
|
||||
}) as Logger["info"];
|
||||
const warn = (() => {}) as Logger["warn"];
|
||||
const coordinator = new ScreenShareCoordinator(entries, send, { debug, info, warn });
|
||||
function participant(id: string, clientId: number, channel = 1n, host = "first.example") {
|
||||
const entry: ScreenShareParticipant = {
|
||||
id, nickname: id, screenPeerId: `peer-${id}`, target: { host, port: 9987 }, members: new Map([[clientId, {}]]),
|
||||
@@ -41,7 +51,7 @@ function fixture() {
|
||||
assert.ok(share);
|
||||
return share.streamId;
|
||||
}
|
||||
return { entries, messages, commands, coordinator, participant, handle, list, start };
|
||||
return { entries, messages, commands, logs, coordinator, participant, handle, list, start };
|
||||
}
|
||||
|
||||
test("sharing is isolated by server and channel, and only its owner can stop it", () => {
|
||||
@@ -80,6 +90,43 @@ test("signaling permits owner-viewer pairs but rejects viewer-to-viewer injectio
|
||||
assert.equal(f.messages.at(-1)?.message.type, "screenShareSignal");
|
||||
});
|
||||
|
||||
test("screen-share diagnostics trace the native viewer handshake without logging SDP or ICE contents", async () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const streamId = f.start(owner);
|
||||
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "ts-stream-1", clid: "1" } });
|
||||
|
||||
f.coordinator.handleNotification(owner, { name: "notifyjoinstreamrequest", params: { id: "wrong-stream", clid: "17" } });
|
||||
f.coordinator.handleNotification(owner, { name: "notifyjoinstreamrequest", params: { id: "ts-stream-1", clid: "17" } });
|
||||
assert.ok(f.messages.some(({ to, message }) => to === owner.id && message.type === "screenShareNativeViewerJoined"));
|
||||
|
||||
f.handle(owner, {
|
||||
type: "screenShareSignal",
|
||||
streamId,
|
||||
targetPeerId: "ts-viewer-17",
|
||||
signal: { kind: "offer", sdp: "private-sdp-marker" },
|
||||
});
|
||||
f.coordinator.handleNotification(owner, {
|
||||
name: "notifystreamsignaling",
|
||||
params: { id: "ts-stream-1", clid: "17", json: JSON.stringify({ cmd: "answer", args: { answer: "private-answer-marker" } }) },
|
||||
});
|
||||
f.coordinator.handleNotification(owner, {
|
||||
name: "notifystreamsignaling",
|
||||
params: { id: "ts-stream-1", clid: "17", json: JSON.stringify({ cmd: "iceCandidate", args: { sdp: "private-candidate-marker", mid: "video", mLine: 0 } }) },
|
||||
});
|
||||
await nextTurn();
|
||||
|
||||
assert.ok(f.logs.some(({ message }) => message === "TeamSpeak screen-share join request did not match an active browser stream"));
|
||||
assert.ok(f.logs.some(({ message }) => message === "Forwarded TeamSpeak screen-share join request to browser owner"));
|
||||
assert.ok(f.logs.some(({ message, context }) => message === "Forwarded browser screen-share signaling to TeamSpeak viewer" && context.signalKind === "offer"));
|
||||
assert.ok(f.logs.some(({ message, context }) => message === "Forwarded TeamSpeak screen-share signaling to browser owner" && context.signalKind === "answer"));
|
||||
assert.ok(f.logs.some(({ message, context }) => message === "Forwarded TeamSpeak screen-share signaling to browser owner" && context.signalKind === "iceCandidate"));
|
||||
const serializedLogs = JSON.stringify(f.logs);
|
||||
assert.equal(serializedLogs.includes("private-sdp-marker"), false);
|
||||
assert.equal(serializedLogs.includes("private-answer-marker"), false);
|
||||
assert.equal(serializedLogs.includes("private-candidate-marker"), false);
|
||||
});
|
||||
|
||||
test("another member moving channels cannot stop the owner's share or evict its viewer", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
@@ -357,3 +404,66 @@ test("native removal notification and acknowledgement publish only one viewer-le
|
||||
assert.equal(f.list(owner)[0]?.viewerCount, 0);
|
||||
assert.equal(f.messages.filter(({ message }) => message.type === "screenShareViewerLeft").length, 1);
|
||||
});
|
||||
|
||||
test("the viewer roster references members by client id instead of inlining avatars", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const streamId = f.start(owner);
|
||||
// Give every viewer the largest avatar the gateway will still accept.
|
||||
const avatar = `data:image/png;base64,${"A".repeat(128 * 1024 - 22)}`;
|
||||
const viewers = Array.from({ length: 8 }, (_, index) => {
|
||||
const clientId = index + 2;
|
||||
const viewer = f.participant(`viewer-${index}`, clientId);
|
||||
const member = viewer.members.get(clientId);
|
||||
assert.ok(member);
|
||||
member.avatar = avatar;
|
||||
f.handle(viewer, { type: "screenShareJoin", streamId });
|
||||
return { viewer, clientId };
|
||||
});
|
||||
const roster = f.messages
|
||||
.filter(({ to, message }) => to === owner.id && message.type === "screenShareViewerCount")
|
||||
.at(-1)?.message;
|
||||
assert.ok(roster?.type === "screenShareViewerCount");
|
||||
const rosterViewers = roster.viewers ?? [];
|
||||
assert.equal(rosterViewers.length, viewers.length);
|
||||
// Eight 128 KiB avatars would be ~1 MB. The roster is rebroadcast to the whole
|
||||
// channel on every join/leave, so it must not scale with avatar size at all.
|
||||
const bytes = Buffer.byteLength(JSON.stringify(roster));
|
||||
assert.ok(bytes < 16 * 1024, `roster payload must stay small regardless of avatars, got ${bytes} bytes`);
|
||||
assert.deepEqual(
|
||||
rosterViewers.map(viewer => viewer.clientId).sort((left, right) => left! - right!),
|
||||
viewers.map(({ clientId }) => clientId).sort((left, right) => left - right),
|
||||
"each roster entry must carry the TeamSpeak client id so the client can resolve the avatar locally",
|
||||
);
|
||||
for (const viewer of rosterViewers) {
|
||||
assert.equal("avatar" in viewer, false, "the roster must not inline avatars");
|
||||
}
|
||||
});
|
||||
|
||||
test("a viewer whose entry disappeared no longer inflates the announced count", () => {
|
||||
const f = fixture();
|
||||
const owner = f.participant("owner", 1);
|
||||
const streamId = f.start(owner);
|
||||
const live = f.participant("live", 2);
|
||||
const gone = f.participant("gone", 3);
|
||||
f.handle(live, { type: "screenShareJoin", streamId });
|
||||
f.handle(gone, { type: "screenShareJoin", streamId });
|
||||
|
||||
const before = f.messages
|
||||
.filter(({ to, message }) => to === owner.id && message.type === "screenShareViewerCount")
|
||||
.at(-1)?.message;
|
||||
assert.ok(before?.type === "screenShareViewerCount");
|
||||
assert.equal(before.viewerCount, 2);
|
||||
|
||||
// The entry disappears without passing through the coordinator's leave path.
|
||||
f.entries.delete(gone.id);
|
||||
const later = f.participant("later", 4);
|
||||
f.handle(later, { type: "screenShareJoin", streamId });
|
||||
|
||||
const after = f.messages
|
||||
.filter(({ to, message }) => to === owner.id && message.type === "screenShareViewerCount")
|
||||
.at(-1)?.message;
|
||||
assert.ok(after?.type === "screenShareViewerCount");
|
||||
assert.equal(after.viewers?.length, 2, "only viewers that still exist are listed");
|
||||
assert.equal(after.viewerCount, 2, "the announced count must match the listed viewers");
|
||||
});
|
||||
@@ -46,8 +46,8 @@ export class ScreenShareCoordinator {
|
||||
|
||||
constructor(
|
||||
private readonly entries: ReadonlyMap<string, ScreenShareParticipant>,
|
||||
private readonly sendToEntry: (entryId: string, message: ServerMessage) => void,
|
||||
private readonly logger: Pick<Logger, "debug" | "warn">,
|
||||
private readonly sendToEntry: (entryId: string, message: ServerMessage) => boolean,
|
||||
private readonly logger: Pick<Logger, "debug" | "info" | "warn">,
|
||||
) {}
|
||||
|
||||
handleMessage(
|
||||
@@ -84,6 +84,13 @@ export class ScreenShareCoordinator {
|
||||
nativeViewerClids: new Set(),
|
||||
};
|
||||
this.screenStreams.set(screenStreamKey(stream.targetKey, stream.streamId), stream);
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: stream.streamId,
|
||||
ownerClientId: stream.ownerClientId ?? null,
|
||||
channelId: String(stream.channelId),
|
||||
}, "Started browser screen-share stream and requested TeamSpeak publication");
|
||||
sendJson({ type: "screenShareStarted", requestId: message.requestId, stream: this.describeScreenStream(stream), owner: true });
|
||||
this.broadcastScreenMessage(stream, {
|
||||
type: "screenShareStarted",
|
||||
@@ -96,10 +103,30 @@ export class ScreenShareCoordinator {
|
||||
|
||||
const stream = this.screenStreams.get(screenStreamKey(teamSpeakTargetKey(entry.target), message.streamId));
|
||||
if (!stream) {
|
||||
if (message.type === "screenShareSignal") {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: message.streamId,
|
||||
targetPeerId: message.targetPeerId,
|
||||
signalKind: message.signal.kind,
|
||||
}, "Dropped screen-share signaling for an unknown stream");
|
||||
}
|
||||
sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_NOT_FOUND", message: "屏幕共享已结束或不存在" });
|
||||
return;
|
||||
}
|
||||
if (stream.targetKey !== teamSpeakTargetKey(entry.target) || stream.channelId !== entry.tsClient.getChannelId()) {
|
||||
if (message.type === "screenShareSignal") {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: stream.streamId,
|
||||
targetPeerId: message.targetPeerId,
|
||||
signalKind: message.signal.kind,
|
||||
sameTarget: stream.targetKey === teamSpeakTargetKey(entry.target),
|
||||
sameChannel: stream.channelId === entry.tsClient.getChannelId(),
|
||||
}, "Dropped screen-share signaling because the stream target changed");
|
||||
}
|
||||
sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_TARGET_MISMATCH", message: "屏幕共享不属于当前服务器或频道" });
|
||||
return;
|
||||
}
|
||||
@@ -233,11 +260,20 @@ export class ScreenShareCoordinator {
|
||||
.filter((entry): entry is ScreenShareParticipant => Boolean(entry))
|
||||
.slice(0, 64)
|
||||
.map((entry) => {
|
||||
const avatar = entry.members.get(entry.tsClient.getClientId())?.avatar;
|
||||
// Send the client id, not the avatar: receivers already hold member
|
||||
// avatars from the directory, and this roster is rebroadcast to the
|
||||
// whole channel on every join and leave. Inlining avatars here scales
|
||||
// with (viewers x avatar size x channel members) per event.
|
||||
let clientId: number | undefined;
|
||||
try {
|
||||
clientId = entry.tsClient.getClientId();
|
||||
} catch {
|
||||
clientId = undefined;
|
||||
}
|
||||
return {
|
||||
peerId: entry.screenPeerId,
|
||||
nickname: entry.nickname,
|
||||
...(avatar && avatar.length <= 128 * 1024 ? { avatar } : {}),
|
||||
...(typeof clientId === "number" && clientId > 0 ? { clientId } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -246,15 +282,29 @@ export class ScreenShareCoordinator {
|
||||
return {
|
||||
type: "screenShareViewerCount",
|
||||
streamId: stream.streamId,
|
||||
viewerCount: stream.viewerCount,
|
||||
// Derive the count from the same call as the roster so the announced
|
||||
// number can never disagree with the entries actually listed.
|
||||
viewerCount: this.screenShareViewerCount(stream),
|
||||
viewers: this.describeScreenViewers(stream),
|
||||
};
|
||||
}
|
||||
|
||||
private screenShareViewerCount(stream: ScreenStreamRecord): number {
|
||||
this.pruneStaleViewers(stream);
|
||||
return stream.viewerEntryIds.size + stream.nativeViewerClids.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop viewer entries whose participant is gone. A client can disappear from
|
||||
* the entry map without passing through the leave path, and a lingering id
|
||||
* inflates the announced count while the roster silently omits it.
|
||||
*/
|
||||
private pruneStaleViewers(stream: ScreenStreamRecord): void {
|
||||
for (const entryId of [...stream.viewerEntryIds.keys()]) {
|
||||
if (!this.entries.has(entryId)) stream.viewerEntryIds.delete(entryId);
|
||||
}
|
||||
}
|
||||
|
||||
private broadcastScreenMessage(stream: ScreenStreamRecord, message: ServerMessage, excludeEntryId?: string): void {
|
||||
for (const candidate of this.entries.values()) {
|
||||
if (candidate.id === excludeEntryId || candidate.target && teamSpeakTargetKey(candidate.target) !== stream.targetKey) continue;
|
||||
@@ -314,6 +364,14 @@ export class ScreenShareCoordinator {
|
||||
signal: ScreenSharePeerSignal,
|
||||
sendJson: (message: ServerMessage) => void,
|
||||
): void {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: stream.streamId,
|
||||
targetPeerId,
|
||||
source: stream.source,
|
||||
signalKind: signal.kind,
|
||||
}, "Received browser screen-share signaling");
|
||||
if (stream.source === "teamspeak") {
|
||||
if (!stream.viewerEntryIds.has(entry.id) || targetPeerId !== stream.ownerPeerId) {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" });
|
||||
@@ -341,6 +399,14 @@ export class ScreenShareCoordinator {
|
||||
json: JSON.stringify(payload),
|
||||
})).catch((error: unknown) => {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" });
|
||||
this.logger.warn({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: stream.streamId,
|
||||
targetPeerId,
|
||||
signalKind: signal.kind,
|
||||
errorName: error instanceof Error ? error.name : "unknown",
|
||||
}, "Could not forward browser screen-share signaling to TeamSpeak source");
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -349,6 +415,16 @@ export class ScreenShareCoordinator {
|
||||
const viewerClid = parseNativeViewerPeerId(targetPeerId);
|
||||
const publisher = stream.teamSpeakPublisherEntryId ? this.entries.get(stream.teamSpeakPublisherEntryId) : undefined;
|
||||
if (!viewerClid || !publisher || !stream.teamSpeakStreamId || !stream.nativeViewerClids.has(viewerClid)) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
streamId: stream.streamId,
|
||||
teamSpeakStreamId: stream.teamSpeakStreamId,
|
||||
targetPeerId,
|
||||
viewerClid: viewerClid ?? null,
|
||||
publisherAvailable: Boolean(publisher),
|
||||
viewerRegistered: viewerClid ? stream.nativeViewerClids.has(viewerClid) : false,
|
||||
signalKind: signal.kind,
|
||||
}, "Dropped browser screen-share signaling because the TeamSpeak viewer was not ready");
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "TeamSpeak 观看者已离开" });
|
||||
return;
|
||||
}
|
||||
@@ -394,8 +470,23 @@ export class ScreenShareCoordinator {
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
void publisher.tsClient.sendProtocolCommand(command).catch((error: unknown) => {
|
||||
const signalContext = {
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: stream.streamId,
|
||||
teamSpeakStreamId: stream.teamSpeakStreamId,
|
||||
viewerClid,
|
||||
signalKind: signal.kind,
|
||||
};
|
||||
this.logger.info(signalContext, "Forwarding browser screen-share signaling to TeamSpeak viewer");
|
||||
void publisher.tsClient.sendProtocolCommand(command).then(() => {
|
||||
this.logger.info(signalContext, "Forwarded browser screen-share signaling to TeamSpeak viewer");
|
||||
}).catch((error: unknown) => {
|
||||
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" });
|
||||
this.logger.warn({
|
||||
...signalContext,
|
||||
errorName: error instanceof Error ? error.name : "unknown",
|
||||
}, "Could not forward browser screen-share signaling to TeamSpeak viewer");
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -433,6 +524,11 @@ export class ScreenShareCoordinator {
|
||||
viewer_limit: "0",
|
||||
audio: stream.audio ? "1" : "0",
|
||||
}));
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: stream.streamId,
|
||||
}, "TeamSpeak accepted browser screen-share publication request");
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
@@ -532,33 +628,81 @@ export class ScreenShareCoordinator {
|
||||
}
|
||||
|
||||
handleNotification(entry: ScreenShareParticipant, notification: TSRawNotification): void {
|
||||
if (this.entries.get(entry.id) !== entry) return;
|
||||
if (this.entries.get(entry.id) !== entry) {
|
||||
if (["notifyjoinstreamrequest", "notifystreamstarted", "notifystreaminfo", "notifyrespondjoinstreamrequest", "notifystreamsignaling"].includes(notification.name)) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
notification: notification.name,
|
||||
}, "Ignored screen-share notification from a stale TeamSpeak connection");
|
||||
}
|
||||
return;
|
||||
}
|
||||
const params = notification.params;
|
||||
if (notification.name === "notifyjoinstreamrequest") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
const viewerClientId = parseNumber(params.clid);
|
||||
if (!streamId || !viewerClientId) return;
|
||||
if (!streamId || !viewerClientId) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
hasStreamId: Boolean(streamId),
|
||||
hasViewerClientId: Boolean(viewerClientId),
|
||||
}, "Ignored TeamSpeak screen-share join request with incomplete identifiers");
|
||||
return;
|
||||
}
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
const activeBrowserStreams = [...this.screenStreams.values()].filter((candidate) => candidate.targetKey === targetKey
|
||||
&& candidate.source === "browser"
|
||||
&& candidate.teamSpeakPublisherEntryId === entry.id
|
||||
&& candidate.teamSpeakStreamId === streamId);
|
||||
if (!stream) return;
|
||||
&& candidate.teamSpeakPublisherEntryId === entry.id);
|
||||
const stream = activeBrowserStreams.find((candidate) => candidate.teamSpeakStreamId === streamId);
|
||||
if (!stream) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
teamSpeakStreamId: streamId,
|
||||
viewerClientId,
|
||||
activeBrowserStreamIds: activeBrowserStreams.map((candidate) => candidate.teamSpeakStreamId ?? null),
|
||||
}, "TeamSpeak screen-share join request did not match an active browser stream");
|
||||
return;
|
||||
}
|
||||
const alreadyRegistered = stream.nativeViewerClids.has(viewerClientId);
|
||||
stream.nativeViewerClids.add(viewerClientId);
|
||||
stream.viewerCount = this.screenShareViewerCount(stream);
|
||||
this.sendToEntry(stream.ownerEntryId, {
|
||||
const deliveredToBrowser = this.sendToEntry(stream.ownerEntryId, {
|
||||
type: "screenShareNativeViewerJoined",
|
||||
streamId: stream.streamId,
|
||||
viewerPeerId: nativeViewerPeerId(viewerClientId),
|
||||
viewerClientId,
|
||||
});
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
ownerEntryId: stream.ownerEntryId,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: stream.streamId,
|
||||
teamSpeakStreamId: streamId,
|
||||
viewerClientId,
|
||||
duplicateRequest: alreadyRegistered,
|
||||
deliveredToBrowser,
|
||||
}, deliveredToBrowser
|
||||
? "Forwarded TeamSpeak screen-share join request to browser owner"
|
||||
: "Could not forward TeamSpeak screen-share join request because browser WebSocket is unavailable");
|
||||
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
|
||||
return;
|
||||
}
|
||||
if (notification.name === "notifystreamstarted" || notification.name === "notifystreaminfo") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
const sourceClientId = parseNumber(params.clid);
|
||||
if (!streamId || !sourceClientId) return;
|
||||
if (!streamId || !sourceClientId) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
notification: notification.name,
|
||||
hasStreamId: Boolean(streamId),
|
||||
hasSourceClientId: Boolean(sourceClientId),
|
||||
}, "Ignored TeamSpeak screen-stream notification with incomplete identifiers");
|
||||
return;
|
||||
}
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const publisherEntry = [...this.entries.values()].find((candidate) => candidate.target
|
||||
&& teamSpeakTargetKey(candidate.target) === targetKey
|
||||
@@ -571,9 +715,26 @@ export class ScreenShareCoordinator {
|
||||
: undefined;
|
||||
if (browserStream) {
|
||||
browserStream.teamSpeakStreamId = streamId;
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: browserStream.streamId,
|
||||
teamSpeakStreamId: streamId,
|
||||
sourceClientId,
|
||||
}, "Linked TeamSpeak publication to browser screen-share stream");
|
||||
return;
|
||||
}
|
||||
if (publisherEntry) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
publisherEntryId: publisherEntry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
teamSpeakStreamId: streamId,
|
||||
sourceClientId,
|
||||
activeBrowserStreamIds: [...this.screenStreams.values()]
|
||||
.filter((candidate) => candidate.targetKey === targetKey && candidate.source === "browser" && candidate.teamSpeakPublisherEntryId === publisherEntry.id)
|
||||
.map((candidate) => candidate.teamSpeakStreamId ?? null),
|
||||
}, "TeamSpeak screen-stream notification did not match the browser publisher stream");
|
||||
// A delayed setup acknowledgement can arrive after the browser stopped.
|
||||
// A gateway-owned publication is never a second native source.
|
||||
void publisherEntry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", { id: streamId, reason: "1" })).catch(() => undefined);
|
||||
@@ -678,7 +839,15 @@ export class ScreenShareCoordinator {
|
||||
}
|
||||
if (notification.name === "notifyrespondjoinstreamrequest" || notification.name === "notifystreamsignaling") {
|
||||
const streamId = params.id || params.stream_id;
|
||||
if (!streamId) return;
|
||||
if (!streamId) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
notification: notification.name,
|
||||
hasStreamId: false,
|
||||
}, "Ignored TeamSpeak screen-share signaling without a stream id");
|
||||
return;
|
||||
}
|
||||
const targetKey = teamSpeakTargetKey(entry.target);
|
||||
const browserStream = notification.name === "notifystreamsignaling"
|
||||
? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
|
||||
@@ -688,28 +857,104 @@ export class ScreenShareCoordinator {
|
||||
: undefined;
|
||||
if (browserStream) {
|
||||
const viewerClientId = parseNumber(params.clid);
|
||||
if (!viewerClientId || !browserStream.nativeViewerClids.has(viewerClientId)) return;
|
||||
if (!viewerClientId || !browserStream.nativeViewerClids.has(viewerClientId)) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
notification: notification.name,
|
||||
teamSpeakStreamId: streamId,
|
||||
viewerClientId: viewerClientId ?? null,
|
||||
viewerRegistered: viewerClientId ? browserStream.nativeViewerClids.has(viewerClientId) : false,
|
||||
}, "Ignored TeamSpeak signaling for an unregistered browser-share viewer");
|
||||
return;
|
||||
}
|
||||
const payload = parseStreamSignalPayload(params.json || params.data || "");
|
||||
if (!payload) return;
|
||||
if (!payload) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
notification: notification.name,
|
||||
teamSpeakStreamId: streamId,
|
||||
viewerClientId,
|
||||
hasSignalPayload: Boolean(params.json || params.data),
|
||||
}, "Ignored unparseable TeamSpeak browser-share signaling payload");
|
||||
return;
|
||||
}
|
||||
const signal = toBrowserScreenSignal(payload);
|
||||
if (!signal) return;
|
||||
this.sendToEntry(browserStream.ownerEntryId, {
|
||||
if (!signal) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
notification: notification.name,
|
||||
teamSpeakStreamId: streamId,
|
||||
viewerClientId,
|
||||
signalKind: payload.cmd,
|
||||
}, "Ignored unsupported TeamSpeak browser-share signaling kind");
|
||||
return;
|
||||
}
|
||||
const deliveredToBrowser = this.sendToEntry(browserStream.ownerEntryId, {
|
||||
type: "screenShareSignal",
|
||||
streamId: browserStream.streamId,
|
||||
fromPeerId: nativeViewerPeerId(viewerClientId),
|
||||
signal,
|
||||
});
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
ownerEntryId: browserStream.ownerEntryId,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId: browserStream.streamId,
|
||||
teamSpeakStreamId: streamId,
|
||||
viewerClientId,
|
||||
signalKind: signal.kind,
|
||||
deliveredToBrowser,
|
||||
}, deliveredToBrowser
|
||||
? "Forwarded TeamSpeak screen-share signaling to browser owner"
|
||||
: "Could not forward TeamSpeak screen-share signaling because browser WebSocket is unavailable");
|
||||
return;
|
||||
}
|
||||
const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId));
|
||||
if (!stream || stream.source !== "teamspeak" || !stream.viewerEntryIds.has(entry.id)) return;
|
||||
if (!stream || stream.source !== "teamspeak" || !stream.viewerEntryIds.has(entry.id)) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
notification: notification.name,
|
||||
teamSpeakStreamId: streamId,
|
||||
knownStreamSource: stream?.source ?? null,
|
||||
viewerJoined: stream?.viewerEntryIds.has(entry.id) ?? false,
|
||||
}, "Ignored TeamSpeak signaling that did not match an active native stream viewer");
|
||||
return;
|
||||
}
|
||||
const payload = notification.name === "notifyrespondjoinstreamrequest"
|
||||
? { cmd: "offer", args: { offer: params.offer || "" } }
|
||||
: parseStreamSignalPayload(params.json || params.data || "");
|
||||
if (!payload) return;
|
||||
if (!payload) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
notification: notification.name,
|
||||
teamSpeakStreamId: streamId,
|
||||
hasSignalPayload: Boolean(params.json || params.data || params.offer),
|
||||
}, "Ignored unparseable TeamSpeak native-share signaling payload");
|
||||
return;
|
||||
}
|
||||
const signal = toBrowserScreenSignal(payload);
|
||||
if (!signal) return;
|
||||
if (!signal) {
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
notification: notification.name,
|
||||
teamSpeakStreamId: streamId,
|
||||
signalKind: payload.cmd,
|
||||
}, "Ignored unsupported TeamSpeak native-share signaling kind");
|
||||
return;
|
||||
}
|
||||
this.sendToEntry(entry.id, { type: "screenShareSignal", streamId, fromPeerId: stream.ownerPeerId, signal });
|
||||
this.logger.info({
|
||||
entryId: entry.id,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
streamId,
|
||||
signalKind: signal.kind,
|
||||
}, "Forwarded TeamSpeak native-share signaling to browser viewer");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { TSVoiceData } from "./ts-client.js";
|
||||
|
||||
@@ -13,6 +14,14 @@ function fixture() {
|
||||
const encoded: Buffer[] = [];
|
||||
const forwarded: Array<{ data: Buffer; codec: number; targets?: number[] }> = [];
|
||||
const notices: ServerMessage[] = [];
|
||||
const warnings: Array<Record<string, unknown>> = [];
|
||||
const logger: LoggerType = {
|
||||
debug: () => {},
|
||||
info: () => {},
|
||||
error: () => {},
|
||||
warn: (objOrMsg: Record<string, unknown> | string) => { if (typeof objOrMsg !== "string") warnings.push(objOrMsg); },
|
||||
child: () => logger,
|
||||
};
|
||||
const socket = { readyState: 1 as 0 | 1 | 2 | 3, bufferedAmount: 0, send: (packet: Buffer) => { packets.push(packet); } };
|
||||
const client = {
|
||||
sendVoice: (data: Buffer, codec: number) => { forwarded.push({ data, codec }); },
|
||||
@@ -23,12 +32,12 @@ function fixture() {
|
||||
dispose() { state.disposed++; },
|
||||
};
|
||||
const transport = new SessionAudioTransport({
|
||||
audio, socket, client, isCurrent: () => state.current, isReady: () => state.ready,
|
||||
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
|
||||
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
|
||||
sendJson: message => { notices.push(message); },
|
||||
}, encoder, () => state.now);
|
||||
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
|
||||
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, remote };
|
||||
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote };
|
||||
}
|
||||
|
||||
test("PCM framing preserves codec, whisper routing and timing counters", () => {
|
||||
@@ -49,19 +58,45 @@ test("PCM framing preserves codec, whisper routing and timing counters", () => {
|
||||
test("invalid PCM is rejected and reconnecting sessions do not encode audio", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.alloc(1_919));
|
||||
f.state.now = 5_000;
|
||||
f.transport.receivePcm(Buffer.alloc(1_921));
|
||||
assert.equal(f.notices.length, 2);
|
||||
assert.deepEqual(f.notices[0], { type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
|
||||
assert.deepEqual(f.notices[1], f.notices[0]);
|
||||
f.state.ready = false;
|
||||
f.state.now = 10_000;
|
||||
f.transport.receivePcm(Buffer.alloc(1_919));
|
||||
assert.equal(f.notices.length, 2, "a frame the route discards must not be reported as malformed");
|
||||
assert.equal(f.warnings.length, 2, "a frame the route discards must not reach the operator log");
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.transport.receiveWebRtc(Buffer.from([1]), 4);
|
||||
f.transport.receiveTeamSpeak(f.remote());
|
||||
assert.equal(f.audio.ingressDroppedFrames, 3);
|
||||
assert.equal(f.audio.ingressDroppedFrames, 4);
|
||||
assert.equal(f.encoded.length, 0);
|
||||
assert.equal(f.forwarded.length, 0);
|
||||
assert.equal(f.packets.length, 0);
|
||||
});
|
||||
|
||||
test("repeated malformed frames are counted in full but reported once per window", () => {
|
||||
const f = fixture();
|
||||
for (const now of [0, 1, 4_999, 5_000]) { f.state.now = now; f.transport.receivePcm(Buffer.alloc(1_919)); }
|
||||
assert.equal(f.audio.ingressDroppedFrames, 4, "every discarded frame still reaches the flow counters");
|
||||
assert.equal(f.notices.length, 2, "the browser sees one error per window, not one per frame");
|
||||
assert.deepEqual(f.warnings, [
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 1 },
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 4 },
|
||||
], "operators get the same rate-limited view through the logger");
|
||||
});
|
||||
|
||||
test("an encoder failure and a malformed frame do not suppress each other", t => {
|
||||
const f = fixture();
|
||||
t.mock.method(f.encoder, "encode", () => { throw new Error("Codec failed"); });
|
||||
f.transport.receivePcm(Buffer.alloc(1_919));
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.deepEqual(f.notices.map(message => message.type), ["error", "audioError"]);
|
||||
t.mock.restoreAll();
|
||||
});
|
||||
|
||||
test("WebRTC ingress excludes queued PCM and fallback re-enables PCM", () => {
|
||||
const f = fixture();
|
||||
f.state.peer = { pushTeamSpeakVoice() {} };
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { WebSocket } from "ws";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { AudioFlowStats } from "./audio-stats.js";
|
||||
import type { TSClient, TSVoiceData } from "./ts-client.js";
|
||||
@@ -7,6 +8,10 @@ import type { WebRtcAudioSession } from "./webrtc-audio.js";
|
||||
const AUDIO_FRAME_BYTES = 1_920; // 20 ms of 48 kHz mono Int16 PCM.
|
||||
// Keep the established byte guard; the browser also bounds playback by time.
|
||||
const MAX_BUFFERED_BYTES = 4_096;
|
||||
// A client that keeps sending bad audio must not turn into one JSON error per
|
||||
// frame: the reply is roughly 100x the offending payload, and the browser only
|
||||
// ever shows the first one because it writes the same error string.
|
||||
const AUDIO_ISSUE_REPORT_MS = 5_000;
|
||||
|
||||
export interface VoiceEncoder {
|
||||
encode(frame: Buffer): Buffer;
|
||||
@@ -17,6 +22,8 @@ export interface SessionAudioOptions {
|
||||
audio: AudioFlowStats;
|
||||
socket: Pick<WebSocket, "readyState" | "bufferedAmount"> & { send(packet: Buffer): void };
|
||||
client: Pick<TSClient, "sendVoice" | "sendWhisper">;
|
||||
/** Optional: audio faults are also surfaced here so operators can see them. */
|
||||
logger?: LoggerType;
|
||||
isCurrent(): boolean;
|
||||
isReady(): boolean;
|
||||
selfId(): number;
|
||||
@@ -29,10 +36,13 @@ export interface SessionAudioOptions {
|
||||
export class SessionAudioTransport {
|
||||
private encoder: VoiceEncoder | null;
|
||||
private closed = false;
|
||||
private warnedAt: number | null = null;
|
||||
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
|
||||
private readonly reportedAt = new Map<string, number>();
|
||||
private readonly logger: LoggerType | null;
|
||||
|
||||
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) {
|
||||
this.encoder = encoder;
|
||||
this.logger = options.logger ?? null;
|
||||
}
|
||||
|
||||
private isCurrent(): boolean {
|
||||
@@ -64,25 +74,59 @@ export class SessionAudioTransport {
|
||||
}
|
||||
}
|
||||
|
||||
private reportEncoderFailure(): void {
|
||||
/**
|
||||
* Decide whether an audio fault is worth reporting right now. Repeated faults
|
||||
* of the same kind collapse into one report per window. Codes are tracked
|
||||
* separately so that one fault cannot hide a different one, which a single
|
||||
* shared window would do.
|
||||
*
|
||||
* The browser only renders the first error string of a run, so dropping the
|
||||
* repeats costs the user nothing; what it saves is the server-side cost, which
|
||||
* is proportional to however fast the client streams bad frames.
|
||||
*/
|
||||
private shouldReportAudioIssue(code: string): boolean {
|
||||
const now = this.clock();
|
||||
if (this.warnedAt !== null && now - this.warnedAt < 5_000) return;
|
||||
this.warnedAt = now;
|
||||
const last = this.reportedAt.get(code);
|
||||
if (last !== undefined && now - last < AUDIO_ISSUE_REPORT_MS) return false;
|
||||
this.reportedAt.set(code, now);
|
||||
return true;
|
||||
}
|
||||
|
||||
private reportEncoderFailure(): void {
|
||||
if (!this.shouldReportAudioIssue("AUDIO_ENCODER_UNAVAILABLE")) return;
|
||||
this.logger?.warn({ code: "AUDIO_ENCODER_UNAVAILABLE" }, "Opus encoder unavailable for the browser uplink");
|
||||
try {
|
||||
this.options.sendJson({ type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" });
|
||||
} catch { /* the socket may have closed while reporting the failure */ }
|
||||
}
|
||||
|
||||
private reportInvalidFrame(length: number): void {
|
||||
if (!this.shouldReportAudioIssue("INVALID_AUDIO_FRAME")) return;
|
||||
// Log the faults that the browser is told about: the outbound error is not
|
||||
// logged anywhere, so without this an operator has no way to notice a client
|
||||
// that keeps sending malformed audio until the session is torn down.
|
||||
this.logger?.warn(
|
||||
{ code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: AUDIO_FRAME_BYTES, droppedFrames: this.options.audio.ingressDroppedFrames },
|
||||
"Discarded malformed browser audio frame",
|
||||
);
|
||||
try {
|
||||
this.options.sendJson({ type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
|
||||
} catch { /* the socket may have closed while reporting the failure */ }
|
||||
}
|
||||
|
||||
receivePcm(frame: Buffer): void {
|
||||
if (!this.isCurrent()) return;
|
||||
const stats = this.options.audio;
|
||||
if (frame.length !== AUDIO_FRAME_BYTES) {
|
||||
stats.ingressDroppedFrames++;
|
||||
this.options.sendJson({ type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
|
||||
return;
|
||||
}
|
||||
// Resolve the route before judging the frame. A frame that arrives while the
|
||||
// route is down is discarded whatever its size, so calling it malformed would
|
||||
// misattribute the drop and raise a spurious client error in the browser.
|
||||
// Late TCP frames from before a WebRTC switch must not duplicate RTP audio.
|
||||
if (!this.options.isReady() || this.options.peer()) { stats.ingressDroppedFrames++; return; }
|
||||
if (frame.length !== AUDIO_FRAME_BYTES) {
|
||||
stats.ingressDroppedFrames++;
|
||||
this.reportInvalidFrame(frame.length);
|
||||
return;
|
||||
}
|
||||
this.recordIngress();
|
||||
const startedAt = this.clock();
|
||||
let encoded: Buffer;
|
||||
@@ -150,6 +194,7 @@ export class SessionAudioTransport {
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
this.reportedAt.clear();
|
||||
const encoder = this.encoder;
|
||||
this.encoder = null;
|
||||
try { encoder?.dispose(); } catch { /* other session resources must still be released */ }
|
||||
|
||||
@@ -108,6 +108,35 @@ test("server icons use the TeamSpeak file transfer path and enforce the download
|
||||
assert.equal(f.sdk.downloaded, 1);
|
||||
});
|
||||
|
||||
test("rapid channel switches wait for each TeamSpeak acknowledgement", async () => {
|
||||
const f = fixture();
|
||||
const firstAck = deferred<void>();
|
||||
const switchCommands: string[] = [];
|
||||
let activeSwitches = 0;
|
||||
let maxActiveSwitches = 0;
|
||||
f.sdk.inputUpdate = async command => {
|
||||
if (!command.startsWith("clientmove ")) return;
|
||||
switchCommands.push(command);
|
||||
activeSwitches += 1;
|
||||
maxActiveSwitches = Math.max(maxActiveSwitches, activeSwitches);
|
||||
if (switchCommands.length === 1) await firstAck.promise;
|
||||
activeSwitches -= 1;
|
||||
};
|
||||
|
||||
const first = f.client.switchChannel(10n);
|
||||
const second = f.client.switchChannel(20n);
|
||||
await nextTurn();
|
||||
assert.equal(switchCommands.length, 1, "the second clientmove waits until the first is acknowledged");
|
||||
assert.equal(maxActiveSwitches, 1, "only one channel move can be active on the session");
|
||||
|
||||
firstAck.resolve();
|
||||
await Promise.all([first, second]);
|
||||
assert.equal(switchCommands.length, 2);
|
||||
assert.match(switchCommands[0], /cid=10(?:\s|$)/);
|
||||
assert.match(switchCommands[1], /cid=20(?:\s|$)/);
|
||||
assert.equal(maxActiveSwitches, 1);
|
||||
});
|
||||
|
||||
test("stream cleanup flood retries back off and stop after two retries", async t => {
|
||||
const f = fixture();
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
@@ -410,3 +439,47 @@ for (const [name, payload] of retiredEvents) {
|
||||
assert.equal(observed.length, 1);
|
||||
});
|
||||
}
|
||||
|
||||
interface RelayFixtureState {
|
||||
accelerationClient: { isClosed(): boolean; close(): void } | null;
|
||||
adapter: { disconnect(): Promise<void> } | null;
|
||||
client: SdkStub | null;
|
||||
dropStaleAccelerationTransport(): void;
|
||||
}
|
||||
|
||||
function relayFixture(tunnelClosed: boolean) {
|
||||
const client = new TSClient({
|
||||
target: { host: "voice.example.invalid", port: 9987 },
|
||||
nickname: "Test",
|
||||
acceleration: { relayHost: "127.0.0.1", relayPort: 39087, token: "test-acceleration-relay-token" },
|
||||
}, pino({ enabled: false }));
|
||||
let disconnectCalls = 0;
|
||||
let closeCalls = 0;
|
||||
const state = client as unknown as RelayFixtureState;
|
||||
state.accelerationClient = {
|
||||
isClosed: () => tunnelClosed,
|
||||
close: () => { closeCalls++; },
|
||||
};
|
||||
state.adapter = { disconnect: async () => { disconnectCalls++; } };
|
||||
state.client = new SdkStub();
|
||||
return { client, state, counts: () => ({ disconnectCalls, closeCalls }) };
|
||||
}
|
||||
|
||||
test("a self-closed relay tunnel is dropped with its adapter so connect() rebuilds both", () => {
|
||||
// Regression: reconnecting reused the adapter bound to the dead tunnel's local
|
||||
// port. Every frame the tunnel sent was a silent no-op, so auto-reconnect
|
||||
// could never recover and nothing reported an error.
|
||||
const f = relayFixture(true);
|
||||
f.state.dropStaleAccelerationTransport();
|
||||
assert.equal(f.state.accelerationClient, null, "the dead tunnel must not be reused");
|
||||
assert.equal(f.state.adapter, null, "the adapter bound to the dead local port must be dropped");
|
||||
assert.equal(f.state.client, null, "the SDK client for the dead transport must be dropped");
|
||||
});
|
||||
|
||||
test("a live relay tunnel survives the reconnect guard untouched", () => {
|
||||
const f = relayFixture(false);
|
||||
f.state.dropStaleAccelerationTransport();
|
||||
assert.notEqual(f.state.accelerationClient, null, "an open tunnel stays usable");
|
||||
assert.notEqual(f.state.adapter, null, "an open tunnel's adapter stays usable");
|
||||
assert.notEqual(f.state.client, null, "an open tunnel's SDK client stays usable");
|
||||
});
|
||||
+44
-3
@@ -112,6 +112,7 @@ export class TSClient extends EventEmitter {
|
||||
private inputState = { muted: false, accompaniment: false };
|
||||
private syncedInputMuted: boolean | null = null;
|
||||
private inputStateQueue: Promise<void> = Promise.resolve();
|
||||
private channelSwitchQueue: Promise<void> = Promise.resolve();
|
||||
private preferredChannelId = 0n;
|
||||
private accelerationClient: AccelerationRelayClient | null = null;
|
||||
private readonly channelCapacities = new Map<bigint, ChannelCapacity>();
|
||||
@@ -127,6 +128,25 @@ export class TSClient extends EventEmitter {
|
||||
this.identity = options.identity ?? generateIdentity(8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Discards an acceleration tunnel that closed itself (socket error, relay
|
||||
* OPEN_ERR/CLOSE, or open timeout) together with the adapter and SDK client
|
||||
* bound to its now-dead local port, so the next connect() builds all three
|
||||
* from scratch. A closed tunnel silently drops every frame, so reusing the
|
||||
* adapter would make reconnection fail forever without an error.
|
||||
*/
|
||||
private dropStaleAccelerationTransport(): void {
|
||||
if (!this.accelerationClient?.isClosed()) return;
|
||||
const staleAdapter = this.adapter;
|
||||
// Detach before teardown: every SDK listener bails when it no longer owns
|
||||
// this.client, so a late "disconnected" from the stale transport cannot
|
||||
// re-enter connect() through the reconnect path.
|
||||
this.accelerationClient = null;
|
||||
this.adapter = null;
|
||||
this.client = null;
|
||||
try { void staleAdapter?.disconnect().catch(() => undefined); } catch { /* already gone */ }
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.connectionGeneration++;
|
||||
this.inputState = { muted: false, accompaniment: false };
|
||||
@@ -135,6 +155,12 @@ export class TSClient extends EventEmitter {
|
||||
this.selfLeaveReasonId = null;
|
||||
this.channelCapacities.clear();
|
||||
this.channelPasswordProtection.clear();
|
||||
// A relay tunnel that tore itself down (socket error, OPEN_ERR/CLOSE frame,
|
||||
// open timeout) reports nothing and no-ops every send, while adapter and
|
||||
// client still look reusable. Reconnecting through the dead local port would
|
||||
// silently fail forever, so drop the whole stack and let the block below
|
||||
// build a fresh tunnel plus adapter.
|
||||
this.dropStaleAccelerationTransport();
|
||||
if (!this.adapter || !this.client) {
|
||||
let transportTarget = this.options.target;
|
||||
if (this.options.acceleration && !this.accelerationClient) {
|
||||
@@ -528,9 +554,24 @@ export class TSClient extends EventEmitter {
|
||||
}
|
||||
|
||||
async switchChannel(channelId: bigint, password?: string): Promise<void> {
|
||||
if (!this.client || !this.connected) return;
|
||||
await tsClientMove(this.client, this.clientId, channelId, password);
|
||||
this.preferredChannelId = channelId;
|
||||
const client = this.client;
|
||||
if (!client) throw new Error("TeamSpeak session is not ready");
|
||||
const clientId = this.clientId;
|
||||
const generation = this.connectionGeneration;
|
||||
const isCurrent = () => client !== null && this.client === client && this.connected && this.connectionGeneration === generation;
|
||||
const move = async () => {
|
||||
if (!isCurrent()) throw new Error("TeamSpeak session is not ready");
|
||||
await tsClientMove(client, clientId, channelId, password);
|
||||
if (!isCurrent()) throw new Error("TeamSpeak session changed while switching channels");
|
||||
this.preferredChannelId = channelId;
|
||||
};
|
||||
|
||||
// Rapid clicks used to issue overlapping clientmove commands. The SDK and
|
||||
// TeamSpeak server both treat these as stateful session operations, so wait
|
||||
// for each acknowledgement before sending the next move.
|
||||
const operation = this.channelSwitchQueue.then(move, move);
|
||||
this.channelSwitchQueue = operation.catch(() => undefined);
|
||||
return operation;
|
||||
}
|
||||
|
||||
/** Move another visible TeamSpeak client; the server enforces both move powers. */
|
||||
|
||||
@@ -85,6 +85,26 @@ async function fixture(t: TestContext, overrides: {
|
||||
return { bridge, sdk, socket, messages, entries, wss };
|
||||
}
|
||||
|
||||
function messageTypes(messages: Array<{ data: Buffer; binary: boolean }>): string[] {
|
||||
return messages
|
||||
.filter(message => !message.binary)
|
||||
.map(message => (JSON.parse(message.data.toString()) as { type: string }).type);
|
||||
}
|
||||
|
||||
function waitForMessage<T extends Record<string, unknown>>(socket: WebSocket, type: string): Promise<T> {
|
||||
return new Promise(resolve => {
|
||||
socket.on("message", (data, binary) => {
|
||||
if (binary) return;
|
||||
const message = JSON.parse(data.toString()) as { type?: string };
|
||||
if (message.type === type) resolve(message as unknown as T);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// The native Opus codec is unavailable in some environments. These tests only
|
||||
// exercise gateway wiring, so the encoder is stubbed out.
|
||||
const stubEncoder = () => ({ encode: () => Buffer.alloc(0), dispose: () => {} });
|
||||
|
||||
test("a TeamSpeak constructor failure releases the admitted gateway slot", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, { createTeamSpeakClient() { throw new Error("Identity initialization failed"); } });
|
||||
if (f.socket.readyState !== WebSocket.CLOSED) await once(f.socket, "close");
|
||||
@@ -127,6 +147,77 @@ test("server identity lookup waits until the directory sync publishes the connec
|
||||
assert.ok(f.bridge.getActiveCount() > 0);
|
||||
});
|
||||
|
||||
test("a TeamSpeak drop before the directory sync fails the connection instead of stalling", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
waitForFirstMessage: false,
|
||||
createEncoder: stubEncoder,
|
||||
configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; },
|
||||
});
|
||||
while (!f.sdk.connectCalls) await nextTurn();
|
||||
await nextTurn();
|
||||
|
||||
// The session is past authentication, but `connected` was never published.
|
||||
assert.deepEqual(messageTypes(f.messages), []);
|
||||
|
||||
const failure = waitForMessage<{ code: string }>(f.socket, "connectionFailed");
|
||||
f.sdk.emit("disconnected");
|
||||
assert.ok((await failure).code.length > 0);
|
||||
await nextTurn();
|
||||
assert.equal(f.bridge.getActiveCount(), 0);
|
||||
});
|
||||
|
||||
test("a kick before the directory sync is reported instead of leaving the session alive", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
waitForFirstMessage: false,
|
||||
createEncoder: stubEncoder,
|
||||
configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; },
|
||||
});
|
||||
while (!f.sdk.connectCalls) await nextTurn();
|
||||
await nextTurn();
|
||||
assert.deepEqual(messageTypes(f.messages), []);
|
||||
|
||||
const failure = waitForMessage<{ code: string; detail?: string }>(f.socket, "connectionFailed");
|
||||
f.sdk.emit("kicked", normalizeTeamSpeakKickedReason("Removed by operator", 4));
|
||||
const message = await failure;
|
||||
assert.equal(message.code, "KICKED");
|
||||
assert.match(message.detail ?? "", /Removed by operator/);
|
||||
await nextTurn();
|
||||
assert.equal(f.bridge.getActiveCount(), 0);
|
||||
});
|
||||
|
||||
test("a drop during a reconnect handshake resumes recovery instead of stalling in syncing", { timeout: 15_000 }, async t => {
|
||||
const f = await fixture(t, {
|
||||
createEncoder: stubEncoder,
|
||||
configureSdk(sdk) {
|
||||
let connects = 0;
|
||||
sdk.connect = async () => {
|
||||
sdk.connectCalls += 1;
|
||||
sdk.disconnected = false;
|
||||
connects += 1;
|
||||
// Only the first handshake publishes the directory, so the reconnect
|
||||
// attempt parks in `syncing` the way a slow server would.
|
||||
if (connects === 1) sdk.emit("directorySnapshot", sdk.directory);
|
||||
};
|
||||
},
|
||||
});
|
||||
assert.ok(messageTypes(f.messages).includes("connected"));
|
||||
|
||||
const firstReconnect = waitForMessage<{ attempt: number }>(f.socket, "reconnecting");
|
||||
f.sdk.emit("disconnected");
|
||||
assert.equal((await firstReconnect).attempt, 1);
|
||||
|
||||
// Wait for the retry handshake to reach `syncing` without republishing `connected`.
|
||||
while (f.sdk.connectCalls < 2) await nextTurn();
|
||||
await nextTurn();
|
||||
await nextTurn();
|
||||
assert.ok(!messageTypes(f.messages).includes("reconnected"));
|
||||
|
||||
const secondReconnect = waitForMessage<{ attempt: number }>(f.socket, "reconnecting");
|
||||
f.sdk.emit("disconnected");
|
||||
assert.equal((await secondReconnect).attempt, 2);
|
||||
assert.ok(f.bridge.getActiveCount() > 0);
|
||||
});
|
||||
|
||||
test("a codec disposal failure cannot abandon TeamSpeak or the browser socket", { timeout: 5_000 }, async t => {
|
||||
const encoder = new OpusEncoder(48000, 1);
|
||||
t.mock.method(encoder, "dispose", () => { throw new Error("Codec already disposed"); });
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import pino from "pino";
|
||||
import { VoiceBridge } from "./voice-bridge.js";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
@@ -222,3 +223,96 @@ test("an unset media override still uses a literal request host", async () => {
|
||||
await f.offer("legacy");
|
||||
assert.deepEqual(f.peers[0].options.publicAddresses, ["192.0.2.10"]);
|
||||
});
|
||||
|
||||
function ipRequest(remoteAddress: string | undefined, headers: Record<string, string> = {}): IncomingMessage {
|
||||
return { headers, socket: { remoteAddress } } as unknown as IncomingMessage;
|
||||
}
|
||||
|
||||
test("a direct client cannot choose the address recorded for it", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1"]);
|
||||
assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), "192.0.2.7");
|
||||
assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-real-ip": "203.0.113.9" }), trusted), "192.0.2.7");
|
||||
assert.equal(
|
||||
resolveClientIp(ipRequest("::ffff:192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted),
|
||||
"192.0.2.7",
|
||||
"an IPv4 peer arrives in mapped form and is still the address we must record",
|
||||
);
|
||||
});
|
||||
|
||||
test("a trusted proxy chain is read from our side towards the client", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1", "::1", "10.0.0.0/8", "2001:db8::/32"]);
|
||||
// The proxy appended the peer it accepted, so a value the client injected to
|
||||
// its left is never the address we record.
|
||||
assert.equal(
|
||||
resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "203.0.113.9, 198.51.100.4" }), trusted),
|
||||
"198.51.100.4",
|
||||
);
|
||||
// Both hops are trusted, so keep walking towards the client.
|
||||
assert.equal(
|
||||
resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "203.0.113.9, 10.1.2.3" }), trusted),
|
||||
"203.0.113.9",
|
||||
);
|
||||
// The same walk over IPv6: a trusted hop, then the client.
|
||||
assert.equal(
|
||||
resolveClientIp(ipRequest("::1", { "x-forwarded-for": "2001:db9::9, 2001:db8::5" }), trusted),
|
||||
"2001:db9::9",
|
||||
);
|
||||
});
|
||||
|
||||
test("X-Real-IP is used only for a trusted single-hop proxy", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1"]);
|
||||
assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-real-ip": "203.0.113.9" }), trusted), "203.0.113.9");
|
||||
assert.equal(
|
||||
resolveClientIp(ipRequest("127.0.0.1", { "x-real-ip": "198.51.100.4", "x-forwarded-for": "203.0.113.9" }), trusted),
|
||||
"203.0.113.9",
|
||||
"the appended chain wins over the single-value header",
|
||||
);
|
||||
});
|
||||
|
||||
test("an all-trusted chain reports the furthest address instead of inventing one", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1"]);
|
||||
assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "127.0.0.1" }), trusted), "127.0.0.1");
|
||||
assert.equal(resolveClientIp(ipRequest("127.0.0.1"), trusted), "127.0.0.1");
|
||||
assert.equal(resolveClientIp(ipRequest(undefined), trusted), "unknown");
|
||||
});
|
||||
|
||||
test("unparseable forwarding values are dropped rather than recorded", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1"]);
|
||||
assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "not-an-ip" }), trusted), "127.0.0.1");
|
||||
assert.equal(
|
||||
resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "not-an-ip, 203.0.113.9" }), trusted),
|
||||
"203.0.113.9",
|
||||
);
|
||||
});
|
||||
|
||||
test("the default trust list is loopback only", () => {
|
||||
const trusted = createTrustedProxies(undefined);
|
||||
assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "203.0.113.9" }), trusted), "203.0.113.9");
|
||||
assert.equal(resolveClientIp(ipRequest("::1", { "x-forwarded-for": "203.0.113.9" }), trusted), "203.0.113.9");
|
||||
// A bridge address belongs to a proxy we have not been told about, so its
|
||||
// headers are ignored and the connection is logged from the proxy.
|
||||
assert.equal(resolveClientIp(ipRequest("172.17.0.1", { "x-forwarded-for": "203.0.113.9" }), trusted), "172.17.0.1");
|
||||
});
|
||||
|
||||
test("a declared trusted proxy accepts CIDR and mapped forms", () => {
|
||||
const cidr = createTrustedProxies(["10.0.0.0/8", "fd00::/8"]);
|
||||
assert.equal(resolveClientIp(ipRequest("10.9.8.7", { "x-forwarded-for": "203.0.113.9" }), cidr), "203.0.113.9");
|
||||
assert.equal(resolveClientIp(ipRequest("fd00::7", { "x-forwarded-for": "2001:db8::9" }), cidr), "2001:db8::9");
|
||||
|
||||
// Mapped entries are unwrapped, so they match both the plain and the
|
||||
// mapped form of the same peer address.
|
||||
const mapped = createTrustedProxies(["::ffff:192.0.2.1"]);
|
||||
assert.equal(resolveClientIp(ipRequest("192.0.2.1", { "x-forwarded-for": "203.0.113.9" }), mapped), "203.0.113.9");
|
||||
assert.equal(resolveClientIp(ipRequest("::ffff:192.0.2.1", { "x-forwarded-for": "203.0.113.9" }), mapped), "203.0.113.9");
|
||||
});
|
||||
|
||||
test("an invalid trust list is rejected instead of silently ignored", () => {
|
||||
for (const entry of ["not-an-ip", "10.0.0.0/33", "fd00::/129", "10.0.0.0/x", "10.0.0.0/-1"]) {
|
||||
assert.throws(() => createTrustedProxies([entry]), /WEBSPEAK_TRUSTED_PROXIES/, entry);
|
||||
}
|
||||
});
|
||||
|
||||
test("trusting every address has to be asked for explicitly", () => {
|
||||
const trusted = createTrustedProxies(["0.0.0.0/0", "::/0"]);
|
||||
assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), "203.0.113.9");
|
||||
});
|
||||
+156
-26
@@ -11,7 +11,7 @@ import type { ServerEvent as SharedServerEvent } from "../shared/voice-models.js
|
||||
import { WebSocketServer, WebSocket } from "ws";
|
||||
import type { IncomingMessage, Server } from "node:http";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { isIP } from "node:net";
|
||||
import { BlockList, isIP } from "node:net";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { TSClient, type TSClientOptions } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
@@ -43,6 +43,10 @@ export interface VoiceBridgeOptions {
|
||||
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
|
||||
acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]);
|
||||
accelerationName?: string | (() => string | undefined);
|
||||
// Addresses whose forwarding headers may be believed. Unset means loopback
|
||||
// only, which covers a reverse proxy on the same host (including the
|
||||
// published host-network container).
|
||||
trustedProxies?: readonly string[];
|
||||
}
|
||||
|
||||
interface VoiceBridgeDependencies {
|
||||
@@ -100,6 +104,7 @@ export class VoiceBridge {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private logger: LoggerType;
|
||||
private readonly trustedProxies: BlockList;
|
||||
|
||||
constructor(
|
||||
private options: VoiceBridgeOptions,
|
||||
@@ -108,9 +113,26 @@ export class VoiceBridge {
|
||||
private readonly dependencies: VoiceBridgeDependencies = {},
|
||||
) {
|
||||
this.logger = logger.child({ component: "voice-bridge" });
|
||||
this.trustedProxies = createTrustedProxies(options.trustedProxies);
|
||||
this.screenShares = new ScreenShareCoordinator(this.entries, (entryId, message) => {
|
||||
const entry = this.entries.get(entryId);
|
||||
if (entry?.ws.readyState === WebSocket.OPEN) entry.ws.send(JSON.stringify(message));
|
||||
if (entry?.ws.readyState === WebSocket.OPEN) {
|
||||
try {
|
||||
entry.ws.send(JSON.stringify(message));
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
entryId,
|
||||
messageType: message.type,
|
||||
errorName: error instanceof Error ? error.name : "unknown",
|
||||
}, "Could not send screen-share message to browser");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (message.type === "screenShareNativeViewerJoined" || (message.type === "screenShareSignal" && message.signal.kind !== "iceCandidate")) {
|
||||
this.logger.info({ entryId, messageType: message.type, readyState: entry?.ws.readyState ?? null }, "Dropped screen-share message because browser WebSocket is unavailable");
|
||||
}
|
||||
return false;
|
||||
}, this.logger);
|
||||
}
|
||||
|
||||
@@ -135,7 +157,7 @@ export class VoiceBridge {
|
||||
ws.close(4006, "ACCELERATION_UNAVAILABLE");
|
||||
return;
|
||||
}
|
||||
const clientIp = resolveClientIp(req);
|
||||
const clientIp = resolveClientIp(req, this.trustedProxies);
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req);
|
||||
let identity;
|
||||
try {
|
||||
@@ -229,6 +251,7 @@ export class VoiceBridge {
|
||||
try {
|
||||
entry.audioTransport = new SessionAudioTransport({
|
||||
audio: entry.audio, socket: ws, client: tsClient,
|
||||
logger: this.logger.child({ component: "session-audio", entryId }),
|
||||
isCurrent: () => this.entries.get(entryId) === entry,
|
||||
isReady: () => tsReady && session.state === "connected",
|
||||
selfId: () => entry!.events?.selfId ?? 0,
|
||||
@@ -245,6 +268,11 @@ export class VoiceBridge {
|
||||
let initialStateSent = false;
|
||||
let serverInfoGeneration = 0;
|
||||
let hasConnectedOnce = false;
|
||||
// `connected` is only published once the directory sync has landed (see
|
||||
// `sendInitialState`), so the session can already be past authentication
|
||||
// while `hasConnectedOnce` is still false. A transport drop inside that
|
||||
// gap must be handled rather than swallowed.
|
||||
const isSettling = () => session.state === "authenticating" || session.state === "syncing";
|
||||
let reconnectStartedAt = 0;
|
||||
let reconnectAttempt = 0;
|
||||
const addServerEvent = (kind: ServerEvent["kind"], message: string) => {
|
||||
@@ -344,6 +372,28 @@ export class VoiceBridge {
|
||||
void this.teardown(entryId, "teamSpeak-connect-failed");
|
||||
};
|
||||
|
||||
const failConnect = (normalized: ReturnType<typeof normalizeTeamSpeakError>) => {
|
||||
// A dead transport can report itself twice -- once as a `disconnected`
|
||||
// event and once as a rejected `connect()`. Report and tear down once.
|
||||
if (session.state === "failed" || session.state === "disconnecting" || session.state === "idle") return;
|
||||
if (entry!.reconnectTimer) {
|
||||
clearTimeout(entry!.reconnectTimer);
|
||||
entry!.reconnectTimer = null;
|
||||
}
|
||||
try {
|
||||
session.transition("failed");
|
||||
} catch { /* teardown below remains authoritative */ }
|
||||
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
|
||||
const failureDetail = publicFailureDetail(normalized);
|
||||
entry!.connectionFailureCode = failureCode;
|
||||
// Send the structured failure before closing. Some browsers and reverse
|
||||
// proxies do not preserve a WebSocket close reason, which would
|
||||
// otherwise collapse every failure into a generic message.
|
||||
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
|
||||
if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode);
|
||||
void this.teardown(entryId, "teamSpeak-connect-failed");
|
||||
};
|
||||
|
||||
const scheduleReconnect = (normalized: ReturnType<typeof normalizeTeamSpeakError> | null) => {
|
||||
if (session.state === "disconnecting" || session.state === "idle" || session.state === "failed") return;
|
||||
if (!isRecoverable(normalized)) {
|
||||
@@ -391,7 +441,6 @@ export class VoiceBridge {
|
||||
} catch (error: unknown) {
|
||||
const normalized = normalizeTeamSpeakError(error);
|
||||
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
|
||||
const failureDetail = publicFailureDetail(normalized);
|
||||
entry!.connectionFailureCode = failureCode;
|
||||
this.logger.warn({
|
||||
code: failureCode,
|
||||
@@ -403,15 +452,7 @@ export class VoiceBridge {
|
||||
attempt: reconnectAttempt,
|
||||
}, "TS connect failed");
|
||||
if (!isReconnect) {
|
||||
try {
|
||||
if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed");
|
||||
} catch { /* teardown below remains authoritative */ }
|
||||
// Send the structured failure before closing. Some browsers and
|
||||
// reverse proxies do not preserve a WebSocket close reason, which
|
||||
// would otherwise collapse every failure into a generic message.
|
||||
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
|
||||
if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode);
|
||||
void this.teardown(entryId, "teamSpeak-connect-failed");
|
||||
failConnect(normalized);
|
||||
return;
|
||||
}
|
||||
if (isReconnect && isRecoverable(normalized)) {
|
||||
@@ -445,7 +486,11 @@ export class VoiceBridge {
|
||||
onKick: kick => {
|
||||
// A transport drop may arrive first and already start recovery. A
|
||||
// subsequent kick is still terminal and must cancel that recovery.
|
||||
if (!hasConnectedOnce) return;
|
||||
// A kick that lands before the session ever settled in (during the
|
||||
// first connect or a reconnect handshake) is terminal too: without
|
||||
// this the client would sit on the connecting screen while the
|
||||
// gateway kept the dead session alive.
|
||||
if (!hasConnectedOnce && !isSettling()) return;
|
||||
resetDirectoryForReconnect();
|
||||
const failureCode = clientConnectionFailureCode(kick, serverPassword);
|
||||
const failureDetail = publicFailureDetail(kick);
|
||||
@@ -455,10 +500,36 @@ export class VoiceBridge {
|
||||
void this.teardown(entryId, "teamSpeak-kicked");
|
||||
},
|
||||
onDisconnect: error => {
|
||||
if (!hasConnectedOnce || session.state !== "connected") return;
|
||||
const normalized = error ? normalizeTeamSpeakError(error) : null;
|
||||
if (isSettling()) {
|
||||
// `connected` was never published, so there is no live session to
|
||||
// interrupt -- but staying in `syncing` would leave the client on
|
||||
// the connecting screen with no recovery scheduled.
|
||||
if (!hasConnectedOnce) {
|
||||
this.logger.warn({
|
||||
entryId,
|
||||
normalizedCode: normalized?.code,
|
||||
...(normalized ? { failureDetail: describeTeamSpeakError(normalized) } : {}),
|
||||
}, "TeamSpeak connection lost before the session became usable");
|
||||
failConnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection lost during startup")));
|
||||
return;
|
||||
}
|
||||
// A reconnect attempt dropped mid-handshake. Detach the dead
|
||||
// transport and fall back into the recovery loop rather than
|
||||
// stalling in `syncing`.
|
||||
resetDirectoryForReconnect();
|
||||
try {
|
||||
session.transition("reconnecting");
|
||||
} catch {
|
||||
failReconnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection lost during reconnect")));
|
||||
return;
|
||||
}
|
||||
scheduleReconnect(normalized);
|
||||
return;
|
||||
}
|
||||
if (session.state !== "connected") return;
|
||||
this.screenShares.removePeer(entryId);
|
||||
resetDirectoryForReconnect();
|
||||
const normalized = error ? normalizeTeamSpeakError(error) : null;
|
||||
sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) });
|
||||
scheduleReconnect(normalized);
|
||||
},
|
||||
@@ -785,17 +856,76 @@ function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveClientIp(request: IncomingMessage): string {
|
||||
const candidates = [
|
||||
firstHeader(request.headers["x-forwarded-for"])?.split(",", 1)[0],
|
||||
firstHeader(request.headers["x-real-ip"]),
|
||||
request.socket.remoteAddress,
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const normalized = normalizeClientIp(candidate);
|
||||
if (normalized) return normalized;
|
||||
// A reverse proxy on the same host reaches us over loopback, which is also what
|
||||
// the published host-network container sees. Anything else has to be declared,
|
||||
// because whoever we believe can choose the address we record.
|
||||
const DEFAULT_TRUSTED_PROXIES = ["127.0.0.1", "::1"];
|
||||
|
||||
/** Build the matcher that decides whether forwarding headers may be believed. */
|
||||
export function createTrustedProxies(entries: readonly string[] | undefined): BlockList {
|
||||
const list = new BlockList();
|
||||
const effective = entries?.length ? entries : DEFAULT_TRUSTED_PROXIES;
|
||||
for (const entry of effective) {
|
||||
const trimmed = entry.trim();
|
||||
if (!trimmed) continue;
|
||||
const separator = trimmed.indexOf("/");
|
||||
const address = normalizeClientIp(separator === -1 ? trimmed : trimmed.slice(0, separator));
|
||||
const family = address ? isIP(address) : 0;
|
||||
if (!address || (family !== 4 && family !== 6)) {
|
||||
throw new Error(`Invalid WEBSPEAK_TRUSTED_PROXIES entry: ${entry}`);
|
||||
}
|
||||
if (separator === -1) {
|
||||
list.addAddress(address, family === 4 ? "ipv4" : "ipv6");
|
||||
continue;
|
||||
}
|
||||
const prefixText = trimmed.slice(separator + 1);
|
||||
const prefix = Number(prefixText);
|
||||
if (!/^\d+$/.test(prefixText) || prefix > (family === 4 ? 32 : 128)) {
|
||||
throw new Error(`Invalid WEBSPEAK_TRUSTED_PROXIES prefix: ${entry}`);
|
||||
}
|
||||
list.addSubnet(address, prefix, family === 4 ? "ipv4" : "ipv6");
|
||||
}
|
||||
return "unknown";
|
||||
return list;
|
||||
}
|
||||
|
||||
function isTrustedProxy(address: string, trustedProxies: BlockList): boolean {
|
||||
const family = isIP(address);
|
||||
if (family !== 4 && family !== 6) return false;
|
||||
return trustedProxies.check(address, family === 4 ? "ipv4" : "ipv6");
|
||||
}
|
||||
|
||||
/**
|
||||
* Address to record for a connection. Each proxy appends the peer it accepted,
|
||||
* so the chain is read from the hop nearest to us towards the client, and the
|
||||
* first address we do not trust is the client. Forwarding headers received
|
||||
* directly from an untrusted peer are ignored entirely: that peer can write
|
||||
* anything, and whatever we return is shown as the source in the admin
|
||||
* connection log.
|
||||
*/
|
||||
export function resolveClientIp(request: IncomingMessage, trustedProxies: BlockList): string {
|
||||
const direct = normalizeClientIp(request.socket.remoteAddress);
|
||||
if (!direct || !isTrustedProxy(direct, trustedProxies)) return direct ?? "unknown";
|
||||
|
||||
const forwarded = firstHeader(request.headers["x-forwarded-for"]);
|
||||
const hops: string[] = [];
|
||||
if (forwarded) {
|
||||
for (const candidate of forwarded.split(",")) {
|
||||
const hop = normalizeClientIp(candidate);
|
||||
if (hop) hops.push(hop);
|
||||
}
|
||||
hops.reverse();
|
||||
}
|
||||
for (const hop of hops) {
|
||||
if (!isTrustedProxy(hop, trustedProxies)) return hop;
|
||||
}
|
||||
if (!hops.length) {
|
||||
// A single-hop proxy may be configured to send only X-Real-IP.
|
||||
const realIp = normalizeClientIp(firstHeader(request.headers["x-real-ip"]));
|
||||
if (realIp && !isTrustedProxy(realIp, trustedProxies)) return realIp;
|
||||
}
|
||||
// Every address we can see belongs to a proxy we trust. Report the furthest
|
||||
// one instead of inventing a client address that was never forwarded.
|
||||
return hops.length ? hops[hops.length - 1]! : direct;
|
||||
}
|
||||
|
||||
function normalizeClientIp(value: string | undefined): string | undefined {
|
||||
|
||||
@@ -173,3 +173,31 @@ test("a rejected peer shutdown is shared without repeating partial cleanup", asy
|
||||
assert.deepEqual(f.released, ["decoder-1", "decoder-2", "encoder", "track", "peer"]);
|
||||
assert.equal(f.resources.decoderByClient.size, 0);
|
||||
});
|
||||
|
||||
test("an unavailable mixer encoder closes the half-built peer before the constructor throws", () => {
|
||||
// The constructor never returns when the codec is missing, so the caller's
|
||||
// `peer?.close()` is a no-op. Instrument the prototype to observe that the
|
||||
// rollback happens inside the constructor instead. Count distinct peers:
|
||||
// werift re-enters close() on the same instance while tearing ICE down.
|
||||
const originalClose = RTCPeerConnection.prototype.close;
|
||||
const closedPeers = new Set<RTCPeerConnection>();
|
||||
RTCPeerConnection.prototype.close = function patchedClose(this: RTCPeerConnection): Promise<void> {
|
||||
closedPeers.add(this);
|
||||
return originalClose.call(this);
|
||||
};
|
||||
try {
|
||||
assert.throws(
|
||||
() => new WebRtcAudioSession({
|
||||
connectionId: "encoder-unavailable",
|
||||
logger: pino({ enabled: false }),
|
||||
createEncoder: () => { throw new Error("Opus codec is unavailable"); },
|
||||
onVoiceFrame() {},
|
||||
onVoiceActivity() {},
|
||||
}),
|
||||
/WebRTC Opus codec is unavailable/,
|
||||
);
|
||||
} finally {
|
||||
RTCPeerConnection.prototype.close = originalClose;
|
||||
}
|
||||
assert.equal(closedPeers.size, 1, "the constructor must roll back the peer it already created");
|
||||
});
|
||||
@@ -41,6 +41,9 @@ export interface WebRtcAudioOptions {
|
||||
udpPortRange?: [number, number];
|
||||
}
|
||||
|
||||
/** The mixer only encodes; per-speaker decoders are created separately below. */
|
||||
type MixerEncoder = Pick<OpusEncoder, "encode" | "dispose">;
|
||||
|
||||
export interface WebRtcAudioSessionOptions {
|
||||
connectionId: string;
|
||||
publicAddresses?: string[];
|
||||
@@ -49,6 +52,8 @@ export interface WebRtcAudioSessionOptions {
|
||||
publicHost?: string;
|
||||
udpPortRange?: [number, number];
|
||||
logger: LoggerType;
|
||||
/** Mirrors `VoiceBridgeDependencies.createEncoder`; production uses `@discordjs/opus`. */
|
||||
createEncoder?: () => MixerEncoder;
|
||||
microphoneMuted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||
@@ -104,7 +109,7 @@ export class WebRtcAudioSession {
|
||||
private readonly opusPayloadTypes = new Set<number>();
|
||||
private audioTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly activityTimer: ReturnType<typeof setInterval>;
|
||||
private encoder: OpusEncoder | null;
|
||||
private encoder: MixerEncoder | null;
|
||||
private sequenceNumber = randomInt(0, 65_536);
|
||||
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
|
||||
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
|
||||
@@ -193,14 +198,19 @@ export class WebRtcAudioSession {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
|
||||
});
|
||||
|
||||
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, 1));
|
||||
try {
|
||||
this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
this.encoder = createEncoder();
|
||||
} 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) {
|
||||
// The constructor never returns, so the caller cannot clean up after us:
|
||||
// its `peer` handle stays null and `peer?.close()` is a no-op. Roll the
|
||||
// half-built peer back here instead of stranding it on the floor.
|
||||
this.outgoingTrack.stop();
|
||||
void this.peer.close().catch(() => { /* rollback is best effort */ });
|
||||
throw new Error("WebRTC Opus codec is unavailable");
|
||||
}
|
||||
|
||||
|
||||
@@ -78,9 +78,27 @@ export type ScreenSharePeerSignal =
|
||||
kind: "close";
|
||||
};
|
||||
|
||||
/**
|
||||
* Ceiling on the total inline avatar bytes a client accepts from a legacy
|
||||
* gateway for one viewer roster. Current gateways send client ids instead of
|
||||
* avatars, so this bounds only the compatibility path; a per-entry limit alone
|
||||
* would still admit 64 x 128 KiB in a single broadcast.
|
||||
*/
|
||||
export const SCREEN_SHARE_LEGACY_AVATAR_BUDGET = 256 * 1024;
|
||||
|
||||
export interface ScreenShareViewerDescription {
|
||||
peerId: string;
|
||||
nickname: string;
|
||||
/**
|
||||
* TeamSpeak client id. The gateway sends this instead of an inline avatar so
|
||||
* a receiving client can resolve the avatar it already holds for that member
|
||||
* from the directory, rather than the roster carrying the image again.
|
||||
*/
|
||||
clientId?: number;
|
||||
/**
|
||||
* Legacy inline avatar. Current gateways do not set this; it is still parsed
|
||||
* so a newer web client keeps rendering avatars against an older gateway.
|
||||
*/
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { parseServerMessage, parseScreenShareStream, parseVoiceAudioBridgeStats, type ServerMessage } from "./server-messages.js";
|
||||
import { SCREEN_SHARE_LEGACY_AVATAR_BUDGET } from "./screen-share.js";
|
||||
|
||||
const stream = {
|
||||
streamId: "stream-1", source: "browser" as const, ownerPeerId: "owner", ownerClientId: 1,
|
||||
@@ -101,3 +102,50 @@ test("legacy screen streams receive defaults and untrusted viewer data is bounde
|
||||
assert.equal(message.streams[0]?.viewers[0]?.nickname.length, 120);
|
||||
assert.equal(parseScreenShareStream({ streamId: "s", ownerPeerId: [] }), null);
|
||||
});
|
||||
|
||||
test("screen share viewers carry a client id and still accept a legacy inline avatar", () => {
|
||||
const message = parseServerMessage({
|
||||
type: "screenShareList",
|
||||
streams: [{
|
||||
streamId: "s", ownerPeerId: "owner",
|
||||
viewers: [
|
||||
{ peerId: "v1", nickname: "One", clientId: 42 },
|
||||
{ peerId: "v2", nickname: "Two", avatar: "data:image/png;base64,AAAA" },
|
||||
{ peerId: "v3", nickname: "Three", clientId: -1 },
|
||||
{ peerId: "v4", nickname: "Four", clientId: 70_000 },
|
||||
],
|
||||
}],
|
||||
});
|
||||
assert.ok(message?.type === "screenShareList");
|
||||
const viewers = message.streams[0]?.viewers ?? [];
|
||||
assert.equal(viewers.length, 4);
|
||||
assert.equal(viewers[0]?.clientId, 42);
|
||||
assert.equal("avatar" in viewers[0]!, false);
|
||||
// An older gateway still inlines the avatar; keep honouring it.
|
||||
assert.equal(viewers[1]?.avatar, "data:image/png;base64,AAAA");
|
||||
assert.equal(viewers[1]?.clientId, undefined);
|
||||
// Out-of-range ids are dropped rather than forwarded.
|
||||
assert.equal(viewers[2]?.clientId, undefined);
|
||||
assert.equal(viewers[3]?.clientId, undefined);
|
||||
});
|
||||
|
||||
test("legacy inline avatars are bounded in total, not merely per entry", () => {
|
||||
const avatar = `data:image/png;base64,${"A".repeat(128 * 1024 - 22)}`;
|
||||
const message = parseServerMessage({
|
||||
type: "screenShareList",
|
||||
streams: [{
|
||||
streamId: "s", ownerPeerId: "owner",
|
||||
viewers: Array.from({ length: 8 }, (_, index) => ({ peerId: `v${index}`, nickname: `n${index}`, avatar })),
|
||||
}],
|
||||
});
|
||||
assert.ok(message?.type === "screenShareList");
|
||||
const viewers = message.streams[0]?.viewers ?? [];
|
||||
assert.equal(viewers.length, 8, "entries are kept even when their avatar is dropped");
|
||||
const accepted = viewers.reduce((total, viewer) => total + (viewer.avatar?.length ?? 0), 0);
|
||||
assert.ok(
|
||||
accepted <= SCREEN_SHARE_LEGACY_AVATAR_BUDGET,
|
||||
`accepted avatar bytes must stay within the roster budget, got ${accepted}`,
|
||||
);
|
||||
assert.ok(accepted > 0, "the legacy path still renders the leading avatars");
|
||||
assert.ok(viewers.some(viewer => viewer.avatar === undefined), "entries past the budget must fall back to a local lookup");
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ChannelMember, ChannelInfo, ServerEvent, VoiceAudioBridgeStats } from "./voice-models.js";
|
||||
import { normalizeScreenShareIceServers, parseScreenShareSignal, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
|
||||
import { normalizeScreenShareIceServers, parseScreenShareSignal, SCREEN_SHARE_LEGACY_AVATAR_BUDGET, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
|
||||
|
||||
import { normalizeVoiceStunServer } from "./voice-ice.js";
|
||||
import { isSessionDescription, type SessionDescription } from "./webrtc.js";
|
||||
@@ -100,11 +100,22 @@ export function parseVoiceAudioBridgeStats(value: unknown): VoiceAudioBridgeStat
|
||||
|
||||
export function parseScreenShareViewers(raw: unknown): ScreenShareViewerDescription[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
let avatarBudget = SCREEN_SHARE_LEGACY_AVATAR_BUDGET;
|
||||
return raw.filter((viewer): viewer is RecordValue & { peerId: string; nickname: string } => isRecord(viewer) && text(viewer.peerId) && text(viewer.nickname))
|
||||
.slice(0, 64).map(viewer => ({
|
||||
peerId: viewer.peerId.slice(0, 128), nickname: viewer.nickname.slice(0, 120),
|
||||
...(text(viewer.avatar) && viewer.avatar.length <= 128 * 1024 ? { avatar: viewer.avatar } : {}),
|
||||
}));
|
||||
.slice(0, 64).map(viewer => {
|
||||
// Client ids replaced inline avatars, so this only serves older gateways.
|
||||
// Bound the roster's total avatar bytes, not just each entry: the
|
||||
// per-entry cap alone still allows 64 x 128 KiB per broadcast.
|
||||
const avatar = text(viewer.avatar) && viewer.avatar.length <= 128 * 1024 && viewer.avatar.length <= avatarBudget
|
||||
? viewer.avatar
|
||||
: undefined;
|
||||
if (avatar) avatarBudget -= avatar.length;
|
||||
return {
|
||||
peerId: viewer.peerId.slice(0, 128), nickname: viewer.nickname.slice(0, 120),
|
||||
...(clientId(viewer.clientId) ? { clientId: viewer.clientId } : {}),
|
||||
...(avatar ? { avatar } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Defaults preserve stream descriptions sent by older gateway versions. */
|
||||
|
||||
@@ -147,6 +147,25 @@ test("server list skins may display only the host-provided TeamSpeak icon image"
|
||||
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
|
||||
});
|
||||
|
||||
test("skin-owned localization messages are available without adding host permissions", () => {
|
||||
const document = validDocument();
|
||||
document.schemaVersion = 3;
|
||||
document.components[0].name = "{{skin.messages.demo.title}}";
|
||||
document.components[0].accessibleName = "{{skin.messages.accessibleName}}";
|
||||
document.components[0].permissions = [];
|
||||
document.components[0].actions = {};
|
||||
document.components[0].root = {
|
||||
tag: "section",
|
||||
attributes: { "aria-label": "{{skin.messages.demo.accessibility.label}}" },
|
||||
children: [{ text: "{{skin.messages.demo.greeting}}" }],
|
||||
};
|
||||
|
||||
const component = parseSkinPluginDocument(document).components[0];
|
||||
assert.equal(component.name, "{{skin.messages.demo.title}}");
|
||||
assert.equal(component.accessibleName, "{{skin.messages.accessibleName}}");
|
||||
assert.equal(component.root.children?.[0].text, "{{skin.messages.demo.greeting}}");
|
||||
});
|
||||
|
||||
test("chat panel visibility is host-controlled and its toggle requires chat access", () => {
|
||||
const document = validDocument();
|
||||
document.schemaVersion = 3;
|
||||
|
||||
@@ -327,10 +327,12 @@ function bindingPermissions(value: string, aliases: ReadonlyMap<string, string>,
|
||||
const found = new Set<SkinPluginPermission>();
|
||||
for (const match of value.matchAll(/\{\{\s*([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}/g)) {
|
||||
const path = match[1].split(".");
|
||||
if (path[0] === "state") {
|
||||
if (path.length !== 2 || !stateKeys.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A state binding must reference a declared local state key.");
|
||||
continue;
|
||||
}
|
||||
if (path[0] === "state") {
|
||||
if (path.length !== 2 || !stateKeys.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A state binding must reference a declared local state key.");
|
||||
continue;
|
||||
}
|
||||
if (path[0] === "skin" && path[1] === "locale" && path.length === 2) continue;
|
||||
if (path[0] === "skin" && path[1] === "messages" && path.length >= 3) continue;
|
||||
const aliasCollection = aliases.get(path[0]);
|
||||
if (aliasCollection) {
|
||||
if (path.length !== 2 || !COLLECTION_FIELDS[aliasCollection]?.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A repeated item binding references an unsupported public field.");
|
||||
|
||||
Binary file not shown.
@@ -180,10 +180,18 @@ export default defineComponent({
|
||||
return SKIN_PLUGIN_PERMISSIONS[permission as keyof typeof SKIN_PLUGIN_PERMISSIONS]?.description ?? permission;
|
||||
}
|
||||
|
||||
function resolvePath(path: string, context: SafeContext, state: Record<string, Scalar>): unknown {
|
||||
const normalized = path.replace(/^\{\{\s*|\s*\}\}$/g, "");
|
||||
const parts = normalized.split(".");
|
||||
let value: unknown = parts[0] === "state" ? state : context;
|
||||
function resolvePath(path: string, context: SafeContext, state: Record<string, Scalar>): unknown {
|
||||
const normalized = path.replace(/^\{\{\s*|\s*\}\}$/g, "");
|
||||
const parts = normalized.split(".");
|
||||
if (parts[0] === "skin" && parts[1] === "messages" && parts.length >= 3) {
|
||||
const skin = context.skin;
|
||||
if (!skin || typeof skin !== "object" || !("messages" in skin)) return undefined;
|
||||
const messages = (skin as { messages?: unknown }).messages;
|
||||
if (!messages || typeof messages !== "object") return undefined;
|
||||
const key = parts.slice(2).join(".");
|
||||
return Object.prototype.hasOwnProperty.call(messages, key) ? (messages as Record<string, unknown>)[key] : undefined;
|
||||
}
|
||||
let value: unknown = parts[0] === "state" ? state : context;
|
||||
const start = parts[0] === "state" ? 1 : 0;
|
||||
for (let index = start; index < parts.length; index += 1) {
|
||||
if (!value || typeof value !== "object" || !Object.prototype.hasOwnProperty.call(value, parts[index])) return undefined;
|
||||
@@ -292,10 +300,10 @@ export default defineComponent({
|
||||
if (!widget) return null;
|
||||
return h("div", {
|
||||
class: ["ws-plugin-host-widget", node.className],
|
||||
"data-ws-plugin-widget": node.widget,
|
||||
"data-ws-plugin-part": node.part ? `${component.id}.${node.part}` : component.id,
|
||||
"data-ws-part": layoutPart(component, node, nodePath),
|
||||
"aria-label": component.accessibleName,
|
||||
"data-ws-plugin-widget": node.widget,
|
||||
"data-ws-plugin-part": node.part ? `${component.id}.${node.part}` : component.id,
|
||||
"data-ws-part": layoutPart(component, node, nodePath),
|
||||
"aria-label": interpolate(component.accessibleName, context, state),
|
||||
}, [widget(node.options)]);
|
||||
}
|
||||
if (!node.tag) {
|
||||
@@ -430,17 +438,20 @@ export default defineComponent({
|
||||
onUnmounted(() => assetUrls.clear());
|
||||
|
||||
return () => {
|
||||
const nodes: VNodeChild[] = renderedComponents.value.map((component) => h("div", {
|
||||
key: `${props.skinId}:${component.id}`,
|
||||
class: ["ws-plugin-component", component.mode === "surface" && "ws-plugin-surface"],
|
||||
"data-ws-plugin-component": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
|
||||
"data-ws-plugin-name": component.name,
|
||||
"data-ws-plugin-part": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
|
||||
"data-ws-part": `skin.${component.page}.${layoutComponentPath(component)}`,
|
||||
...(props.componentNamespace ? { "data-ws-runtime-plugin": props.componentNamespace } : {}),
|
||||
...(component.mode === "surface" ? { "data-ws-plugin-surface": component.page } : {}),
|
||||
"aria-label": component.accessibleName,
|
||||
}, [renderNode(component, component.root, props.data, localState(component, props.data), { remaining: SKIN_PLUGIN_RENDER_NODE_LIMIT })]));
|
||||
const nodes: VNodeChild[] = renderedComponents.value.map((component) => {
|
||||
const state = localState(component, props.data);
|
||||
return h("div", {
|
||||
key: `${props.skinId}:${component.id}`,
|
||||
class: ["ws-plugin-component", component.mode === "surface" && "ws-plugin-surface"],
|
||||
"data-ws-plugin-component": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
|
||||
"data-ws-plugin-name": interpolate(component.name, props.data, state),
|
||||
"data-ws-plugin-part": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
|
||||
"data-ws-part": `skin.${component.page}.${layoutComponentPath(component)}`,
|
||||
...(props.componentNamespace ? { "data-ws-runtime-plugin": props.componentNamespace } : {}),
|
||||
...(component.mode === "surface" ? { "data-ws-plugin-surface": component.page } : {}),
|
||||
"aria-label": interpolate(component.accessibleName, props.data, state),
|
||||
}, [renderNode(component, component.root, props.data, state, { remaining: SKIN_PLUGIN_RENDER_NODE_LIMIT })]);
|
||||
});
|
||||
const hasPermissions = matchingComponents.value.some((component) => component.permissions.length > 0);
|
||||
const showConsent = (PROMPT_FOR_SKIN_PERMISSIONS && pendingApproval.value.length > 0) || manageOpen.value;
|
||||
const accessToggle = hasPermissions && editorMode.isEnabled.value ? h(Teleport, { to: "body" }, [h("button", {
|
||||
@@ -474,7 +485,7 @@ export default defineComponent({
|
||||
h("h2", { id: "ws-plugin-consent-title" }, "皮肤组件权限 / Skin component access"),
|
||||
h("p", null, "此皮肤包含会读取公开语音界面数据或请求宿主动作的组件。只有你批准的组件才会启用。/ This skin requests limited access for its components. Only approved components will run."),
|
||||
...requested.map((component) => h("div", { class: "ws-plugin-consent-item", key: component.id }, [
|
||||
h("strong", null, component.name),
|
||||
h("strong", null, interpolate(component.name, props.data, localState(component, props.data))),
|
||||
h("ul", null, component.permissions.map((permission) => h("li", { key: permission }, permissionLabel(permission)))),
|
||||
])),
|
||||
h("p", { class: "ws-plugin-consent-note" }, "页面可以替换公开客户端外观;内置控件仍由 WebSpeak 处理。皮肤不能运行脚本、访问网络或存储,也不能读取连接地址、密码和身份材料。/ A surface can replace the public client UI while built-in controls remain host-owned. Skins cannot run code, access network or storage, or read connection targets, passwords, or identity material."),
|
||||
|
||||
@@ -96,15 +96,31 @@ function updateMenuPosition(): void {
|
||||
const menuElement = menu.value;
|
||||
if (!rect || !menuElement || typeof window === "undefined") return;
|
||||
|
||||
// Measure the menu at its content width first. The viewport cap lets long
|
||||
// device names wrap only when the full label cannot fit on screen.
|
||||
const maxWidth = Math.max(0, window.innerWidth - 16);
|
||||
const minWidth = Math.min(rect.width, maxWidth);
|
||||
menuElement.style.width = "max-content";
|
||||
menuElement.style.minWidth = `${minWidth}px`;
|
||||
menuElement.style.maxWidth = `${maxWidth}px`;
|
||||
const naturalMenuWidth = menuElement.getBoundingClientRect().width;
|
||||
|
||||
const computedStyle = window.getComputedStyle(menuElement);
|
||||
const borderHeight = Number.parseFloat(computedStyle.borderTopWidth || "0") + Number.parseFloat(computedStyle.borderBottomWidth || "0");
|
||||
const naturalMenuHeight = menuElement.scrollHeight + (Number.isFinite(borderHeight) ? borderHeight : 0);
|
||||
const placement = placeAudioDeviceMenu(rect, { width: window.innerWidth, height: window.innerHeight }, naturalMenuHeight);
|
||||
const placement = placeAudioDeviceMenu(
|
||||
rect,
|
||||
{ width: window.innerWidth, height: window.innerHeight },
|
||||
naturalMenuHeight,
|
||||
naturalMenuWidth,
|
||||
);
|
||||
|
||||
menuStyle.value = {
|
||||
top: `${placement.top}px`,
|
||||
left: `${placement.left}px`,
|
||||
width: `${placement.width}px`,
|
||||
minWidth: `${minWidth}px`,
|
||||
maxWidth: `${maxWidth}px`,
|
||||
maxHeight: `${placement.maxHeight}px`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createWebRtcTransport } from "../voice/webrtc-transport.js";
|
||||
import { createVoiceConnection } from "../voice/connection.js";
|
||||
import { createVoiceCommands } from "../voice/commands.js";
|
||||
import { createVoiceSessionState } from "../voice/session-state.js";
|
||||
import { applySavedMemberVolumes } from "../voice/member-volume-preferences.js";
|
||||
import { createAudioDiagnostics, type AudioPermission, type VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
|
||||
export type { AudioPermission, BrowserVoiceAudioStats, VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
|
||||
import type { SinkAudioElement } from "../voice/webrtc-playback.js";
|
||||
@@ -412,11 +413,10 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
function syncKnownMemberVolumes(): void {
|
||||
for (const member of members) {
|
||||
if (!member.uid) continue;
|
||||
const saved = storedVolumesByUid[member.uid];
|
||||
if (saved !== undefined) volumes[member.id] = Math.max(0, Math.min(4, saved));
|
||||
}
|
||||
const updatedIds = applySavedMemberVolumes(members, storedVolumesByUid, volumes);
|
||||
if (!updatedIds.length) return;
|
||||
for (const clientId of updatedIds) remotePlayback.updateVolume(clientId);
|
||||
syncWebRtcMemberVolumes();
|
||||
}
|
||||
|
||||
const audioPreferencesReady = loadLocalPreferences().then((preferences) => {
|
||||
|
||||
@@ -31,6 +31,8 @@ interface UseWebClientScreenShareOptions {
|
||||
leaveScreenShare: () => void;
|
||||
nickname: Ref<string>;
|
||||
avatarStyle: (name: string, isSelf?: boolean, avatar?: string) => Record<string, string>;
|
||||
/** Resolves a member's avatar from the local directory by TeamSpeak client id. */
|
||||
memberAvatar: (clientId: number) => string;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
@@ -47,6 +49,7 @@ export function useWebClientScreenShare({
|
||||
leaveScreenShare,
|
||||
nickname,
|
||||
avatarStyle,
|
||||
memberAvatar,
|
||||
t,
|
||||
}: UseWebClientScreenShareOptions) {
|
||||
const videoElement = ref<HTMLVideoElement | null>(null);
|
||||
@@ -74,7 +77,15 @@ export function useWebClientScreenShare({
|
||||
const bitratePreset = ref<ScreenShareBitratePreset>(bitrateOptions.some((option) => option.value === storedBitrate) ? storedBitrate! : "auto");
|
||||
const settingsOpen = ref(false);
|
||||
const activeStream = computed<ScreenShareStream | null>(() => streams.find((stream) => stream.streamId === viewingStreamId.value) ?? null);
|
||||
const viewers = computed(() => activeStream.value?.viewers.slice(-5) ?? []);
|
||||
const viewers = computed(() =>
|
||||
(activeStream.value?.viewers.slice(-5) ?? []).map(viewer => ({
|
||||
...viewer,
|
||||
// The gateway sends a client id; resolve the avatar from the directory the
|
||||
// client already holds instead of shipping the image in every roster
|
||||
// update. An older gateway may still include the avatar inline.
|
||||
avatar: viewer.avatar ?? (typeof viewer.clientId === "number" ? memberAvatar(viewer.clientId) : ""),
|
||||
})),
|
||||
);
|
||||
const viewerCount = computed(() => activeStream.value?.viewerCount ?? activeStream.value?.viewers.length ?? 0);
|
||||
const ownerName = computed(() => activeStream.value?.ownerNickname ?? t("screenShare"));
|
||||
const errorText = computed(() => errorCode.value === "SCREEN_SHARE_NATIVE_BRIDGE_REQUIRED" ? t("screenShareNativeUnavailable") : error.value);
|
||||
|
||||
@@ -34,6 +34,30 @@ test("device menu width stays inside narrow viewport bounds", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("device menu grows to fit long device labels when there is room", () => {
|
||||
assert.deepEqual(
|
||||
placeAudioDeviceMenu(
|
||||
{ top: 20, bottom: 40, left: 40, width: 180 },
|
||||
{ width: 1280, height: 720 },
|
||||
120,
|
||||
420,
|
||||
),
|
||||
{ top: 44, left: 40, width: 420, maxHeight: 120 },
|
||||
);
|
||||
});
|
||||
|
||||
test("device menu caps long labels to the viewport and allows them to wrap", () => {
|
||||
assert.deepEqual(
|
||||
placeAudioDeviceMenu(
|
||||
{ top: 20, bottom: 40, left: 200, width: 90 },
|
||||
{ width: 300, height: 720 },
|
||||
320,
|
||||
600,
|
||||
),
|
||||
{ top: 44, left: 8, width: 284, maxHeight: 240 },
|
||||
);
|
||||
});
|
||||
|
||||
test("device menu preserves the skin-defined natural height for short lists", () => {
|
||||
assert.deepEqual(
|
||||
placeAudioDeviceMenu({ top: 80, bottom: 120, left: 40, width: 280 }, { width: 1280, height: 720 }, 84),
|
||||
|
||||
@@ -20,9 +20,14 @@ export function placeAudioDeviceMenu(
|
||||
anchor: AudioDeviceMenuAnchor,
|
||||
viewport: { width: number; height: number },
|
||||
naturalMenuHeight: number,
|
||||
naturalMenuWidth = anchor.width,
|
||||
): AudioDeviceMenuPlacement {
|
||||
const insetX = Math.min(VIEWPORT_INSET, Math.max(0, viewport.width / 2));
|
||||
const width = Math.min(Math.max(0, anchor.width), Math.max(0, viewport.width - insetX * 2));
|
||||
const availableWidth = Math.max(0, viewport.width - insetX * 2);
|
||||
const desiredWidth = Number.isFinite(naturalMenuWidth)
|
||||
? Math.max(anchor.width, naturalMenuWidth)
|
||||
: anchor.width;
|
||||
const width = Math.min(Math.max(0, desiredWidth), availableWidth);
|
||||
const left = Math.max(insetX, Math.min(anchor.left, viewport.width - insetX - width));
|
||||
const fullHeight = Math.min(MAX_MENU_HEIGHT, Number.isFinite(naturalMenuHeight) ? Math.max(0, naturalMenuHeight) : 0);
|
||||
const below = Math.max(0, viewport.height - VIEWPORT_INSET - anchor.bottom - MENU_GAP);
|
||||
|
||||
@@ -46,7 +46,7 @@ export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [
|
||||
{
|
||||
id: BUILTIN_KAAK_SKIN_ID,
|
||||
name: "KAAK",
|
||||
version: "3.1.115",
|
||||
version: "3.1.121",
|
||||
author: "WebSpeak Project",
|
||||
license: "AGPL-3.0-only",
|
||||
description: "A KOOK-inspired WebSpeak skin with a split-screen connection home, searchable server header, TeamSpeak banner, nested channel members, unified chat with local history, and a compact audio dock.",
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { resolveSkinMessages } from "./skin-content.js";
|
||||
|
||||
test("localized skin messages merge the package default with the selected language", () => {
|
||||
const messages = resolveSkinMessages({
|
||||
defaultLocale: "zh-CN",
|
||||
locales: {
|
||||
"zh-CN": { messages: { hello: "你好", fallback: "默认文案" } },
|
||||
de: { messages: { hello: "Hallo" } },
|
||||
"de-DE": { messages: { hello: "Guten Tag" } },
|
||||
},
|
||||
}, "de");
|
||||
|
||||
assert.deepEqual(messages, { hello: "Guten Tag", fallback: "默认文案" });
|
||||
});
|
||||
|
||||
test("a skin without package messages resolves to an empty map", () => {
|
||||
assert.deepEqual(resolveSkinMessages(undefined, "en"), {});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Language } from "../i18n/web-client.js";
|
||||
import type { SkinContent } from "./skin-pack.js";
|
||||
|
||||
/** Resolve package-defined localized strings with the package default as fallback. */
|
||||
export function resolveSkinMessages(content: SkinContent | undefined, locale: Language): Record<string, string> {
|
||||
if (!content) return {};
|
||||
const fullLocale = locale === "zh" ? "zh-CN" : locale === "en" ? "en-US" : locale === "de" ? "de-DE" : locale === "ru" ? "ru-RU" : "ja-JP";
|
||||
const candidates = [...new Set([content.defaultLocale, locale, fullLocale])];
|
||||
const messages: Record<string, string> = {};
|
||||
for (const candidate of candidates) Object.assign(messages, content.locales[candidate]?.messages ?? {});
|
||||
return messages;
|
||||
}
|
||||
@@ -486,10 +486,18 @@ test("the distributable KAAK package provides full home and voice surfaces", asy
|
||||
const file = new File([archive], "kaak-voice.wskin", { type: "application/octet-stream" });
|
||||
const skin = await importSkinPack(file);
|
||||
assert.equal(skin.id, "community.kaak-voice");
|
||||
assert.equal(skin.version, "3.1.115");
|
||||
assert.equal(BUILTIN_SKIN_CATALOG.find((entry) => entry.id === skin.id)?.version, skin.version);
|
||||
assert.equal(skin.schemaVersion, 3);
|
||||
const home = skin.pluginData?.components.find((component) => component.page === "home");
|
||||
assert.equal(skin.version, "3.1.121");
|
||||
assert.equal(BUILTIN_SKIN_CATALOG.find((entry) => entry.id === skin.id)?.version, skin.version);
|
||||
assert.equal(skin.schemaVersion, 3);
|
||||
const baseMessages = skin.contentData?.locales["zh-CN"]?.messages ?? {};
|
||||
for (const locale of ["zh-CN", "en", "de", "ru", "ja"]) {
|
||||
assert.deepEqual(
|
||||
Object.keys(skin.contentData?.locales[locale]?.messages ?? {}).sort(),
|
||||
Object.keys(baseMessages).sort(),
|
||||
`KAAK provides the same complete message set for ${locale}`,
|
||||
);
|
||||
}
|
||||
const home = skin.pluginData?.components.find((component) => component.page === "home");
|
||||
const voice = skin.pluginData?.components.find((component) => component.page === "voice");
|
||||
assert.deepEqual(skin.pluginData?.components.map((component) => [component.id, component.mode]), [
|
||||
["kaak-home", "surface"],
|
||||
@@ -534,6 +542,12 @@ test("the distributable KAAK package provides full home and voice surfaces", asy
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
assert.equal(home?.name, "{{skin.messages.kaakHomeComponentName}}");
|
||||
assert.equal(home?.accessibleName, "{{skin.messages.kaakHomeAccessibleName}}");
|
||||
assert.equal(findPart(home?.root, "welcome-title")?.children?.[0]?.text, "{{skin.messages.kaakWelcomeTitle}}");
|
||||
assert.equal(voice?.name, "{{skin.messages.kaakVoiceComponentName}}");
|
||||
assert.equal(voice?.accessibleName, "{{skin.messages.kaakVoiceAccessibleName}}");
|
||||
assert.equal(findPart(voice?.root, "voice-stage")?.attributes?.["aria-label"], "{{skin.messages.kaakVoiceRoomAccessibleName}}");
|
||||
assert.equal(findPart(home?.root, "home-language")?.widget, "app.language-switcher", "the KAAK connection home has a language switcher in its top corner");
|
||||
assert.equal(findPart(home?.root, "server-announcement")?.widget, "home.server-announcement", "the KAAK connection home displays the localized administrator announcement");
|
||||
assert.equal(findPart(home?.root, "visitor-stats")?.widget, "home.visitor-count", "the KAAK home composes the public visitor count widget over the monitor screen");
|
||||
@@ -619,7 +633,7 @@ test("the distributable KAAK package provides full home and voice surfaces", asy
|
||||
assert.equal(chatExpand?.children?.[0]?.text, "#");
|
||||
const voiceStageInvite = findPart(voice?.root, "voice-stage-invite");
|
||||
assert.equal(voiceStageInvite?.events?.click, "copy-invite-link");
|
||||
assert.equal(voiceStageInvite?.attributes?.["aria-label"], "复制邀请链接 / Copy invite link");
|
||||
assert.equal(voiceStageInvite?.attributes?.["aria-label"], "{{skin.messages.kaakCopyInviteLink}}");
|
||||
assert.equal(findPart(voice?.root, "chat-panel")?.widget, "voice.chat-panel");
|
||||
assert.deepEqual(findPart(voice?.root, "chat-panel")?.when, { path: "chat.status.panelOpen", equals: true });
|
||||
assert.equal(voice?.root.attributes?.["data-chat-open"], "{{chat.status.panelOpen}}");
|
||||
@@ -646,13 +660,13 @@ test("the distributable KAAK package provides full home and voice surfaces", asy
|
||||
assert.equal(findPart(voiceStageHeading, "voice-stage-capacity")?.children?.[0]?.text, "/{{stagechannel.maxClients}}");
|
||||
assert.equal(findPart(voice?.root, "channel-count"), undefined, "real member counts come from the host-owned channel tree");
|
||||
assert.equal(findPart(voice?.root, "channel-voice-member"), undefined, "avatar resources stay inside trusted host UI");
|
||||
assert.equal(findPart(voice?.root, "voice-stage")?.attributes?.["aria-label"], "语音房间 / Voice room");
|
||||
assert.equal(findPart(voice?.root, "voice-stage")?.attributes?.["aria-label"], "{{skin.messages.kaakVoiceRoomAccessibleName}}");
|
||||
assert.equal(findPart(voice?.root, "member-cards")?.widget, "voice.member-cards");
|
||||
assert.deepEqual(findPart(voice?.root, "member-cards")?.options, { screenShare: true, memberActions: true });
|
||||
assert.equal(findPart(voice?.root, "member-list"), undefined);
|
||||
assert.equal(findPart(voice?.root, "screen-share-player")?.widget, "voice.screen-share-player");
|
||||
assert.equal(findPart(voice?.root, "performance-panel")?.widget, "voice.performance-panel");
|
||||
assert.deepEqual(findPart(voice?.root, "performance-panel")?.options, { screenShare: false });
|
||||
assert.equal(findPart(voice?.root, "performance-panel")?.options?.screenShare, undefined, "KAAK should show screen-share transport stats in the host panel");
|
||||
assert.equal(findPart(voice?.root, "chat-input"), undefined, "KAAK uses the host-owned unified chat composer");
|
||||
assert.ok(skin.css.includes("data-session-connected=\"true\""));
|
||||
assert.ok(skin.css.includes("[data-ws-plugin-part=\"kaak-workspace.workspace\"][data-session-connected=\"true\"]:not([data-mobile-channels=\"true\"])"));
|
||||
@@ -662,7 +676,10 @@ test("the distributable KAAK package provides full home and voice surfaces", asy
|
||||
assert.ok(skin.css.includes("mobile-room-return"));
|
||||
assert.ok(skin.css.includes('[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"][data-mobile-channels="true"] [data-ws-plugin-part="kaak-workspace.mobile-room-menu"]'), "the room menu stays hidden on the channel tree page");
|
||||
assert.ok(skin.css.includes("grid-template-columns: 86px minmax(0, 1fr)"));
|
||||
assert.ok(skin.css.includes("inset: 0 0 0 86px"));
|
||||
assert.match(skin.css, /kaak-workspace\.conversation.*data-chat-open="true"[\s\S]*?position: fixed;[\s\S]*?inset: 0 0 0 86px;[\s\S]*?pointer-events: auto;/, "the compact chat stays beside the interactive server rail");
|
||||
assert.match(skin.css, /@media \(max-width: 360px\)[\s\S]*?kaak-workspace\.conversation.*data-chat-open="true"\]\s*\{\s*inset-inline-start: 70px;/, "the compact chat respects the narrower server rail on small phones");
|
||||
assert.match(skin.css, /data-mobile-channels="true"[\s\S]*?kaak-workspace\.conversation.*data-chat-open="true"[\s\S]*?display: none;\s*pointer-events: none;/, "an open chat panel cannot cover or intercept the channel-tree page");
|
||||
assert.match(skin.css, /modal-backdrop:has\(\[data-ws-part="voice\.audio-settings"\]\)\s*\{\s*z-index: 1000;/, "the host audio settings dialog stays above the narrow chat overlay");
|
||||
assert.match(skin.css, /kaak-workspace"\]\[data-ws-plugin-surface="voice"\]:has\([\s\S]{0,180}kaak-workspace\.voice-stage"\]\s*\{[^}]*grid-column: 1;[^}]*grid-row: 3;/, "the collapsed chat state must not push the connected narrow room into an implicit side column");
|
||||
assert.match(skin.css, /kaak-workspace\.conversation\"]\[data-chat-open="true"\]\s*\{\s*position: absolute;/);
|
||||
assert.match(skin.css, /voice-dock-actions"\] \{ grid-template-columns: minmax\(0, 1fr\) 28px 28px 36px; grid-template-rows: 29px 26px; column-gap: 6px; row-gap: 21px; \}/);
|
||||
@@ -717,6 +734,7 @@ test("the distributable KAAK package provides full home and voice surfaces", asy
|
||||
assert.match(skin.css, /\[data-ws-plugin-part="kaak-workspace\.voice-dock-share"\] \{ grid-column: 1 \/ 4; grid-row: 1;/);
|
||||
assert.match(skin.css, /\[data-ws-plugin-part="kaak-workspace\.voice-dock-share"\] \.skin-runtime-screen-share-start \{[\s\S]*?background: #69c000;/);
|
||||
assert.match(skin.css, /\[data-ws-plugin-part="kaak-workspace\.desktop-room-settings"\][\s\S]*?grid-column: 1;[\s\S]*?grid-row: 2;[\s\S]*?justify-content: flex-start;[\s\S]*?gap: 8px;/);
|
||||
assert.match(skin.css, /desktop-room-controls"\]\s+\[data-ws-plugin-part="kaak-workspace\.desktop-room-settings"\]\s*\{[^}]*justify-self: stretch;[^}]*box-sizing: border-box;[^}]*width: 100%;[^}]*max-width: 100%;[^}]*min-width: 0;/, "the settings control fills its own grid track so its icon and label cannot escape the dock");
|
||||
assert.match(skin.css, /\[data-ws-plugin-part="kaak-workspace\.desktop-room-noise-suppression"\] \{ grid-column: 2; grid-row: 2; color: #fff; background: #6cbf00; \}/);
|
||||
assert.match(skin.css, /\[data-ws-plugin-part="kaak-workspace\.desktop-room-noise-suppression"\]\[aria-pressed="false"\],[\s\S]*?background: #e34848;/);
|
||||
assert.match(skin.css, /\[data-ws-plugin-part="kaak-workspace\.desktop-room-microphone"\] \{ grid-column: 3; grid-row: 2; \}/);
|
||||
@@ -762,7 +780,7 @@ test("the distributable KAAK package provides full home and voice surfaces", asy
|
||||
assert.match(skin.css, /settings-select:hover:not\(:disabled\) \{\s*border-color: #6cbf00;/);
|
||||
assert.match(skin.css, /voice\.audio-settings"] \.settings-select-menu \{[\s\S]*?padding: 8px;[\s\S]*?border-radius: 12px;[\s\S]*?background: #25262a;[\s\S]*?box-shadow: 0 2px 8px rgba\(0, 0, 0, \.32\);/);
|
||||
assert.match(skin.css, /settings-select:focus-visible \{\s*border-color: #6cbf00;\s*box-shadow: 0 0 0 3px #6cbf001a;/);
|
||||
assert.match(skin.css, /voice\.audio-settings"] \.settings-select-option \{[\s\S]*?height: 32px;[\s\S]*?margin-bottom: 2px;[\s\S]*?padding-inline: 8px;[\s\S]*?border-radius: 8px;/);
|
||||
assert.match(skin.css, /voice\.audio-settings"] \.settings-select-option \{[\s\S]*?height: auto;[\s\S]*?min-height: 32px;[\s\S]*?padding: 6px 8px;[\s\S]*?line-height: 1\.45;[\s\S]*?overflow-wrap: anywhere;[\s\S]*?white-space: normal;[\s\S]*?border-radius: 8px;/);
|
||||
assert.match(skin.css, /settings-select\[aria-expanded="true"\] \.settings-select-chevron::before \{\s*transform: rotate\(225deg\);/);
|
||||
assert.match(skin.css, /settings-select-option:hover \{ background: #ffffff0f; \}/);
|
||||
assert.match(skin.css, /voice\.audio-settings\"] \.settings-range::-webkit-slider-thumb \{\s*width: 16px;\s*height: 16px;\s*margin-top: -6px;/);
|
||||
|
||||
@@ -27,6 +27,26 @@
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
:global(html[data-ws-route="webclient"] .web-client .rail-avatar),
|
||||
:global(html[data-ws-route="webclient"] .web-client .server-avatar),
|
||||
:global(html[data-ws-route="webclient"] .web-client .profile-avatar),
|
||||
:global(html[data-ws-route="webclient"] .web-client .dock-avatar),
|
||||
:global(html[data-ws-route="webclient"] .web-client .mini-avatar),
|
||||
:global(html[data-ws-route="webclient"] .web-client .favorite-server-avatar),
|
||||
:global(html[data-ws-route="webclient"] .web-client [data-ws-part$=".avatar"]) {
|
||||
-webkit-user-select: none !important;
|
||||
user-select: none !important;
|
||||
}
|
||||
|
||||
:deep(.voice-avatar),
|
||||
:deep(.member-avatar),
|
||||
:deep(.message-avatar),
|
||||
:deep(.screen-share-player-viewer-avatar),
|
||||
:deep(.ws-voice-channel-member-avatar) {
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.join-page {
|
||||
min-height: 100dvh;
|
||||
display: flex;
|
||||
@@ -3210,10 +3230,12 @@
|
||||
}
|
||||
|
||||
:deep(.settings-select-label) {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
overflow: visible;
|
||||
overflow-wrap: anywhere;
|
||||
text-overflow: clip;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
:deep(.settings-select-chevron) {
|
||||
@@ -3235,6 +3257,8 @@
|
||||
position: fixed;
|
||||
z-index: 24;
|
||||
box-sizing: border-box;
|
||||
width: max-content;
|
||||
max-width: calc(100vw - 16px);
|
||||
margin: 0;
|
||||
padding: 4px 0;
|
||||
overflow-x: hidden;
|
||||
@@ -3248,10 +3272,13 @@
|
||||
}
|
||||
|
||||
:deep(.settings-select-option) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
display: block;
|
||||
box-sizing: border-box;
|
||||
min-height: 32px;
|
||||
padding: 0 12px;
|
||||
line-height: 1.45;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: normal;
|
||||
cursor: pointer;
|
||||
transition: background-color .12s ease;
|
||||
}
|
||||
|
||||
@@ -69,6 +69,7 @@ import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
import SkinLoadRecoveryNotice from "../components/SkinLoadRecoveryNotice.vue";
|
||||
import SkinSwitcher, { type SkinOption } from "../components/SkinSwitcher.vue";
|
||||
import { saveLocalPreferences } from "../services/local-persistence.js";
|
||||
import { resolveSkinMessages } from "../services/skin-content.js";
|
||||
import { BUILTIN_ILLUSIA_SKIN_ID, isPublicSkinEnabled } from "../services/skin-catalog.js";
|
||||
import { BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN } from "../services/skin-runtime.js";
|
||||
import { usePublicSkin } from "../composables/usePublicSkin.js";
|
||||
@@ -105,6 +106,7 @@ const copy = computed(() => {
|
||||
}
|
||||
return result;
|
||||
});
|
||||
const skinMessages = computed(() => resolveSkinMessages(activeSkin.value?.contentData, language.value));
|
||||
const selectedChannelId = ref("quiet");
|
||||
const activeTab = ref<Tab>("channel");
|
||||
const speakingId = ref("illusia");
|
||||
@@ -139,6 +141,7 @@ function sendMessage() { const text = draft.value.trim(); if (!text) return; mes
|
||||
function avatarStyle(name: string) { let hash = 0; for (const char of name) hash = char.charCodeAt(0) + ((hash << 5) - hash); const colors = ["#168f83", "#7b9ed0", "#b99070", "#8b78b9"]; return { background: colors[Math.abs(hash) % colors.length] }; }
|
||||
|
||||
const skinPluginContext = computed(() => ({
|
||||
skin: { locale: language.value, messages: skinMessages.value },
|
||||
session: {
|
||||
status: { connected: true, connecting: false, channelId: selectedChannel.value.id, channelName: selectedChannel.value.name, userName: "illusia" },
|
||||
channels: channels.map((channel, depth) => ({ id: channel.id, name: channel.name, parentId: "", depth, memberCount: channel.members.length, current: channel.id === selectedChannel.value.id })),
|
||||
|
||||
+14
-13
@@ -1003,6 +1003,7 @@ import { applyTheme, getStoredTheme, type ThemeMode } from "../services/theme.js
|
||||
import { createScreenWakeLockController, getScreenWakeLockApi, type ScreenWakeLockController, type ScreenWakeLockSnapshot } from "../services/screen-wake-lock.js";
|
||||
import { createMobileAwayController, type MobileAwayController } from "../services/mobile-away.js";
|
||||
import { createSkinPluginQuickServerProjection, safeSkinServerDisplayName } from "../services/skin-plugin-context.js";
|
||||
import { resolveSkinMessages } from "../services/skin-content.js";
|
||||
import { loadSkinPluginAuthoringDocument } from "../services/skin-plugin-authoring.js";
|
||||
import type { SkinPluginDocument, SkinPluginWidgetOptions } from "../../../src/shared/skin-plugin.js";
|
||||
import { combineTeamSpeakTarget, DEFAULT_TEAM_SPEAK_PORT, isValidTeamSpeakPort, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
@@ -1147,7 +1148,7 @@ watch(activeSkin, () => {
|
||||
skinPluginSurfaceActive.value = false;
|
||||
skinRuntimePluginSurfaceActive.value = false;
|
||||
}, { flush: "sync" });
|
||||
const skinMessageOverrides = computed(() => resolveSkinMessages(activeSkin.value, language.value));
|
||||
const skinMessageOverrides = computed(() => resolveSkinMessages(activeSkin.value?.contentData, language.value));
|
||||
const { t: translate, localizedMessage, localizedAudioNotice, visibleErrorCode } = useWebClientI18n(language);
|
||||
function t(key: string, variables: Record<string, string | number> = {}) {
|
||||
const template = skinMessageOverrides.value[key];
|
||||
@@ -1313,6 +1314,7 @@ const screenShareControls = useWebClientScreenShare({
|
||||
leaveScreenShare,
|
||||
nickname,
|
||||
avatarStyle,
|
||||
memberAvatar: memberAvatarById,
|
||||
t,
|
||||
});
|
||||
const { settingsOpen: screenShareSettingsOpen, errorText: screenShareErrorText } = screenShareControls;
|
||||
@@ -1598,8 +1600,12 @@ const skinPluginMembers = computed(() => memberChannels.value.flatMap((item) =>
|
||||
};
|
||||
})));
|
||||
|
||||
const skinPluginContext = computed(() => ({
|
||||
session: {
|
||||
const skinPluginContext = computed(() => ({
|
||||
skin: {
|
||||
locale: language.value,
|
||||
messages: skinMessageOverrides.value,
|
||||
},
|
||||
session: {
|
||||
status: {
|
||||
connected: voiceState.connected,
|
||||
connecting: voiceState.connecting,
|
||||
@@ -2190,6 +2196,10 @@ function avatarStyle(name: string, isSelf = false, avatar = "") {
|
||||
};
|
||||
}
|
||||
|
||||
function memberAvatarById(clientId: number): string {
|
||||
return members.find((candidate) => candidate.id === clientId)?.avatar ?? "";
|
||||
}
|
||||
|
||||
function messageAvatar(message: ChatMessage): string {
|
||||
const member = members.find((candidate) =>
|
||||
(typeof message.senderId === "number" && candidate.id === message.senderId) ||
|
||||
@@ -2225,16 +2235,7 @@ function resolveSkinHomeCopy(skin: InstalledSkin | null, locale: Language): Skin
|
||||
return result;
|
||||
}
|
||||
|
||||
function resolveSkinMessages(skin: InstalledSkin | null, locale: Language): Record<string, string> {
|
||||
const content = skin?.contentData;
|
||||
if (!content) return {};
|
||||
const fullLocale = locale === "zh" ? "zh-CN" : locale === "en" ? "en-US" : locale === "de" ? "de-DE" : locale === "ru" ? "ru-RU" : "ja-JP";
|
||||
const candidates = [...new Set([content.defaultLocale, locale, fullLocale])];
|
||||
const result: Record<string, string> = {};
|
||||
for (const candidate of candidates) Object.assign(result, content.locales[candidate]?.messages ?? {});
|
||||
return result;
|
||||
}
|
||||
</script>
|
||||
</script>
|
||||
|
||||
<style scoped src="../styles/web-client.css"></style>
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { applySavedMemberVolumes } from "./member-volume-preferences.js";
|
||||
|
||||
test("saved member volume follows the stable UID to a new connection-local client ID", () => {
|
||||
const volumes: Record<number, number> = {};
|
||||
const updated = applySavedMemberVolumes([
|
||||
{ id: 19, nickname: "Peer", uid: "stable-peer-uid" },
|
||||
{ id: 20, nickname: "No UID" },
|
||||
], { "stable-peer-uid": 0.35 }, volumes);
|
||||
|
||||
assert.deepEqual(updated, [19]);
|
||||
assert.deepEqual(volumes, { 19: 0.35 });
|
||||
});
|
||||
|
||||
test("saved member volumes are clamped and unchanged or invalid values are ignored", () => {
|
||||
const volumes: Record<number, number> = { 19: 0.5, 20: 1 };
|
||||
const updated = applySavedMemberVolumes([
|
||||
{ id: 19, nickname: "Peer", uid: "unchanged" },
|
||||
{ id: 20, nickname: "Peer 2", uid: "invalid" },
|
||||
{ id: 21, nickname: "Peer 3", uid: "too-high" },
|
||||
], { unchanged: 0.5, invalid: Number.NaN, "too-high": 8 }, volumes);
|
||||
|
||||
assert.deepEqual(updated, [21]);
|
||||
assert.deepEqual(volumes, { 19: 0.5, 20: 1, 21: 4 });
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ChannelMember } from "../../../src/shared/voice-models.js";
|
||||
|
||||
/** Restore stable per-member preferences onto the connection-local client IDs. */
|
||||
export function applySavedMemberVolumes(
|
||||
members: readonly ChannelMember[],
|
||||
savedByUid: Readonly<Record<string, number>>,
|
||||
volumes: Record<number, number>,
|
||||
): number[] {
|
||||
const updatedIds: number[] = [];
|
||||
for (const member of members) {
|
||||
if (!member.uid) continue;
|
||||
const saved = savedByUid[member.uid];
|
||||
if (typeof saved !== "number" || !Number.isFinite(saved)) continue;
|
||||
const normalized = Math.max(0, Math.min(4, saved));
|
||||
if (volumes[member.id] === normalized) continue;
|
||||
volumes[member.id] = normalized;
|
||||
updatedIds.push(member.id);
|
||||
}
|
||||
return updatedIds;
|
||||
}
|
||||
@@ -3,6 +3,13 @@ import { parseScreenShareStream, parseScreenShareViewers, type ServerMessage } f
|
||||
import { normalizeScreenShareIceServers, type ScreenShareIceServer, type ScreenShareClientMessage, type ScreenShareStreamDescription as ScreenShareStream, type ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
|
||||
|
||||
const SCREEN_SHARE_NEGOTIATION_TIMEOUT_MS = 15_000;
|
||||
const SCREEN_SHARE_DIAGNOSTICS_ENABLED = typeof window !== "undefined"
|
||||
&& new URLSearchParams(window.location.search).get("debugScreenShare") === "1";
|
||||
|
||||
function traceScreenShare(event: string, details: Record<string, string | number | boolean | null> = {}): void {
|
||||
if (!SCREEN_SHARE_DIAGNOSTICS_ENABLED) return;
|
||||
console.info("[WebSpeak screen-share]", { event, ...details });
|
||||
}
|
||||
|
||||
export interface ScreenShareOutputSettings {
|
||||
maxWidth?: number;
|
||||
@@ -78,13 +85,21 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
const screenSharePendingIce = new Map<string, RTCIceCandidateInit[]>();
|
||||
const screenSharePeerStreams = new Map<string, MediaStream>();
|
||||
const screenSharePeerTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const screenShareLoggedIcePeers = new Set<string>();
|
||||
let screenShareRequestSequence = 0;
|
||||
let screenSharePendingStartId = "";
|
||||
let screenShareStartCancelled = false;
|
||||
let screenShareStartGeneration = 0;
|
||||
|
||||
function sendScreenShareMessage(message: ScreenShareClientMessage): void {
|
||||
if (transport.isOpen()) transport.send(message);
|
||||
if (transport.isOpen()) {
|
||||
transport.send(message);
|
||||
if (message.type === "screenShareSignal" && message.signal.kind !== "iceCandidate") {
|
||||
traceScreenShare("signal-sent", { streamId: message.streamId, peerId: message.targetPeerId, signalKind: message.signal.kind });
|
||||
}
|
||||
} else if (message.type === "screenShareSignal") {
|
||||
traceScreenShare("signal-dropped-transport-closed", { streamId: message.streamId, peerId: message.targetPeerId, signalKind: message.signal.kind });
|
||||
}
|
||||
}
|
||||
|
||||
type ScreenShareStatsRecord = Record<string, unknown>;
|
||||
@@ -247,6 +262,7 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
screenSharePeerTimers.set(peerId, setTimeout(() => {
|
||||
screenSharePeerTimers.delete(peerId);
|
||||
if (!screenSharePeers.has(peerId)) return;
|
||||
traceScreenShare("negotiation-timeout", { peerId });
|
||||
failScreenSharePeer(peerId, "屏幕共享直连协商超时,请确认双方网络允许浏览器直连");
|
||||
}, SCREEN_SHARE_NEGOTIATION_TIMEOUT_MS));
|
||||
}
|
||||
@@ -258,6 +274,7 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
screenSharePeerRoles.delete(peerId);
|
||||
screenShareStatsPrevious.delete(peerId);
|
||||
screenSharePendingIce.delete(peerId);
|
||||
screenShareLoggedIcePeers.delete(peerId);
|
||||
screenSharePeerStreams.get(peerId)?.getTracks().forEach(track => track.stop());
|
||||
screenSharePeerStreams.delete(peerId);
|
||||
if (peer) {
|
||||
@@ -289,6 +306,11 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
function failScreenSharePeer(peerId: string, message?: string): void {
|
||||
const viewingStream = screenShareStreams.find((stream) => stream.streamId === screenShareViewingStreamId.value && stream.ownerPeerId === peerId);
|
||||
if (viewingStream) sendScreenShareMessage({ type: "screenShareLeave", streamId: viewingStream.streamId });
|
||||
traceScreenShare("peer-failed", {
|
||||
peerId,
|
||||
streamId: viewingStream?.streamId ?? screenShareStreams.find((stream) => stream.streamId === screenShareActiveStreamId.value)?.streamId ?? null,
|
||||
message: message ?? null,
|
||||
});
|
||||
closeScreenSharePeer(peerId);
|
||||
if (viewingStream) {
|
||||
screenShareViewingStreamId.value = "";
|
||||
@@ -303,13 +325,26 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
// STUN discovers server-reflexive candidates; it does not carry media.
|
||||
// TURN is accepted only when explicitly configured by the deployment, and
|
||||
// would use that external TURN service rather than the WebSpeak gateway.
|
||||
const peer = new RTCPeerConnection({ iceServers: screenShareIceServers });
|
||||
let peer: RTCPeerConnection;
|
||||
try {
|
||||
peer = new RTCPeerConnection({ iceServers: screenShareIceServers });
|
||||
} catch (error: unknown) {
|
||||
traceScreenShare("peer-create-failed", { streamId, peerId, role, errorName: error instanceof Error ? error.name : "unknown" });
|
||||
throw error;
|
||||
}
|
||||
screenSharePeers.set(peerId, peer);
|
||||
screenSharePeerRoles.set(peerId, role);
|
||||
startScreenShareStatsPolling();
|
||||
traceScreenShare("peer-created", { streamId, peerId, role });
|
||||
if (role === "owner") {
|
||||
for (const track of screenShareLocalStream?.getTracks() ?? []) {
|
||||
// Match TeamSpeak's screen-share offer shape: video is MID 0, optional
|
||||
// audio follows it, and a publisher only sends media.
|
||||
const localTracks = [...(screenShareLocalStream?.getTracks() ?? [])];
|
||||
localTracks.sort((left, right) => left.kind === right.kind ? 0 : left.kind === "video" ? -1 : 1);
|
||||
for (const track of localTracks) {
|
||||
const sender = peer.addTrack(track, screenShareLocalStream!);
|
||||
const transceiver = peer.getTransceivers().find((candidate) => candidate.sender === sender);
|
||||
if (transceiver) transceiver.direction = "sendonly";
|
||||
if (track.kind === "video") void configureScreenShareVideoSender(sender, track);
|
||||
}
|
||||
} else {
|
||||
@@ -317,10 +352,18 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
const stream = screenShareStreams.find((candidate) => candidate.streamId === streamId);
|
||||
if (stream?.audio) peer.addTransceiver("audio", { direction: "recvonly" });
|
||||
}
|
||||
preferScreenShareCodecs(peer);
|
||||
// TeamSpeak's native receiver logs show that its decoder rejects the
|
||||
// H.264 constrained-baseline profile advertised by browsers. Prefer the
|
||||
// universally supported VP8 profile for browser-to-native peers, while
|
||||
// keeping the higher-quality codec order for browser-to-browser sharing.
|
||||
preferScreenShareCodecs(peer, role === "owner" && peerId.startsWith("ts-viewer-"));
|
||||
peer.onicecandidate = (event) => {
|
||||
if (!isCurrentPeer(peerId, peer) || !event.candidate) return;
|
||||
const candidate = event.candidate;
|
||||
if (!screenShareLoggedIcePeers.has(peerId)) {
|
||||
screenShareLoggedIcePeers.add(peerId);
|
||||
traceScreenShare("first-ice-candidate-sent", { streamId, peerId, role });
|
||||
}
|
||||
sendScreenShareMessage({
|
||||
type: "screenShareSignal",
|
||||
streamId,
|
||||
@@ -335,6 +378,7 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
};
|
||||
peer.ontrack = (event) => {
|
||||
if (!isCurrentPeer(peerId, peer) || role !== "viewer") return;
|
||||
traceScreenShare("remote-track-received", { streamId, peerId, role, kind: event.track.kind, readyState: event.track.readyState });
|
||||
clearScreenSharePeerTimer(peerId);
|
||||
const remote = event.streams[0] ?? screenSharePeerStreams.get(peerId) ?? new MediaStream();
|
||||
if (!event.streams[0]) remote.addTrack(event.track);
|
||||
@@ -343,6 +387,7 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
};
|
||||
peer.onconnectionstatechange = () => {
|
||||
if (!isCurrentPeer(peerId, peer)) return;
|
||||
traceScreenShare("connection-state", { streamId, peerId, role, state: peer.connectionState });
|
||||
// `completed` belongs to RTCIceConnectionState, not the aggregate
|
||||
// RTCPeerConnection.connectionState. Treating it as a connection state
|
||||
// both trips the type checker and can hide the actual failed/closed
|
||||
@@ -354,6 +399,10 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
}
|
||||
if (peer.connectionState === "closed" && screenSharePeers.get(peerId) === peer) closeScreenSharePeer(peerId);
|
||||
};
|
||||
peer.oniceconnectionstatechange = () => {
|
||||
if (!isCurrentPeer(peerId, peer)) return;
|
||||
traceScreenShare("ice-connection-state", { streamId, peerId, role, state: peer.iceConnectionState });
|
||||
};
|
||||
return peer;
|
||||
}
|
||||
|
||||
@@ -411,14 +460,17 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
}
|
||||
}
|
||||
|
||||
function preferScreenShareCodecs(peer: RTCPeerConnection): void {
|
||||
function preferScreenShareCodecs(peer: RTCPeerConnection, preferNativeCompatibility = false): void {
|
||||
const transceiver = peer.getTransceivers().find((candidate) => candidate.sender.track?.kind === "video" || candidate.receiver.track?.kind === "video");
|
||||
const capabilities = typeof RTCRtpSender !== "undefined" ? RTCRtpSender.getCapabilities?.("video") : null;
|
||||
if (!transceiver?.setCodecPreferences || !capabilities?.codecs?.length) return;
|
||||
// Prefer H.264/AV1 for screen content: both compress text/UI far better
|
||||
// than VP8 at the bitrates typical of relayed screen shares. VP8 stays as
|
||||
// a fallback when neither is available.
|
||||
const preferred = ["video/h264", "video/av1", "video/vp8"].flatMap((mimeType) =>
|
||||
// Prefer H.264/AV1 for browser peers. TeamSpeak's native receiver logs
|
||||
// show that its decoder rejects the browser H.264 profile, so put VP8
|
||||
// first when the viewer is a native TeamSpeak client.
|
||||
const codecOrder = preferNativeCompatibility
|
||||
? ["video/vp8", "video/h264", "video/av1"]
|
||||
: ["video/h264", "video/av1", "video/vp8"];
|
||||
const preferred = codecOrder.flatMap((mimeType) =>
|
||||
capabilities.codecs.filter((codec) => codec.mimeType.toLowerCase() === mimeType),
|
||||
);
|
||||
if (!preferred.length) return;
|
||||
@@ -465,7 +517,18 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
|
||||
async function startNativeScreenShareViewer(streamId: string, peerId: string): Promise<void> {
|
||||
const stream = screenShareStreams.find((candidate) => candidate.streamId === streamId);
|
||||
if (!stream || stream.source !== "browser" || screenShareActiveStreamId.value !== streamId || stream.ownerPeerId !== screenShareLocalPeerId()) return;
|
||||
if (!stream || stream.source !== "browser" || screenShareActiveStreamId.value !== streamId || stream.ownerPeerId !== screenShareLocalPeerId()) {
|
||||
traceScreenShare("native-viewer-request-ignored", {
|
||||
streamId,
|
||||
peerId,
|
||||
streamFound: Boolean(stream),
|
||||
streamSource: stream?.source ?? null,
|
||||
activeStreamMatches: screenShareActiveStreamId.value === streamId,
|
||||
ownerMatchesLocalPeer: stream?.ownerPeerId === screenShareLocalPeerId(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
traceScreenShare("native-viewer-request-accepted", { streamId, peerId });
|
||||
closeScreenSharePeer(peerId);
|
||||
const peer = createScreenSharePeer(streamId, peerId, "owner");
|
||||
try {
|
||||
@@ -474,20 +537,26 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
await peer.setLocalDescription(offer);
|
||||
if (!isCurrentPeer(peerId, peer)) return;
|
||||
armScreenSharePeerTimer(peerId);
|
||||
traceScreenShare("native-viewer-offer-ready", { streamId, peerId });
|
||||
sendScreenShareMessage({
|
||||
type: "screenShareSignal",
|
||||
streamId,
|
||||
targetPeerId: peerId,
|
||||
signal: { kind: "offer", sdp: peer.localDescription?.sdp ?? offer.sdp ?? "" },
|
||||
});
|
||||
} catch {
|
||||
} catch (error: unknown) {
|
||||
traceScreenShare("native-viewer-offer-failed", { streamId, peerId, errorName: error instanceof Error ? error.name : "unknown" });
|
||||
if (isCurrentPeer(peerId, peer)) failScreenSharePeer(peerId, "无法为 TeamSpeak 观看端创建屏幕共享直连");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleScreenShareSignal(streamId: string, fromPeerId: string, signal: ScreenShareSignal): Promise<void> {
|
||||
traceScreenShare("signal-received", { streamId, peerId: fromPeerId, signalKind: signal.kind });
|
||||
const stream = screenShareStreams.find((candidate) => candidate.streamId === streamId);
|
||||
if (!stream) return;
|
||||
if (!stream) {
|
||||
traceScreenShare("signal-ignored-stream-not-found", { streamId, peerId: fromPeerId, signalKind: signal.kind });
|
||||
return;
|
||||
}
|
||||
if (signal.kind === "close") {
|
||||
closeScreenSharePeer(fromPeerId);
|
||||
if (screenShareViewingStreamId.value === streamId) {
|
||||
@@ -764,12 +833,24 @@ export function createScreenShareController(transport: ScreenShareTransport) {
|
||||
}
|
||||
case "screenShareNativeViewerJoined":
|
||||
if (typeof msg.streamId === "string" && typeof msg.viewerPeerId === "string") {
|
||||
traceScreenShare("native-viewer-joined-event", { streamId: msg.streamId, peerId: msg.viewerPeerId });
|
||||
void startNativeScreenShareViewer(msg.streamId, msg.viewerPeerId);
|
||||
} else {
|
||||
traceScreenShare("native-viewer-joined-event-invalid", {
|
||||
hasStreamId: typeof msg.streamId === "string",
|
||||
hasPeerId: typeof msg.viewerPeerId === "string",
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "screenShareSignal":
|
||||
if (typeof msg.streamId === "string" && typeof msg.fromPeerId === "string" && msg.signal) {
|
||||
void handleScreenShareSignal(msg.streamId, msg.fromPeerId, msg.signal as ScreenShareSignal);
|
||||
} else {
|
||||
traceScreenShare("signal-event-invalid", {
|
||||
hasStreamId: typeof msg.streamId === "string",
|
||||
hasPeerId: typeof msg.fromPeerId === "string",
|
||||
hasSignal: Boolean(msg.signal),
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "screenShareViewerLeft":
|
||||
|
||||
@@ -15,7 +15,7 @@ before(async () => {
|
||||
({ default: VoiceChannelTree } = await vite.ssrLoadModule("/src/components/web-client/VoiceChannelTree.vue"));
|
||||
});
|
||||
after(async () => { await vite?.close(); });
|
||||
function mount(t, initialStream = null) {
|
||||
function mount(t, initialStream = null, memberAvatar = () => "") {
|
||||
const listeners = new Set(), starts = [], storage = new Map(); let exits = 0, ui;
|
||||
class Element {}
|
||||
class Video extends Element { srcObject = null; volume = 1; plays = 0; async play() { this.plays++; } }
|
||||
@@ -26,7 +26,7 @@ function mount(t, initialStream = null) {
|
||||
t.after(() => { if (original) Object.defineProperty(globalThis, key, original); else delete globalThis[key]; });
|
||||
}
|
||||
const viewing = shallowRef(true), stream = shallowRef(initialStream), volume = shallowRef(.4), streams = [];
|
||||
const app = renderer.createApp({ setup() { ui = useWebClientScreenShare({ streams, viewing, viewingStreamId: shallowRef("s"), remoteStream: stream, remoteVolume: volume, error: shallowRef(""), errorCode: shallowRef(""), startScreenShare: async (...args) => starts.push(args), joinScreenShare() {}, leaveScreenShare() {}, nickname: shallowRef("Self"), avatarStyle: () => ({}), t: key => key }); return () => null; } });
|
||||
const app = renderer.createApp({ setup() { ui = useWebClientScreenShare({ streams, viewing, viewingStreamId: shallowRef("s"), remoteStream: stream, remoteVolume: volume, error: shallowRef(""), errorCode: shallowRef(""), startScreenShare: async (...args) => starts.push(args), joinScreenShare() {}, leaveScreenShare() {}, nickname: shallowRef("Self"), avatarStyle: () => ({}), memberAvatar, t: key => key }); return () => null; } });
|
||||
app.mount({});
|
||||
return { ui, app, doc, viewing, stream, volume, streams, starts, storage, listeners, exits: () => exits, video: () => markRaw(new Video()), player: () => markRaw(new Element()) };
|
||||
}
|
||||
@@ -98,6 +98,32 @@ test("known screen owner IDs cannot fall back to another member with the same ni
|
||||
} finally { f.app.unmount(); }
|
||||
});
|
||||
|
||||
test("viewers resolve their avatar locally from a client id instead of the roster payload", async t => {
|
||||
// `streams` is a plain array, so `viewers` (a computed) caches its first read:
|
||||
// each scenario needs its own mount.
|
||||
async function avatarFor(viewer, memberAvatar = () => "") {
|
||||
const f = mount(t, null, memberAvatar);
|
||||
try {
|
||||
f.streams[0] = { streamId: "s", viewers: [viewer] };
|
||||
await nextTick();
|
||||
assert.equal(f.ui.viewers.value.length, 1);
|
||||
return f.ui.viewers.value[0].avatar;
|
||||
} finally { f.app.unmount(); }
|
||||
}
|
||||
// Current gateway: the roster carries a client id and the avatar comes from the directory.
|
||||
assert.equal(
|
||||
await avatarFor({ peerId: "v", nickname: "Visitor", clientId: 42 }, clientId => (clientId === 42 ? "data:image/png;base64,LOCAL" : "")),
|
||||
"data:image/png;base64,LOCAL",
|
||||
);
|
||||
// Legacy gateway: the inline avatar still renders.
|
||||
assert.equal(
|
||||
await avatarFor({ peerId: "v", nickname: "Visitor", avatar: "data:image/png;base64,LEGACY" }),
|
||||
"data:image/png;base64,LEGACY",
|
||||
);
|
||||
// Unknown member: degrades to the initial instead of throwing.
|
||||
assert.equal(await avatarFor({ peerId: "v", nickname: "Visitor", clientId: 99 }), "");
|
||||
});
|
||||
|
||||
test("member cards detect and expose a remote share without depending on local share status", async () => {
|
||||
let lookupCount = 0;
|
||||
const html = await renderToString(createSSRApp(VoiceMemberCards, {
|
||||
|
||||
@@ -162,7 +162,7 @@ test("ICE configuration belongs to each controller independently", async () => {
|
||||
} finally { second.stopTransport(false); }
|
||||
});
|
||||
|
||||
test("screen share codecs are ordered H.264, AV1, then VP8 independent of browser order", async () => {
|
||||
test("browser viewers prefer H.264, AV1, then VP8 independent of browser order", async () => {
|
||||
const codecs = [
|
||||
{ mimeType: "video/vp8", clockRate: 90_000 },
|
||||
{ mimeType: "video/rtx", clockRate: 90_000, sdpFmtpLine: "apt=96" },
|
||||
@@ -182,6 +182,34 @@ test("screen share codecs are ordered H.264, AV1, then VP8 independent of browse
|
||||
]);
|
||||
});
|
||||
|
||||
test("native TeamSpeak viewers prefer VP8 for decoder compatibility", async () => {
|
||||
const codecs = [
|
||||
{ mimeType: "video/h264", clockRate: 90_000, sdpFmtpLine: "packetization-mode=1;profile-level-id=42e01f" },
|
||||
{ mimeType: "video/rtx", clockRate: 90_000, sdpFmtpLine: "apt=96" },
|
||||
{ mimeType: "video/av1", clockRate: 90_000 },
|
||||
{ mimeType: "video/vp8", clockRate: 90_000 },
|
||||
] satisfies RTCRtpCodecCapability[];
|
||||
replaceGlobal("RTCRtpSender", { getCapabilities: () => ({ codecs }) });
|
||||
|
||||
await controller.api.startScreenShare();
|
||||
const requestId = sent.at(-1)?.requestId;
|
||||
controller.handleMessage({
|
||||
type: "screenShareStarted",
|
||||
owner: true,
|
||||
requestId,
|
||||
stream: { ...remote, streamId: "local", ownerPeerId: "local-owner" },
|
||||
});
|
||||
controller.handleMessage({ type: "screenShareNativeViewerJoined", streamId: "local", viewerPeerId: "ts-viewer-7" });
|
||||
await nextTurn();
|
||||
|
||||
assert.deepEqual(Peer.instances[0]?.codecPreferences.map((codec) => codec.mimeType), [
|
||||
"video/vp8",
|
||||
"video/h264",
|
||||
"video/av1",
|
||||
"video/rtx",
|
||||
]);
|
||||
});
|
||||
|
||||
test("viewer visibility follows the selected stream so the player and card cannot disagree", async () => {
|
||||
assert.equal(controller.api.screenShareViewing.value, false);
|
||||
assert.equal(controller.api.screenShareViewingStreamId.value, "");
|
||||
|
||||
Reference in new issue
Block a user